veko
ORO Homoiconic Language • Custom VM • Wasm 3.0 (vvm) • Native x86_64 & arm64

Full Veko Language Tutorial

This hands-on tutorial walks through everything you can write and run in Veko today using veko check, veko run, veko compile, veko repl, and veko inspect.


Lesson 1: Running Programs, Inspecting Code, and the REPL

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.

Interactive SVG • Click any node (6 components)
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 Lexer 4 Whitespace Rules [tight] vs [spaced] bits Lexer First-Class Literals 5s, 64kb, 0xFF, '...' Parser Pass 1 Pass 1: Signature Scan fn / struct / def / use Parser Pass 2 Pass 2: Pratt Precedence BP 80 postfix .. BP 10 pipe Homoiconicity quote & compose Code-as-Data Templates Dialects parse-block Dialects Embedded Domain Grammars
Components:
Lexer
4 Whitespace Rules
lexer.vk
Component 1 of 6
Architectural Role & Purpose

Eliminates grammar ambiguity using single-character attachment flags.

Contextual Description & System Interaction

Inspect exact attachment flags anytime with veko inspect --tokens.

Core Functionality & Mechanics
  • n - 1 (subtraction) vs n-1 (kebab word) vs -1 (negative literal)
  • a / b (division) vs str/join (module path) vs /or (refinement)
  • buf[0..n] & s.trim (tight postfix) vs .tls (spaced enum)
Lexer
First-Class Literals
lexer.vk
Component 2 of 6
Architectural Role & Purpose

Parses human-readable durations, binary sizes, hex/binary ints, and UTF-8 strings.

Contextual Description & System Interaction

Eliminates magic numbers in network timeouts and buffer capacities.

Core Functionality & Mechanics
  • Durations scale to i64 nanoseconds (500ms, 3s, 2m)
  • Binary sizes scale by powers of 1024 (64b, 4kb, 16mb)
  • Single-quoted UTF-8 strings avoid JSON double-quote escaping
Parser Pass 1
Pass 1: Signature Scan
parser.vk
Component 3 of 6
Architectural Role & Purpose

Collects top-level function arities, refinements, structs, and module imports.

Contextual Description & System Interaction

Makes parentheseless prefix calls deterministic without forward declarations.

Core Functionality & Mechanics
  • Enables order-independent top-level mutually recursive functions
  • Computes exact call arity (+1 for /or or value refinements)
  • Registers macro definitions before Pass 2 expression parsing
Parser Pass 2
Pass 2: Pratt Precedence
parser.vk
Component 4 of 6
Architectural Role & Purpose

Binds tight postfix chains, prefix word arguments, infix math, comparisons, and \ pipes.

Contextual Description & System Interaction

Ensures expressions like a + b == c and raw \ json/decode read naturally.

Core Functionality & Mechanics
  • BP 80: tight .field, .ufcs, and [idx] / [lo..hi] slicing
  • BP 60..30: * / % >>> & then + - | ^ then == != < <= > >=
  • BP 10: left-to-right \ pipe feeds result as arg 1 of next word
Homoiconicity
quote & compose
macro_eval.vk
Component 5 of 6
Architectural Role & Purpose

Treats [ ... ] blocks as inspectable values and splices computed expressions cleanly.

Contextual Description & System Interaction

Delivers Lisp-grade metaprogramming without parentheses or backtick clutter.

Core Functionality & Mechanics
  • quote [ ... ] returns unevaluated token/value blocks
  • compose evaluates only parenthesized (expr) slots
  • macro transforms raw argument blocks at compile time
Dialects
parse-block Dialects
parser.vk lib/dialect.vk
Component 6 of 6
Architectural Role & Purpose

Matches typed pattern rules over homoiconic blocks to drive custom DSLs.

Contextual Description & System Interaction

Lets teams craft readable domain dialects without writing external parsers.

Core Functionality & Mechanics
  • Matches literals, typed captures, enums, and nested sub-blocks
  • Powers firewall rules, SQL-like queries, and vault ACL policies
  • Runs identically on VM, Wasm 3.0, and Native binaries

Start by running an existing example or opening the interactive ORO REPL:

POWERSHELL
# Run a Veko script on the ORO bytecode VM
veko run examples/01_basics_and_math.vk

# Inspect lexer tokens, Pratt AST, or compiled 64-bit VKO bytecode
veko inspect --tokens examples/01_basics_and_math.vk
veko inspect --ast examples/01_basics_and_math.vk
veko inspect --bytecode examples/hello.vk

# Start the interactive REPL
veko repl

Inside veko repl, bindings persist across lines, multi-line [ ... ] and { ... } blocks balance automatically, and built-in REPL commands let you watch ORO memory live:

  • :stats prints live_slabs, globals, and compiled fns count.
  • :reset clears all globals and slabs back to a clean VM.
  • :quit exits the REPL.

Lesson 2: Bindings, Rich Literals, Math, and Slicing

Veko keeps everyday code on unshifted keys: = binds values, '...' defines UTF-8 strings, .word creates enum symbols, and durations/sizes are native literals (1024-based for byte sizes):

VEKO
// examples/01_basics_and_math.vk
title   = 'Veko Basics'
timeout = 250ms
buf-cap = 4kb
proto   = .tcp

// Spaced infix arithmetic & bitwise ring-buffer indexing
head = 12
offset = 7
cap = 16
next-slot = (head + offset) & (cap - 1)   // 3

// Ranges & tight slicing
nums = 1..=5                              // [1 2 3 4 5]
sub  = nums[1..4]                         // [2 3 4]

// Mutable loop state
mut i = 0
mut sum = 0
while i < 5 [
    i = i + 1
    sum = sum + i
]
println sum                               // 15

unless zero? sum [
    println 'sum-nonzero'
]

Important Spacing Rule: Always put spaces around binary - and / (cap - 1, total / count) so the lexer does not treat them as kebab-case words (read-into) or module paths (str/trim).


Lesson 3: Pipes, UFCS Dot-Chains, JSON, and match

Because every word has a fixed compile-time arity, pipelines flow cleanly from left to right without nested parentheses. Use \ pipes to pass a value as the first argument to the next multi-argument word, and tight . chains for field access or 1-argument transforms:

VEKO
// examples/02_pipelines_and_json.vk
use [j = json, s = strings]

payload = '[{"name": " alpha ", "score": 90, "active": true}, {"name": " beta ", "score": 40, "active": false}, {"name": " gamma ", "score": 85, "active": true}]'

names = payload
    \ j/decode
    \ filter fn [item] [item.active]
    \ map fn [item] [item.name.trim.upper]

println (s/join names ' | ')    // ALPHA | GAMMA

scores = payload
    \ j/decode
    \ filter fn [item] [item.active]
    \ map fn [item] [item.score]

total = reduce scores 0 fn [acc x] [acc + x]
println total                   // 175.0

ev = { kind = .ready, code = 200 }
status-msg = match ev.kind [
    .starting ['booting']
    .ready    ['serving']
    _         ['unknown']
]
println status-msg              // serving

Lesson 4: ORO Buffers, Secrets, defer, /or, and recur

Veko gives you deterministic zero-GC memory through One Reference Only (ORO) rules:

  • bytes/with-cap allocates a reusable byte slab once; mut loans mutate it in place with zero reallocations.
  • bytes/with-secret marks a slab with flag_secret so its contents are overwritten with zero bytes the moment its scope exits.
  • defer [ ... ] runs cleanup blocks in LIFO order when the enclosing function returns.
  • /or [ ... ] catches errors inline on any fallible call (str/index-of/or, os/read-file/or, net/http/fetch/or; note that pure-.vk codec/http1 + net/* works identically across all three tracks including --native).
  • recur performs constant-stack tail recursion back to the top of the current fn.
VEKO
// examples/03_oro_buffers_and_errors.vk
use [bytes, ascii, str]

pkt = bytes/with-cap 4kb
bytes/push-all mut pkt (bytes/from-str '  ping trustnode  ')
ascii/trim-right! mut pkt
ascii/upper! mut pkt
bytes/push mut pkt 33
println (str/from-bytes pkt)      //   PING TRUSTNODE!

use-secret = fn [label] [
    secret = bytes/with-secret 64b
    bytes/push-all mut secret (bytes/from-str 'ephemeral-session-key')
    println (str/append label ':secret-ready')
    secret.len
]
println (use-secret 'auth')       // 21 (and secret slab zeroed on return)

safe-find = fn [hay needle] [
    defer [println 'cleanup-done']
    str/index-of/or hay needle [-1]
]
println (safe-find 'veko-oro-vm' 'oro')      // 5, then cleanup-done
println (safe-find 'veko-oro-vm' 'missing')  // -1, then cleanup-done

gcd = fn [a b] [
    if zero? b [return a]
    recur b (a % b)
]
println (gcd 84 36)               // 12

Lesson 5: Homoiconicity, compose, parse-block, and Macros

Code inside [ ... ] is a live homoiconic list of words, numbers, enums, durations, strings, and nested blocks:

VEKO
// examples/04_macros_and_dialects.vk
spec = quote [route .tcp '10.0.0.0/8' 8443 30s]
println spec.len            // 5
println (type-of spec[1])   // .enum_sym
println spec[4]             // 30s

port = 9000
tls-mode = .strict
server-cfg = compose/deep [
    bind '127.0.0.1' (port)
    policy [mode (tls-mode) timeout 15s]
]
println (mold server-cfg)   // [bind '127.0.0.1' 9000 policy [mode .strict timeout 15s]]

mut endpoints = []
parsed-ok = parse-block (quote [allow .tcp '10.1.0.0/16' 443 allow .udp '10.2.0.0/16' 51820]) [
    any [
        ['allow' proto = enum! cidr = str! p = int!] [
            push mut endpoints (compose [(proto) (cidr) (p)])
        ]
    ]
]
println parsed-ok           // true
println (mold endpoints)    // [[.tcp '10.1.0.0/16' 443] [.udp '10.2.0.0/16' 51820]]

triple = macro [x] [
    compose [(x) + (x) + (x)]
]
println (triple 14)         // 42

Lesson 6: Stateful Closures & Capability Records (No OOP Needed)

Closures capture outer variables into their own private ORO slab—making stateful generators cycle-free and giving you clean runtime polymorphism via explicit records of closures:

VEKO
// examples/05_closures_and_capabilities.vk
use [str]

make-seq = fn [start] [
    mut cur = start
    fn [step] [
        out = cur
        cur = cur + step
        out
    ]
]

next-port = make-seq 8000
println (next-port 10)   // 8000
println (next-port 10)   // 8010
println (next-port 10)   // 8020

make-logger = fn [prefix] [
    {
        info  = fn [msg] [println (str/append prefix msg)]
        warn  = fn [msg] [println (str/append '[WARN] ' msg)]
        flush = fn []    [println (str/append prefix 'flushed')]
    }
]

app-log = make-logger '[veko] '
log-info = app-log.info
log-warn = app-log.warn
(log-info 'initialized') // [veko] initialized
(log-warn 'cache-miss')  // [WARN] cache-miss
call app-log.flush       // [veko] flushed

Lesson 7: Multi-File Projects, pub/export, and veko.vk Manifests

As programs grow, split reusable helpers across logical modules without OS paths or circular imports. Everything in a module stays private by default; export only functions or compile-time macros using pub or export [...]:

VEKO
// src/lib/codec.vk
salt = 7
mask = fn [x] [x ^ salt]       // private helper (cannot be called externally)

pub encode = fn [x] [mask (x * 3)]
wrap-add = macro [a b] [compose [(a) + (b)]]
export [wrap-add]

Add an optional homoiconic veko.vk manifest in your project folder to declare the source root, external dependencies, and least-privilege capability limits:

VEKO
// veko.vk
{
  name = 'edge-app'
  root = 'src'
  allow-caps = [.fs]
}

Then import modules by logical name in your entry file, audit capabilities, and run identically on ORO VM, .vko, WebAssembly 3.0, or standalone native x86_64 & AArch64:

VEKO
// src/main.vk
use [c = lib/codec]
println (c/encode 4)       // 11
println (c/wrap-add 20 22) // 42
println (4 \ c/encode)     // 11
POWERSHELL
# Audit module DAG, exported arities, and effective capabilities
veko inspect --modules src/main.vk

# Run identically across ORO VM, compiled .vko bytecode, Wasm 3.0, or native x86_64 & arm64
veko run src/main.vk
veko compile --vko src/main.vk -o dist/app.vko
veko run dist/app.vko
veko run --wasm src/main.vk
veko run --native src/main.vk
veko compile --native src/main.vk -o dist/app.exe
./dist/app.exe
# Or cross-compile standalone Windows ARM64, Linux x86_64, Linux ARM64, or macOS Apple Silicon binaries
veko compile --native --target=win-arm64   src/main.vk -o dist/app_win_arm64.exe
veko compile --native --target=linux-x64   src/main.vk -o dist/app_lx64
veko compile --native --target=linux-arm64 src/main.vk -o dist/app_arm64
veko compile --native --target=macos-arm64 src/main.vk -o dist/app_macos

Lesson 8: Shared-Nothing Concurrency & Guarded Networking

Veko pairs isolated spawn [ ... ] workers with bounded ownership-transfer channels (chan/*) and guarded networking across host OS sockets (--vm), wasi:sockets@0.3.0 / wasi:http@0.3.0 (--wasm), and native WinSock2 / Linux / macOS sockets (--native)—blocking mutable aliasing, data races, .secret network leaks, and SSRF by construction:

VEKO
ch = chan/new 4

worker = spawn [
    chan/send ch 'ready-from-worker'
    42
]

msg = chan/recv ch
res = task/await worker
chan/close ch
println msg   // ready-from-worker
println res   // 42

When running network clients or local servers, grant least-privilege flags explicitly (--allow-net, --allow-listen, --allow-private-net) on veko run (applies to both --vm and --wasm), and declare allow-caps = [.net] inside veko.vk. Standalone --native binaries execute directly as OS processes with .secret egress blocks still enforced at runtime.


Lesson 9: Typed Structs, veko check, Checked Conversions & Secrets

Opt into static types incrementally with struct { ... }, interface { ... }, parameter/return annotations, secret field qualifiers, and checked numeric/string conversions—preserving clean /or fallbacks and cross-backend speed:

VEKO
Upstream = struct {
    name    str
    host    str
    port    i64 = 443
    api_key secret str = ''
}

score-samples = fn [ep Upstream, factor u8, n i64] i64 [
    mut acc = 0
    mut i = 0
    while i < n [
        acc = acc + factor + i
        i = i + 1
    ]
    acc + ep.port
]

parsed-port = str/to-i64/or '8443' [443]
weight      = as-u8/or 12 [as-u8 0]
tok         = os/getenv/secret/or 'API_KEY' ['local-dev-key']

u1 = Upstream { name = 'edge-us', host = 'api.veko.local', api_key = tok }
u2 = u1 \ struct/with { port = parsed-port }
println (score-samples u2 weight 5000)
POWERSHELL
# Static type + secret taint verification across modules
veko check examples/12_typed_structs_and_secrets.vk
veko check --strict-types examples/12_typed_structs_and_secrets.vk

# Execute identically on ORO VM, Wasm 3.0 (unboxed math loops), or native x86_64 / arm64
veko run examples/12_typed_structs_and_secrets.vk
veko run --wasm examples/12_typed_structs_and_secrets.vk
veko run --native examples/12_typed_structs_and_secrets.vk
veko compile --native examples/12_typed_structs_and_secrets.vk -o dist/12.exe
./dist/12.exe
veko compile --native --target=linux-x64   examples/12_typed_structs_and_secrets.vk -o dist/12
veko compile --native --target=linux-arm64 examples/12_typed_structs_and_secrets.vk -o dist/12_arm64

Next Steps

Continue along the End-User reading path: