Garbage collection, exceptions, records and modules in a small native compiler
compilersgarbage-collectionmark-and-sweepexceptionstype-tablerecordsmodulesx86-64h-language
Once a toy compiler has functions, lists and closures, four features turn it into something that can run real programs: memory that is freed, errors that can be caught, user-defined data types, and more than one source file. This is how each was added to H, a statically typed language compiled straight to x86-64 assembly with a C runtime library (Writing a native compiler in C that emits x86-64 assembly), and which design choices kept each one small. The language-level decisions are in Designing a programming language's syntax and semantics (lessons from H).
Mark and sweep with safe points
The simplest collector that works with code that keeps raw pointers on the machine stack is mark and sweep, objects never move.
- Every heap object comes from one allocator and is registered in a hash table of (address, size). Buffers an object owns (a list's items, a file's text) are plain
mallocand are freed when the owner is swept. - Allocating never collects. It only sets a "collection due" byte once enough has been allocated (8 MB, or as much as survived the last collection, whichever is more). Compiled code tests that byte at safe points: the top of each loop, the top of each pipeline stage loop, and each function's entry.
- Safe points are chosen so that no runtime function is active and no live value exists only in a register. The roots are then just the globals (scanned precisely, between two linker symbols around the globals section) and the stack (scanned conservatively).
- Conservative stack scanning is safe here because a word counts as a pointer only if it is exactly a registered object's address. Return addresses, saved frame pointers and stale slots never match. Nothing moves, so a false match only delays freeing.
- Tracing from a found object is exact, by the object's type tag. The mark is one spare bit in the object header, set only during a collection.
- Static objects (string literals, constant lists emitted into the data section) are never registered, so the collector skips them for free.
- A file handle is an object too: collecting a stream closes its file, which also covers a pipeline abandoned by an exception.
The rule this places on all later code generation: before a loop or a call, every live value is pushed or in a stack slot.
Two environment switches pay for themselves immediately: one prints a summary at exit, and a stress mode collects at every safe point. Running the whole test suite in stress mode finds missing roots that would otherwise show up once a month. A test with a memory cap (ulimit -v) proves the collector actually frees: one program needed 136 MB without it and ran in 47 MB with it. The cost was real (that test went from 0.13 s to 0.47 s, mostly registering and sweeping), which is the price of the simple design.
Exceptions without unwinding tables
try { ... } catch (e) { ... } needs no DWARF unwinder if the generated code is simple enough:
- The runtime keeps a stack of handlers: entering a
tryrecords the catch label's address and the current stack and frame pointers. - Every runtime error goes through one function that builds an exception object (message, file, line) and raises it. With no handler open it prints
file:line:col: runtime error: messageand exits 1, exactly as before exceptions existed. Otherwise it restores the saved stack and frame pointers and jumps to the innermost catch label with the exception in the result register. That issetjmp/longjmpwritten by hand. - Leaving a try early must pop its handler.
breakandreturnout of atryrestore the handler depth saved when the loop or function began; a function that contains atrysaves the depth on entry and restores it at its single return label. - Callee-saved registers bite. Generated code never used
%rbxor%r12to%r15, but the C runtime functions being jumped out of do. Without saving those registers at program start and restoring them on a raise, the Cmaincrashed after a perfectly good caught error. - Under AddressSanitizer, call
__asan_handle_no_returnbefore the jump, or the sanitizer's shadow stack reports garbage. - Stack overflow and out of memory stay fatal. Catching them means running handler code in the very state that failed.
Making the caught value a built-in type with members (e.message, e.file, e.line) instead of a string costs one object kind now and lets it grow kinds later without breaking code. A re-thrown exception keeps the place it first happened.
From one bit per type to a type table
Representing a static type as a bit set (int, string, bool, nil, each a bit) makes "int or nil" and "never returns" trivial, and it tempts you to give each list or function type its own bit too. That stops the build at the 25th distinct list type in one program. The fix keeps a type as one int:
- the low 8 bits remain the bit set of built-in kinds;
- the bits above are an index into a growable, interned table of structured types (list of T, function signature, record, or a set of entries for "int[] or string[]").
Interning means equal types have equal ints, so every == comparison in the checker keeps working. The one new rule: join two types with a type_union() function, never with |, because two table indexes or-ed together are nonsense. There were exactly three such sites (if, try, and &&/||). New kinds of type become a new entry kind, not a new bit.
Records and methods by desugaring
- A record type is a table entry holding the field names, types and defaults. At run time a record is one object: header, a pointer to a static descriptor (for printing and field-by-field
==), a frozen flag, then the fields. - The parser pre-registers every
type Name {in a file before parsing it, soName { ... }andName x = ...can be told from an expression without backtracking, and a type can be used above its definition. - Methods need no code generator or runtime support. A method is parsed into an ordinary function named
Type.methodwhose first parameter isthis, andx.m(a)is rewritten to the callType.m(x, a). - Bare field names inside a method are one more rewrite at the top of expression checking: a name resolves as a local or parameter, then a field or method of
this, then the top level (Java's order).this.namestays valid and is required when a local shadows a field. - A good error for a mistyped type (
Rom r = 3;gives "unknown type 'Rom'") is worth a special case in the parser; otherwise the user gets "expected ;".
Modules
- Each source file gets a number, and every position carries it, so errors and run-time errors name the right file.
- All files are checked as one program with one table of top-level names; a module's names are qualified by its prefix, and its symbols are emitted with the module number in the name so two files may define the same name.
- A module's top-level code runs once, before any importer's, in import order. Import circles are a compile error.
- Once modules can define types, imports have to be loaded while the importing file is being parsed (right after its import lines), not afterward, because the parser needs to know which names are types.
Program basics that unblock real use
Arguments, an exit status, writing a file and running another program are small individually and together decide whether the language can replace a shell script. Two implementation notes: feed a child's standard input from a temporary file rather than a pipe, so nothing can block on a full pipe; and an output file opened by a pipeline stage should be a collected object, so it is closed even when the pipeline is left by an exception.
Gotchas
- A raw stack address saved in a frame slot (to reset the stack on
break) is not a value. With exact-address matching the collector ignores it; with a looser "points anywhere into the heap" test it would not. - A feature that works in the default build can fail only in the stress, sanitizer or fuzz build. Run all of them for every change: gcc, clang, sanitizers, collector stress, and the differential fuzzer.
- To run compiled programs against a sanitizer-built runtime when the compiler driver takes a single program name for its C compiler, write a two-line wrapper script that adds the flags.
- Tests for modules need directories; a test runner that globs only the top level silently skips them unless they are registered another way.
See also
- Writing a native compiler in C that emits x86-64 assembly
- Designing a programming language's syntax and semantics (lessons from H)
- Editor support for your own language as a VS Code extension