Skip to content

Compiler Architecture

Buntos edited this page Dec 5, 2026 · 1 revision

Compiler Architecture

H is a self-hosted, ahead-of-time native compiler built on LLVM-C 19–23. Its architecture cleanly separates frontend semantic verification (compiler/typecheck.hl, zero LLVM dependency, shared verbatim between hlc and hl-lsp) from LLVM IR code generation (compiler/codegen.hl), backed by a pure-H @[nogc] runtime (runtime/hl_runtime.hl) and a frozen Zig bootstrap seed (src/*.zig).


1. Frozen Bootstrap Seed vs. Self-Hosted Compiler

Component Frozen Bootstrap Seed (src/, runtime/hl_runtime.c) Self-Hosted Toolchain (compiler/, runtime/hl_runtime.hl)
Implementation language Zig 0.17.1+ & C11 Pure H (.hl)
Role Frozen bootstrap seed kept strictly so a machine without an existing H binary can compile compiler/main.hl once Primary compiler (hlc / hlc-pure), pure-H runtime (libhl_runtime_h.o), and tools (hlfmt, hl-lsp, hl-bindgen-cpp)
Maintenance policy Frozen at the core subset needed to bootstrap compiler/ All new language features, semantic rules, and optimizations live exclusively in compiler/typecheck.hl and compiler/codegen.hl
Semantic analysis Separate src/typecheck.zig (bootstrap only) Single zero-LLVM compiler/typecheck.hl shared verbatim by both hlc and hl-lsp
LLVM integration src/llvm_c.zig (LLVMRunPasses + object emit) compiler/llvm_c.hl (LLVM-C 19–23 bindings, LLVMRunPasses, DIBuilder, target machine emit)

build.zig automatically detects installed LLVM 19–23 libraries by probing llvm-config-23 through llvm-config-19 and llvm-config, or accepts explicit -Dllvm-lib= and -Dllvm-libdir= options.


2. Compilation Pipeline & Shared Typechecker Architecture

flowchart LR
    Src[".hl Source Modules"] --> Loader["ModuleLoader (main.hl / LspLoader)"]
    Loader --> Lex["Lexer (compiler/lexer.hl)"]
    Lex --> Parse["Parser (compiler/parser.hl)"]
    Parse --> TC["Single Typechecker (compiler/typecheck.hl)<br/>Pure H • Zero LLVM"]
    TC -->|"Live multi-diagnostics<br/>(no libLLVM)"| LSP["hl-lsp (~218 KB)<br/>JSON-RPC 2.0 stdio"]
    TC -->|"Validated AST"| CG["Trusted Codegen (compiler/codegen.hl)<br/>LLVM IR + DWARF DIBuilder"]
    CG --> Opt["LLVMRunPasses<br/>default&lt;O1|O2|O3&gt;<br/>(skipped at -O0 / -g)"]
    Opt --> Obj["TargetMachine Emit (.o) + gcc Link"]
Loading

3. Self-Hosting & Fixed-Point Verification

flowchart LR
    Seed["Frozen Zig Bootstrap Seed + libhl_runtime.a"] -->|"compile compiler/main.hl"| Self1["First Self-Compiled hlc (C runtime)"]
    Self1 -->|"hlc -c runtime/hl_runtime.hl"| RtH["Pure-H Runtime (libhl_runtime_h.o)"]
    Self1 -->|"compile compiler/ with libhl_runtime_h.o"| PureA["hlc-pure (Build A)"]
    RtH --> PureA
    PureA -->|"compile compiler/ with libhl_runtime_h.o"| PureB["hlc-pure2 (Build B)"]
    RtH --> PureB
    PureA --> Check{"cmp: Bit-for-Bit ELF Equality"}
    PureB --> Check
Loading

Fixed-point determinism is verified in two places:

  • zig build fixed-point: Recompiles compiler/ with zig-out/bin/hlc-pure against zig-out/lib/libhl_runtime_h.o to produce zig-out/bin/hlc-pure2 and asserts byte-for-byte ELF identity with cmp.
  • zig build test (src/tests.zig): Verifies bit-for-bit equality both on the C-runtime self-hosted pair and on the pure-H runtime pair, then exercises all example programs, negative semantic checks, and C++/D/Objective-C/.NET interop suites.

4. Pure-H @[nogc] Runtime (runtime/hl_runtime.hl)

runtime/hl_runtime.hl implements the entire C-ABI runtime specification declared in runtime/hl_runtime.h using @[nogc] H functions compiled with -c into a relocatable .o object file (libhl_runtime_h.o).

Exported symbol groups:

  • Initialization & CLI args: hl_init, hl_init_args (stores g_hl_argc/g_hl_argv and calls GC_init), hl_argc, hl_argv, hl_getpid.
  • GC allocation: hl_gc_alloc (GC_malloc, panicking on OOM) and hl_gc_alloc_atomic (GC_malloc_atomic + memset zero-fill for pointer-free string buffers).
  • Growable Array[T]: hl_array_new, hl_array_push_slot (2x geometric growth starting at capacity 4), hl_array_pop_slot, plus hl_bounds_check and hl_slice_check.
  • Scoped bump arenas & manual heap: hl_arena_create, hl_arena_alloc, hl_arena_destroy, hl_manual_alloc (calloc), hl_manual_free (free).
  • String & formatting helpers: hl_cstr_len, hl_str_concat_len, hl_str_from_bytes, hl_str_eq_len, hl_i64_to_str_len, hl_u64_to_str_len, hl_f64_to_str_len, hl_bool_to_str_len, hl_puts, hl_puts_len, hl_eputs, hl_panic.
  • File & process primitives: hl_read_file, hl_write_file, hl_remove_file, hl_run_cmd.

5. Frontend Pipeline (compiler/)

main.hl, os.hl & ModuleLoader

  • Detects H_HOME via $H_HOME, /proc/self/exe (os.exe_path()), or working directory so hlc runs cleanly from any directory.
  • Resolves entry points (.hl file, <dir>/main.hl, or h.toml manifest including [dependencies]).
  • Loads the import graph via depth-first traversal (load_file), deduplicating via loaded_paths, detecting cycles via visiting, and searching [dependencies] -> relative dir -> CWD -> -I dirs -> std/ -> $H_HOME/std/.
  • Populates ModuleAst nodes in topological dependency order (imported modules precede importers).

lexer.hl & token.hl

  • Single-pass scanner classifying uppercase identifiers (type_ident), lowercase identifiers/keywords (ident / kw_*), range tokens (.., ..=), and @field (ivar) vs @[ (attr_open).
  • Tracks nested string interpolation via interp_depth and resume_string, emitting str_part, embedded expression tokens, interp_end, and str_end while plain strings emit a single string_lit.
  • Handles multi-line chaining by peeking ahead across whitespace/comments after \n: if the next token starts with . (not ..) or &., the newline token is suppressed.

parser.hl, ast.hl & diag.hl

  • Recursive-descent declaration/statement parser with precedence-climbing expression parsing.
  • Parses operator overload method names (+, -, *, /, %, ==, !=, <, <=, >, >=, [], []=) into canonical internal method names (__op_add, ..., __op_index, __op_index_set) and records default parameter expressions on Param.default_val.
  • Resolves [...] ambiguity with single-token lookahead (type_ident after [ in postfix position parses generic type arguments; anything else parses element indexing).
  • Represents types via TypeRef (ast.hl) with structural equality (type_eql), deterministic name mangling (type_mangle), and recursive generic type substitution (type_subst).
  • diag.hl formats lexer, parser, and typechecker diagnostics with file:line:col, source-line extraction, aligned line-number gutter, and caret (^) indicator.

6. Single Zero-LLVM Typechecker (compiler/typecheck.hl)

compiler/typecheck.hl is the single source of truth for static semantics and has zero dependency on llvm_c.hl or libLLVM. Both hlc (compiler/main.hl) and hl-lsp (tools/hl_lsp.hl) invoke TypeChecker.check_modules(mods) directly.

Key responsibilities:

  • Multi-diagnostic collection: Records every error in diags: Array[TcDiag] (with file_path, line, msg, and source-formatted output) and uses an internal poison @err_ty to recover cleanly without cascading noise.
  • Full semantic enforcement:
    • Type inference, literal adaptation, explicit numeric casts, and call/default-argument arity validation
    • Compile-time nil safety, strict Bool? rejection on branch/logical ops, ?? and &. typing, and flow-sensitive narrowing across if/else/unless/while/and/or and post-early-exit statements
    • @[nogc] call-graph and allocation verification
    • const immutability and mut def lvalue checks
    • for ... in range and collection typing, plus operator overloading resolution (including auto-derived != from == and []/[]= indexing)
    • Exhaustive and non-duplicate enum match verification
    • Generic template instantiation, structural type argument unification, explicit < Interface conformance, and [T: Bound] constraint verification
    • Postfix ? validation on Result[T, E] enums and T? optionals

Because hl-lsp links only against compiler/typecheck.hl (and never compiler/codegen.hl or libLLVM), the language server remains small (~218 KB) while reporting the exact same semantic diagnostics as the compiler.


7. Trusted LLVM Backend (compiler/codegen.hl)

compiler/codegen.hl assumes compiler/typecheck.hl has already validated all types, nil safety, @[nogc], interfaces, and exhaustiveness, and focuses strictly on LLVM IR lowering, DWARF debug info, optimization, and object emission.

Multi-Pass IR Emission

  1. Pass 1a: Pre-register interfaces, generic templates (gen_enums, gen_aggs, gen_fns), concrete enums, and concrete named LLVM structs (LLVMStructCreateNamed).
  2. Pass 1b: Resolve concrete payload enum fields and compute { i32, [W x i64] } layouts.
  3. Pass 1c / 1c2: Resolve concrete struct/class field layouts (LLVMStructSetBody) and declare module globals.
  4. Pass 1d: Declare extern "C" functions, concrete methods (mangled Type__method or mod__Type__method), and concrete functions (entry main -> __hl_user_main, non-entry -> mod__fn).
  5. Pass 2: Emit non-yield concrete method and function bodies.
  6. Pass 2b: Drain the pending_mono_fns monomorphization queue iteratively until fixpoint (since emitting a specialized generic body may instantiate additional generic types or functions).
  7. Entry trampoline & DWARF finalization: emit_c_main() generates C ABI main(argc, argv) calling hl_init_args(argc, argv) before __hl_user_main(), followed by LLVMDIBuilderFinalize.

Dual-Builder Stack Slot Allocation

Every function and closure body initializes two basic blocks (entry and body) with two LLVM builders:

  • @alloca_builder stays positioned at entry so every alloca emitted anywhere inside a function is hoisted to the function prologue, guaranteeing SSA dominance and avoiding stack growth inside loops.
  • @builder emits instructions starting at body, and @alloca_builder terminates entry with a branch to body when the function completes.

Lowering Mechanics

  • Scoped cleanup stack (@cleanups with @scope_depth): Tracks defer expressions and with_arena allocations so normal exits (pop_and_emit_cleanups) and early exits (return, break, next, ? via emit_cleanups_down_to) execute cleanups in strict LIFO order.
  • for ... in lowering: Lowers range loops (start..stop, start..=stop) and collection loops (Array, Slice, StaticArray, String) into zero-allocation indexed basic blocks supporting break, next, and defer.
  • yield inlining & closure lowering: Functions containing yield inline their AST directly into callers via @active_yield. First-class fn(...) closures run free-variable analysis (scan_stmts_free / scan_expr_free): zero-capture closures emit raw LLVM functions (__hl_fn_N), while capturing closures allocate a GC environment struct and emit { ptr __hl_closure_N, ptr env } (with __hl_raw_thunk_N auto-boxing when coercing raw functions to fat Fn).
  • DWARF DIBuilder (-g): Sets Debug Info Version = 3 and Dwarf Version = 4, creates per-module DIFiles, DICompileUnit, DISubprograms, per-statement DILocations, and LLVMDIBuilderInsertDeclareRecordAtEnd records for parameters and locals (temporarily clearing debug scope inside synthetic thunks/closures).

LLVM Optimization Passes (LLVMRunPasses) & Object Emission

In emit_object_file(obj_path, opt_level):

  1. Initializes X86 and AArch64 LLVM targets, queries LLVMGetDefaultTargetTriple(), constructs a PIC LLVMTargetMachine, and sets module target triple and data layout.
  2. Runs LLVMVerifyModule.
  3. When opt_level > 0, runs LLVM's new pass manager via LLVMRunPasses:
    • -O1 -> "default<O1>"
    • -O2 -> "default<O2>" (default for hlc build / hlc run)
    • -O3 -> "default<O3>"
    • -O0 (and -g without explicit -O*) skips LLVMRunPasses to preserve unoptimized debug stepping.
  4. Calls LLVMTargetMachineEmitToFile to write a native .o object file, then invokes gcc to link <obj>.o, the runtime (libhl_runtime_h.o or libhl_runtime.a), -lgc -lm -lpthread, and any extra -l/-L/-Wl,/.o/.a flags.

Return to Wiki Home

Clone this wiki locally