veko-lang.org
Download Free EPUB 3.0

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

Veko Language and Runtime
Veko Language and Runtime

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.

UNIFIED COMPILER & RUNTIMES

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.

SHARED PURE-VEKO FRONTEND lexer.vk + parser.vk + macro_eval.vk + types.vk 79-MODULE PURE-VEKO STDLIB lib/* (shared across all 3 tracks) TRACK A: 64-BIT VKO VM vko_emit.vk + oro_vm.vk TRACK B: WASM 3.0 SANDBOX codegen.vk + runtime*.vk + vvm TRACK C: NATIVE X86_64 & AARCH64 native_emit.vk + arm64_emit.vk Tokens + tight RawBlock Expanded AST use DAG 64-bit VKO PAL calls Typed AST .wasm Typed AST Machine code FrontendWhitespace Lexer[tight] vs [spaced] FrontendTwo-Pass Pratt Parserarity scan + BP 80..0 MetaprogrammingHomoiconic Dialect Passquote / compose / parse-block Static AnalysisGradual Types & Capstypes.vk + .secret audit Standard Library79-Module Standard LibraryPQC + Reactor + Web + DB + UI Track A64-Bit VKO Bytecode VMsuperinstructions + REPL Track A HostGuarded VM Host PALVmPolicy + offscreen UI Track BWasm 3.0 Code Generatorlinear-RAM ORO + bulk mem Track B Hostvvm Zero-Trust SandboxWASI 0.3 + fuel + SSRF guard Track Cx86_64 & AArch64 AOTSIMD + 79-group DCE Track C LinkersPE32+ / ELF64 / Mach-Owin-x64, linux, macos-arm64
Component & ModuleArchitectural Role
Whitespace Lexer
lexer.vk
Tokenizes kebab-case words, slash paths, enums, unit literals, and attachment flags.
Two-Pass Pratt Parser
parser.vk
Resolves top-level arities and module aliases in Pass 1, then builds the AST in Pass 2.
Homoiconic Dialect Pass
macro_eval.vk
Expands compile-time macros and structural block dialects before code generation.
Gradual Types & Caps
types.vk
Checks gradual/strict types, generics [T], mut loans, .secret sinks, and veko.vk allow-caps.
79-Module Standard Library
lib/*
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 VM
vko_emit.vk + oro_vm.vk
Executes fixed-width 64-bit VKO instructions, interactive REPL sessions, and .vko bundles.
Guarded VM Host PAL
oro_vm.vk
Enforces runtime capability flags (--allow-fs, --allow-net) and .secret sink checks.
Wasm 3.0 Code Generator
codegen.vk + wasm_enc.vk
Emits standalone WebAssembly 3.0 modules with embedded 12-bucket ORO slab allocators.
vvm Zero-Trust Sandbox
runtime*.vk
Runs Wasm modules under deterministic fuel quotas, memory caps, and host sandboxes.
x86_64 & AArch64 AOT
native_emit.vk + arm64_emit.vk
Compiles directly to native x86_64 and ARM64 machine code with zero external toolchain.
PE32+ / ELF64 / Mach-O
pe_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.vkSingle-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.vkGradual 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.vkZero-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.vk3-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.vkFixed-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*.vkLogical 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*.vkDirect 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.vkDirect 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 VKO Bytecode VM (oro_vm.vk + vko_emit.vk):
    • Purpose: Instant developer iteration, interactive veko repl, dynamic runtime eval, deterministic call-frame profiling (--profile / --flamegraph), and portable 64-bit .vko execution.
    • Pipeline: Compiles ASTs into fixed-width 64-bit VKO words (op:u8 | flags:u8 | a:u16 | bx:u32), shakes unreachable imported functions, executes frames with LIFO defer and TRY_OR /or recovery, and enforces VmPolicy host capability guards.
  • 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, unboxed i64/f64 loops, 12-bucket linear-memory ORO free-lists) executing inside vvm's HostSandbox with WASI 0.3, --fuel metering, --mem-pages caps, content-hashed .veko_cache/<hash>.wasm caching, and shared-memory HTML5 <canvas> presentation in browsers.
  • 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), and macos-arm64 (Mach-O) with zero external C/LLVM toolchains or crypto DLLs.
    • Pipeline: Lowers 64-bit VKO IR via leaf inlining, devirtualization, KindMask scalar/escape retain-release elision, unboxed i64/f64 loop lowering, callee-saved regalloc (RBX/RBP/RSI/RDI, XMM6..XMM9, X19..X28), CPUID SIMD/AES-NI dispatch, and dead-helper worklist pruning.

2. Whitespace-Aware Lexing, Desugaring & Two-Pass Pratt Parsing

SYNTAX & HOMOICONICITY

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.

LEXICAL DISAMBIGUATION lexer.vk TWO-PASS PRATT ENGINE parser.vk HOMOICONIC EVALUATION macro_eval.vk + lib/dialect.vk Token stream Typed literals Arity table AST + RawBlock Block values Lexer4 Whitespace Rules[tight] vs [spaced] bits LexerFirst-Class Literals5s, 64kb, 0xFF, '...' Parser Pass 1Pass 1: Signature Scanfn / struct / def / use Parser Pass 2Pass 2: Pratt PrecedenceBP 80 postfix .. BP 10 pipe Homoiconicityquote & composeCode-as-Data Templates Dialectsparse-block DialectsEmbedded Domain Grammars
Component & ModuleArchitectural Role
4 Whitespace Rules
lexer.vk
Eliminates grammar ambiguity using single-character attachment flags.
First-Class Literals
lexer.vk
Parses human-readable durations, binary sizes, hex/binary ints, and UTF-8 strings.
Pass 1: Signature Scan
parser.vk
Collects top-level function arities, refinements, structs, and module imports.
Pass 2: Pratt Precedence
parser.vk
Binds tight postfix chains, prefix word arguments, infix math, comparisons, and \ pipes.
quote & compose
macro_eval.vk
Treats [ ... ] blocks as inspectable values and splices computed expressions cleanly.
parse-block Dialects
parser.vk + lib/dialect.vk
Matches typed pattern rules over homoiconic blocks to drive custom DSLs.

Lexical Disambiguation Rules

  1. Slash (/): Tight internal attachment (net/read-into/or) builds a module/refinement path; leading /port in parameter lists declares an optional refinement; spaced / lexes as binary division (total / count).
  2. Dot (.): Tight attachment after an expression (node.url.trim) lexes as UFCS/field dot_chain; spaced . or . after [/(/{/, lexes as enum_lit (.tls, .ok).
  3. Hyphen (-): Inside words (read-into, sha-256) it continues the kebab-case identifier; spaced - before a digit lexes as negative int_lit (-1); spaced - before alpha/(/[ lexes as unary_neg; otherwise it lexes as binary minus (a - b).
  4. Left Bracket ([): Tight after an expression (table[i], buf[0..n]) lexes as postfix index/slice; spaced [ opens a homoiconic code or data block.
  5. Backtick Templates (`...`): Lexes interpolated segments {expr} with balanced nested braces, lowering into type-safe formatting chains that automatically preserve .secret taint if any interpolated expression is secret.

Two-Pass Resolution & Desugaring

  • Pass 1 (scan-top-level-headers): Walks tokens once to register fn/macro positional arities, user /refinement descriptors and defaults, interface contracts, def aliases, and use module prefix mappings, enabling order-independent top-level calls.
  • Pass 2 (parse-expr) & desugar.vk: Applies Pratt binding powers (80 tight postfix > 70 prefix calls & unary > 60 * / % << >> >>> & > 50 + - ^ | > 40 .. ..= > 30 comparisons > 20 and or > 10 \ pipes > 0 statements), desugaring [a b] / { host, port } destructuring, 2-variable for [i x] / for [k v] loops, structural match, and compile-time embed-str / embed-bytes confinement checks before backend emission.

3. Homoiconicity, Closures & Universal /or Unwinding

  • Dual RawBlock Capture: Every [ ... ] block preserves its exact RawBlock token tree alongside parsed statements so quote, compose, macro, and parse-block inspect typed homoiconic tokens directly.
  • Universal /or Error Handling: Every builtin and user-defined function automatically supports /or [fallback] and error-binding /or [e -> fallback].
    • 64-Bit VKO VM (oro_vm.vk): Pushes TRY_OR handler frames (recording optional err_slot) and runs LIFO DEFER_PUSH blocks before jumping to the inline handler.
    • Wasm 3.0 (codegen.vk): Lowers /or to structured Wasm 3.0 try_table + throw exception tags with shadow-frame cleanup.
    • Native x86_64 & AArch64 (native_emit.vk + arm64_emit.vk): Pushes unwind records onto per-thread RT-TRY-TOP, isolating outer error registers across nested defer cleanups.

4. Self-Hosting Fixed-Point Convergence

SELF-HOSTING 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.

UNIFIED PURE-VEKO SOURCE src/ (39) + lib/ (79) DETERMINISTIC BOOTSTRAP CHAIN Reproducible S1 == S2 Proof Compile S1 Same source S1 builds S2 SHA-256 Bit-equal! Source TreeSelf-Hosted Source39 src/*.vk + 79 lib/*.vk Stage 1Stage 1 Compiler (S1)veko compile --native src/main.vk Stage 2Stage 2 Compiler (S2)S1 compiles src/main.vk -> S2 Release GateBit-Identical Fixed PointSHA-256(S1) == SHA-256(S2)
Component & ModuleArchitectural Role
Self-Hosted Source
src/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 Point
build.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:

  1. Stage 1 (S1) compiles src/main.vk (77 compiler modules + transitive lib/ dependencies) into a standalone native binary.
  2. Stage 2 (S2) uses S1 to recompile the exact same source graph.
  3. Byte-for-byte SHA-256(S1) == SHA-256(S2) fixed-point identity verifies deterministic code generation, constant interning, register allocation, and binary linking across PE32+, ELF64, Mach-O, Wasm 3.0, and VKO.

5. Shared-Nothing Concurrency, Readiness Reactor & Desktop .ui PAL

SHARED-NOTHING CONCURRENCY

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.

PARENT TASK HEAP Thread-Local ORO Arena #0 MESSAGE-PASSING BROKER Bounded chan/* + task/await ISOLATED WORKER HEAP Thread-Local ORO Arena #N Immutable captures Boot worker chan/send / return chan/recv / await CallerParent Taskspawn [ ... ] BoundaryDeep-Frozen CaptureAcyclic Value Snapshot CoordinationBounded chan/* & selectsend / recv / timeout / select WorkerIsolated Worker ThreadCreateThread / clone / pthread
Component & ModuleArchitectural Role
Parent Task
vko_emit.vk + native_pal3.vk
Spawns isolated concurrent tasks and coordinates results via channels or task/await.
Deep-Frozen Capture
runtime_net_conc.vk + native_pal3.vk
Deep-copies captured immutable values into the worker's independent slab allocator.
Bounded chan/* & select
oro_vm.vk + native_pal3.vk
Transfers deep-copied message values across bounded FIFO queues with backpressure.
Isolated Worker Thread
native_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 isolated vvm HostSandbox stores 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 Linux epoll + eventfd2, macOS kqueue + EVFILT_USER, Windows IOCP + WSAPoll, and WASI net-poll.
  • Cross-Platform .ui Desktop & Browser Surface (lib/ui.vk, lib/ui/widgets.vk, lib/ui/wayland.vk, lib/ui/x11.vk):
    • Windows (win-x64): Win32 StretchDIBits top-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-libc Wayland (memfd_create + SCM_RIGHTS wl_shm ARGB8888 + xdg_toplevel) and zero-libc X11R6 (/tmp/.X11-unix/X<n>, .Xauthority MIT-MAGIC-COOKIE-1, scanline-band PutImage <= 128 KB), cascading automatically with headless fallback.
    • macOS Apple Silicon (macos-arm64): Conditional AppKit/CoreGraphics NSApplication + NSWindow + Retina backingScaleFactor (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.

(See Detailed Technical Overview, Safety & ORO Memory Model, and Requirements & Decisions for instruction encodings, ABI layouts, and complete ADR records.)