Part IV · Compiler Architecture, Backend Internals, Safety Proofs & ADRs
Chapter 15
Compiler & Three-Backend System Architecture
Architectural specification of the self-hosted compiler, two-pass Pratt frontend, and triple-target S1 == S2 convergence
This specification documents Veko's unified pure-.vk single-binary SDK and compiler toolchain (src/ — 77 modules, embedding all 95 lib/ standard library modules via the 'VFS2' indexed lazy per-module zlib archive in stdlib_vfs.vk with content-addressed .veko_cache/mod_v1 frontend/type caching), homoiconic intermediate representation, ORO + Copy-on-Write memory subsystem, three-backend execution architecture (oro_vm.vk, codegen.vk / vvm, and direct native native_emit.vk + arm64_emit.vk across win-x64, linux-x64, linux-arm64, and macos-arm64), OS-native readiness reactor (epoll/kqueue/IOCP), .ui desktop window PAL (Win32 Per-Monitor V2 Hi-DPI + zero-libc Linux Wayland/X11 + macOS arm64 AppKit/CoreGraphics + Wasm <canvas>), source debugger & DAP server (debug_cmd.vk), opt-in .ffi boundary (VEKO_LIB), and S1 == S2 self-hosting convergence.
1. Three-Backend System Architecture
Veko separates surface syntax, static types, and ownership semantics (lexer.vk, parser.vk, desugar.vk, macro_eval.vk, types.vk) from three execution backends (oro_vm.vk, codegen.vk, and native_emit.vk / arm64_emit.vk). All three backends consume the same AST, fixed-width 64-bit VKO IR (vko_emit.vk), pure-.vk standard library (lib/), and ORO ownership rules so semantics remain identical across REPL scripts, sandboxed WebAssembly 3.0 modules, and standalone native executables.
Veko 1.0 Shared Frontend & Three-Track Execution Pipeline
39 compiler modules (src/) and 79 stdlib modules (lib/) feeding 64-bit VKO VM, Wasm 3.0 sandbox, and 4 native OS/CPU targets.
| Component & Module | Architectural Role |
|---|---|
Whitespace Lexerlexer.vk | Tokenizes kebab-case words, slash paths, enums, unit literals, and attachment flags. |
Two-Pass Pratt Parserparser.vk | Resolves top-level arities and module aliases in Pass 1, then builds the AST in Pass 2. |
Homoiconic Dialect Passmacro_eval.vk | Expands compile-time macros and structural block dialects before code generation. |
Gradual Types & Capstypes.vk | Checks gradual/strict types, generics [T], mut loans, .secret sinks, and veko.vk allow-caps. |
79-Module Standard Librarylib/* | Delivers codecs, NIST FIPS 203/204/205 PQC, TLS 1.3, HTTP/2, Reactor, Durable Workflows, DBs, and TUI/2D UI. |
64-Bit VKO Bytecode VMvko_emit.vk + oro_vm.vk | Executes fixed-width 64-bit VKO instructions, interactive REPL sessions, and .vko bundles. |
Guarded VM Host PALoro_vm.vk | Enforces runtime capability flags (--allow-fs, --allow-net) and .secret sink checks. |
Wasm 3.0 Code Generatorcodegen.vk + wasm_enc.vk | Emits standalone WebAssembly 3.0 modules with embedded 12-bucket ORO slab allocators. |
vvm Zero-Trust Sandboxruntime*.vk | Runs Wasm modules under deterministic fuel quotas, memory caps, and host sandboxes. |
x86_64 & AArch64 AOTnative_emit.vk + arm64_emit.vk | Compiles directly to native x86_64 and ARM64 machine code with zero external toolchain. |
PE32+ / ELF64 / Mach-Ope_emit.vk + elf_emit.vk + macho_emit.vk | Links standalone executables for Windows x64, Linux x64/arm64, and Apple Silicon. |
Subsystem Breakdown (src/ — 77 Pure-.vk Modules)
Subsystem (src/) | Responsibility |
|---|---|
lexer.vk + parser.vk + desugar.vk + macro_eval.vk | Single-pass whitespace-sensitive lexer, homoiconic RawBlock capture, backtick template interpolation, user /refinements, destructuring, structural match, interface declarations, compile-time embed-str/embed-bytes, spawn capture analysis, and macro / compose / parse-block expansion |
types.vk + diag.vk | Gradual and --strict-types static inference (T|err fallible tracking with /or & if err? narrowing, exhaustive match, homogeneous block[T], strict mut), [T] generic monomorphic checking, sealed struct & interface conformance, disjoint mut field-loan verification, checked narrowing, Levenshtein hints, and .secret taint/sink analysis (veko check) |
init_cmd.vk + test_cmd.vk + fmt_cmd.vk + lsp_cmd.vk + bindgen_cmd.vk + migrate_cmd.vk + v2vk_cmd.vk | Zero-flag workspace resolver & veko init / veko mod sync, veko test & veko bench (--flamegraph), idempotent veko fmt, JSON-RPC 2.0 veko lsp, header .ffi generator (veko bindgen), and Go/Python/Rust/V source translators |
docgen.vk + doc_cmd.vk + book_cmd.vk + inspect.vk | 3-column interactive HTML handbooks (veko docs), single-file self-contained API reference with precompiled Wasm 3.0 doctests & <canvas> preview (veko doc --html), dual pure-Veko Light-Mode EPUB 3.0 book compiler (veko book / --cookbook / --all), and 6-mode binary/IR inspector (veko inspect) |
vko_emit.vk + oro_vm.vk | Fixed-width 64-bit VKO bytecode compiler (op:u8 | flags:u8 | a:u16 | bx:u32) with whole-program dead-function tree-shaking, source-mapped stack traces, zero-W^X superinstructions, deterministic call-frame profiler (--profile / --flamegraph), veko repl, runtime eval, and guarded host I/O |
codegen.vk + stdlib_vfs.vk + wasm_enc.vk + runtime*.vk | Logical DAG module loader with content-addressed .veko_cache/mod_v1 AST/type cache (--no-cache) and 'VFS2' indexed lazy per-module zlib stdlib VFS, veko.vk capability auditor, homoiconic veko.lock & .veko/pkg_cache/ verifier, linear-memory ORO runtime (14B SSO, 12-bucket free-lists, bulk memory.copy/memory.fill), Wasm 3.0 codegen (try_table, return_call, unboxed i64/f64), WASI 0.3 + reactor + shared-memory <canvas> .ui PAL, and veko:conc workers |
native_emit.vk + x64_enc.vk + pe_emit.vk + elf_emit.vk + native_rt.vk + native_pal*.vk | Direct native x86_64 Win64 PE32+ (--target=win-x64, --gui Subsystem=2) & Linux ELF64 (--target=linux-x64, static zero-libc default + opt-in dynamic PT_INTERP only for .ffi), flat block/set analysis arrays, native vstack len fusion, single-pass $O(L+F)$ label relocation patching, CPUID AVX2/SSE2/AES-NI intrinsics, readiness reactor (IOCP+WSAPoll, epoll), Win32 Hi-DPI + clipboard & Linux zero-libc Wayland/X11 window PALs, and static C-ABI .ffi trampolines |
arm64_emit.vk + arm64_enc.vk + arm64_rt_*.vk + arm64_pal*.vk + macho_emit.vk | Direct native AArch64 backend for static Linux ELF64 (--target=linux-arm64, EM_AARCH64, epoll) and 16 KiB-aligned Apple Silicon Mach-O (--target=macos-arm64, kqueue, dyld chained fixups, /usr/lib/libSystem.B.dylib stubs, and pure-Veko SHA-256 ad-hoc LC_CODE_SIGNATURE) |
Three-Backend Design: Purpose, Pipelines & Use Cases
- Track A — 64-Bit
VKOBytecode VM (oro_vm.vk+vko_emit.vk):- Purpose: Instant developer iteration, interactive
veko repl, dynamic runtimeeval, deterministic call-frame profiling (--profile/--flamegraph), and portable 64-bit.vkoexecution. - Pipeline: Compiles ASTs into fixed-width 64-bit
VKOwords (op:u8 | flags:u8 | a:u16 | bx:u32), shakes unreachable imported functions, executes frames with LIFOdeferandTRY_OR/orrecovery, and enforcesVmPolicyhost capability guards.
- Purpose: Instant developer iteration, interactive
- Track B — WebAssembly 3.0 Sandbox (
codegen.vk+runtime_ops.vk+vvm):- Purpose: Zero-trust, capability-confined portable sandboxing across host and browser boundaries (strictly prohibits
.ffi). - Pipeline: Compiles ASTs and homoiconic dialects directly to validated WebAssembly 3.0 (
try_table,return_call,call_indirect, unboxedi64/f64loops, 12-bucket linear-memory ORO free-lists) executing insidevvm'sHostSandboxwith WASI 0.3,--fuelmetering,--mem-pagescaps, content-hashed.veko_cache/<hash>.wasmcaching, and shared-memory HTML5<canvas>presentation in browsers.
- Purpose: Zero-trust, capability-confined portable sandboxing across host and browser boundaries (strictly prohibits
- Track C — Native x86_64 & AArch64 Compiler (
native_emit.vk+arm64_emit.vk):- Purpose: Standalone, toolchain-free native executables for
win-x64(PE32+),linux-x64(ELF64),linux-arm64(ELF64), andmacos-arm64(Mach-O) with zero external C/LLVM toolchains or crypto DLLs. - Pipeline: Lowers 64-bit
VKOIR via leaf inlining, devirtualization,KindMaskscalar/escape retain-release elision, unboxedi64/f64loop lowering, callee-saved regalloc (RBX/RBP/RSI/RDI,XMM6..XMM9,X19..X28), CPUID SIMD/AES-NI dispatch, and dead-helper worklist pruning.
- Purpose: Standalone, toolchain-free native executables for
2. Whitespace-Aware Lexing, Desugaring & Two-Pass Pratt Parsing
Whitespace Disambiguation & Two-Pass Pratt Homoiconic Engine
How [tight] vs [spaced] tokens let kebab-case prefix calls coexist cleanly with infix math, UFCS chains, and macros.
| Component & Module | Architectural Role |
|---|---|
4 Whitespace Ruleslexer.vk | Eliminates grammar ambiguity using single-character attachment flags. |
First-Class Literalslexer.vk | Parses human-readable durations, binary sizes, hex/binary ints, and UTF-8 strings. |
Pass 1: Signature Scanparser.vk | Collects top-level function arities, refinements, structs, and module imports. |
Pass 2: Pratt Precedenceparser.vk | Binds tight postfix chains, prefix word arguments, infix math, comparisons, and \ pipes. |
quote & composemacro_eval.vk | Treats [ ... ] blocks as inspectable values and splices computed expressions cleanly. |
parse-block Dialectsparser.vk + lib/dialect.vk | Matches typed pattern rules over homoiconic blocks to drive custom DSLs. |
Lexical Disambiguation Rules
- Slash (
/): Tight internal attachment (net/read-into/or) builds a module/refinementpath; leading/portin parameter lists declares an optional refinement; spaced/lexes as binary division (total / count). - Dot (
.): Tight attachment after an expression (node.url.trim) lexes as UFCS/fielddot_chain; spaced.or.after[/(/{/,lexes asenum_lit(.tls,.ok). - Hyphen (
-): Inside words (read-into,sha-256) it continues the kebab-case identifier; spaced-before a digit lexes as negativeint_lit(-1); spaced-before alpha/(/[lexes asunary_neg; otherwise it lexes as binaryminus(a - b). - Left Bracket (
[): Tight after an expression (table[i],buf[0..n]) lexes as postfix index/slice; spaced[opens a homoiconic code or data block. - Backtick Templates (
`...`): Lexes interpolated segments{expr}with balanced nested braces, lowering into type-safe formatting chains that automatically preserve.secrettaint if any interpolated expression is secret.
Two-Pass Resolution & Desugaring
- Pass 1 (
scan-top-level-headers): Walks tokens once to registerfn/macropositional arities, user/refinementdescriptors and defaults,interfacecontracts,defaliases, andusemodule prefix mappings, enabling order-independent top-level calls. - Pass 2 (
parse-expr) &desugar.vk: Applies Pratt binding powers (80tight postfix >70prefix calls & unary >60* / % << >> >>> &>50+ - ^ |>40.. ..=>30comparisons >20and or>10\pipes >0statements), desugaring[a b]/{ host, port }destructuring, 2-variablefor [i x]/for [k v]loops, structuralmatch, and compile-timeembed-str/embed-bytesconfinement checks before backend emission.
3. Homoiconicity, Closures & Universal /or Unwinding
- Dual
RawBlockCapture: Every[ ... ]block preserves its exactRawBlocktoken tree alongside parsed statements soquote,compose,macro, andparse-blockinspect typed homoiconic tokens directly. - Universal
/orError Handling: Every builtin and user-defined function automatically supports/or [fallback]and error-binding/or [e -> fallback].- 64-Bit VKO VM (
oro_vm.vk): PushesTRY_ORhandler frames (recording optionalerr_slot) and runs LIFODEFER_PUSHblocks before jumping to the inline handler. - Wasm 3.0 (
codegen.vk): Lowers/orto structured Wasm 3.0try_table+throwexception tags with shadow-frame cleanup. - Native x86_64 & AArch64 (
native_emit.vk+arm64_emit.vk): Pushes unwind records onto per-threadRT-TRY-TOP, isolating outer error registers across nesteddefercleanups.
- 64-Bit VKO VM (
4. Self-Hosting Fixed-Point Convergence
Veko 1.0 Self-Hosted Toolchain & Triple-Target S1 == S2 Fixed Point
How the 39-module pure-Veko compiler compiles itself to bit-identical native binaries across architectures.
| Component & Module | Architectural Role |
|---|---|
Self-Hosted Sourcesrc/main.vk | 100% of lexer, parser, typechecker, VKO VM, Wasm emitter, x64/arm64 emitters, fmt, lsp, and docgen. |
Stage 1 Compiler (S1)native_emit.vk + arm64_emit.vk | Promoted host compiler compiles src/main.vk into a fresh Stage 1 native executable. |
Stage 2 Compiler (S2)pe_emit.vk + elf_emit.vk | Stage 1 executes natively (or under QEMU for arm64) to compile src/main.vk a second time. |
Bit-Identical Fixed Pointbuild.vk + tests/run_tests.vk | Byte-for-byte SHA-256 equality across Win64 PE32+, Linux x86_64 ELF64, and Linux AArch64 ELF64. |
Veko is 100% self-hosted in .vk with zero external compiler dependencies:
- Stage 1 (
S1) compilessrc/main.vk(77compiler modules + transitivelib/dependencies) into a standalone native binary. - Stage 2 (
S2) usesS1to recompile the exact same source graph. - Byte-for-byte
SHA-256(S1) == SHA-256(S2)fixed-point identity verifies deterministic code generation, constant interning, register allocation, and binary linking acrossPE32+,ELF64,Mach-O,Wasm 3.0, andVKO.
5. Shared-Nothing Concurrency, Readiness Reactor & Desktop .ui PAL
Isolated spawn Workers, Bounded Channels & Multi-Wait Select
Data-race-free parallelism by construction: zero shared mutable memory, zero locks in user code, and isolated worker heaps.
| Component & Module | Architectural Role |
|---|---|
Parent Taskvko_emit.vk + native_pal3.vk | Spawns isolated concurrent tasks and coordinates results via channels or task/await. |
Deep-Frozen Captureruntime_net_conc.vk + native_pal3.vk | Deep-copies captured immutable values into the worker's independent slab allocator. |
Bounded chan/* & selectoro_vm.vk + native_pal3.vk | Transfers deep-copied message values across bounded FIFO queues with backpressure. |
Isolated Worker Threadnative_pal3.vk + arm64_pal.vk | Executes on a real OS kernel thread (or isolated vvm Store on Wasm) with private slabs. |
- Shared-Nothing Workers & Structured Scopes (
spawn,chan/*,lib/conc/scope.vk): Workers execute on isolated OS threads (CreateThread,sys_clone+sys_futex,pthread_create) or isolatedvvmHostSandboxstores with zero shared mutable heap memory, exchanging values strictly by ownership transfer over bounded channels. - Readiness Reactor (
lib/reactor.vk): Multiplexes non-blocking TCP sockets, timers, and cross-thread wakeups (send-wake) over Linuxepoll+eventfd2, macOSkqueue+EVFILT_USER, WindowsIOCP+WSAPoll, and WASInet-poll. - Cross-Platform
.uiDesktop & Browser Surface (lib/ui.vk,lib/ui/widgets.vk,lib/ui/wayland.vk,lib/ui/x11.vk):- Windows (
win-x64): Win32StretchDIBitstop-down RGBA->BGRA presenter, dynamic Per-Monitor V2 Hi-DPI scaling (ui/dpi-scale), and Win32 clipboard integration (ui/clipboard-get,ui/clipboard-set). - Linux (
linux-x64/linux-arm64): Zero-libcWayland (memfd_create+SCM_RIGHTSwl_shmARGB8888 +xdg_toplevel) and zero-libcX11R6 (/tmp/.X11-unix/X<n>,.XauthorityMIT-MAGIC-COOKIE-1, scanline-bandPutImage<= 128 KB), cascading automatically with headless fallback. - macOS Apple Silicon (
macos-arm64): ConditionalAppKit/CoreGraphicsNSApplication+NSWindow+ RetinabackingScaleFactor(ui/dpi-scale) presenter. - Browser WebAssembly (
docgen/assets/interactive.js): Zero-import shared-linear-memory framebuffer blitting onto interactive HTML5<canvas>elements with live mouse and keyboard event forwarding.
- Windows (
(See Detailed Technical Overview, Safety & ORO Memory Model, and Requirements & Decisions for instruction encodings, ABI layouts, and complete ADR records.)