Repository navigation
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).
| 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.
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<O1|O2|O3><br/>(skipped at -O0 / -g)"]
Opt --> Obj["TargetMachine Emit (.o) + gcc Link"]
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
Fixed-point determinism is verified in two places:
-
zig build fixed-point: Recompilescompiler/withzig-out/bin/hlc-pureagainstzig-out/lib/libhl_runtime_h.oto producezig-out/bin/hlc-pure2and asserts byte-for-byte ELF identity withcmp. -
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.
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(storesg_hl_argc/g_hl_argvand callsGC_init),hl_argc,hl_argv,hl_getpid. -
GC allocation:
hl_gc_alloc(GC_malloc, panicking on OOM) andhl_gc_alloc_atomic(GC_malloc_atomic+memsetzero-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, plushl_bounds_checkandhl_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.
- Detects
H_HOMEvia$H_HOME,/proc/self/exe(os.exe_path()), or working directory sohlcruns cleanly from any directory. - Resolves entry points (
.hlfile,<dir>/main.hl, orh.tomlmanifest including[dependencies]). - Loads the import graph via depth-first traversal (
load_file), deduplicating vialoaded_paths, detecting cycles viavisiting, and searching[dependencies]-> relative dir -> CWD ->-Idirs ->std/->$H_HOME/std/. - Populates
ModuleAstnodes in topological dependency order (imported modules precede importers).
- 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_depthandresume_string, emittingstr_part, embedded expression tokens,interp_end, andstr_endwhile plain strings emit a singlestring_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.
- 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 onParam.default_val. - Resolves
[...]ambiguity with single-token lookahead (type_identafter[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.hlformats lexer, parser, and typechecker diagnostics withfile:line:col, source-line extraction, aligned line-number gutter, and caret (^) indicator.
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](withfile_path,line,msg, and source-formatted output) and uses an internal poison@err_tyto 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 acrossif/else/unless/while/and/orand post-early-exit statements -
@[nogc]call-graph and allocation verification -
constimmutability andmut deflvalue checks -
for ... inrange and collection typing, plus operator overloading resolution (including auto-derived!=from==and[]/[]=indexing) - Exhaustive and non-duplicate
enummatchverification - Generic template instantiation, structural type argument unification, explicit
< Interfaceconformance, and[T: Bound]constraint verification - Postfix
?validation onResult[T, E]enums andT?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.
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.
-
Pass 1a: Pre-register interfaces, generic templates (
gen_enums,gen_aggs,gen_fns), concrete enums, and concrete named LLVM structs (LLVMStructCreateNamed). -
Pass 1b: Resolve concrete payload enum fields and compute
{ i32, [W x i64] }layouts. -
Pass 1c / 1c2: Resolve concrete struct/class field layouts (
LLVMStructSetBody) and declare module globals. -
Pass 1d: Declare
extern "C"functions, concrete methods (mangledType__methodormod__Type__method), and concrete functions (entrymain->__hl_user_main, non-entry ->mod__fn). -
Pass 2: Emit non-
yieldconcrete method and function bodies. -
Pass 2b: Drain the
pending_mono_fnsmonomorphization queue iteratively until fixpoint (since emitting a specialized generic body may instantiate additional generic types or functions). -
Entry trampoline & DWARF finalization:
emit_c_main()generates C ABImain(argc, argv)callinghl_init_args(argc, argv)before__hl_user_main(), followed byLLVMDIBuilderFinalize.
Every function and closure body initializes two basic blocks (entry and body) with two LLVM builders:
-
@alloca_builderstays positioned atentryso everyallocaemitted anywhere inside a function is hoisted to the function prologue, guaranteeing SSA dominance and avoiding stack growth inside loops. -
@builderemits instructions starting atbody, and@alloca_builderterminatesentrywith a branch tobodywhen the function completes.
-
Scoped cleanup stack (
@cleanupswith@scope_depth): Tracksdeferexpressions andwith_arenaallocations so normal exits (pop_and_emit_cleanups) and early exits (return,break,next,?viaemit_cleanups_down_to) execute cleanups in strict LIFO order. -
for ... inlowering: Lowers range loops (start..stop,start..=stop) and collection loops (Array,Slice,StaticArray,String) into zero-allocation indexed basic blocks supportingbreak,next, anddefer. -
yieldinlining & closure lowering: Functions containingyieldinline their AST directly into callers via@active_yield. First-classfn(...)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_Nauto-boxing when coercing raw functions to fatFn). -
DWARF
DIBuilder(-g): SetsDebug Info Version = 3andDwarf Version = 4, creates per-moduleDIFiles,DICompileUnit,DISubprograms, per-statementDILocations, andLLVMDIBuilderInsertDeclareRecordAtEndrecords for parameters and locals (temporarily clearing debug scope inside synthetic thunks/closures).
In emit_object_file(obj_path, opt_level):
- Initializes X86 and AArch64 LLVM targets, queries
LLVMGetDefaultTargetTriple(), constructs a PICLLVMTargetMachine, and sets module target triple and data layout. - Runs
LLVMVerifyModule. - When
opt_level > 0, runs LLVM's new pass manager viaLLVMRunPasses:-
-O1->"default<O1>" -
-O2->"default<O2>"(default forhlc build/hlc run) -
-O3->"default<O3>" -
-O0(and-gwithout explicit-O*) skipsLLVMRunPassesto preserve unoptimized debug stepping.
-
- Calls
LLVMTargetMachineEmitToFileto write a native.oobject file, then invokesgccto link<obj>.o, the runtime (libhl_runtime_h.oorlibhl_runtime.a),-lgc -lm -lpthread, and any extra-l/-L/-Wl,/.o/.aflags.
Return to Wiki Home