veko-lang.org
Download Free EPUB 3.0

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).

CODEGEN & BINARY LINKERS

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.

IR & BYTECODE TRACK vko_emit.vk + oro_vm.vk X86_64 NATIVE BACKEND x64_enc.vk + native_emit.vk AARCH64 NATIVE BACKEND arm64_enc.vk + arm64_emit.vk VKO1 words x86_64 code ARM64 code Shared AST PAL parity Bytecode IR64-Bit VKO Emitterop:u8 | flags:u8 | a:u16 | bx:u32 VM EngineVM SuperinstructionsZero-JIT Dispatch Fusion x86_64 Codegenx86_64 Machine EmitterCPUID AVX2 / SSE2 / AES-NI x86_64 LinkersWin64 PE32+ & Linux ELF64pe_emit.vk + elf_emit.vk ARM64 CodegenAArch64 Machine EmitterARMv8-A + NEON-ready PAL ARM64 LinkersLinux ELF64 & macOS Mach-Oelf_emit.vk + macho_emit.vk
Component & ModuleArchitectural Role
64-Bit VKO Emitter
vko_emit.vk
Compiles ASTs into fixed-width 64-bit instructions serialized as portable 'VKO1' binaries.
VM Superinstructions
oro_vm.vk
Fuses hot local-load, arithmetic, comparison, and branch sequences in pure AOT code.
x86_64 Machine Emitter
x64_enc.vk + native_emit.vk
Lowers typed ASTs directly to x86_64 machine code with 79-group dead-code elimination.
Win64 PE32+ & Linux ELF64
pe_emit.vk + elf_emit.vk
Writes standalone Windows .exe and static zero-libc Linux x86_64 executables.
AArch64 Machine Emitter
arm64_enc.vk + arm64_emit.vk
Encodes fixed 32-bit ARM64 instructions with dedicated callee-saved runtime registers.
Linux ELF64 & macOS Mach-O
elf_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: tight is not had_space at token start. Opening delimiters ([, (, {) and , set had_space = true so leading tokens inside delimiters ([-1], [.tls]) are recognized as spaced.
  • Single-Character Lookahead Disambiguation:
    • - spaced + digit $\rightarrow$ negative int_lit; spaced + alpha/(/[ $\rightarrow$ unary_neg; tight inside word $\rightarrow$ kebab-case identifier; otherwise $\rightarrow$ binary minus.
    • . + . $\rightarrow$ range (..) or range_inc (..=); tight . + ident $\rightarrow$ dot_chain; spaced . + ident $\rightarrow$ enum_lit.
    • / inside word + alpha $\rightarrow$ path (net/read-into/or); leading /name inside parameter lists $\rightarrow$ optional refinement declaration; // $\rightarrow$ line comment; spaced / $\rightarrow$ binary slash.
    • Backtick `...` $\rightarrow$ tmpl_lit scanning balanced { ... } expression interpolations.
    • Digits + unit suffix $\rightarrow$ dur_lit (ns, us, ms, s, m, h) or 1024-based size_lit (b, kb, mb, gb, kib, mib, gib).

Two-Pass Pratt Parser & AST Desugaring

  1. Pass 1 (scan-top-level-headers): Walks tokens once to register fn/macro positional arities, user /refinement parameter specs and defaults, interface method/field contracts, def aliases, and use module imports.
  2. 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) consuming positional_arity + active_refinements arguments at min_bp = 70.
    • 60..20 (Infix): * / % << >> >>> & (60), + - ^ | (50), .. ..= (40), == != < <= > >= (30), and or (20).
    • 10 (Pipe): \ (spanning newlines when min_bp <= 10) injects lhs as argument 1 of the right-hand word/path.
    • Dual Block Capture: Every [ ... ] block preserves its raw homoiconic RawBlock token tree alongside parsed statements.
  3. AST Desugaring (desugar.vk): Lowers backtick templates (preserving .secret taint via concatenation/redaction helpers), user /refinement call argument ordering and default injection, [a b] / { k1, k2 } destructuring, 2-variable for [i x] / for [k v] loops, structural match patterns, and workspace-confined compile-time embed-str / embed-bytes literals.

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): Tracks flag_owned, flag_secret, flag_const, flag_mut_ref, flag_struct (fixed-schema O(1) slot layout), and flag_map_hashed (open-addressed i32 hash tail when >16 entries). On str_inline, the upper nibble stores inline UTF-8 length (0..14), overlaying bytes 2..15 with zero heap allocation.
  • aux (u16): Native arity, canonical struct schema symbol ID, or inline SSO bytes 0..1.
  • meta (u32): Slab pointer/index, interned symbol ID, closure fn_idx, or inline SSO bytes 2..5.
  • data (8 B): Unboxed i64 / IEEE-754 f64, inline SSO bytes 6..13, or closure env_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_owned without touching rc. Static .rdata literals carry rc = -1 and flag_const so retain/release short-circuit immediately.
  • Deterministic release & .secret Wipe: When rc drops 1 -> 0, child elements of value slabs are released recursively, flag_secret slabs zeroize their entire allocated capacity, and slabs up to 64 KiB return to 12 power-of-two size-class free-lists (32 B..65536 B), while >64 KiB slabs return directly to the OS (VirtualFree / munmap).
  • Copy-on-Write ensure_unique: In-place mut operations mutate directly when rc == 1, or clone into a fresh rc == 1 slab and decrement the shared snapshot rc.

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.vk builds a reachability graph from module entry statements and pub exports, pruning unreferenced functions across imported stdlib and workspace modules before emission.
  • Source-Mapped Stack Traces: Each VkoFn carries source { file, line } metadata so uncaught runtime errors format crisp at 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 LIFO defer closures cleanly during unwind.
  • Zero-W^X Superinstructions, Native Crypto Fast-Paths, Hardened VmPolicy, Source Debugger & Profiler: oro_vm.vk fuses hot local increment, comparison-branch, and indexed-load sequences in memory (op >= 64) without RWX code 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) at CALL-FN while preserving .secret taint propagation (vm-wrap-secret-limbs). VmPolicy enforces optional max_steps (--fuel), max_sleep_ns, max_output_bytes, capture_output, and per-capability gates (allow_env, allow_exec, allow_exit, allow_spawn). When veko debug (--dap JSON-RPC Debug Adapter Protocol or interactive CLI) or veko test --coverage is active, vko_emit.vk emits un-inlined pc_lines metadata and oro_vm.vk activates trace_hooks_en (debug_en / coverage_en) with strict <secret> variable redaction and zero overhead on normal runs. When --profile or --flamegraph is active (vm.profile_en = true), prof-enter and prof-exit record exact call counts, exclusive (self_ns), and inclusive (incl_ns) nanosecond durations across folded call stacks, feeding lib/profile/flamegraph.vk to 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:

  1. 16-Byte Multi-Value ABI & Unboxed Loops: Runtime functions exchange (hdr: i64, data: i64) pairs, while statically typed i64 and f64 locals, arithmetic, and while conditions lower directly to unboxed Wasm register instructions (i64.*, f64.*, i64.rotr) and bulk-memory ops (memory.copy, memory.fill).
  2. Structured Wasm 3.0 Control Flow: Tail recursion lowers to return_call, closures dispatch through typed call_indirect table slots, and /or handlers lower to Wasm 3.0 try_table + throw tags.
  3. 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 inside vvm.
  4. Zero-Import Browser <canvas> & Clipboard Scratch Bridge (runtime_pal4.vk, interactive.js): Wasm .ui operations 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 in vvm require 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): R12 holds per-thread ThreadState ([R12 + RT-SHARED-PTR] addresses the 1024 B shared .data block), R13 indexes the 1 MiB ORO value stack, R14 indexes frame locals, and R15 holds the active closure environment. Flat block/set-indexed analysis arrays, native vstack len fusion (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, while KindMask escape analysis elides rt_retain/rt_release on scalar locals and allocates loop-hot scalars to RBX, RBP, RSI, RDI, and XMM6..XMM9. Startup CPUID + XGETBV enables AVX2, SSE2, AES-NI, and PCLMULQDQ paths.
  • AArch64 Internal Convention (arm64_emit.vk, arm64_enc.vk): Encodes 32-bit ARMv8-A instructions directly, anchoring ThreadState, value stack, locals, and closure environments in X19..X28, returning 16-byte (hdr, pay) pairs in X0..X1, and executing IEEE-754 f64 math in D0..D15.
  • 292-Year Monotonic Clock Scaling (native_pal.vk): On win-x64, rt_pal_clock_ns computes (delta / freq) * 1_000_000_000 + ((delta % freq) * 1_000_000_000) / freq via 64-bit idiv quotient + remainder so QueryPerformanceCounter deltas 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 importing kernel32.dll, plus ws2_32.dll only when .net is used and user32.dll/gdi32.dll only when .ui is used (--gui sets Subsystem = 2).
  • --target=linux-x64 & --target=linux-arm64 (elf_emit.vk): Emits 100% static zero-libc ET_EXEC ELF64 executables (EM_X86_64 or EM_AARCH64, 0o755 permissions) invoking direct Linux kernel syscalls (mmap, clone, futex, epoll_pwait, openat, sockets), switching to dynamic PT_INTERP + libc.so.6 (dlopen/dlsym/dlclose) only when opt-in .ffi is active.
  • --target=macos-arm64 (macho_emit.vk): Emits 16 KiB page-aligned Apple Silicon MH_EXECUTE Mach-O binaries with LC_MAIN, LC_DYLD_CHAINED_FIXUPS, /usr/lib/libSystem.B.dylib bindings (pthread_create, kqueue), and a pure-Veko SHA-256 CS_ADHOC LC_CODE_SIGNATURE SuperBlob.

6. Readiness Reactor, Desktop .ui PAL, .ffi & Supply-Chain Locking

NON-BLOCKING ASYNC I/O

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.

OS KERNEL READINESS POLLERS 11 net/poll-* & net/try-* PAL ops LIB/REACTOR.VK EVENT LOOP Sockets + Min-Heap Timers + Waker HIGH-CONCURRENCY CONSUMERS Server & Batch Client Ready tokens .would_block Next deadline Accept / Read / Write Parallel sockets Kernel PALOS Kernel Poller Backendsepoll / kqueue / IOCP+WSAPoll Zero-Alloc I/ONon-Blocking Socket Opstry-accept / try-read-into / try-write Event LoopReactor Loop & Dispatchregister / modify / step / run SchedulingMin-Heap Timers & Wakerafter / every + poll-wake Async Serverweb/serve-reactorKeep-Alive HTTP Multiplexer Async Clientnet/client/request-batchParallel Outbound Fan-Out
Component & ModuleArchitectural Role
OS Kernel Poller Backends
native_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 Ops
lib/io/net.vk
Returns .would_block cleanly instead of blocking the OS thread when buffers aren't ready.
Reactor Loop & Dispatch
lib/reactor.vk
Multiplexes READABLE and WRITABLE readiness tokens alongside scheduled deadlines.
Min-Heap Timers & Waker
lib/reactor.vk
Combines O(log n) monotonic timers with cross-thread spawn wakeup notifications.
web/serve-reactor
lib/web.vk
Serves concurrent HTTP/1.1 keep-alive connections and slow clients on a single reactor.
net/client/request-batch
lib/net/client.vk
Executes dozens of concurrent HTTP requests in parallel over one readiness reactor.
  1. OS Readiness Reactor (native_pal4.vk, arm64_pal2.vk, lib/reactor.vk): Binds 11 non-blocking socket and poll primitives onto Linux epoll + eventfd2, macOS kqueue + EVFILT_USER, Windows IOCP + WSAPoll, and WASI net-poll, powering web/serve-reactor, sse-write, serve-static-range (206 Partial Content), and net/client keep-alive pools.
  2. Desktop .ui PAL (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)), queries GetDpiForWindow (ui/dpi-scale), blits top-down BGRA surfaces via StretchDIBits, and syncs UTF-8 text with the Win32 clipboard (OpenClipboard / GetClipboardData / SetClipboardData) while blocking .secret values at ui/clipboard-set and tainting ui/clipboard-get/secret reads.
    • Linux (linux-x64 & linux-arm64): Cascades automatically from VEKO_HEADLESS=1 $\rightarrow$ zero-libc Wayland (AF_UNIX $XDG_RUNTIME_DIR/$WAYLAND_DISPLAY, memfd_create + SCM_RIGHTS wl_shm ARGB8888 shared memory, xdg_wm_base / xdg_toplevel) $\rightarrow$ zero-libc X11 (/tmp/.X11-unix/X<n>, .Xauthority MIT-MAGIC-COOKIE-1, scanline-band PutImage) $\rightarrow$ Headless fallback, requiring zero libwayland-client, libX11, or libc dependencies.
    • macOS Apple Silicon (macos-arm64): Emits conditional LC_LOAD_DYLIB entries (libobjc.A.dylib, AppKit, CoreGraphics) only when .ui is referenced (dylibs == 1 on CLI binaries), driving NSApplication, NSWindow, CGBitmapContext RGBA32 blitting, and Retina backingScaleFactor (ui/dpi-scale) directly via Objective-C objc_msgSend.
  3. Opt-In .ffi, VEKO_LIB & veko bindgen (native_pal5.vk, lib/ffi.vk, bindgen_cmd.vk): Searches VEKO_LIB before OS loader paths, dispatches up to 6 scalar/str/bytes arguments across Win64, SysV x86_64, and AAPCS64 static C-ABI trampolines, and parses header declarations into ready-to-import .vk wrapper modules via veko bindgen.
  4. Portable 'VFS2' Lazy SDK, Content-Addressed mod_v1 Cache & Decentralized veko-lang.org .vkp Registry (src/stdlib_vfs.vk, src/codegen.vk, lib/pkg/vkp.vk, lib/pkg/lock.vk): veko embeds all 95 lib/*.vk modules inside stdlib_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-cache forces cold recompilation). Imports resolve across workspace deps $\rightarrow$ VEKO_MODULES / ~/.veko_modules $\rightarrow$ VEKO_HOME/lib $\rightarrow$ embedded 'VFS2' VFS. veko pkg add fetches official packages from https://veko-lang.org/pkg/<name>/<ver>.vkp (or any custom https:// URL / VEKO_REGISTRY mirror) over pure-Veko TLS 1.3 (validating Ed25519, ECDSA P-256/P-384, and RSA chains against built-in public CA roots), pinning archive SHA-256, merkle_root, and Ed25519 / ML-DSA-65 signatures in veko.lock.
  5. 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, incremental os/pwrite page commits, multi-page 0x02/0x0a B-tree indexes, and INNER/LEFT JOIN) + homoiconic ORM, SplitMix64 structure-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).