veko-lang.org
Download Free EPUB 3.0

Part IV · Onboarding, Inspection & Quick Reference

Chapter 9

Newcomer Pointers, Token/AST Inspection & Syntax Pitfalls

Reading prefix commands, mastering [tight] vs [spaced] tokens with veko inspect, and avoiding C/Go/Rust traps

Step-by-step pointers for reading and writing idiomatic .vk code, inspecting parsed programs, building Veko workspaces, and regenerating documentation.


0. Pointers & Best Practices for Newcomers (How to Read & Write Veko)

1. Shift Your Mental Model from "Punctuation" to "CLI Commands"

Newcomers arriving from Go, Rust, or TypeScript often try to read Veko like C without parentheses and get tripped up. Instead, read each Veko line like a Unix shell command with fixed compile-time arity:

VEKO
os/write-file out_path payload
  • Reading tip: Every word consumes a known number of arguments to its right. Zero-argument functions (such as host-bin-path in build.vk) run simply by naming them — no () needed.
  • Parentheses rule of thumb: Never attach ( directly to a function name (len(xs) is wrong). Use (...) only when an argument is itself a multi-token expression:
VEKO
  while i < (len items) [ ... ]

2. Treat Whitespace as Semantic Punctuation

In C-family languages, spaces are mostly optional decoration. In Veko, spaces separate words while tightness glues paths and accessors together:

  • Space around - and / when doing math: n - 1 and a / b. Without spaces, n-1 is a single kebab-case identifier and str/join is a module path.
  • Keep . and [...] tight to the target: user.name.trim, buf[0..n]. A leading space turns .ok or .tls into an enum literal (return .ok).
  • Space before unary -: add x -1 passes -1; x - 1 subtracts 1.

3. Flatten Nested Parentheses with \ Pipes and . Chains

The primary readability anti-pattern in prefix languages (such as Lisp) is deeply nested parentheses like (f (g (h x))). Idiomatic Veko stays flat in three ways:

  1. Bind intermediate steps with short names when performing side effects.
  2. Use tight . chains for 1-argument transforms: raw.trim.lower.
  3. Use \ pipes for multi-step data transformations (feeding the left result into argument 1 of the next word):
VEKO
   urls = body
       \ json/decode
       \ filter fn [p] [p.active]
       \ map fn [p] [p.url.trim]

4. Read /refinements and /or as Inline Control Flow

Instead of option structs, overloaded functions, or try/catch blocks, Veko extends words with / refinements and handles errors right at the call site with /or:

VEKO
port = str/to-i64/or raw_port [ 443 ]
raw  = os/read-file/or path [ e -> return (err `cannot read {path}: {mold e}`) ]
  • Best practice: Handle or propagate errors immediately with /or (or if err? x [ return x ] in sequential scripts), and pair resource acquisition with defer [ ... ] right below it. Never look for nil or null — unit actions return .ok, wire JSON null is .null, and missing lookups return err.

5. Follow the mut Trail & Visual Casing Conventions

When reading unfamiliar Veko code, scan for the word mut. Because Veko requires mut at both the declaration and every mutating call site (bytes/push mut buf 10), any line without mut is guaranteed not to mutate its arguments in place.

  • Naming convention: Stick to Veko's visual casing and hyphenation split — kebab-case for functions and words (encode-header), snake_case for local variables and struct fields (out_path), and PascalCase for types (Upstream). That lets your eye distinguish callable words from values immediately without () at call sites.

1. Build, Test, and Render Documentation

Run the Test Suite

POWERSHELL
veko run tests/run_tests.vk

This verifies:

  • Whitespace-aware lexical disambiguation (tight vs spaced brackets, dot-chains, enums, unary -, binary -).
  • Two-pass Pratt precedence (hash a == hash b, CRC bitwise indexing, multiline \ pipes).
  • Optional gradual and strict types, struct { ... } and interface { ... } definitions, and static + runtime .secret firewalls.
  • O(1) put, CoW isolation, fixed-width 64-bit VKO bytecode roundtripping, veko inspect modes, HTML documentation synthesis, and 3-track parity.

Build Everything in One Step

POWERSHELL
# Refresh HTML documentation only (dist/docs/)
veko docs

# Or run the pure-Veko build orchestrator (`all`, `test`, `docs`, `build`, `fixed-point`, `check`)
veko run build.vk -- all

Running veko run build.vk -- all executes static checks, runs tests/run_tests.vk, refreshes both HTML documentation suites in dist/docs/, and verifies the two-stage S1 == S2 native self-hosting fixed point (dist/bin/veko).

Render Documentation Only

POWERSHELL
veko docs

2. Inspect Tokens and ASTs While Writing .vk Code

Use veko inspect to see exactly how the whitespace-aware lexer and two-pass Pratt parser interpret your source file:

POWERSHELL
# Inspect raw tokens with line:col and [tight] / [spaced] flags
veko inspect --tokens examples/tour.vk

# Inspect the resolved two-pass AST
veko inspect --ast examples/tour.vk

# Inspect compiled 64-bit VKO bytecode
veko inspect --bytecode examples/hello.vk

# Execute a script or launch the interactive REPL
veko run examples/hello.vk
veko repl

Understanding [tight] vs [spaced] in Token Output

Source SnippetLexer OutputMeaning
buf[0..n]lbracket([) [tight]Postfix index/slice on buf
if ok [break]lbracket([) [spaced]Homoiconic code block argument to if
node.urldot_chain(url) [tight]Field read or 1-arg UFCS call on node
mode = .tlsenum_lit(tls) [spaced]Shorthand enum symbol .tls
total = a - bminus(-) [spaced]Binary subtraction
add x -1int_lit(-1) [spaced]Negative integer literal

3. Write Order-Independent Functions and Aliases

Pass 1 of the Veko parser scans fn, macro, def, and use declarations before Pass 2 builds expression trees. You can call helpers defined lower in the same file without forward declarations:

VEKO
use [h = net/http, j = json]
def fetch-fast = h/fetch/timeout

main = fn [url] [
    format-result (fetch-fast url 5s \ j/decode)
]

format-result = fn [data] [
    data.status
]

4. Avoid Common Syntax Traps

  1. Always put spaces around binary - and /:
    • a - b is subtraction; a-b is a single kebab-case identifier.
    • If you accidentally write n-1 when n is in scope, Veko reports:

unknown word 'n-1' -- add spaces for subtraction: 'n - 1'.

  1. Use { ... } for maps and structs, [ ... ] for blocks and lists:
    • Struct definition: Node = struct { url str, port i64 = 443 }
    • Struct literal: Node { url = 'https://veko-lang.org', port = 8443 }
    • List or code block: [1 2 3] or [print 'ok']
  2. Mark in-place mutations with mut on both sides:
    • Signature: trim-buf = fn [mut buf] [ ... ]
    • Call site: trim-buf mut pkt

5. Configure vvm for WebAssembly 3.0 Execution (--wasm)

When executing veko run --wasm <file.vk>, Veko compiles your program to validated WebAssembly 3.0 and launches vvm automatically (discovering ../vvm/dist/bin/windows/vvm.exe, ../vvm/dist/bin/linux/vvm, dist/bin/vvm, or VVM_BIN when set):

POWERSHELL
# Optional override if your vvm binary lives in a custom path
$env:VVM_BIN = "C:\path\to\vvm.exe"
veko run --wasm --check-slabs examples/hello.vk

You can also invoke vvm run --veko directly against .wasm artifacts emitted by veko compile --wasm.


6. Structure Multi-File Projects & Compile .vko Modules

  1. Create a veko.vk manifest at your project root specifying name, relative root (e.g., 'src'), optional external deps, and optional allow-caps = [.fs .clocks .env .net .exec .ui] (plus default-deny .ffi only when explicitly integrating native shared libraries).
  2. Export types, functions, and macros explicitly using pub Type = struct {...}, pub name = fn|macro [...] [...], or export [sym1 sym2]—mutable module globals (pub mut) are rejected by design.
  3. Import using logical names (use [c = lib/codec, auth]); Veko checks reserved built-in namespaces first, project root second, standard library lib/ third, and declared deps fourth.
  4. Audit before running: Run veko inspect --modules src/main.vk to verify topological order, public exports, and transitive capabilities, or compile ORO VM bytecode modules via veko compile --vko mod.vk -o mod.vko and inspect them with veko inspect --vko mod.vko.

7. Run Concurrent Workers & Guarded Networking

  1. Fan out work across isolated spawn tasks: Pass read-only config/values or transfer payloads via bounded chan/new queues (chan/send, chan/recv, chan/select), and collect results deterministically using task/await.
  2. Respect ORO isolation boundaries: Keep mut buffers local to one task (spawn rejects outer mut captures), and tag sensitive keys with bytes/with-secret so channel/network firewalls block accidental leaks.
  3. Authorize networking explicitly when needed: Networking stays disabled by default on VM/Wasm (allow_network = false); enable only required permissions at runtime (veko run --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk or --allow-hosts=api.example.com), or run cached native binaries via veko run --native.

8. Choose Backends & Cross-Compile veko Across All Five Native Targets

EXECUTION MODES

Choosing Between Veko's Three Execution Tracks

Write idiomatic .vk code once and select the runtime envelope matching development speed, isolation, or native deployment.

SOURCE WORKSPACE veko.vk + src/*.vk RUNTIME & DEPLOYMENT ENVELOPES Identical ORO & .secret semantics --vm (default) --wasm --native .wasm PE / ELF / Mach-O SourceVeko Source & Manifestveko check --strict-types DevelopmentTrack A: ORO Bytecode VMveko run app.vk / veko repl Zero-TrustTrack B: Wasm 3.0 Sandboxveko run --wasm --fuel=... ProductionTrack C: Native Machine Codeveko compile --native DeliveryShipped Artifacts.exe / ELF64 / Mach-O / .vkp
Component & ModuleArchitectural Role
Veko Source & Manifest
main.vk + types.vk
Single source of truth defining module imports, types, and capability declarations.
Track A: ORO Bytecode VM
oro_vm.vk
Fastest edit-run-test cycle, interactive REPL, and portable .vko bytecode bundles.
Track B: Wasm 3.0 Sandbox
codegen.vk
Deterministic capability-confined execution for untrusted extensions and CI leak audits.
Track C: Native Machine Code
native_emit.vk + arm64_emit.vk
Standalone zero-GC executables with SIMD acceleration and cross-OS compilation.
Shipped Artifacts
pe_emit.vk + elf_emit.vk + macho_emit.vk
Self-contained binaries and Ed25519/ML-DSA signed VKP1 source bundles.

When to Choose --vm/.vko, --wasm, or --native

  • Choose --vm or .vko for instant local iteration, veko repl, dynamic eval, and precompiled 64-bit VKO distribution.
  • Choose --wasm when executing untrusted or multi-tenant code under vvm's HostSandbox (fuel caps, --mem-pages, --allow-fs, --allow-hosts, --check-slabs).
  • Choose --native (veko run --native or veko compile --native [--target=<win-x64|win-arm64|linux-x64|linux-arm64|macos-arm64>]) when shipping standalone Windows PE32+ (win-x64 & win-arm64 0xAA64, --gui optional), static Linux ELF64 (x86_64 & arm64), or signed 16 KiB Apple Silicon Mach-O (macos-arm64) binaries with zero C/LLVM toolchain dependencies.

src/main.vk hosts the unified 46-module single-binary veko SDK (with all 93 lib/ modules embedded via src/stdlib_vfs.bin) and compiles projects (including itself) to all targets:

POWERSHELL
# Compile the self-hosted veko toolchain to .vko, .wasm, or any of the 5 native OS/CPU targets
veko compile --vko    src/main.vk -o dist/veko.vko
veko compile --wasm   src/main.vk -o dist/veko.wasm
veko compile --native src/main.vk -o dist/bin/veko_s1.exe
veko compile --native --target=win-arm64   src/main.vk -o dist/bin/veko_win_arm64.exe
veko compile --native --target=linux-x64   src/main.vk -o dist/bin/veko_linux_x64
veko compile --native --target=linux-arm64 src/main.vk -o dist/bin/veko_linux_arm64
veko compile --native --target=macos-arm64 src/main.vk -o dist/bin/veko_macos_arm64

9. Predictable Memory, Zero Pauses, Zero Lifetimes: How ORO Works in Plain English

Veko's memory model is called ORO (One Reference Only). In plain English, Veko gives you the clean feel of a high-level language with the predictable memory and speed of systems code — without garbage-collection pauses and without lifetime annotations:

  1. Zero-GC (No Garbage Collector): Unlike Python, Go, Java, or JavaScript, Veko runs no background collector thread that periodically pauses your service to scan memory for unreachable objects.
  2. One Clear Owner ("Passing a Physical Clipboard"): Instead of a "Shared Google Doc" where ten distant functions hold hidden references and silently mutate your map behind your back, every Veko value has one clear owner at a time:
    • Reading is free: Passing a value to a read-only function costs zero copying.
    • In-place updates are explicit (mut): If a function updates your buffer in place, you pass mut on the page (bytes/push mut buf 10), and ownership returns immediately when the call completes.
    • Independent copies use Copy-on-Write: Assigning snapshot = draft shares the underlying slab safely until one variable actually mutates it, and strings up to 14 bytes live inline inside the 16-byte value with zero heap allocation.
  3. Deterministic Cleanup & True Secret Zeroization: Because every value has one owner, Veko knows the exact closing ] where a variable goes out of scope:
VEKO
handle-webhook = fn [payload bytes] str [
    // 1. <= 14-byte strings sit inline on registers/stack — 0 heap allocations
    status = 'verified'

    // 2. Explicit in-place mutation: any line without `mut` CANNOT mutate `buf`
    mut buf = bytes/with-cap 256
    bytes/push-all mut buf payload

    // 3. Single-owner secrets zeroize deterministically at scope exit
    api_key = os/getenv/secret/or 'STRIPE_SECRET' [ bytes/with-secret 0 ]

    status
] // <-- Right here: `buf` is freed immediately, and `api_key` RAM bytes are overwritten with 0x00!
Your BackgroundWhat Zero-GC ORO Determinism Means in Practice
Python / Node / RubyServices run in 15–30 MB of RAM instead of 500 MB, never suffer random GC latency spikes, and functions cannot silently mutate your maps or lists.
GoSame single-binary compile-and-ship workflow, with zero GOGC/GOMEMLIMIT tail-latency tuning, zero nil panics, and explicit mut on state changes.
RustDeterministic RAII drops, single-owner safety, and zero GC — without <'a> lifetime annotations, Rc<RefCell<T>>, or Arc<Mutex<T>>.
Security & FinTechA moving garbage collector never copies passwords or keys across RAM; single ownership lets Veko zeroize secret slabs at the exact closing ].

10. Coming from Python, TypeScript, Go, or Rust: Stack Migration Map

Use veko pkg search <query> and veko pkg info <name> to discover any of the 30 official Ed25519-signed .vkp packages on veko-lang.org:

Familiar Stack in Other EcosystemsIdiomatic Pure-Veko Stack (stdlib + veko pkg add ...)
Python: FastAPI + Pydantic + Celery + Chroma/Polarsweb + openapi@1.0.0 + jobs_cron@1.0.0 + vec_rag@1.0.0 / dataframe_parquet@1.0.0
TypeScript / Node: Next.js + Prisma + Stripe + Apollo + Playwright + Yjsweb_live@1.0.0 + db/sqlite (sqlite_orm_ext@1.0.0) + payments_ledger@1.0.0 + graphql@1.0.0 + browser_cdp@1.0.0 + crdt_sync@1.0.0
Go: net/http + chi + grpc-go + ko + client-go + etcd/raftweb (net/http2, net/http3) + http_router@1.2.0 + grpc_proto@1.0.0 + oci_k8s@1.0.0 + cluster_raft@1.0.0
Rust: axum + tower + snow (Noise) + extism + rumqttcweb + resilience@1.0.0 + noise_tunnel@1.0.0 + wasm_plugin_sdk@1.0.0 + iot_mqtt@1.0.0
Enterprise / DevOps: boto3 + Ansible/Terraform + Okta SAML/SCIM + WebAuthncloud_s3@1.0.0 + iac_fleet@1.0.0 + ldap_saml@1.0.0 + webauthn@1.0.0 + ai_mcp@1.0.0 + ai_llm@1.0.0