veko-lang.org
Download Free EPUB 3.0

Part I · Language Foundations, Syntax, Cookbook & Tooling

Chapter 3

Complete Language Guide: Syntax, ORO Memory, Closures & Dialects

Slash refinements, universal /or, templates, Copy-on-Write ownership, zero nil, [T] generics, interfaces, and parse-block grammars

This guide introduces Veko's syntax, memory model, closures, homoiconicity, non-OOP composition patterns, and three execution backends.


1. Words, Refinements, and Pipelines

Veko eliminates outer parentheses and commas for normal function calls. Because every word has a fixed compile-time arity, expressions read cleanly from left to right:

VEKO
// Bindings use '=', strings use single quotes, durations and sizes are native literals
timeout = 5s
max-buf = 64kb
mode    = .tls

print 'starting sync'

Slash Refinements

Optional behavior never relies on positional boolean flags or multi-line option structs. Words expose slash refinements that extend static arity at the call site:

VEKO
use [h = net/http, j = json, s = strings, os]

// Base call takes 1 argument (url)
body = h/fetch 'https://example.com/peers'

// Adding /timeout extends static arity to 2 (url, duration)
body = h/fetch/timeout 'https://example.com/peers' 3s

// Universal /or handles errors inline without try/catch pyramids
body = h/fetch/timeout/or 'https://example.com/peers' 3s [
    log/warn 'using cached peer list'
    os/read-file 'peers.cache.json'
]

UFCS Dot-Chains and \ Pipes

  • Tight dot-chains (.) read struct/map fields (peer.endpoint) or chain 1-argument transforms (raw.trim.upper).
  • Pipes (\) inject the left-hand result as the first argument of the next multi-argument word:
VEKO
sync-peers = fn [endpoint out-path] [
    active-urls = h/fetch/timeout endpoint 5s
        \ j/decode
        \ filter fn [p] [p.active]
        \ map fn [p] [p.url.trim]

    os/write-file out-path (s/join active-urls '\n')
    active-urls.len
]

Arithmetic and Tight Indexing

Binary math and bitwise operators work with standard infix precedence when spaced cleanly:

VEKO
crc       = (crc >> 8) ^ table[(crc ^ b) & 0xff]
next-slot = (head + offset) & (cap - 1)
header    = packet[0..16]

2. Deterministic Memory Without a Garbage Collector (ORO + CoW)

MEMORY MODEL

ORO Single-Owner Memory: Borrow, Move, mut Loan & Copy-on-Write

Rust-grade deterministic cleanup and zero garbage collector pauses without lifetime annotations.

ZERO-COPY FAST PATH (RC == 1) 99% of calls & mutations SHARED SPLIT & SCOPE EXIT Cycle-free DAG + zeroize 16B header rc == 1 bind / return mut when rc > 1 scope exit old rc-- Allocation1. Create ValueSSO <=14B or Unique Slab Fast Call2. Read-Only CallZero-Cost Borrow In-Place Mutation3. Explicit mut Loanmut param + mut call site Move / Share4. Binding & ReturnOwnership Transfer Copy-on-Write5. Lazy CoW Splitensure_unique on rc > 1 Cleanup6. Deterministic DropFree-List + .secret Wipe
Component & ModuleArchitectural Role
1. Create Value
runtime.vk + native_rt.vk
Allocates scalars and <=14B strings/bytes inline in 16B Value; larger data gets rc=1 slab.
2. Read-Only Call
vko_emit.vk + native_emit.vk
Normal function parameters borrow the 16-byte Value header with zero refcount traffic.
3. Explicit mut Loan
types.vk + native_emit.vk
Mutates uniquely owned buffers, blocks, maps, and struct fields directly in place.
4. Binding & Return
oro_vm.vk + native_rt.vk
Rebinding or returning transfers ownership cleanly; aliasing increments non-atomic rc.
5. Lazy CoW Split
runtime.vk + native_rt.vk
Clones the backing slab only at the exact moment a shared container is mutated.
6. Deterministic Drop
runtime.vk + native_rt.vk
Reclaims dead slabs immediately at lexical scope exit or /or unwind.

Veko enforces One Reference Only (ORO) backed by Copy-on-Write (CoW):

  1. Plain Words Borrow for Free: Passing packet to log/debug packet lends read-only access for the call duration—zero copies and zero reference-count updates.
  2. = Moves Ownership: Assigning b = a transfers ownership to b and deterministically frees whatever b previously held.
  3. mut Mutates in Place: Functions may modify an argument in place only when both the parameter and call site carry mut:
VEKO
use [net, bytes, ascii]

echo-session = fn [mut conn] [
    defer [net/close/or mut conn []]

    // Allocated once; freed deterministically when echo-session returns
    mut buf = bytes/with-cap 4kb

    forever [
        n = net/read-into/or mut conn mut buf [break]
        if zero? n [break]

        ascii/trim-right! mut buf
        ascii/upper! mut buf
        bytes/push mut buf 10

        net/write/or mut conn buf [break]
    ]
]

Closures Without Reference Cycles

When a fn captures outer variables, those values move (or CoW-snapshot) into the closure's owned environment block:

VEKO
make-counter = fn [start] [
    fn [step] [
        start = start + step
        start
    ]
]

next-id = make-counter 100
print (next-id 1)   // 101
print (next-id 5)   // 106

Because each closure owns its private environment tree and recursive self-calls use an implicit recur/self word without storing the closure inside its own capture block, reference cycles cannot form.

Higher-Order Functions & Dynamic Closure Calls

Functions in Veko (fn [...] [...]) are first-class values that can be passed to combinators (filter, map, each, reduce), returned from factories, or stored inside capability records:

  • Static-arity bindings call directly: Top-level or local name = fn [a b] [...] bindings have known compile-time arity and call left-to-right without parentheses (name 1 2).
  • Dynamic closure values use (callee arg1 ...) or (f) / call: When invoking a function parameter, returned closure, or record callback whose arity is only known at runtime, wrap the call in parentheses ((next-id 1), (transport.read mut buf), or 0-arg (transport.flush) / call f). Note that spawn blocks reject capturing runtime closures across isolated workers.

"No nil" Discipline, Disjoint Field mut Loans & [T] Generics

Veko 1.0 eliminates nil completely so missing data never silently propagates:

  • Missing Lookups & Empty Pops Return err: map/get m k, m[k], m.k, json/get s k, and empty pop, first, or last return catchable err values handled explicitly with /or (host = map/get/or cfg 'host' ['127.0.0.1']).
  • Explicit .ok & .null Enums: Side-effect actions (print, log/*, time/sleep, net/close, chan/send, os/mkdir), one-armed if expressions, loops, and 0-arg return evaluate to .ok, while JSON null round-trips cleanly via .null (json/decode 'null' == .null).
  • Struct-Field mut Loans (mut ctx.field): Mutable struct bindings can lend disjoint fields directly in place (bytes/push mut state.buf 10, put mut state .count (state.count + 1)) while preserving Copy-on-Write snapshots automatically.
  • Parametric [T] Generics, sealed Structs & /internal/ Modules: Functions and structs support checker-level type parameters (id = fn [T] [x T] T [ x ], pub Box = sealed struct [T] { val T }), sealed struct restricts direct construction and mut field loans to the defining module, and pkg/internal/* modules are confined to importers under pkg/*.

3. Homoiconicity and Compile-Time Dialects

Everything inside [ ... ] is a live homoiconic block of typed values (words, paths, numbers, durations, sizes, enums, strings, and nested blocks).

  • quote [ ... ] preserves a block as unevaluated data.
  • compose [ ... ] walks a block and evaluates only expressions wrapped in ( ... ), avoiding Lisp backtick/comma punctuation soup.
  • parse-block matches structural token patterns (word!, enum!, str!, int!, dur!, block!) inside compile-time macro definitions to lower domain mini-languages directly into static code.

4. Intentional Non-OOP Design

Veko intentionally omits classes, inheritance, and mutable this object graphs because shared mutable identities break ORO determinism and opaque private fields break homoiconicity:

  • Closed Variants: Use tagged unions with match ev.kind [ .ping [...] .data [...] ].
  • Open Pluggability: Pass explicit capability records (Transport { read = fn [mut dst] [...], write = fn [src] [...] }) constructed from ORO closures.

5. Multi-File Modules & Private-by-Default Encapsulation

Veko separates local code organization from public module APIs without ambient filesystem searching or mutable global leaks:

  • Logical Module Paths Only: Imports (use [alias = lib/codec, crypto]) never mention ./, ../, OS path separators, or .vk extensions. Precedence resolves reserved built-ins (bytes, str, json, os, time, log, net, http), then project root, then declared deps in veko.vk.
  • Functions, Macros & Structs (pub / export): All top-level bindings are private by default. Export functions, compile-time macros, and struct schemas (pub encode = fn [...] [...], pub Endpoint = struct { ... }, or export [fn1 macro2 Endpoint]), while forbidding shared mutable globals across modules.
  • Single Diamond Initialization: Shared modules initialize once in topological order with isolated global namespaces, preventing cross-module name collisions even when private helper names match.

6. Shared-Nothing Concurrency & Cross-Backend Networking

Veko extends ORO ownership rules across threads cleanly:

  • Isolated spawn [ ... ] Tasks & Bounded Channels: Each spawned task executes inside its own private ORO arena (oro_vm.vk), isolated Wasm HostSandbox (codegen.vk), or private OS worker thread state (native_emit.vk / arm64_emit.vk). Capturing or mutating outer mut variables across spawn, or sending .secret, mut loans, or closures through chan/send, is rejected deterministically.
  • Explicit Network Capabilities: net/listen-tcp, net/connect-tcp, net/accept, net/read-bytes, net/read-into, net/write, net/write-string, net/resolve, UDP sockets, and the 11 net/poll-* / net/try-* readiness reactor primitives—along with pure-.vk net/dns, net/client, web, codec/http1, net/http2, net/websocket, and Hybrid PQC net/tls13—run across all three backends (oro_vm.vk, codegen.vk, and native_emit.vk / arm64_emit.vk), while host-bridged http/fetch and http/request run on --vm and --wasm. Under veko run (--vm and --wasm), networking stays disabled by default until authorized (--allow-net, --allow-listen, --allow-private-net), and all backends block .secret values on every network sink and enforce SSRF guards.

7. Gradual & Strict Types, O(1) Structs & Secret Flow Governance

Veko keeps zero-annotation scripting effortless while letting critical paths and shared module boundaries opt into static verification and unboxed execution:

  • Typed struct Schemas & struct/with: Define schemas with defaults (Upstream = struct { host str, port i64 = 443, api_key secret str = '' }), verify missing/unknown fields at compile time, read fields directly in O(1), and produce updated snapshots cleanly with primary \ struct/with { port = 8443 }.
  • Checked Narrowing & Runtime Guards: Use str/to-i64, str/to-f64, as-u8, as-i64, and as-f64 paired with /or instead of silent truncation; annotated functions (fn [factor u8, ep Upstream] i64 [...]) enforce runtime entry guards across Veko's execution backends.
  • veko check [--strict-types]: Validate cross-module types, mut borrows, and .secret sink policies statically before running or deploying; os/getenv/secret, redaction to <secret>, and deep .secret blocking on json/encode and os/write-file provide runtime defense in depth.

Designing Safe & Resilient Systems in Veko

Veko combines four built-in guarantees so everyday scripts and production services stay predictable under invalid input, concurrency, and resource pressure:

  • Memory Safe in Everyday .vk Code: Indexing and slicing on bytes, str, block, and struct values are bounds-checked (spatial safety), single-owner ORO + Copy-on-Write (CoW) prevents use-after-free, double-free, and cyclic leaks without GC pauses (temporal safety), and spawn forbids sharing mutable references or closures across threads (data-race freedom).
  • Explicit Error & Cleanup Paths: Division/modulo by zero (/ 0, % 0), integer/float parsing (str/to-i64, str/to-f64), and range narrowing (as-u8) raise catchable /or errors instead of silently truncating or crashing the process. Pair /or with LIFO defer so files, sockets, and buffers always clean up cleanly along both normal and error paths.
  • Schema & Capability Discipline: Enforce required fields and defaults in struct definitions, apply immutable snapshots with struct/with, load credentials via os/getenv/secret (automatic <secret> redaction, egress blocking, and zero-wipe on free), and declare explicit allow-caps in veko.vk audited with veko check --strict-types and veko inspect --modules.

8. Choosing Your Execution Backend

Veko compiles the same .vk source language across three backends—each built for a distinct purpose:

  1. 64-Bit VKO Bytecode VM (--vm / .vko): Created for instant script execution, the interactive veko repl, dynamic eval, and precompiled 64-bit VKO distribution. Ideal for everyday development, doctests, and rapid iteration.
  2. WebAssembly 3.0 Sandbox (--wasm via vvm): Created for zero-trust, portable sandboxing. Compiles .vk programs to validated Wasm 3.0 with unboxed i64/f64 loops and runs inside vvm's HostSandbox with explicit --fuel, --mem-pages, --allow-fs, --allow-hosts, and --check-slabs leak verification.
  3. Native x86_64 & AArch64 (--native via veko): Created for standalone Windows (--target=win-x64 and --target=win-arm64 0xAA64 PE32+, with optional --gui), Linux (--target=linux-x64 and --target=linux-arm64 static ELF64 via direct syscalls), and macOS Apple Silicon (--target=macos-arm64 16 KiB Mach-O + SHA-256 LC_CODE_SIGNATURE) executables with zero external C compiler, LLVM, or OpenSSL dependencies. Emits register-allocated native loops, CPUID AVX2/SSE2/AES-NI bulk operations, 12-bucket ORO slab recycling, OS-native readiness reactors (epoll/kqueue/IOCP), full DNS/TCP/UDP/TLS 1.3 networking (net/dns, net/client, web), and opt-in .ffi C-ABI shared library interop.