Part VI · Complete Annotated Examples & Showcase Applications
Appendix C.1
Complete Examples Catalog: Introductory Tours & Examples 01–12
Unabridged listings covering syntax, pipelines, ORO buffers, macros, closures, concurrency, modules, and typed structs
Every listing in Appendix C is a complete, unabridged .vk program from examples/ verified across Veko execution tracks.
Quickstart Tour: JSON & UFCS Pipelines (examples/hello.vk)
Run command: veko examples/hello.vk
Runnable Veko tour: pipes, UFCS dot-chains, closures, and JSON Track A (.vko) : veko compile --vko examples/hello.vk -o dist/hello.vko ; veko run dist/hello.vko Track C (Native) : veko compile --native examples/hello.vk -o dist/hello.exe ; ./dist/hello.exe Self-host (veko1): veko compile --vko bootstrap/veko1/src/main.vk -o dist/veko1.vko ; veko run dist/veko1.vko -- --vko examples/hello.vk -o dist/hello_s1.vko
1 │ // Runnable Veko tour: pipes, UFCS dot-chains, closures, and JSON
2 │ // Track A (ORO VM) : veko run examples/hello.vk
3 │ // Track A (.vko) : veko compile --vko examples/hello.vk -o dist/hello.vko ; veko run dist/hello.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/hello.vk
5 │ // Track C (Native) : veko compile --native examples/hello.vk -o dist/hello.exe ; ./dist/hello.exe
6 │ // Self-host (veko1): veko compile --vko bootstrap/veko1/src/main.vk -o dist/veko1.vko ; veko run dist/veko1.vko -- --vko examples/hello.vk -o dist/hello_s1.vko
7 │ use [j = json, s = strings]
8 │
9 │ raw-json = '[{"url": " https://a.trustnode.sh ", "active": true}, {"url": "https://off.invalid", "active": false}, {"url": "https://b.trustnode.sh", "active": true}]'
10 │
11 │ active-urls = raw-json
12 │ \ j/decode
13 │ \ filter fn [n] [n.active]
14 │ \ map fn [n] [n.url.trim]
15 │
16 │ println (s/join active-urls ', ')
17 │ active-urlsWhitespace & Prefix Call Micro-Tour (examples/tour.vk)
Run command: veko inspect --tokens examples/tour.vk
Sample Veko program demonstrating pipes, refinements, structs, and blocks
1 │ // Sample Veko program demonstrating pipes, refinements, structs, and blocks
2 │ // Inspect frontend stages: veko inspect --tokens examples/tour.vk ; veko inspect --ast examples/tour.vk ; veko inspect --modules examples/tour.vk
3 │ use [h = net/http, j = json, s = strings]
4 │ def fetch-fast = h/fetch/timeout
5 │
6 │ Node = struct {
7 │ url str
8 │ port int = 443
9 │ active bool = true
10 │ }
11 │
12 │ sync-nodes = fn [path] [
13 │ urls = fetch-fast 'https://example.com/nodes' 5s
14 │ \ j/decode
15 │ \ filter fn [n] [n.active]
16 │ \ map fn [n] [n.url]
17 │
18 │ os/write-file path (s/join urls '\n')
19 │ urls.len
20 │ ]Stateful ORO Closures, Tail recur & /or (examples/oro_closures.vk)
Run command: veko examples/oro_closures.vk
Stateful ORO closures, tail recursion (recur), mut buffers, and /or error recovery Track A (.vko) : veko compile --vko examples/oro_closures.vk -o dist/oro_closures.vko ; veko run dist/oro_closures.vko Track C (Native) : veko compile --native examples/oro_closures.vk -o dist/oro_closures.exe ; ./dist/oro_closures.exe
1 │ // Stateful ORO closures, tail recursion (recur), mut buffers, and /or error recovery
2 │ // Track A (ORO VM) : veko run examples/oro_closures.vk
3 │ // Track A (.vko) : veko compile --vko examples/oro_closures.vk -o dist/oro_closures.vko ; veko run dist/oro_closures.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/oro_closures.vk
5 │ // Track C (Native) : veko compile --native examples/oro_closures.vk -o dist/oro_closures.exe ; ./dist/oro_closures.exe
6 │ use [bytes, ascii, str]
7 │
8 │ make-counter = fn [start] [
9 │ fn [step] [
10 │ start = start + step
11 │ start
12 │ ]
13 │ ]
14 │
15 │ next-id = make-counter 100
16 │ println (next-id 1)
17 │ println (next-id 5)
18 │
19 │ // Tail-recursive factorial using `recur`
20 │ fact = fn [n acc] [
21 │ if n <= 1 [return acc]
22 │ recur (n - 1) (acc * n)
23 │ ]
24 │ println (fact 6 1)
25 │
26 │ // Zero-alloc in-place mut buffer mutation + /or error handling
27 │ mut buf = bytes/with-cap 4kb
28 │ bytes/push-all mut buf (bytes/from-str ' hello veko! ')
29 │ ascii/trim-right! mut buf
30 │ ascii/upper! mut buf
31 │ println (str/from-bytes buf)
32 │
33 │ missing = os/read-file/or 'does-not-exist.txt' ['fallback-content']
34 │ println missingHomoiconic quote, compose/deep & parse-block (examples/dialects.vk)
Run command: veko examples/dialects.vk
Homoiconicity, quote, compose/deep, and parse-block dialect matching Track A (.vko) : veko compile --vko examples/dialects.vk -o dist/dialects.vko ; veko run dist/dialects.vko Track C (Native) : veko compile --native examples/dialects.vk -o dist/dialects.exe ; ./dist/dialects.exe
1 │ // Homoiconicity, quote, compose/deep, and parse-block dialect matching
2 │ // Track A (ORO VM) : veko run examples/dialects.vk
3 │ // Track A (.vko) : veko compile --vko examples/dialects.vk -o dist/dialects.vko ; veko run dist/dialects.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/dialects.vk
5 │ // Track C (Native) : veko compile --native examples/dialects.vk -o dist/dialects.exe ; ./dist/dialects.exe
6 │ rule = quote [allow .tcp '10.0.0.0/8' 443 30s]
7 │ println rule.len
8 │ println rule[1]
9 │ println rule[4]
10 │
11 │ // Template blocks with compose/deep
12 │ port = 8443
13 │ mode = .tls
14 │ cfg = compose/deep [
15 │ listen (port)
16 │ transport [mode (mode) idle 30s]
17 │ ]
18 │ println (mold cfg)
19 │
20 │ // Structural pattern matching over homoiconic data
21 │ mut routes = []
22 │ ok = parse-block (quote [route .tcp '10.10.0.0/16' 8443 route .udp '192.168.1.0/24' 51820]) [
23 │ any [
24 │ ['route' proto = enum! cidr = str! p = int!] [
25 │ push mut routes { proto = proto, cidr = cidr, port = p }
26 │ ]
27 │ ]
28 │ ]
29 │ println ok
30 │ println (mold routes)
31 │ routesExample 01: 01_basics_and_math.vk
Run command: veko examples/01_basics_and_math.vk
Example 01: Core syntax, rich literals, spaced infix math, bitwise ops, ranges, and loops Track A (.vko) : veko compile --vko examples/01_basics_and_math.vk -o dist/01.vko ; veko run dist/01.vko Track C (Native) : veko compile --native examples/01_basics_and_math.vk -o dist/01.exe ; ./dist/01.exe
1 │ // Example 01: Core syntax, rich literals, spaced infix math, bitwise ops, ranges, and loops
2 │ // Track A (ORO VM) : veko run examples/01_basics_and_math.vk
3 │ // Track A (.vko) : veko compile --vko examples/01_basics_and_math.vk -o dist/01.vko ; veko run dist/01.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/01_basics_and_math.vk
5 │ // Track C (Native) : veko compile --native examples/01_basics_and_math.vk -o dist/01.exe ; ./dist/01.exe
6 │
7 │ title = 'Veko Basics'
8 │ timeout = 250ms
9 │ buf-cap = 4kb
10 │ proto = .tcp
11 │
12 │ println title
13 │ println timeout
14 │ println buf-cap
15 │ println proto
16 │
17 │ // Spaced infix arithmetic & bitwise ring-buffer indexing
18 │ head = 12
19 │ offset = 7
20 │ cap = 16
21 │ next-slot = (head + offset) & (cap - 1)
22 │ println next-slot
23 │
24 │ // Ranges & tight slicing
25 │ nums = 1..=5
26 │ println (mold nums)
27 │ println (mold nums[1..4])
28 │
29 │ // Control flow: if, unless, while
30 │ mut i = 0
31 │ mut sum = 0
32 │ while i < 5 [
33 │ i = i + 1
34 │ sum = sum + i
35 │ ]
36 │ println sum
37 │
38 │ unless zero? sum [
39 │ println 'sum-nonzero'
40 │ ]Example 02: 02_pipelines_and_json.vk
Run command: veko examples/02_pipelines_and_json.vk
Example 02: Module aliases, pipes, UFCS dot-chains, JSON, match, and reduce Track A (.vko) : veko compile --vko examples/02_pipelines_and_json.vk -o dist/02.vko ; veko run dist/02.vko Track C (Native) : veko compile --native examples/02_pipelines_and_json.vk -o dist/02.exe ; ./dist/02.exe
1 │ // Example 02: Module aliases, pipes, UFCS dot-chains, JSON, match, and reduce
2 │ // Track A (ORO VM) : veko run examples/02_pipelines_and_json.vk
3 │ // Track A (.vko) : veko compile --vko examples/02_pipelines_and_json.vk -o dist/02.vko ; veko run dist/02.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/02_pipelines_and_json.vk
5 │ // Track C (Native) : veko compile --native examples/02_pipelines_and_json.vk -o dist/02.exe ; ./dist/02.exe
6 │ use [j = json, s = strings]
7 │
8 │ payload = '[{"name": " alpha ", "score": 90, "active": true}, {"name": " beta ", "score": 40, "active": false}, {"name": " gamma ", "score": 85, "active": true}]'
9 │
10 │ names = payload
11 │ \ j/decode
12 │ \ filter fn [item] [item.active]
13 │ \ map fn [item] [item.name.trim.upper]
14 │
15 │ println (s/join names ' | ')
16 │
17 │ scores = payload
18 │ \ j/decode
19 │ \ filter fn [item] [item.active]
20 │ \ map fn [item] [item.score]
21 │
22 │ total = reduce scores 0 fn [acc x] [acc + x]
23 │ println total
24 │
25 │ // Tagged variant matching with match
26 │ ev = { kind = .ready, code = 200 }
27 │ status-msg = match ev.kind [
28 │ .starting ['booting']
29 │ .ready ['serving']
30 │ _ ['unknown']
31 │ ]
32 │ println status-msgExample 03: 03_oro_buffers_and_errors.vk
Run command: veko examples/03_oro_buffers_and_errors.vk
Example 03: ORO mut buffer loans, secret slabs, defer LIFO, /or error recovery, and recur Track A (.vko) : veko compile --vko examples/03_oro_buffers_and_errors.vk -o dist/03.vko ; veko run dist/03.vko Track C (Native) : veko compile --native examples/03_oro_buffers_and_errors.vk -o dist/03.exe ; ./dist/03.exe
1 │ // Example 03: ORO mut buffer loans, secret slabs, defer LIFO, /or error recovery, and recur
2 │ // Track A (ORO VM) : veko run examples/03_oro_buffers_and_errors.vk
3 │ // Track A (.vko) : veko compile --vko examples/03_oro_buffers_and_errors.vk -o dist/03.vko ; veko run dist/03.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/03_oro_buffers_and_errors.vk
5 │ // Track C (Native) : veko compile --native examples/03_oro_buffers_and_errors.vk -o dist/03.exe ; ./dist/03.exe
6 │ use [bytes, ascii, str]
7 │
8 │ // In-place mutation without reallocating per step
9 │ mut pkt = bytes/with-cap 4kb
10 │ bytes/push-all mut pkt (bytes/from-str ' ping trustnode ')
11 │ ascii/trim-right! mut pkt
12 │ ascii/upper! mut pkt
13 │ bytes/push mut pkt 33
14 │ println (str/from-bytes pkt)
15 │
16 │ // Secret buffer zeroized deterministically when scope ends
17 │ use-secret = fn [label] [
18 │ mut secret = bytes/with-secret 64b
19 │ bytes/push-all mut secret (bytes/from-str 'ephemeral-session-key')
20 │ println (str/append label ':secret-ready')
21 │ secret.len
22 │ ]
23 │ println (use-secret 'auth')
24 │
25 │ // Inline /or error handling + LIFO defer
26 │ safe-find = fn [hay needle] [
27 │ defer [println 'cleanup-done']
28 │ idx = str/index-of/or hay needle [-1]
29 │ idx
30 │ ]
31 │ println (safe-find 'veko-oro-vm' 'oro')
32 │ println (safe-find 'veko-oro-vm' 'missing')
33 │
34 │ // Constant-stack tail recursion with recur
35 │ gcd = fn [a b] [
36 │ if zero? b [return a]
37 │ recur b (a % b)
38 │ ]
39 │ println (gcd 84 36)Example 04: 04_macros_and_dialects.vk
Run command: veko examples/04_macros_and_dialects.vk
Example 04: Homoiconic blocks, quote, compose/deep, parse-block, and compile-time macros Track A (.vko) : veko compile --vko examples/04_macros_and_dialects.vk -o dist/04.vko ; veko run dist/04.vko Track C (Native) : veko compile --native examples/04_macros_and_dialects.vk -o dist/04.exe ; ./dist/04.exe
1 │ // Example 04: Homoiconic blocks, quote, compose/deep, parse-block, and compile-time macros
2 │ // Track A (ORO VM) : veko run examples/04_macros_and_dialects.vk
3 │ // Track A (.vko) : veko compile --vko examples/04_macros_and_dialects.vk -o dist/04.vko ; veko run dist/04.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/04_macros_and_dialects.vk
5 │ // Track C (Native) : veko compile --native examples/04_macros_and_dialects.vk -o dist/04.exe ; ./dist/04.exe
6 │
7 │ // 1. Inspecting unevaluated homoiconic blocks with quote
8 │ spec = quote [route .tcp '10.0.0.0/8' 8443 30s]
9 │ println spec.len
10 │ println (type-of spec[1])
11 │ println spec[4]
12 │
13 │ // 2. Templating blocks without backtick/comma soup
14 │ port = 9000
15 │ tls-mode = .strict
16 │ server-cfg = compose/deep [
17 │ bind '127.0.0.1' (port)
18 │ policy [mode (tls-mode) timeout 15s]
19 │ ]
20 │ println (mold server-cfg)
21 │
22 │ // 3. Declarative DSL parsing via parse-block
23 │ mut endpoints = []
24 │ parsed-ok = parse-block (quote [allow .tcp '10.1.0.0/16' 443 allow .udp '10.2.0.0/16' 51820]) [
25 │ any [
26 │ ['allow' proto = enum! cidr = str! p = int!] [
27 │ push mut endpoints (compose [(proto) (cidr) (p)])
28 │ ]
29 │ ]
30 │ ]
31 │ println parsed-ok
32 │ println (mold endpoints)
33 │
34 │ // 4. Compile-time macro expansion
35 │ triple = macro [x] [
36 │ compose [(x) + (x) + (x)]
37 │ ]
38 │ println (triple 14)Example 05: 05_closures_and_capabilities.vk
Run command: veko examples/05_closures_and_capabilities.vk
Example 05: Stateful ORO closures and explicit capability records (non-OOP polymorphism) Track A (.vko) : veko compile --vko examples/05_closures_and_capabilities.vk -o dist/05.vko ; veko run dist/05.vko Track C (Native) : veko compile --native examples/05_closures_and_capabilities.vk -o dist/05.exe ; ./dist/05.exe
1 │ // Example 05: Stateful ORO closures and explicit capability records (non-OOP polymorphism)
2 │ // Track A (ORO VM) : veko run examples/05_closures_and_capabilities.vk
3 │ // Track A (.vko) : veko compile --vko examples/05_closures_and_capabilities.vk -o dist/05.vko ; veko run dist/05.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/05_closures_and_capabilities.vk
5 │ // Track C (Native) : veko compile --native examples/05_closures_and_capabilities.vk -o dist/05.exe ; ./dist/05.exe
6 │ use [str]
7 │
8 │ // Stateful generator owning its private ORO capture slab
9 │ make-seq = fn [start] [
10 │ mut cur = start
11 │ fn [step] [
12 │ out = cur
13 │ cur = cur + step
14 │ out
15 │ ]
16 │ ]
17 │
18 │ next-port = make-seq 8000
19 │ println (next-port 10)
20 │ println (next-port 10)
21 │ println (next-port 10)
22 │
23 │ // Explicit capability record built from ORO closures (no classes or inheritance)
24 │ make-logger = fn [prefix] [
25 │ {
26 │ info = fn [msg] [println (str/append prefix msg)]
27 │ warn = fn [msg] [println (str/append '[WARN] ' msg)]
28 │ flush = fn [] [println (str/append prefix 'flushed')]
29 │ }
30 │ ]
31 │
32 │ app-log = make-logger '[veko] '
33 │ log-info = app-log.info
34 │ log-warn = app-log.warn
35 │ (log-info 'initialized')
36 │ (log-warn 'cache-miss')
37 │ call app-log.flushExample 06: 06_policy_firewall_compiler.vk
Run command: veko examples/06_policy_firewall_compiler.vk
Example 06: Declarative Firewall Policy DSL Compiler & Stateful Rate-Limiter Track A (.vko) : veko compile --vko examples/06_policy_firewall_compiler.vk -o dist/06.vko ; veko run dist/06.vko Track C (Native) : veko compile --native examples/06_policy_firewall_compiler.vk -o dist/06.exe ; ./dist/06.exe
1 │ // Example 06: Declarative Firewall Policy DSL Compiler & Stateful Rate-Limiter
2 │ // Track A (ORO VM) : veko run examples/06_policy_firewall_compiler.vk
3 │ // Track A (.vko) : veko compile --vko examples/06_policy_firewall_compiler.vk -o dist/06.vko ; veko run dist/06.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/06_policy_firewall_compiler.vk
5 │ // Track C (Native) : veko compile --native examples/06_policy_firewall_compiler.vk -o dist/06.exe ; ./dist/06.exe
6 │ use [str]
7 │
8 │ // Helper invoked by the parse-block dialect to construct typed rule records
9 │ make-rule = fn [proto cidr port auth limit] [
10 │ {
11 │ proto = proto
12 │ cidr = cidr
13 │ port = port
14 │ auth = auth
15 │ limit = limit
16 │ }
17 │ ]
18 │
19 │ // 1. Parse declarative policy rules from homoiconic [ ... ] data
20 │ mut rules = []
21 │ mut default-action = .deny
22 │
23 │ policy-spec = quote [
24 │ default .deny
25 │ route .tcp '10.10.' 8443 .mtls 2
26 │ route .udp '192.168.' 51820 .open 5
27 │ route .tcp '0.0.0.' 80 .deny 0
28 │ ]
29 │
30 │ ok = parse-block policy-spec [
31 │ any [
32 │ ['default' act = enum!] [
33 │ default-action = act
34 │ ]
35 │ ['route' p = enum! c = str! pt = int! a = enum! lim = int!] [
36 │ push mut rules (make-rule p c pt a lim)
37 │ ]
38 │ ]
39 │ ]
40 │
41 │ println (str/append 'compiled-rules=' (mold rules.len))
42 │
43 │ // 2. Build a stateful evaluator closure with per-rule hit counters (ORO map)
44 │ make-evaluator = fn [rule-list fallback] [
45 │ mut hits = {}
46 │ fn [pkt] [
47 │ matched = filter rule-list fn [r] [
48 │ (r.proto == pkt.proto) and (r.port == pkt.port) and (str/contains? pkt.ip r.cidr)
49 │ ]
50 │ if empty? matched [return fallback]
51 │
52 │ rule = first matched
53 │ if rule.auth == .deny [return .blocked]
54 │ if (rule.auth == .mtls) and (not pkt.has-cert) [return .unauthenticated]
55 │
56 │ key = str/append pkt.ip (mold pkt.port)
57 │ cur = if map/has? hits key [map/get hits key] else [0]
58 │ if cur >= rule.limit [return .rate-limited]
59 │
60 │ hits = map/set hits key (cur + 1)
61 │ .allowed
62 │ ]
63 │ ]
64 │
65 │ eval-pkt = make-evaluator rules default-action
66 │
67 │ // 3. Simulate traffic stream against the compiled policy
68 │ traffic = [
69 │ { proto = .tcp, ip = '10.10.4.20', port = 8443, has-cert = false }
70 │ { proto = .tcp, ip = '10.10.4.20', port = 8443, has-cert = true }
71 │ { proto = .tcp, ip = '10.10.4.20', port = 8443, has-cert = true }
72 │ { proto = .tcp, ip = '10.10.4.20', port = 8443, has-cert = true }
73 │ { proto = .udp, ip = '192.168.1.9', port = 51820, has-cert = false }
74 │ { proto = .tcp, ip = '0.0.0.5', port = 80, has-cert = true }
75 │ { proto = .tcp, ip = '172.16.0.1', port = 9999, has-cert = true }
76 │ ]
77 │
78 │ each traffic fn [pkt] [
79 │ verdict = (eval-pkt pkt)
80 │ label = match verdict [
81 │ .allowed ['ALLOW']
82 │ .rate-limited ['LIMIT']
83 │ .unauthenticated ['NO_MTLS']
84 │ .blocked ['BLOCK']
85 │ _ ['DENY_DEFAULT']
86 │ ]
87 │ println (str/join [label pkt.ip pkt.port] ' ')
88 │ ]Example 07: 07_binary_frame_codec.vk
Run command: veko examples/07_binary_frame_codec.vk
Example 07: Binary Wire-Protocol Frame Encoder & Zero-Alloc Validator Track A (.vko) : veko compile --vko examples/07_binary_frame_codec.vk -o dist/07.vko ; veko run dist/07.vko Track C (Native) : veko compile --native examples/07_binary_frame_codec.vk -o dist/07.exe ; ./dist/07.exe
1 │ // Example 07: Binary Wire-Protocol Frame Encoder & Zero-Alloc Validator
2 │ // Track A (ORO VM) : veko run examples/07_binary_frame_codec.vk
3 │ // Track A (.vko) : veko compile --vko examples/07_binary_frame_codec.vk -o dist/07.vko ; veko run dist/07.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/07_binary_frame_codec.vk
5 │ // Track C (Native) : veko compile --native examples/07_binary_frame_codec.vk -o dist/07.exe ; ./dist/07.exe
6 │ use [bytes, ascii, str]
7 │
8 │ // Frame format:
9 │ // [0..2] Magic 'TN' (0x54 0x4e)
10 │ // [2] Version (u8)
11 │ // [3] OpCode (u8)
12 │ // [4..6] Payload Length (u16 big-endian)
13 │ // [6..N] Payload bytes
14 │ // [N] XOR Checksum (u8 over version..payload)
15 │
16 │ xor-checksum = fn [buf start end] [
17 │ mut acc = 0
18 │ mut i = start
19 │ while i < end [
20 │ acc = acc ^ buf[i]
21 │ i = i + 1
22 │ ]
23 │ acc & 0xff
24 │ ]
25 │
26 │ encode-frame = fn [ver op payload-str] [
27 │ payload = bytes/from-str payload-str
28 │ plen = payload.len
29 │ mut frame = bytes/with-cap (7 + plen)
30 │ bytes/push mut frame 0x54
31 │ bytes/push mut frame 0x4e
32 │ bytes/push mut frame ver
33 │ bytes/push mut frame op
34 │ bytes/push mut frame ((plen >> 8) & 0xff)
35 │ bytes/push mut frame (plen & 0xff)
36 │ bytes/push-all mut frame payload
37 │ csum = xor-checksum frame 2 (6 + plen)
38 │ bytes/push mut frame csum
39 │ frame
40 │ ]
41 │
42 │ decode-and-normalize = fn [mut frame] [
43 │ if frame.len < 7 [return err 'frame-too-short']
44 │ if (bytes/to-str frame[0..2]) != 'TN' [return err 'bad-magic']
45 │
46 │ ver = frame[2]
47 │ op = frame[3]
48 │ plen = (frame[4] << 8) | frame[5]
49 │ if frame.len != (7 + plen) [return err 'length-mismatch']
50 │
51 │ expected = xor-checksum frame 2 (6 + plen)
52 │ actual = frame[6 + plen]
53 │ if expected != actual [return err 'checksum-mismatch']
54 │
55 │ // Zero-alloc in-place uppercase normalization of payload slice
56 │ mut body = bytes/from-str (bytes/to-str frame[6..(6 + plen)])
57 │ ascii/trim-right! mut body
58 │ ascii/upper! mut body
59 │
60 │ {
61 │ version = ver
62 │ op = op
63 │ payload = bytes/to-str body
64 │ }
65 │ ]
66 │
67 │ // 1. Encode and decode a valid frame
68 │ mut pkt = encode-frame 1 0x07 ' ping trustnode '
69 │ println pkt.len
70 │ println (bytes/to-str pkt[0..2])
71 │
72 │ decoded = decode-and-normalize/or mut pkt [{ error = 'decode-failed' }]
73 │ println (mold decoded)
74 │
75 │ // 2. Corrupt the checksum byte and verify /or recovery triggers cleanly
76 │ mut bad-pkt = bytes/with-cap pkt.len
77 │ bytes/push-all mut bad-pkt pkt
78 │ // Append extra trailing byte to trigger length-mismatch
79 │ bytes/push mut bad-pkt 0xff
80 │ bad-res = decode-and-normalize/or mut bad-pkt ['recovered-corrupt-frame']
81 │ println bad-resExample 08: 08_kv_store_and_audit_log.vk
Run command: veko examples/08_kv_store_and_audit_log.vk
Example 08: ORO Data-Oriented KV Store, Hash-Chained Audit Log & Secret Zeroization Track A (.vko) : veko compile --vko examples/08_kv_store_and_audit_log.vk -o dist/08.vko ; veko run dist/08.vko Track C (Native) : veko compile --native examples/08_kv_store_and_audit_log.vk -o dist/08.exe ; ./dist/08.exe
1 │ // Example 08: ORO Data-Oriented KV Store, Hash-Chained Audit Log & Secret Zeroization
2 │ // Track A (ORO VM) : veko run examples/08_kv_store_and_audit_log.vk
3 │ // Track A (.vko) : veko compile --vko examples/08_kv_store_and_audit_log.vk -o dist/08.vko ; veko run dist/08.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/08_kv_store_and_audit_log.vk
5 │ // Track C (Native) : veko compile --native examples/08_kv_store_and_audit_log.vk -o dist/08.exe ; ./dist/08.exe
6 │ use [bytes, j = json, str]
7 │
8 │ // Verify audit hash chain recursively in constant stack via `recur`
9 │ verify-chain = fn [entries idx prev-hash] [
10 │ if idx >= entries.len [return true]
11 │ entry = entries[idx]
12 │ expected = hash (str/join [prev-hash entry.op entry.key] '|')
13 │ if entry.sig != expected [return false]
14 │ recur entries (idx + 1) expected
15 │ ]
16 │
17 │ // Single-owner ORO store closure: owns data, audit log, and tip hash in one private slab
18 │ make-kv-store = fn [secret-seed] [
19 │ mut data = {}
20 │ mut audit = []
21 │ base-hash = hash secret-seed
22 │ mut tip-hash = base-hash
23 │
24 │ fn [cmd k v] [
25 │ match cmd [
26 │ .put [
27 │ map/set mut data k v
28 │ tip-hash = hash (str/join [tip-hash 'put' k] '|')
29 │ push mut audit { op = 'put', key = k, sig = tip-hash }
30 │ true
31 │ ]
32 │ .get [
33 │ map/get data k
34 │ ]
35 │ .snapshot [
36 │ { keys = map/keys data, audit = audit, tip = tip-hash }
37 │ ]
38 │ .verify [
39 │ verify-chain audit 0 base-hash
40 │ ]
41 │ _ [
42 │ err 'unknown-kv-command'
43 │ ]
44 │ ]
45 │ ]
46 │ ]
47 │
48 │ // Ephemeral secret buffer wiped deterministically on scope exit
49 │ derive-session-seed = fn [] [
50 │ mut secret = bytes/with-secret 64b
51 │ bytes/push-all mut secret (bytes/from-str 'veko-galago-audit-key-2026')
52 │ hash (bytes/to-str secret)
53 │ ]
54 │
55 │ seed = mold (call derive-session-seed)
56 │ kv = make-kv-store seed
57 │
58 │ (kv .put 'node.host' '127.0.0.1')
59 │ (kv .put 'node.port' 8443)
60 │ (kv .put 'node.mode' 'mtls')
61 │
62 │ println (kv .get 'node.host' .none)
63 │ println (kv .get 'node.port' .none)
64 │
65 │ snap = (kv .snapshot .none .none)
66 │ println (str/append 'audit-valid=' (mold (kv .verify .none .none)))
67 │ println (str/append 'entries=' (mold snap.audit.len))
68 │
69 │ // JSON round-trip persistence check
70 │ encoded = j/encode snap
71 │ reloaded = j/decode encoded
72 │ println (str/append 'roundtrip-keys=' (mold reloaded.keys.len))Example 09: 09_concurrent_worker_pool.vk
Run command: veko examples/09_concurrent_worker_pool.vk
Example 09: Shared-Nothing Concurrent Worker Pool, Select Multiplexing & Isolation Guards (M6) Track A (.vko) : veko compile --vko examples/09_concurrent_worker_pool.vk -o dist/09.vko ; veko run dist/09.vko Track C (Native) : veko compile --native examples/09_concurrent_worker_pool.vk -o dist/09.exe ; ./dist/09.exe
1 │ // Example 09: Shared-Nothing Concurrent Worker Pool, Select Multiplexing & Isolation Guards (M6)
2 │ // Track A (ORO VM) : veko run examples/09_concurrent_worker_pool.vk
3 │ // Track A (.vko) : veko compile --vko examples/09_concurrent_worker_pool.vk -o dist/09.vko ; veko run dist/09.vko
4 │ // Track B (Wasm 3) : veko run --wasm examples/09_concurrent_worker_pool.vk
5 │ // Track C (Native) : veko compile --native examples/09_concurrent_worker_pool.vk -o dist/09.exe ; ./dist/09.exe
6 │ use [bytes, str]
7 │
8 │ // Immutable config & top-level pure transforms are safely visible inside every `spawn` worker
9 │ worker-cfg = { factor = 10, offset = 3 }
10 │
11 │ transform-job = fn [job] [
12 │ score = job.value * worker-cfg.factor + worker-cfg.offset
13 │ { worker = job.lane, id = job.id, score = score }
14 │ ]
15 │
16 │ // 1. Fan-out / fan-in over bounded ownership channels + channel multiplexing (`chan/select`)
17 │ fast-q = chan/new 4
18 │ slow-q = chan/new 4
19 │ out-q = chan/new 4
20 │
21 │ w1 = spawn [
22 │ // Workers maintain their own isolated local state without sharing heaps
23 │ mut processed = 0
24 │ forever [
25 │ item = chan/recv/or fast-q [break]
26 │ chan/send out-q (transform-job item)
27 │ processed = processed + 1
28 │ ]
29 │ processed
30 │ ]
31 │
32 │ w2 = spawn [
33 │ mut processed = 0
34 │ forever [
35 │ item = chan/recv/or slow-q [break]
36 │ chan/send out-q (transform-job item)
37 │ processed = processed + 1
38 │ ]
39 │ processed
40 │ ]
41 │
42 │ // Non-blocking drain check on empty channel returns clean `/or` fallback
43 │ println (chan/try-recv/or out-q ['queue-empty'])
44 │
45 │ // Dispatch jobs (immutable maps move cleanly across threads)
46 │ job1 = { lane = 'fast', id = 1, value = 4 }
47 │ job2 = { lane = 'slow', id = 2, value = 7 }
48 │ chan/send fast-q job1
49 │ chan/send slow-q job2
50 │
51 │ // Wait deterministically for both workers to publish to `out-q`
52 │ mut total-score = 0
53 │ mut seen = 0
54 │ while seen < 2 [
55 │ res = chan/recv out-q
56 │ total-score = total-score + res.score
57 │ seen = seen + 1
58 │ ]
59 │ println (str/append 'total-score=' (mold total-score))
60 │
61 │ // Close queues cleanly so workers finish their loops and return counts via `task/await`
62 │ chan/close fast-q
63 │ chan/close slow-q
64 │ c1 = task/await w1
65 │ c2 = task/await w2
66 │ println (str/append 'workers-done=' (mold (c1 + c2)))
67 │
68 │ // 2. Priority lane selection & timeout handling (`chan/select`, `task/await/timeout/or`)
69 │ lane-a = chan/new 2
70 │ lane-b = chan/new 2
71 │
72 │ _notifier = spawn [
73 │ chan/send lane-b 'priority-alert'
74 │ .ok
75 │ ]
76 │ picked = chan/select [lane-a lane-b]
77 │ println (str/join ['selected-lane=' (mold picked[0]) ':' picked[1]] '')
78 │
79 │ // Deadline check on blocked worker unblocks cleanly without leaking tasks
80 │ barrier = chan/new 1
81 │ deferred-task = spawn [
82 │ msg = chan/recv barrier
83 │ msg
84 │ ]
85 │ deadline-hit = task/await/timeout/or deferred-task 10ms ['deadline-exceeded']
86 │ println deadline-hit
87 │ chan/send barrier 'completed-after-deadline'
88 │ println (task/await deferred-task)
89 │
90 │ // 3. Zero-trust channel transfer firewall: `.secret`, `mut` loans, and closures cannot leak across tasks
91 │ mut tok = bytes/with-secret 32b
92 │ bytes/push-all (mut tok) (bytes/from-str 'ephemeral-token')
93 │ sec-guard = chan/send/or out-q tok ['secret-blocked']
94 │ println sec-guard
95 │
96 │ mut counter = 9
97 │ mut-guard = chan/send/or out-q (mut counter) ['mut-loan-blocked']
98 │ println mut-guard
99 │
100 │ cls-guard = chan/send/or out-q (fn [x] [x + 1]) ['closure-blocked']
101 │ println cls-guard
102 │
103 │ chan/close out-q
104 │ chan/close lane-a
105 │ chan/close lane-b
106 │ chan/close barrierExample 10: 10_loopback_tcp_echo_service.vk
Run command: veko examples/10_loopback_tcp_echo_service.vk
Example 10: Loopback TCP Service Across Isolated Workers + In-Place ORO Buffers & Secret Firewall (M6) Track A (.vko) : veko compile --vko examples/10_loopback_tcp_echo_service.vk -o dist/10.vko ; veko run --allow-net --allow-listen --allow-private-net dist/10.vko Track C (Native) : veko compile --native examples/10_loopback_tcp_echo_service.vk -o dist/10.exe ; ./dist/10.exe
1 │ // Example 10: Loopback TCP Service Across Isolated Workers + In-Place ORO Buffers & Secret Firewall (M6)
2 │ // Track A (ORO VM) : veko run --allow-net --allow-listen --allow-private-net examples/10_loopback_tcp_echo_service.vk
3 │ // Track A (.vko) : veko compile --vko examples/10_loopback_tcp_echo_service.vk -o dist/10.vko ; veko run --allow-net --allow-listen --allow-private-net dist/10.vko
4 │ // Track B (Wasm 3) : veko run --wasm --allow-net --allow-listen --allow-private-net examples/10_loopback_tcp_echo_service.vk
5 │ // Track C (Native) : veko compile --native examples/10_loopback_tcp_echo_service.vk -o dist/10.exe ; ./dist/10.exe
6 │ use [ascii, bytes, net, str]
7 │
8 │ parse-port = fn [addr-str] [
9 │ parts = str/split addr-str ':'
10 │ bs = bytes/from-str parts[1]
11 │ mut acc = 0
12 │ mut i = 0
13 │ while i < (len bs) [
14 │ b = bs[i]
15 │ acc = acc * 10 + (b - 48)
16 │ i = i + 1
17 │ ]
18 │ acc
19 │ ]
20 │
21 │ // Bind ephemeral loopback listener (`127.0.0.1:0`); requires explicit `--allow-listen` & `--allow-private-net`
22 │ ln = net/listen-tcp .ip '127.0.0.1:0'
23 │ bound-addr = net/addr ln
24 │ port = parse-port bound-addr
25 │
26 │ // Spawn isolated TCP client worker
27 │ client-worker = spawn [
28 │ cli = net/connect-tcp '127.0.0.1' port
29 │
30 │ // Secret taint firewall: `.secret` buffers are blocked before leaving any socket
31 │ mut api-key = bytes/with-secret 32b
32 │ bytes/push-all (mut api-key) (bytes/from-str 'sk-never-egress')
33 │ sec-verdict = net/write/or cli api-key 'secret-write-blocked'
34 │
35 │ // Normal payload writes over real OS TCP / WASI sockets
36 │ net/write-string cli ' hello veko socket '
37 │ reply = net/read-bytes cli 64
38 │ net/close cli
39 │ { sec = sec-verdict, reply = (bytes/to-str reply) }
40 │ ]
41 │
42 │ // Accept client connection, normalize bytes in-place inside ORO `mut` buffer, and respond
43 │ mut srv = net/accept ln
44 │ mut rx-buf = bytes/with-cap 64
45 │ nbytes = net/read-into (mut srv) (mut rx-buf)
46 │
47 │ ascii/trim-right! (mut rx-buf)
48 │ ascii/upper! (mut rx-buf)
49 │ net/write srv rx-buf
50 │ net/close srv
51 │ net/close ln
52 │
53 │ client-res = task/await client-worker
54 │ println (str/append 'server-rx-bytes=' (mold nbytes))
55 │ println (str/append 'client-secret-guard=' client-res.sec)
56 │ println (str/append 'client-rx=' client-res.reply)Example 11: Multi-File Modular Service (examples/11_modular_service/)
Run command: veko examples/11_modular_service
{
name = 'edge-telemetry-service'
root = 'src'
allow-caps = [.clocks]
}Module lib/protocol (M5): private helpers stay isolated while pub/export expose clean frame APIs + macros
1 │ // Module `lib/protocol` (M5): private helpers stay isolated while `pub`/`export` expose clean frame APIs + macros
2 │ use [bytes, str]
3 │
4 │ // Private helper & secret salt cannot be accessed outside `lib/protocol`
5 │ salt-xor = 0x5a
6 │ mix-byte = fn [b] [(b ^ salt-xor) & 0xff]
7 │
8 │ // Compute deterministic masked checksum across a message string
9 │ pub checksum-hex = fn [msg] [
10 │ bs = bytes/from-str msg
11 │ mut acc = 0
12 │ mut i = 0
13 │ while i < (len bs) [
14 │ acc = (acc + (mix-byte bs[i])) & 0xffff
15 │ i = i + 1
16 │ ]
17 │ acc
18 │ ]
19 │
20 │ // Public message formatter callable cleanly inside concurrent `spawn` workers
21 │ pub format-telemetry = fn [node seq payload] [
22 │ csum = checksum-hex payload
23 │ { node = node, seq = seq, payload = payload, csum = csum }
24 │ ]
25 │
26 │ // Compile-time macro expanding threshold expressions directly at the caller with zero runtime overhead
27 │ alert-threshold = macro [base margin] [
28 │ compose [ (base) + (margin) ]
29 │ ]
30 │
31 │ export [alert-threshold]Example 11: Multi-File Modular Service Combining M5 (veko.vk, pub/export, Macros) & M6 (spawn + Channels) Track A (.vko) : veko compile --vko examples/11_modular_service/src/main.vk -o dist/11.vko ; veko run dist/11.vko Track C (Native) : veko compile --native examples/11_modular_service/src/main.vk -o dist/11.exe ; ./dist/11.exe
1 │ // Example 11: Multi-File Modular Service Combining M5 (`veko.vk`, `pub`/`export`, Macros) & M6 (`spawn` + Channels)
2 │ // Audit DAG & caps : veko inspect --modules examples/11_modular_service/src/main.vk
3 │ // Track A (ORO VM) : veko run examples/11_modular_service/src/main.vk
4 │ // Track A (.vko) : veko compile --vko examples/11_modular_service/src/main.vk -o dist/11.vko ; veko run dist/11.vko
5 │ // Track B (Wasm 3) : veko run --wasm examples/11_modular_service/src/main.vk
6 │ // Track C (Native) : veko compile --native examples/11_modular_service/src/main.vk -o dist/11.exe ; ./dist/11.exe
7 │ use [proto = lib/protocol, str]
8 │
9 │ t0 = time/now
10 │ limit = proto/alert-threshold 80 15
11 │
12 │ outbox = chan/new 4
13 │
14 │ w1 = spawn [
15 │ pkt = proto/format-telemetry 'edge-west-01' 1 'cpu=42%'
16 │ chan/send outbox pkt
17 │ 'ok-w1'
18 │ ]
19 │
20 │ w2 = spawn [
21 │ pkt = proto/format-telemetry 'edge-east-02' 2 'mem=68%'
22 │ chan/send outbox pkt
23 │ 'ok-w2'
24 │ ]
25 │
26 │ mut total-csum = 0
27 │ mut count = 0
28 │ while count < 2 [
29 │ pkt = chan/recv outbox
30 │ total-csum = total-csum + pkt.csum
31 │ count = count + 1
32 │ ]
33 │
34 │ r1 = task/await w1
35 │ r2 = task/await w2
36 │ chan/close outbox
37 │ elapsed = time/since t0
38 │
39 │ println (str/append 'threshold=' (mold limit))
40 │ println (str/append 'over-limit=' (mold (total-csum > limit)))
41 │ println (str/append 'workers=' (str/join [r1 r2] ','))
42 │ println (str/append 'packets=' (mold count))
43 │ println (str/append 'csum-sum=' (mold total-csum))
44 │ println (str/append 'clock-ok=' (mold (elapsed >= 0ns)))Example 12: 12_typed_structs_and_secrets.vk
Run command: veko check --strict-types examples/12_typed_structs_and_secrets.vk
M7 Practical Showcase: Typed Structs, Secret Governance, Checked Conversions & Unboxed Loops Try: veko compile --vko examples/12_typed_structs_and_secrets.vk -o dist/12.vko ; veko run dist/12.vko veko compile --native examples/12_typed_structs_and_secrets.vk -o dist/12.exe ; ./dist/12.exe
1 │ // M7 Practical Showcase: Typed Structs, Secret Governance, Checked Conversions & Unboxed Loops
2 │ // Try:
3 │ // veko check --strict-types examples/12_typed_structs_and_secrets.vk
4 │ // veko run examples/12_typed_structs_and_secrets.vk
5 │ // veko compile --vko examples/12_typed_structs_and_secrets.vk -o dist/12.vko ; veko run dist/12.vko
6 │ // veko run --wasm examples/12_typed_structs_and_secrets.vk
7 │ // veko compile --native examples/12_typed_structs_and_secrets.vk -o dist/12.exe ; ./dist/12.exe
8 │
9 │ Upstream = struct {
10 │ name str
11 │ host str
12 │ port i64 = 443
13 │ tls bool = true
14 │ api_key secret str = ''
15 │ }
16 │
17 │ RouteSummary = struct {
18 │ name str
19 │ host str
20 │ port i64
21 │ load i64
22 │ }
23 │
24 │ // Runtime entry type guards enforce Upstream schema and u8 bounds [0..255]
25 │ compute-weight = fn [ep Upstream, factor u8, samples i64] i64 [
26 │ mut acc = 0
27 │ mut i = 0
28 │ while i < samples [
29 │ acc = acc + (i & 7) + factor
30 │ i = i + 1
31 │ ]
32 │ acc + ep.port
33 │ ]
34 │
35 │ format-target = fn [ep Upstream] str [
36 │ str/join [ep.name ep.host (mold ep.port)] ':'
37 │ ]
38 │
39 │ // 14-byte inline SSO holds short hostnames with zero heap allocations
40 │ secret-tok = os/getenv/secret/or 'VEKO_GATEWAY_KEY' ['dev-secret-fallback']
41 │ secret-buf = bytes/with-secret 8
42 │ println (str/join ['secret-buf-mold=' (mold secret-buf)] '')
43 │
44 │ // Checked conversions fail cleanly with /or instead of truncating or panicking
45 │ parsed-port = str/to-i64/or '8443' [443]
46 │ bad-port = str/to-i64/or 'not-a-number' [-1]
47 │ clamped-u8 = as-u8/or 300 [as-u8 255]
48 │ ok-u8 = as-u8/or 12 [as-u8 0]
49 │
50 │ primary = Upstream {
51 │ name = 'edge-us'
52 │ host = 'api.veko.local'
53 │ api_key = secret-tok
54 │ }
55 │ standby = primary \ struct/with { name = 'edge-eu', host = 'eu.veko.local', port = parsed-port }
56 │
57 │ // Passing `standby` or `secret-buf` directly to `json/encode` or `os/write-file` is blocked
58 │ // both statically by `veko check` and recursively at runtime; print/mold safely redact to `<secret>`.
59 │ println (str/join ['target=' (format-target standby)] '')
60 │ println (str/join ['bad-port=' (mold bad-port)] '')
61 │ println (str/join ['clamped-u8=' (mold clamped-u8)] '')
62 │
63 │ // Unboxed typed register loop runs without heap tag boxing per iteration
64 │ score = compute-weight standby ok-u8 5000
65 │ summary = RouteSummary {
66 │ name = standby.name
67 │ host = standby.host
68 │ port = standby.port
69 │ load = score
70 │ }
71 │ println (str/join ['summary=' (json/encode summary)] '')