Golden Examples
Working code examples demonstrating Vox language features. Each .vox file is a complete, self-contained program validated by the CI pipeline. See examples/PARSE_STATUS.md for the latest parse matrix and examples/STYLE.md for contribution guidelines.
Hello World
The smallest valid Vox program: a typed function that returns a string. Demonstrates the fn keyword, explicit return type, string concatenation, and ret.
fn hello(name: str) -> str {
ret "Hello " + name + "!"
}
CRUD API — Table, Query, Mutation, and Endpoint
A complete data layer in one file. @table generates the database schema, @query wires a read-only resolver, @mutation wires a write operation, and @get exposes an HTTP handler — all with the Rust Axum backend generated automatically.
@table type User {
name: str
active: bool
}
@query
fn user_count() -> int {
ret len(db.User.all())
}
@query
fn active_user_count() -> int {
ret len(db.User.filter({ active: true }))
}
@mutation
fn seed_user(name: str) -> Unit {
db.User.insert({ name: name, active: true })
}
http get "/api/users" to int {
ret len(db.User.all())
}
Counter Actor — Stateful Concurrent Actor
Actors are isolated units of concurrency. This actor holds an integer counter in its state and exposes an Increment message handler that returns the new count. Spawning the actor allocates a mailbox and an address.
actor CounterActor {
on Increment(current: int) -> int {
ret current + 1
}
}
Checkout Workflow — Durable Execution with Error Handling
Workflows survive server restarts by journaling each activity result. The charge_card activity is idempotent and retryable. Pattern matching on Result makes both happy-path and error-path explicit.
activity charge_card(amount: int) -> Result[str] {
if amount > 1000 {
ret Error("Amount too large")
}
ret Ok("tx_123")
}
workflow checkout(amount: int) -> str {
let result = charge_card(amount)
match result {
Ok(tx) -> "Success: " + tx
Error(msg) -> "Failed: " + msg
}
}
MCP Tools — AI-Callable Tool and Resource
The @mcp.tool decorator generates a Model Context Protocol tool schema from the function signature. AI agents (including Vox's built-in DEI orchestrator) can discover and call these functions without any glue code.
@mcp.tool "read_file: Reads a file from disk"
fn read_file(path: str) -> str {
ret "file contents"
}
@mcp.tool "file_uri: Echo path as a logical file URI"
fn file_uri(path: str) -> str {
ret "file://" + path
}
@mcp.resource("vox://golden/mcp-status", "Static status blob for golden tests")
fn mcp_golden_status() -> str {
ret "ok"
}
Agent Pipeline — Multi-Agent Message Passing
Demonstrates an actor-based multi-agent system. TaskMessage is a structured message type. WorkerAgent receives HandleTask messages and tracks the number of processed tasks in its actor state.
type TaskMessage =
| Msg(id: int, payload: str)
fn data_agent_ready() -> str {
ret "Ready"
}
actor WorkerAgent {
on HandleTask(id: int, payload: str) -> str {
ret "Task " + str(id) + " done"
}
}
Dashboard UI — Layout, Islands, and Routes
Full-stack UI composition. @island marks interactive components that get client-side hydration. layout wraps every route with shared chrome. routes maps URL paths to components.
type DashboardStatus =
| Loading
| Ready(data: str)
@island DataChart {
data: list[int]
}
component DashboardView() {
view: <div className="dashboard">
<h1>"Dashboard"</h1>
<DataChart data=[1, 2, 3] />
</div>
}
routes {
"/" to DashboardView
}
Type System — ADTs, Generics, and Traits
Demonstrates algebraic data types with a type parameter, trait definition, and impl block. AppResult[T] is a generic union type (Vox's alternative to exceptions). The Serializable trait requires a serialize method.
type AppResult =
| Success(value: int)
| Failure(err: str)
fn serialize_app_result(r: AppResult) -> str {
match r {
Success(val) -> "num:" + str(val)
Failure(err) -> "err:" + err
}
}
Test Suite — Fixtures, Mocks, and Assertions
@fixture sets up shared test data. @mock replaces external dependencies. @test declares a test function. The |> pipe operator and len built-in demonstrate Vox's functional style.
fn setup_user() -> list[str] {
ret ["alice", "bob"]
}
fn mock_db_read() -> str {
ret "mock_data"
}
@test
fn test_user_count() -> Unit {
let users = setup_user()
assert(len(users) > 0)
let db_val = mock_db_read()
assert(db_val is "mock_data")
}
Config and Deploy — Environment Configuration
Typed configuration blocks and named environment definitions. config generates validated config structs. environment names deployment targets with typed key-value pairs.
type DatabaseConfig =
| DatabaseConfig(url: str, pool_size: int)
fn sample_database_url() -> str {
ret "libsql://example.turso.io"
}
fn prod_replica_count() -> int {
ret 3
}
fn prod_debug_enabled() -> bool {
ret false
}
Reactive component — state, derived, effect, lifecycle
Counter demo using the current component surface: state, derived, effect, on mount, on cleanup, and a view with click handlers.
/// Reactive counter demo (current `component` surface). Uses `on mount` / `on cleanup`
/// (not bare `mount:` / `cleanup:`). See `crates/vox-compiler/tests/reactive_smoke.rs`.
component Counter(initial: int) {
state count: int = initial
derived double = count * 2
derived label = "Count is " + str(count)
effect: {
print("count changed to " + str(count))
}
on mount: {
print("Counter mounted with initial=" + str(initial))
}
on cleanup: {
print("Counter unmounted")
}
view: (
<div class="counter">
<h2>"Count: {count}"</h2>
<p>"Doubled: {double}"</p>
<p>"Label: {label}"</p>
<button on:click={count = count + 1}>"Increment"</button>
<button on:click={count = count - 1}>"Decrement"</button>
<button on:click={count = 0}>"Reset"</button>
</div>
)
}
std.http — get_text / post_json
Narrow host HTTP helpers on std.http (dotted path; see parser tests). Suitable for scripting and smoke tests against real endpoints.
// Narrow `std.http` wrapper demo (`get_text` / `post_json`). Requires `http` to parse as a
// dotted path segment (see `parse_ident_name` / `parse_import_path`).
fn main() {
let ping = std.http.get_text("https://example.com")
let payload = "{\"source\":\"vox\",\"kind\":\"health\"}"
let posted = std.http.post_json("https://httpbin.org/post", payload)
std.log.info("std.http wrapper demo")
print(str(ping))
print(str(posted))
}
Mobile handlers (std.mobile surface)
Small UI handlers using the mobile namespace pattern (onclick={fn() { … }}).
// Minimal notify demo — same handler shape as `examples/golden/mobile_camera.vox`.
import std.mobile
component App() {
view:
<button onclick={fn() {
mobile.notify("Hello", "From Vox!")
}}>"Notify Me"</button>
}
Mesh worker script (minimal main)
Bundled as /opt/vox/mesh-noop.vox in the Docker image for compose-based workers (vox run --mode script).
// Minimal script worker for mesh/compose examples (`vox run --mode script`).
fn main() -> int {
ret 0
}
Rosetta inventory (multi-language walkthrough)
Two golden files back the Rosetta inventory explanation: core merge + @table in inventory_rosetta_core.vox, and actor / workflow / MCP / UI / capability layers in inventory_rosetta_platform.vox. Use that page for C++ / Rust / Python contrast snippets; Vox sections pull anchored regions from these files.