Part IV · Compiler Architecture, Backend Internals, Safety Proofs & ADRs
Chapter 16
Detailed Technical Overview & Backend Internals
Instruction-level mechanics of 64-bit VKO bytecode, Wasm 3.0 linear-RAM ABI, x86_64/AArch64 codegen, and PE32+/ELF64/Mach-O linkers
This technical reference documents the concrete internals of Veko's 77-module self-hosted compiler and single-binary portable SDK (src/, including 'VFS2' lazy stdlib_vfs.vk, content-addressed mod_v1 module caching, and debug_cmd.vk) and 95-module pure-.vk standard library (lib/, including db/sqlite.vk, net/http3.vk, durable/workflow.vk, testing/fuzz.vk, and ui/wayland.vk): the whitespace-aware frontend (lexer.vk, parser.vk, desugar.vk, macro_eval.vk), deterministic ORO memory subsystem, fixed-width 64-bit VKO bytecode compiler, source debugger, line-coverage tracer, and profiler-equipped VM (vko_emit.vk, oro_vm.vk, debug_cmd.vk, test_cmd.vk), gradual/strict type, T|err fallibility, [T] generic, interface, and .secret checker (types.vk), portable VEKO_HOME / ~/.veko_modules / embedded 'VFS2' module DAG bundler & veko-lang.org .vkp registry verifier (codegen.vk, lib/pkg/lock.vk), WebAssembly 3.0 backend (codegen.vk, wasm_enc.vk, runtime*.vk), direct native x86_64 & AArch64 backends (native_emit.vk, arm64_emit.vk, native_pal*.vk, arm64_pal*.vk, pe_emit.vk, elf_emit.vk, macho_emit.vk), readiness reactor, .ui Win32/Wayland/X11/AppKit/Canvas PALs, VEKO_LIB-aware opt-in .ffi C-ABI trampolines, and pure-Veko HTML/EPUB publishing (docgen.vk, doc_cmd.vk, book_cmd.vk).
64-Bit VKO ISA, Hardware SIMD & Four-Target Native Binary Emitters
Zero-JIT, zero-W^X compilation from typed ASTs to superinstruction bytecode, x86_64, and AArch64 executables.
| Component & Module | Architectural Role |
|---|---|
64-Bit VKO Emittervko_emit.vk | Compiles ASTs into fixed-width 64-bit instructions serialized as portable 'VKO1' binaries. |
VM Superinstructionsoro_vm.vk | Fuses hot local-load, arithmetic, comparison, and branch sequences in pure AOT code. |
x86_64 Machine Emitterx64_enc.vk + native_emit.vk | Lowers typed ASTs directly to x86_64 machine code with 79-group dead-code elimination. |
Win64 PE32+ & Linux ELF64pe_emit.vk + elf_emit.vk | Writes standalone Windows .exe and static zero-libc Linux x86_64 executables. |
AArch64 Machine Emitterarm64_enc.vk + arm64_emit.vk | Encodes fixed 32-bit ARM64 instructions with dedicated callee-saved runtime registers. |
Linux ELF64 & macOS Mach-Oelf_emit.vk + macho_emit.vk | Emits static Linux EM_AARCH64 ELF64 and ad-hoc SHA-256 signed 16 KiB Apple Silicon Mach-O. |
1. Frontend Internals (lexer.vk, parser.vk, desugar.vk)
Whitespace-Aware Lexical State Machine
lexer.vk converts UTF-8 source text into Token structs carrying { kind, lit, pos, line, col, tight } using a single boolean state had_space (initialized to true):
- Tight vs. Spaced Delimiters:
tightisnot had_spaceat token start. Opening delimiters ([,(,{) and,sethad_space = trueso leading tokens inside delimiters ([-1],[.tls]) are recognized as spaced. - Single-Character Lookahead Disambiguation:
-spaced + digit $\rightarrow$ negativeint_lit; spaced + alpha/(/[$\rightarrow$unary_neg; tight inside word $\rightarrow$ kebab-case identifier; otherwise $\rightarrow$ binaryminus..+.$\rightarrow$range(..) orrange_inc(..=); tight.+ ident $\rightarrow$dot_chain; spaced.+ ident $\rightarrow$enum_lit./inside word + alpha $\rightarrow$path(net/read-into/or); leading/nameinside parameter lists $\rightarrow$ optional refinement declaration;//$\rightarrow$ line comment; spaced/$\rightarrow$ binaryslash.- Backtick
`...`$\rightarrow$tmpl_litscanning balanced{ ... }expression interpolations. - Digits + unit suffix $\rightarrow$
dur_lit(ns,us,ms,s,m,h) or1024-basedsize_lit(b,kb,mb,gb,kib,mib,gib).
Two-Pass Pratt Parser & AST Desugaring
- Pass 1 (
scan-top-level-headers): Walks tokens once to registerfn/macropositional arities, user/refinementparameter specs and defaults,interfacemethod/field contracts,defaliases, andusemodule imports. - Pass 2 (
parse-expr):80(Postfix): tight.field(ChainExpr), tight[idx](IndexExpr), tight[a..b]/[..b]/[a..](SliceExpr).70(Prefix):-x,not x,mut ident/mut ident.field(MutArgExpr), and fixed-arity prefix calls (CallExpr) consumingpositional_arity + active_refinementsarguments atmin_bp = 70.60..20(Infix):* / % << >> >>> &(60),+ - ^ |(50),.. ..=(40),== != < <= > >=(30),and or(20).10(Pipe):\(spanning newlines whenmin_bp <= 10) injectslhsas argument 1 of the right-hand word/path.- Dual Block Capture: Every
[ ... ]block preserves its raw homoiconicRawBlocktoken tree alongside parsed statements.
- AST Desugaring (
desugar.vk): Lowers backtick templates (preserving.secrettaint via concatenation/redaction helpers), user/refinementcall argument ordering and default injection,[a b]/{ k1, k2 }destructuring, 2-variablefor [i x]/for [k v]loops, structuralmatchpatterns, and workspace-confined compile-timeembed-str/embed-bytesliterals.
2. ORO Memory Subsystem & 16-Byte Value ABI
16-Byte Value Cell & Inline 14-Byte SSO
Every stack slot, local variable, global entry, and value-slab element is an aligned 16-byte Value cell ((hdr: i64, data: i64)):
tag(u8):uninit(0),boolean,i64_val,f64_val,duration,size_val,enum_sym,word,str_inline,str_heap,bytes,block,map_val,closure,native_fn,err_val.flags(u8): Tracksflag_owned,flag_secret,flag_const,flag_mut_ref,flag_struct(fixed-schema O(1) slot layout), andflag_map_hashed(open-addressedi32hash tail when>16entries). Onstr_inline, the upper nibble stores inline UTF-8 length (0..14), overlaying bytes2..15with zero heap allocation.aux(u16): Native arity, canonicalstructschema symbol ID, or inline SSO bytes0..1.meta(u32): Slab pointer/index, interned symbol ID, closurefn_idx, or inline SSO bytes2..5.data(8 B): Unboxedi64/ IEEE-754f64, inline SSO bytes6..13, or closureenv_slab.
Slab Headers, 12-Bucket Recycling & Copy-on-Write
Heap slabs begin with a 16-byte header [+0 rc:i32, +4 cap:i32, +8 len:i32, +12 flags:i32]:
- Zero-Cost Borrow vs. Retain: Passing a value without moving ownership clears
flag_ownedwithout touchingrc. Static.rdataliterals carryrc = -1andflag_constsoretain/releaseshort-circuit immediately. - Deterministic
release&.secretWipe: Whenrcdrops1 -> 0, child elements of value slabs are released recursively,flag_secretslabs zeroize their entire allocated capacity, and slabs up to64 KiBreturn to 12 power-of-two size-class free-lists (32 B..65536 B), while>64 KiBslabs return directly to the OS (VirtualFree/munmap). - Copy-on-Write
ensure_unique: In-placemutoperations mutate directly whenrc == 1, or clone into a freshrc == 1slab and decrement the shared snapshotrc.
3. Fixed-Width 64-Bit VKO Bytecode, Tree-Shaking & Profiler (vko_emit.vk, oro_vm.vk)
Every VKO instruction is a 64-bit i64 word (op: u8 | flags: u8 | a: u16 | bx: u32) serialized with the 'VKO\x00' header:
- Call-Graph Tree-Shaking:
vko_emit.vkbuilds a reachability graph from module entry statements andpubexports, pruning unreferenced functions across imported stdlib and workspace modules before emission. - Source-Mapped Stack Traces: Each
VkoFncarries source{ file, line }metadata so uncaught runtime errors format crispat fn-name (path.vk:line)traces (vm.last_trace). - Universal
/or& Error Binding:OP-TRY-OR-PUSH(a = err_slot + 1,bx = handler_pc) captures catchable errors from both builtins and user functions, binding[e -> ...]when present and executing LIFOdeferclosures cleanly during unwind. - Zero-
W^XSuperinstructions, Native Crypto Fast-Paths, HardenedVmPolicy, Source Debugger & Profiler:oro_vm.vkfuses hot local increment, comparison-branch, and indexed-load sequences in memory (op >= 64) withoutRWXcode pages, and accelerates leaf cryptographic kernels (mont-mul,bn-mod-add,bn-mod-sub,bn-cmp,fe-mul,fe-sq,keccak-f1600,sha256/sha384/sha512) atCALL-FNwhile preserving.secrettaint propagation (vm-wrap-secret-limbs).VmPolicyenforces optionalmax_steps(--fuel),max_sleep_ns,max_output_bytes,capture_output, and per-capability gates (allow_env,allow_exec,allow_exit,allow_spawn). Whenveko debug(--dapJSON-RPC Debug Adapter Protocol or interactive CLI) orveko test --coverageis active,vko_emit.vkemits un-inlinedpc_linesmetadata andoro_vm.vkactivatestrace_hooks_en(debug_en/coverage_en) with strict<secret>variable redaction and zero overhead on normal runs. When--profileor--flamegraphis active (vm.profile_en = true),prof-enterandprof-exitrecord exact call counts, exclusive (self_ns), and inclusive (incl_ns) nanosecond durations across folded call stacks, feedinglib/profile/flamegraph.vkto emit Light-Mode interactive SVG flamegraphs.
4. WebAssembly 3.0 Backend & Browser <canvas> Bridge (codegen.vk, wasm_enc.vk, runtime*.vk)
codegen.vk compiles Veko module DAGs directly into validated WebAssembly 3.0 binaries:
- 16-Byte Multi-Value ABI & Unboxed Loops: Runtime functions exchange
(hdr: i64, data: i64)pairs, while statically typedi64andf64locals, arithmetic, andwhileconditions lower directly to unboxed Wasm register instructions (i64.*,f64.*,i64.rotr) and bulk-memory ops (memory.copy,memory.fill). - Structured Wasm 3.0 Control Flow: Tail recursion lowers to
return_call, closures dispatch through typedcall_indirecttable slots, and/orhandlers lower to Wasm 3.0try_table+throwtags. - Minimal Capability-Driven WASI Imports: AST capability scanning imports only referenced
wasi_snapshot_preview1/ WASI 0.3 interfaces, enforcing--fuel,--mem-pages, confined--allow-fs, and SSRF-guarded networking insidevvm. - Zero-Import Browser
<canvas>& Clipboard Scratch Bridge (runtime_pal4.vk,interactive.js): Wasm.uioperations store frame dimensions, sequence counters, a 16-slot input event ring, Hi-DPI scale, and a 2 KiB clipboard buffer inside reserved linear-memory scratch addresses (1024..4095). CLI runs invvmrequire zero extra host imports and maintain_oro_live_slabs == 0, while browser hosts (veko doc --html/veko docs) allocate linear framebuffer pages, blit live RGBA32 frames onto HTML5<canvas>, and stream mouse/keyboard events back into Wasm.
5. Direct Native x86_64 & AArch64 Backends (native_emit.vk, arm64_emit.vk)
Register Allocation, Scalar Elision & SIMD
- x86_64 Internal Convention (
native_emit.vk,x64_enc.vk):R12holds per-threadThreadState([R12 + RT-SHARED-PTR]addresses the1024 Bshared.datablock),R13indexes the1 MiBORO value stack,R14indexes frame locals, andR15holds the active closure environment. Flatblock/set-indexed analysis arrays, nativevstacklenfusion (reading[slab - 8]inline without helper calls), and single-pass $O(L+F)$ label relocation patching (patch-labels) keep incremental native codegen around~48 ms, whileKindMaskescape analysis elidesrt_retain/rt_releaseon scalar locals and allocates loop-hot scalars toRBX,RBP,RSI,RDI, andXMM6..XMM9. StartupCPUID+XGETBVenablesAVX2,SSE2,AES-NI, andPCLMULQDQpaths. - AArch64 Internal Convention (
arm64_emit.vk,arm64_enc.vk): Encodes 32-bit ARMv8-A instructions directly, anchoringThreadState, value stack, locals, and closure environments inX19..X28, returning 16-byte(hdr, pay)pairs inX0..X1, and executing IEEE-754f64math inD0..D15. - 292-Year Monotonic Clock Scaling (
native_pal.vk): Onwin-x64,rt_pal_clock_nscomputes(delta / freq) * 1_000_000_000 + ((delta % freq) * 1_000_000_000) / freqvia 64-bitidivquotient + remainder soQueryPerformanceCounterdeltas never overflow signed 64-bit nanoseconds across multi-hour or multi-year server runs.
Binary Linkers (pe_emit.vk, elf_emit.vk, macho_emit.vk)
--target=win-x64(pe_emit.vk): Emits standalone PE32+ executables importingkernel32.dll, plusws2_32.dllonly when.netis used anduser32.dll/gdi32.dllonly when.uiis used (--guisetsSubsystem = 2).--target=linux-x64&--target=linux-arm64(elf_emit.vk): Emits 100% static zero-libcET_EXECELF64 executables (EM_X86_64orEM_AARCH64,0o755permissions) invoking direct Linux kernel syscalls (mmap,clone,futex,epoll_pwait,openat, sockets), switching to dynamicPT_INTERP+libc.so.6(dlopen/dlsym/dlclose) only when opt-in.ffiis active.--target=macos-arm64(macho_emit.vk): Emits 16 KiB page-aligned Apple SiliconMH_EXECUTEMach-O binaries withLC_MAIN,LC_DYLD_CHAINED_FIXUPS,/usr/lib/libSystem.B.dylibbindings (pthread_create,kqueue), and a pure-Veko SHA-256CS_ADHOCLC_CODE_SIGNATURESuperBlob.
6. Readiness Reactor, Desktop .ui PAL, .ffi & Supply-Chain Locking
OS-Native Readiness Reactor, Timer Wheel & Multiplexed HTTP Engine
Single-threaded readiness multiplexing over epoll, kqueue, IOCP+WSAPoll, and WASI net-poll without async/await coloring.
| Component & Module | Architectural Role |
|---|---|
OS Kernel Poller Backendsnative_pal4.vk + arm64_pal2.vk | Maps net/poll-new, net/poll-ctl, and net/poll-wait directly to each OS's readiness facility. |
Non-Blocking Socket Opslib/io/net.vk | Returns .would_block cleanly instead of blocking the OS thread when buffers aren't ready. |
Reactor Loop & Dispatchlib/reactor.vk | Multiplexes READABLE and WRITABLE readiness tokens alongside scheduled deadlines. |
Min-Heap Timers & Wakerlib/reactor.vk | Combines O(log n) monotonic timers with cross-thread spawn wakeup notifications. |
web/serve-reactorlib/web.vk | Serves concurrent HTTP/1.1 keep-alive connections and slow clients on a single reactor. |
net/client/request-batchlib/net/client.vk | Executes dozens of concurrent HTTP requests in parallel over one readiness reactor. |
- OS Readiness Reactor (
native_pal4.vk,arm64_pal2.vk,lib/reactor.vk): Binds 11 non-blocking socket and poll primitives onto Linuxepoll+eventfd2, macOSkqueue+EVFILT_USER, WindowsIOCP+WSAPoll, and WASInet-poll, poweringweb/serve-reactor,sse-write,serve-static-range(206 Partial Content), andnet/clientkeep-alive pools. - Desktop
.uiPAL (native_pal5.vk,arm64_pal3.vk,lib/ui.vk,lib/ui/wayland.vk,lib/ui/x11.vk):- Windows (
win-x64): Dynamically enables Per-Monitor V2 Hi-DPI (SetProcessDpiAwarenessContext(-4)), queriesGetDpiForWindow(ui/dpi-scale), blits top-down BGRA surfaces viaStretchDIBits, and syncs UTF-8 text with the Win32 clipboard (OpenClipboard/GetClipboardData/SetClipboardData) while blocking.secretvalues atui/clipboard-setand taintingui/clipboard-get/secretreads. - Linux (
linux-x64&linux-arm64): Cascades automatically fromVEKO_HEADLESS=1$\rightarrow$ zero-libcWayland (AF_UNIX$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY,memfd_create+SCM_RIGHTSwl_shmARGB8888 shared memory,xdg_wm_base/xdg_toplevel) $\rightarrow$ zero-libcX11 (/tmp/.X11-unix/X<n>,.XauthorityMIT-MAGIC-COOKIE-1, scanline-bandPutImage) $\rightarrow$ Headless fallback, requiring zerolibwayland-client,libX11, orlibcdependencies. - macOS Apple Silicon (
macos-arm64): Emits conditionalLC_LOAD_DYLIBentries (libobjc.A.dylib,AppKit,CoreGraphics) only when.uiis referenced (dylibs == 1on CLI binaries), drivingNSApplication,NSWindow,CGBitmapContextRGBA32 blitting, and RetinabackingScaleFactor(ui/dpi-scale) directly via Objective-Cobjc_msgSend.
- Windows (
- Opt-In
.ffi,VEKO_LIB&veko bindgen(native_pal5.vk,lib/ffi.vk,bindgen_cmd.vk): SearchesVEKO_LIBbefore OS loader paths, dispatches up to 6 scalar/str/bytesarguments across Win64, SysV x86_64, and AAPCS64 static C-ABI trampolines, and parses header declarations into ready-to-import.vkwrapper modules viaveko bindgen. - Portable
'VFS2'Lazy SDK, Content-Addressedmod_v1Cache & Decentralizedveko-lang.org.vkpRegistry (src/stdlib_vfs.vk,src/codegen.vk,lib/pkg/vkp.vk,lib/pkg/lock.vk):vekoembeds all 95lib/*.vkmodules insidestdlib_vfs.bin('VFS2'indexed per-module zlib archive so standalone SDK invocations outside the repository decompress only imported modules on demand) and caches parsed/desugared/type-checked module bundles in.veko_cache/mod_v1/<sha256>.vbin(--no-cacheforces cold recompilation). Imports resolve across workspacedeps$\rightarrow$VEKO_MODULES/~/.veko_modules$\rightarrow$VEKO_HOME/lib$\rightarrow$ embedded'VFS2'VFS.veko pkg addfetches official packages fromhttps://veko-lang.org/pkg/<name>/<ver>.vkp(or any customhttps://URL /VEKO_REGISTRYmirror) over pure-Veko TLS 1.3 (validating Ed25519, ECDSA P-256/P-384, and RSA chains against built-in public CA roots), pinning archiveSHA-256,merkle_root, andEd25519/ML-DSA-65signatures inveko.lock. - Pure-Veko Zero-FFI SQLite 3, Fuzzing & HTML/EPUB 3.0 Publishing (
lib/db/sqlite.vk,lib/testing/fuzz.vk,docgen.vk,doc_cmd.vk,book_cmd.vk): Provides a zero-FFI"SQLite format 3\0"4096-byte slotted B-tree engine (with'VKJRNL01'rollback journal, incrementalos/pwritepage commits, multi-page0x02/0x0aB-tree indexes, andINNER/LEFT JOIN) + homoiconic ORM,SplitMix64structure-aware byte/UTF-8/block fuzzing with delta-debugging shrinking, and the 23-page HTML documentation suite + two strict-XML-validated Light-Mode EPUB 3.0 books (veko book --all).