What's New in v0.8.9

Most of 0.8.9 is about memory: where it comes from, and how a program checks that. A container takes its memory from an arena or a free list, a block of code names the allocator for everything inside it, and @no_heap checks a function at compile time. par for runs on several threads on every backend.

Some checks are stricter. Read Stricter checks if a program that built with 0.8.8 no longer does. A few changes make the same program compute something else: see Behavior changes.

Memory

Containers in an arena

An array<T> or a map<K,V> names its allocator in its type:

var frame: Arena
frame.init(4096)
var xs: array<i32>(allocator = &frame)
var m: map<i32, i32>(allocator = &frame)

xs.init(&frame) does the same after the declaration. A map’s tables and the copies of its str keys come from that allocator; they were always the heap. In an arena, the array that made the last allocation grows where it is. A map takes no memory until its first set, as an array takes none until its first push.

A default allocator for a block

Every container in the block that names no allocator, and every string built there, takes its memory from the one in with:

with (&frame) {
    var hits: array<i32>
    hits.push(3)
    var label = "{name}: {score}"
}

The allocator before it is back on every way out of the block, including return and break. A container takes the default at its first allocation, not at its declaration. heap names the heap whatever the default is, and with (none) stops the program at any allocation inside, with the line of the block.

A string built inside with on an arena or a free list is not overwritten 16 string operations later. One built with + or "{x}" in one expression may be up to 64 KB, and the string methods have no limit.

The threads of a par for do not share an arena. par for (...) with (&arenas) gives each thread arenas[thread].

Arenas

  • reset() and reset_to_mark(m) keep the arena’s blocks and reuse them. reset() used to free all but the first, so a frame larger than the first block took memory from the system every frame.
  • mark() returns the position as an i64, and marks nest. reset_to_mark() takes the mark; it had one slot and no argument.
  • trim() and compact() give memory back when the program chooses.
  • arena.init_buffer(buf) runs on a u8[N] or a []u8, and arena.init_virtual(size) on reserved address space committed 1 MB at a time, where nothing moves.
  • a.clone(alloc) and m.clone(alloc) copy a container into an allocator. chan<T>(capacity = N, allocator = &a) takes a channel’s buffer from one.
  • A container used after its arena was reset stops the program in a checked build.

Functions that do not touch the heap

@no_heap on a function is checked at compile time:

@no_heap fn fill:i32(out a: *Arena, n: i32) {
    var xs: array<i32>(allocator = a)
    for (i = 1:n) { xs.push(i) }
    return xs.len()
}

A container inside takes memory the program chose, heap and arena.init are refused, and only @no_heap functions are called. A C function counts when its extern is marked; math, random and time are. @no_heap alone on a line marks a whole file.

gx main.gx --no-heap checks the whole program and builds every C unit without malloc, calloc, realloc and free, so a call left in C code fails to link.

Heap numbers and the memory report

heap.total_allocated(), heap.high_water_mark() and heap.alloc_count() give the bytes the runtime holds from the heap, the most it held, and its allocations so far. A C library that calls malloc itself is not counted.

A -g build prints at exit what was not freed, by the line that allocated it, largest first:

memory not freed at exit: 208 bytes in 4 allocations
tests/98_mem_report.gx:16: 144 bytes in 3 allocations
tests/98_mem_report.gx:11: 64 bytes in 1 allocation

It also stops the program at memory freed a second time. ch.free() gives a channel’s buffer back; there was no way to, and the report found the leak in the concurrency examples.

Running out of memory stops the program with what was asked (“panic: out of memory: N bytes for an array”). A full Pool or FreeList stops it too, where alloc returned null and push returned false, unchecked.

Handles for a pool

Handle<T> names a slot of a Pool by its index and a generation:

var e = pool.alloc(Enemy)
var h = pool.handle(e)
pool.free(h)
print("{pool.has(h)}\n")    // false, also after the slot is reused

pool.get(h) of an old handle stops the program instead of reading the object that took the slot. Handles compare with ==, are not numbers, and Handle<A> is not Handle<B>.

Chunks<T>

A container whose elements never move, so &c[i] stays valid while it grows. It keeps blocks of about 4 KB and has c[i], for, where, collect, push, len, clear, free and an allocator like array<T>. It has no sort and no removal, and it is not a slice.

Aligned structs

@align(N) struct places the struct at a multiple of N (a power of two up to 4096) as a local, a global, an array element, from arena.alloc(T) and pool.alloc(T), and as the element of a container. Its size is a multiple of N. It cannot be a field of another struct yet. Every heap block is now aligned as asked.

Long strings

Outside a with block, a string longer than 1 KB keeps every byte. +, "{x}", replace, upper, lower and repeat used to cut the result to 1023 bytes without a word, so a 1.7 KB level written through replace was saved short. The result still lives in the scratch ring: a longer one gets a heap buffer owned by its slot and freed when the slot next holds a short string. split keeps every piece; it stopped at 64. Under --no-heap a string longer than 1 KB outside with stops the program.

Threads

par for runs on several threads on the llvm and llvm-clang backends, which ran the loop on one. The body becomes its own function and a thread pool runs it. The C backend keeps OpenMP at -O1 and up. Every backend splits the range the same way: thread k of W runs from floor(k*n/W) up to floor((k+1)*n/W), with W the hardware threads or GX_THREADS.

A par for inside a running one stays on its thread and keeps its worker number. break and return in a par for are compile errors.

Language and library

  • A cast to an enum or an alias, (Kind)x and (al.Kind)x, is a cast. It was the value (Kind) followed by a statement x.
  • for and collect over a str walk its code points on every backend. 'é' is the code point 233, and char is 32 bits everywhere.
  • collect makes an array of the collected expression’s type: for (x in a) collect (f32)x * 0.5 over i32 gives 0.5 1.5, not 0 1.
  • A fixed array is a value: each copy has its own elements, on every backend.
  • A global whose value needs code run (var g = cube(4), var s = "hi " + NAME) gets it before main, in source order.
  • Integer constants in both branches of ? : take the type of the variable: var col: u32 = hot ? 0xFF40F0FF : 0xFF30A0FF builds.
  • io.fs.modified_ns(path) gives when a file was last written, in nanoseconds since 1970 UTC. On Windows it has 100 ns steps, so a watcher sees two saves within one second.
  • microaudio plays streams a callback fills: audio_stream_open(rate, channels, callback). Stopping a looping sound no longer hangs.
  • cimgui_sokol draws 524 288 vertices per frame; sokol_imgui’s default of 65 536 dropped the last windows without a word. gx_imgui_sokol_set_max_vertices(n) sets it before setup.
  • sokol, cimgui, cimgui_sokol, enet and sdl3 take the library’s memory from an arena given once at setup. clay, xml, io, threading, json and microaudio have forms that use the program’s memory, and the leaks in clay’s gx_clay_init and xml’s parser are fixed.

Toolchain

  • The bundled TinyCC on Windows x64 is 0.9.28rc. 0.9.27 wrote to address 0 when a call passed a struct over 8 bytes by value next to an && or || argument.
  • The C backend uses clang for a program with a @cppfile and for structs aligned above 16 bytes, which TinyCC cannot build.
  • gx run starts the program by its full path, so it works in shells that do not search the current directory, and -o creates its folder.
  • A module that calls localtime or fopen builds without CRT warnings on the LLVM backends. A program that imported time printed 48 of them.
  • --backend tcc-native hands the typed AST to TinyCC’s code generator and writes a Windows x64 executable without C source. It exists only in a compiler built with -DGX_ENABLE_TCC_NATIVE=ON and is not in the release.

Stricter checks

  • print(n) with a number is an error: print takes a str or a cstr. Write print("{n}").
  • A map is not indexed: m["key"] is an error that names get and set. So is an index into a type that has none (v[2] on a vec3).
  • A type name alone is not a value: var k = Kind is an error.
  • A collect is only a var initializer, var xs = for (...) collect .... The array is heap memory its owner frees, and an unnamed one could not be.
  • An import the compiler cannot find is an error at the import, which says where it looked. It was dropped, and each use failed later.
  • A read-only *Arena parameter cannot allocate: write out a: *Arena.
  • break and return in a par for are errors.
  • On the LLVM backends, a @c_abi function with an out parameter and an aggregate passed by value is an error.

Behavior changes

  • Integer comparisons on llvm and llvm-clang follow C’s common type: below 32 bits both sides become i32, the wider side decides, and at equal width unsigned wins. llvm-clang used the left operand’s type and llvm compared signed whenever either side was, so u64 > i64 and 4294967295 < top could differ from the C backend. They no longer do.
  • c_long and c_ulong are 32 bits on Windows on the LLVM backends, as C’s long is. They were 64, which put struct fields at other offsets than C.
  • The layout of Arena, FreeList, Pool and map changed. C code that mirrors them must be updated.
  • A program that built strings longer than 1 KB now gets them whole, and "a,".split(",") gives two pieces, not three.

Bugs fixed

Wrong results at run time

BackendWasNow
C(Kind)x, a cast to an enum, printed garbageA cast
C, llvmcollect (f32)x * 0.5 over i32 truncated to 0 10.5 1.5
Cwhere on a for over a str was ignoredApplied
CA for-each over a fixed array that is a struct field (for (x in b.items)) ran no iterationsRuns over every element
jsCopying a fixed array or a struct shared it: after q = p, q.x = 5 changed p. A struct read from a map or array was the stored objectA copy, as on the other backends
js{s[i]} printed the character, the other backends the byte; (i32)c of a char was 0The byte; the code point
llvm-clangA global whose value needs code run was 0, and so was a global struct with an initializerSet before main
llvm, llvm-clangvar big: u64 = 0x100 << 32 was 01099511627776
llvm, llvm-clangIn for (var key, value in m) with a struct value, value.x read and wrote the key’s variablevalue is its own variable
llvm-clangA byte of a str passed to a char parameter had garbage upper bitsWidened to 32 bits
llvm-clangA call through a fn value with a vector or matrix argument crashedPassed as GX functions expect
llvm-clangExecutables crashed on ARM64 Linux and macOS: runtime results went through sret, which AArch64 passes in another register than the shim readsAn ordinary first pointer
allA local map in a function called every frame allocated three tables each frame, and leaked unless freedNo memory until the first set
allA container in an arena ignored its element’s alignmentAligned as asked
allpool.free of a slot already free broke the pool without a wordStops the program
allStrings over 1 KB outside with were cut to 1023 bytes; split kept 64 piecesWhole

Accepted by GX, rejected by the C compiler

WasNow
print(n) with a number, m["key"] on a mapGX errors (see Stricter checks)
var keep = h.value with a fixed-array field: a C array copyA value copy
xs.push({...}), m.set(k, {...}), ch.send({...}): the initializer had no typeTakes the element type
pool.alloc(u8): “‘u8’ undeclared”Any type
arena.total(), arena.hwm() and .used of a Pool passed GXtotal_allocated(), high_water_mark(), block_count(), used()
var copied = item in a map loopA copy with its own .key and .value
c_ssize with clang and MSVC: ssize_t is POSIX onlyptrdiff_t
"\{" and "\}" went into the C as written: TinyCC and clang warned “unknown escape sequence”The brace alone

Rejected by GX, although valid

WasNow
c[i] on a cstr on the LLVM backendsA byte, as on str
a.len and a.cap of an array<T> on llvm-clangRead from the array header
A for over a str on the LLVM backends; collect over a str on C and llvmWalk the code points
a.alloc(T) on an allocator passed as out a: *ArenaWorks through the pointer
var col: u32 = hot ? 0xFF40F0FF : 0xFF30A0FFBuilds

Found, not fixed yet

  • A template struct with a container of its parameter, items: array<T>, still names T in the output, and methods on a template are not there yet.
  • A function-pointer type cannot name a container parameter (fn(array<i32>):i32).
  • A read-only container converts to a []T argument whose elements are writable. Slices have no read-only form yet.
  • Enum members are names of the whole program: two enums cannot share a member name.
  • input() reads at most 1023 bytes of a line.

Tests

The compiler suite is 194 programs, each run on c, llvm-clang and native llvm. tests/runtime_heap.py checks that the runtime calls the heap only in the heap allocator and the allocators’ own memory.