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()andreset_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 ani64, and marks nest.reset_to_mark()takes the mark; it had one slot and no argument.trim()andcompact()give memory back when the program chooses.arena.init_buffer(buf)runs on au8[N]or a[]u8, andarena.init_virtual(size)on reserved address space committed 1 MB at a time, where nothing moves.a.clone(alloc)andm.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)xand(al.Kind)x, is a cast. It was the value(Kind)followed by a statementx. forandcollectover astrwalk its code points on every backend.'é'is the code point 233, andcharis 32 bits everywhere.collectmakes an array of the collected expression’s type:for (x in a) collect (f32)x * 0.5overi32gives0.5 1.5, not0 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 beforemain, in source order. - Integer constants in both branches of
? :take the type of the variable:var col: u32 = hot ? 0xFF40F0FF : 0xFF30A0FFbuilds. 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.microaudioplays streams a callback fills:audio_stream_open(rate, channels, callback). Stopping a looping sound no longer hangs.cimgui_sokoldraws 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,jsonandmicroaudiohave forms that use the program’s memory, and the leaks in clay’sgx_clay_initand 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
@cppfileand for structs aligned above 16 bytes, which TinyCC cannot build. gx runstarts the program by its full path, so it works in shells that do not search the current directory, and-ocreates its folder.- A module that calls
localtimeorfopenbuilds without CRT warnings on the LLVM backends. A program that importedtimeprinted 48 of them. --backend tcc-nativehands 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=ONand is not in the release.
Stricter checks
print(n)with a number is an error:printtakes astror acstr. Writeprint("{n}").- A map is not indexed:
m["key"]is an error that namesgetandset. So is an index into a type that has none (v[2]on avec3). - A type name alone is not a value:
var k = Kindis an error. - A
collectis only avarinitializer,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
*Arenaparameter cannot allocate: writeout a: *Arena. breakandreturnin apar forare errors.- On the LLVM backends, a
@c_abifunction with anoutparameter and an aggregate passed by value is an error.
Behavior changes
- Integer comparisons on
llvmandllvm-clangfollow C’s common type: below 32 bits both sides becomei32, the wider side decides, and at equal width unsigned wins.llvm-clangused the left operand’s type andllvmcompared signed whenever either side was, sou64 > i64and4294967295 < topcould differ from the C backend. They no longer do. c_longandc_ulongare 32 bits on Windows on the LLVM backends, as C’slongis. They were 64, which put struct fields at other offsets than C.- The layout of
Arena,FreeList,Poolandmapchanged. 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
| Backend | Was | Now |
|---|---|---|
| C | (Kind)x, a cast to an enum, printed garbage | A cast |
C, llvm | collect (f32)x * 0.5 over i32 truncated to 0 1 | 0.5 1.5 |
| C | where on a for over a str was ignored | Applied |
| C | A for-each over a fixed array that is a struct field (for (x in b.items)) ran no iterations | Runs over every element |
js | Copying 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 object | A copy, as on the other backends |
js | {s[i]} printed the character, the other backends the byte; (i32)c of a char was 0 | The byte; the code point |
llvm-clang | A global whose value needs code run was 0, and so was a global struct with an initializer | Set before main |
llvm, llvm-clang | var big: u64 = 0x100 << 32 was 0 | 1099511627776 |
llvm, llvm-clang | In for (var key, value in m) with a struct value, value.x read and wrote the key’s variable | value is its own variable |
llvm-clang | A byte of a str passed to a char parameter had garbage upper bits | Widened to 32 bits |
llvm-clang | A call through a fn value with a vector or matrix argument crashed | Passed as GX functions expect |
llvm-clang | Executables crashed on ARM64 Linux and macOS: runtime results went through sret, which AArch64 passes in another register than the shim reads | An ordinary first pointer |
| all | A local map in a function called every frame allocated three tables each frame, and leaked unless freed | No memory until the first set |
| all | A container in an arena ignored its element’s alignment | Aligned as asked |
| all | pool.free of a slot already free broke the pool without a word | Stops the program |
| all | Strings over 1 KB outside with were cut to 1023 bytes; split kept 64 pieces | Whole |
Accepted by GX, rejected by the C compiler
| Was | Now |
|---|---|
print(n) with a number, m["key"] on a map | GX errors (see Stricter checks) |
var keep = h.value with a fixed-array field: a C array copy | A value copy |
xs.push({...}), m.set(k, {...}), ch.send({...}): the initializer had no type | Takes the element type |
pool.alloc(u8): “‘u8’ undeclared” | Any type |
arena.total(), arena.hwm() and .used of a Pool passed GX | total_allocated(), high_water_mark(), block_count(), used() |
var copied = item in a map loop | A copy with its own .key and .value |
c_ssize with clang and MSVC: ssize_t is POSIX only | ptrdiff_t |
"\{" and "\}" went into the C as written: TinyCC and clang warned “unknown escape sequence” | The brace alone |
Rejected by GX, although valid
| Was | Now |
|---|---|
c[i] on a cstr on the LLVM backends | A byte, as on str |
a.len and a.cap of an array<T> on llvm-clang | Read from the array header |
A for over a str on the LLVM backends; collect over a str on C and llvm | Walk the code points |
a.alloc(T) on an allocator passed as out a: *Arena | Works through the pointer |
var col: u32 = hot ? 0xFF40F0FF : 0xFF30A0FF | Builds |
Found, not fixed yet
- A template struct with a container of its parameter,
items: array<T>, still namesTin 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
[]Targument 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.