What's New in v0.8.7
This release came out of writing a large application (FluxGX) in GX and fixing every place where the language said one thing and the compiler did another. Most of it is bug fixes for code that compiled and then did the wrong thing. The rest removes limits that forced C-style workarounds.
Two changes can alter the behaviour of existing programs. Read Breaking changes first.
Breaking changes
#for is inclusive
#for (i=a:b) now runs for a through b inclusive, exactly like the
runtime for (i = a:b) and like slice ranges. Before 0.8.7 it stopped one
short of b, so the same range syntax meant two different things.
#for (i=0:3) { print("{i} ") } // 0 1 2 3 (was: 0 1 2)
// Reflection loops need "- 1" now:
#for (i=0:@fields(Point) - 1) {
print("{@field(Point, i)}\n")
}
A loop that was not updated walks one index past the end, which the reflection intrinsics report as an error, so stale code fails loudly.
Only 0 and null convert to a pointer
An integer expression used to be accepted wherever a pointer was expected. That made two common mistakes compile:
fn set(out v: i32) { v = 42 } // assigned the pointer, stored nothing
set(c) // passed the VALUE of c as an address
Both are now errors that say what to write:
error: 'v' is an 'out' parameter (a pointer). Write '*v = ...' to store the value
error: Argument 1: expected *i32 for an 'out' parameter, got i32. Pass '&c'
The constant 0 and null still convert. See
Out Parameters for the full rules.
Statement boundaries
Semicolons are optional, and a line that starts with *, (, ++ or --
now starts a new statement instead of continuing the previous line:
*a = 1
*b = 2 // was parsed as *a = 1 * b = 2
var d = c
++c // was parsed as d = c++ then c
Inside (...) and [...] a line break never ends the expression, so
wrapped call arguments and conditions are unaffected. A multiplication that
continues onto the next line must keep the * at the end of the first line
(or be wrapped in parentheses).
Bugs fixed
| Bug | Was | Now |
|---|---|---|
| Long string interpolation with clang | More than about five {} in one string printed garbage (f=6 came out as f=a) in every clang build, so in every -O1+ build and every raylib program | Pieces are appended in order; any number of interpolations works |
| Indexing evaluated its index twice | In bounds-checked builds a[i++] advanced i by 2 and a[next()] called next twice | Evaluated once |
| Explicit enum values ignored | enum E { A = 10 B = 20 } produced 0 and 1 | C numbering: explicit value, otherwise previous + 1 |
| Struct declaration order | A struct embedding one declared later failed in the C compiler (“incomplete type”) | Definitions are emitted in dependency order |
arr.at(i).field | Invalid C (missing parentheses) | Works, and is bounds-checked |
arr[i] on array<T> | Invalid C, no GX error | Works for reading and writing, bounds-checked |
(*p).field | Emitted as *p.field | Emitted as (*p).field |
| Method call on a pointer receiver | q.scale(2.0) with q: *P emitted an unmangled call | Works |
alloc(T) returned garbage | Arena / Pool / FreeList handed out uninitialized (and, after reset, stale) memory | Zeroed, like every other GX value |
map<str, V> dangling keys | The map kept the caller’s pointer; a key built with "k{i}" was overwritten a few string operations later | The map owns a copy of each key |
remove_swap / remove_shift on an empty array | Length underflowed | No-op |
Compiler hang on a lone { | A string with an interpolation and a later plain { ("x={a} and { b") made the compiler loop forever | The brace is literal text |
fn() function pointers | A pointer to a function with no parameters got a phantom *void parameter: var h: fn() = f was a type mismatch | fn() takes nothing |
out x: T with 0 | x = 0 and f(0) slipped through as null-pointer conversions | Both are errors |
@cfile compiled twice | A C file named by @cfile and also found as the companion of an @c_included header was passed to the C compiler twice (duplicate symbols) | Sources are added once |
| Calling a C variadic | printf("%d", n) was rejected (“Function expects 1 argument(s), got 2”) | Fixed parameters are checked, extra arguments pass through; a str passed for %s is lowered to its pointer |
| Integer literal width | Any 10-digit literal was an i64, so var a: i32 = 1073741824 failed | Typed by value: i32 when it fits |
Language additions
Containers and richer types in structs
Struct and union fields may now be array<T>, map<K,V>, a template
instance, a function pointer, a slice, or a fixed array sized by a const.
const MAX_WEIGHTS = 8
#type T
struct Pair { first: T second: T }
struct Geo {
pts: array<vec3>
names: map<str, i32>
children: array<*Geo> // pointer element types are allowed
range: Pair<i32>
weights: f32[MAX_WEIGHTS]
cook: fn(i32):i32
}
fn geo_add(out g: *Geo, p: vec3) {
g.pts.push(p) // first push allocates
g.names.set("p{g.pts.len()}", g.pts.len())
}
fn main() {
var g: Geo // no allocation
geo_add(&g, vec3{1.0, 2.0, 3.0})
g.pts[0].x = 10.0
g.pts.free()
g.names.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() yourself.
Calling a modifying method (push, set, clear, remove, sort,
free, …) through a read-only pointer parameter is a compile error; mark
the parameter out.
array<T> indexing
a[i] and a.at(i) are the same bounds-checked element access and both can
be assigned through:
var a: array<i32> = {5, 6, 7}
a[1] = 60
a[2] += 1
ps[0].x = 9.0 // array<P>
var q: *P = &ps[0] // valid until the next push
self in ex blocks
Inside an ex block self is a writable pointer to the receiver. Fields
are still in scope by their bare names; self is for calling a sibling
method or passing the object on.
ex P {
fn scale(k: f32) { x = x * k; y = y * k }
fn twice() { self.scale(2.0) }
fn dump() { show(self) }
}
A bare sibling call (scale(2.0)) is still an error, and the message now
points at self.scale(...).
const-sized arrays
const N = 8
var a: i32[N]
struct S { d: f32[N] }
The size must be a top-level integer const.
String literals inside interpolation
print("alice: {scores.get("alice")}\n")
An interpolation cannot begin with a string literal: { followed by a quote
still means a string that ends in a brace, so "{" + key + "}" stays three
strings. Wrap it in parentheses instead: "{("a" + b)}".
cstr converts to str
A cstr is accepted where a str is expected in arguments, variable
initializers and assignments. It is wrapped (pointer plus strlen), not
copied.
var s: str = getenv("HOME")
Pointer casts to user types
var n: *Node = (*Node)raw
The cast must be followed directly by a name, a call or null. This keeps
(*p).x and (*p) = v unambiguous.
Dear ImGui, with docking
The cimgui module now binds the whole Dear ImGui 1.92.9b API from the
docking branch (1524 functions, 1066 enum members, the commonly used
structs), generated from the vendored header. ImVec2 and ImVec4 are GX’s
vec2 and vec4. Two backends ship with it:
cimgui_sokolforsokol.app+sokol.gfx, wrapping sokol’s ownsokol_imgui.h(examples/56_cimgui_sokol.gx)cimgui_raylibfor raylib (examples/55_cimgui_raylib.gx)
Docking works inside the main window with both. See the Dear ImGui module page.
sokol.app gained bindings for the general-purpose sapp_* functions
(sapp_dpi_scale, sapp_request_quit, sapp_set_window_title, clipboard,
mouse lock, dropped files).
Backends
All three native backends now pass the same test suite (70 tests, nothing skipped), build every example, and print the same output for each of them:
| Backend | 0.8.6 | 0.8.7 |
|---|---|---|
--backend=c | reference | 70 / 70 |
--backend=llvm-clang (text emitter) | several core constructs refused | 70 / 70 |
--backend=llvm (native) | most real programs refused | 70 / 70 |
Behaviour that differed between backends and is now the same everywhere:
&&and||short-circuit on the LLVM backends. Both used to evaluate the right operand unconditionally, sop != null && p.x > 0dereferenced null andi < n && a[i] > 0hit the bounds check, while the C backend was fine.c ? a : bevaluates only the selected branch onllvm-clang(it evaluated both).- A method call on a temporary (
p.scaled(2.0).len2(), also insideexthroughself) compiles with every C compiler. The C backend emitted&f(), which only TCC accepts. - Compound assignment on a whole vector (
v *= 2.0,v += w) works. It emitted invalid C and invalid IR. - Union members through a pointer (
p.iwithp: *U) and stores through an indexed pointer (p[i] = v) work onllvm-clang. - A float literal passed to an
f64parameter or to a C variadic keeps double precision on the LLVM backends (3.14159arrived as 3.141590118408203).
What changed in the LLVM text emitter:
array<T>indexing (a[i],a.at(i)) as values and as assignment targets, with bounds checks- containers, function pointers and template instances as struct fields
- compound assignment and
++/--on any addressable target. They were limited to local variables, sop.x += 1,arr[i] += 1and globals were refused - extension methods on pointer receivers, calls through function-pointer fields
- string building through the same runtime builder as the C backend (nested string building printed garbage)
cstrtostrconversion,var c: cstr = "literal"- C variadic calls: a fixed-arity wrapper per call shape is generated into the glue file
@cppfilesources are compiled and linked (Dear ImGui programs build)
The native backend (--backend=llvm) has its own in-process IR builder. In
0.8.6 it rejected most real programs with “still being built out”. It now
lowers all 103 test and example programs itself, including with -g. What
was added to it:
- extension methods (value and pointer receivers,
self, bare field names) array<T>,Arena/Pool/FreeListandchan<T>types and methods- function references as values, calls through function-pointer variables, parameters and struct fields
?:,sizeof, unions, pointer arithmetic andp[i]- vectors, matrices, enums and
cstrin string interpolation - C variadic calls,
main(args: str[]),dot/cross/identity_mat4,.sort()on fixed arrays and slices
A safety net remains for anything not covered: if the builder cannot lower a
program, GX lowers it through the text emitter instead, parses that IR in
process, and continues with the native pipeline. On that path there is no
DWARF variable information; -g prints a note when it happens and
--verbose lists the constructs. Setting GX_LLVM_NO_FALLBACK=1 turns the
fallback into an error; tests/run_tests.sh --backend llvm --native runs
the suite that way, so a regression in the builder fails a test instead of
silently taking the other path.
Every extern fn is now called through a generated C shim on the native
backend too, so static inline functions in module headers link.
Smaller changes
- Casts to C types are accepted:
(cstr)p,(c_int)x,(c_size)nand the otherc_*scalars. Only the GX scalar types were recognized before. - An interpolation may start with a dereference:
"{*p}". It was printed literally, braces included, while"{-x}"and"{!b}"already worked. - Defining a function with the name of a built-in (
print,input,dot,cross,mul,identity_mat4) is a compile error. It used to crash the compiler without a message.
Fixes after the first 0.8.7 build
Found while checking the documentation, the editor plugins and the language server against the first build. They are part of the released 0.8.7.
Type checker
-
Operand rules. Whether two operands could be combined was decided by comparing against a position in the compiler’s internal list of types, which went stale as types were added. The effect: arithmetic on structs, arrays and pointers (
s + 1) passed GX and failed in the C compiler, whilech == '0'on twocharvalues anda == trueon twoboolvalues were rejected. The rule is now explicit: numbers, enums,boolandcharcombine; pointers (alsocstrand function pointers) compare with each other and withnull/0. -
Integer declarations. The same kind of comparison decided
var x: T = exprfor integers, sovar b: u8 = some_i64was accepted (silent truncation) andvar b: i8 = 100was rejected. Now a compile-time constant converts to any integer type its value fits, and anything else may widen or keep its size but needs a cast to narrow.var a: i8 = 100 // OK: the constant fits var b: u8 = 300 // error: does not fit var big: i64 = 70000 var c: u8 = big // error: narrowing needs a cast var d: u8 = (u8)big // OK -
The wider operand of a mixed integer expression (
i64 | u8, the two branches of?:) is chosen by size.
Compiler
- Two
defer { ... }blocks in one function crashed the compiler. - A
deferin a loop body did not run when the iteration left throughbreakorcontinueon the C backend and onllvm-clang; only the native backend ran it. All three run it now, innermost scope first. breakin amatcharm inside a loop left only thematchon the C backend. It leaves the loop, as on the LLVM backends.- A
#fncalled outside aconstinitializer (in an array literal, avarinitializer, a condition, a#forbody) failed in the C compiler with an undefined symbol. A call whose arguments are known is replaced by its value on every backend. - An initializer naming a struct that was never declared
(
var p = Vec3{1.0, 2.0, 3.0}with noVec3) passed GX and failed in the C compiler. It is reported asUnknown type 'Vec3'.
JavaScript backend
The playground runs programs through --backend=js. Several examples
printed something different there than they do natively:
- Integer arithmetic is integer arithmetic:
7 / 2is3, 32-bit results wrap, and a store intoi8/u8/i16/u16wraps to that width. - Floats print with six significant digits, as the native backends do.
Matrices print as
mat4([...], ...). outparameters and pointers to plain values work, including pointer arithmetic andp[i]. Writes through them used to be lost.- Unions share storage, so writing one member and reading another gives the same bytes as natively.
- A slice is a view of its array: sorting or writing through it changes the
array.
.sort()on a fixed array or slice sorts numerically. - Indexing an array or slice out of range panics instead of yielding
undefined. A fixed array has its elements from the start. deferruns onbreakandcontinue, andbreakin amatcharm leaves the loop.sizeofof a struct follows the native layout.remove_swapswaps.cap()reports the native capacity.io:eprint/eprintlnand the file functions work against a file system kept in memory.input()reads a line under Node.random:rand_intno longer returns mostly zeros.
Allocators (Arena, Pool, FreeList), 64-bit integers past 2^53 and
cstr casts are still native-only.
collectover anarray<T>, a slice or an array field produced an empty array on the C backend and was refused byllvm-clang. It works on all three backends.- A
charpassed to acharparameter emitted invalid C. ?:with branches of different integer widths emitted invalid IR onllvm-clang.- An unknown
@directive(and four other parser errors) produced no message and the declaration was skipped;@bogus fn main() { }compiled. They are reported now.
Language server
- Hover, go-to-definition, find references, rename and signature help work
inside
exblocks,for/match/deferbodies and#if/#for. Rename used to miss calls inside aforbody and leave a broken program. - Member completion for the built-in types:
str,T[N],[]T,array<T>,map<K,V>,chan<T>, the allocators and vectors, including through struct fields and indexes (g.pts.,self.items[0].) and while the line is still being typed. selfand bare field names insideex; loop variables in completion;exmethods in the symbol list; references and rename followobj.method()calls.outparameters are shown asout v: i32(they appeared asv: *i32, which reads as a read-only pointer).- The std modules are found next to the executable, as the compiler does, so
a project outside the GX tree resolves
import sokol.app. The workspace folder and itssrc/are module search directories;initializationOptions.includeDirsadds more. tests/lsp_features.pycovers the above.
Notes for binding authors
- For
@c_imported extern struct, the C backend takes the layout from the header, but the LLVM backends compute field offsets from the GX declaration. A partial declaration therefore has to be padded to the real layout. The cimgui generator does this automatically by asking the C compiler forsizeof/offsetof. (SDL_Eventin the sdl3 module was 38 bytes on LLVM instead of 128 for this reason; it now declares SDL’s ownpaddingmember.) - The LLVM backends compile a typed C shim for every
extern fn, so a wrong parameter or return type in a binding is a compile error there even though the C backend accepts it. Building a binding once with--backend=llvm-clangis a cheap way to check it against its header.
Upgrade checklist
- Add
- 1to the upper bound of every#forthat counts up to a size. - Replace
x = vonout x: Tparameters with*x = v, and pass&xat call sites. The compiler points at each one. - If a multiplication continues on the next line, move the
*to the end of the first line. - Enums with explicit values now have those values. Code that relied on them being 0, 1, 2 regardless must be reviewed.