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:
// 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:
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:
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:
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)
ORO Single-Owner Memory: Borrow, Move, mut Loan & Copy-on-Write
Rust-grade deterministic cleanup and zero garbage collector pauses without lifetime annotations.
| Component & Module | Architectural Role |
|---|---|
1. Create Valueruntime.vk + native_rt.vk | Allocates scalars and <=14B strings/bytes inline in 16B Value; larger data gets rc=1 slab. |
2. Read-Only Callvko_emit.vk + native_emit.vk | Normal function parameters borrow the 16-byte Value header with zero refcount traffic. |
3. Explicit mut Loantypes.vk + native_emit.vk | Mutates uniquely owned buffers, blocks, maps, and struct fields directly in place. |
4. Binding & Returnoro_vm.vk + native_rt.vk | Rebinding or returning transfers ownership cleanly; aliasing increments non-atomic rc. |
5. Lazy CoW Splitruntime.vk + native_rt.vk | Clones the backing slab only at the exact moment a shared container is mutated. |
6. Deterministic Dropruntime.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):
- Plain Words Borrow for Free: Passing
packettolog/debug packetlends read-only access for the call duration—zero copies and zero reference-count updates. =Moves Ownership: Assigningb = atransfers ownership toband deterministically frees whateverbpreviously held.mutMutates in Place: Functions may modify an argument in place only when both the parameter and call site carrymut:
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:
make-counter = fn [start] [
fn [step] [
start = start + step
start
]
]
next-id = make-counter 100
print (next-id 1) // 101
print (next-id 5) // 106Because 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 thatspawnblocks 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 emptypop,first, orlastreturn catchableerrvalues handled explicitly with/or(host = map/get/or cfg 'host' ['127.0.0.1']). - Explicit
.ok&.nullEnums: Side-effect actions (print,log/*,time/sleep,net/close,chan/send,os/mkdir), one-armedifexpressions, loops, and 0-argreturnevaluate to.ok, while JSONnullround-trips cleanly via.null(json/decode 'null' == .null). - Struct-Field
mutLoans (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,sealedStructs &/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 structrestricts direct construction andmutfield loans to the defining module, andpkg/internal/*modules are confined to importers underpkg/*.
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-blockmatches structural token patterns (word!,enum!,str!,int!,dur!,block!) inside compile-timemacrodefinitions 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.vkextensions. Precedence resolves reserved built-ins (bytes,str,json,os,time,log,net,http), then projectroot, then declareddepsinveko.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 { ... }, orexport [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 WasmHostSandbox(codegen.vk), or private OS worker thread state (native_emit.vk/arm64_emit.vk). Capturing or mutating outermutvariables acrossspawn, or sending.secret,mutloans, or closures throughchan/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 11net/poll-*/net/try-*readiness reactor primitives—along with pure-.vknet/dns,net/client,web,codec/http1,net/http2,net/websocket, and Hybrid PQCnet/tls13—run across all three backends (oro_vm.vk,codegen.vk, andnative_emit.vk/arm64_emit.vk), while host-bridgedhttp/fetchandhttp/requestrun on--vmand--wasm. Underveko run(--vmand--wasm), networking stays disabled by default until authorized (--allow-net,--allow-listen,--allow-private-net), and all backends block.secretvalues 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
structSchemas &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 withprimary \ struct/with { port = 8443 }. - Checked Narrowing & Runtime Guards: Use
str/to-i64,str/to-f64,as-u8,as-i64, andas-f64paired with/orinstead 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,mutborrows, and.secretsink policies statically before running or deploying;os/getenv/secret, redaction to<secret>, and deep.secretblocking onjson/encodeandos/write-fileprovide 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
.vkCode: Indexing and slicing onbytes,str,block, andstructvalues 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), andspawnforbids 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/orerrors instead of silently truncating or crashing the process. Pair/orwith LIFOdeferso files, sockets, and buffers always clean up cleanly along both normal and error paths. - Schema & Capability Discipline: Enforce required fields and defaults in
structdefinitions, apply immutable snapshots withstruct/with, load credentials viaos/getenv/secret(automatic<secret>redaction, egress blocking, and zero-wipe on free), and declare explicitallow-capsinveko.vkaudited withveko check --strict-typesandveko inspect --modules.
8. Choosing Your Execution Backend
Veko compiles the same .vk source language across three backends—each built for a distinct purpose:
- 64-Bit
VKOBytecode VM (--vm/.vko): Created for instant script execution, the interactiveveko repl, dynamiceval, and precompiled 64-bitVKOdistribution. Ideal for everyday development, doctests, and rapid iteration. - WebAssembly 3.0 Sandbox (
--wasmviavvm): Created for zero-trust, portable sandboxing. Compiles.vkprograms to validated Wasm 3.0 with unboxedi64/f64loops and runs insidevvm'sHostSandboxwith explicit--fuel,--mem-pages,--allow-fs,--allow-hosts, and--check-slabsleak verification. - Native x86_64 & AArch64 (
--nativeviaveko): Created for standalone Windows (--target=win-x64and--target=win-arm640xAA64PE32+, with optional--gui), Linux (--target=linux-x64and--target=linux-arm64static ELF64 via direct syscalls), and macOS Apple Silicon (--target=macos-arm6416 KiB Mach-O + SHA-256LC_CODE_SIGNATURE) executables with zero external C compiler, LLVM, or OpenSSL dependencies. Emits register-allocated native loops, CPUIDAVX2/SSE2/AES-NIbulk 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.ffiC-ABI shared library interop.