# Xu Programming Language > Xu is a systems language for operating system and AI development. It provides custom native AOT backends, inferred ownership, and zero-GC execution. Official website: https://xulang.org Language repository: https://github.com/xulang-org/xu Selected released SDK: 0.16.0 License: MIT (see the repository LICENSE; preserve third-party notices). ## Language and safety model Xu uses static typing, ownership inference, borrow checking, and deterministic resource cleanup. It uses custom AOT backends rather than LLVM. Coroutines start with `xu f()` and communicate through typed channels. There is no garbage collector. Ownership and borrow diagnostics constrain value use and mutable access. Shared mutable state in concurrent code still requires appropriate synchronization. Native code, FFI, and concurrent libraries have their own safety requirements; this is not a blanket guarantee against every data race or undefined behavior. See https://xulang.org/docs/lang/memory/ and https://xulang.org/docs/lang/concurrency/. Parameters, fields, and receivers use `name Type`, without a colon. Bindings use `name := value`, with a `$` prefix (`$name := value`) for reassignment; `$&T` is an exclusive borrow. `<<` returns, `>>` throws an error, and `>>> (err) { ... }` handles errors (`>>>` propagates at a call site). Error text is obtained with `err.msg()`. ## Essential syntax cheat sheet & anti-hallucination rules When answering questions about or generating Xu code: - **No colons in declarations**: Use `fn add(a int, b int) int` and `name Type`, never `a: int` or `name: Type`. - **Bindings and reassignment**. Declare a mutable binding with `$name := value` and reassign it with `name = new_value`. - **Return and Throw**: Use `<< expr` to return from a function (never `return expr`). Use `>> err` to throw a new error (never `throw err` or bare `>>> err` at statement level). Use `<<< code` to exit the process with an exit status code. - **Loop Control**: Use `<-` to break out of a loop (never `break`). Use `->` to continue to the next iteration (never `continue`). - **Error Handling**: Xu 0.15.0 removed legacy `or` error handling syntax (freeing `or` as an ordinary identifier). Always use `val := may_fail() >>> (err) { << err }` to handle errors at a call site, or postfix `val := may_fail() >>>` to propagate errors to the caller (never `or (err)`, `or >>`, `try/catch`, or `if err != nil`). Obtain the error message string with `err.msg()`. - **Borrowing**: `&T` denotes a shared read-only borrow; `$&T` denotes an exclusive mutable borrow. - **Coroutines and Channels**: Start coroutines with `xu f()` (never `go f()`). Create typed channels with `chan Type{cap: N}`. Send with `ch <- value`, receive with `val := <-ch`. - **Imports**: Standard library imports use a leading `#` (e.g. `#fmt`, `#strings`, `#net/http`, `#io`, `#time`, `#sync`, `#simd`, `#bytes/span`). - **Top-of-file `const` rule (Xu 0.16.0+)**: Module-level `const` / `pub const` declarations must appear after the package tag/imports and strictly above `fn`, `struct`, `enum`, `interface`, `impl`, and module `let` declarations; block-local `const` inside functions is forbidden. ## Complete examples Save each block in its own `main.xu`, then run `xu check main.xu` and `xu run main.xu`. These examples share their sources with the site playground and the bundled official error-handling example. ### Hello world ```xu @main fn main() int { println("Hello from XU Programming Language!") << 0 } ``` ### Coroutines and channels Use `chan int{cap: N}`, `ch <- value` to send, and `<-ch` to receive. The example collects three results before exiting. ```xu @main fn main() int { results := chan int{cap: 3} xu worker(1, results) xu worker(2, results) xu worker(3, results) $total := 0 for i in 0:3 { value := <-results total += value } println(total) << 0 } fn worker(id int, results chan int) { results <- id * 10 } ``` ### Error handling ```xu @main #errors fn read_name(ok bool) string { if !ok { >> errors.new("empty name") } << "ada" } fn load_or_fallback(ok bool) string { << read_name(ok) >>> (err) { println(err.msg()) << "fallback" } } fn main() int { s := load_or_fallback(false) println(s) t := read_name(true) >>> (err) { println(err.msg()) << 1 } println(t) << 0 } ``` ## Tools and package installation - `xu build main.xu -o app`: compile a native executable. - `xu run main.xu`: compile and execute. - `xu check main.xu`: check syntax, types, and ownership. - `xu debug main.xu`: build with debug information (DWARF compound types and symbolized panic backtraces in Xu 0.15.0+) and launch LLDB, with GDB as fallback; an installed debugger is required. - `xu test test.example.xu -v`: execute tests. Test and benchmark functions belong in `test..xu`, in `@main`, without parameters or return types. - `xu fmt main.xu`: format source. - `xu lsp`: serve LSP over stdin/stdout, including workspace symbol search and quick-fix code actions (such as migrating legacy `or` handlers to `>>>`). Completion mainly covers keywords, built-ins, and current-file declarations; references use identifier text matching in the current file and same-directory Xu files, and rename edits only the current file. - `xu install`: resolve dependencies already declared in `xu.xun`, populate `vendor/`, and write `xu.lock`. - `xu get @`: syntax template for adding a dependency with a verified published SemVer tag. Replace both placeholders. A module's declared version does not establish that a matching Git tag exists. - `xu native`: compile/archive native modules, pack `.xulib` slices, and inspect/extract them. One-step static linking with `xu build`/`xu run` currently supports `macos-arm64` and `macos-x64` only. Other targets require object emission, conversion, and external linking. Use the official packages bundled with the selected SDK, or the matching immutable source commit documented at https://xulang.org/docs/packages/. External imports use an explicit alias and full module path, for example `redis #github.com/xulang-org/packages/redis`. Standard-library and local-package imports have separate resolution rules (`#fmt`, `#util`). Redis connections use `redis.open`, `open_auth`, or `open_url`; consult the API for exact signatures. SQLite dynamically loads system `libsqlite3` via pure-Xu `sqlite_native` (built-in `winsqlite3.dll` on Windows) without requiring `.xulib` compilation. ## SDK, playground, and development scope The browser playground implements a language subset with cooperative channel scheduling and interactive `#ui` Canvas 2D, `#ui/widgets`, and `#ui/webgl` 3D demos. Native execution on Linux/macOS includes the M:N multi-core coroutine scheduler and `#sync/pool` (`pool.set_max_procs(N)`, `pool.max_procs()`, `pool.new_thread_pool(N)`) alongside thread-safe heap/FFI locking and hardware atomics; real multithreading, networking, C FFI, and desktop UI require the native SDK. See https://xulang.org/playground/ for the current sandbox limits. Operating system development uses the released freestanding toolchain. Build ELF64 kernels with `--profile=freestanding` and `--target=x64-none`, `arm64-none`, or `riscv64-none`, UEFI images with `--target=x64-uefi` / `arm64-uefi`, or ESP32 / ESP32-C3 (RV32) ELF32 objects with `--emit-obj` (`--no-sse`, `--no-fp`, `--stack-size`, `@interrupt`, `@panic_handler`, `@weak`, `@naked`, `#core/{arch,sync,task,virtio,uefi,acpi,pci,fdt,elf,mmio,mem,alloc,mmu,backtrace,net,disk,crc,uart,ahci,nvme,rtc,xhci}`). See https://xulang.org/docs/os/. Local AI inference and numerical computing span four layers in Xu: `#tensor` provides F16/BF16/FP8 encodings (`dequant_f16_to_f32`, `dequant_bf16_to_f32`), GGML `Q4Block`/`Q5Block`/`Q8Block`/`Q4KBlock`/`Q5KBlock`/`Q6KBlock` decoders + `Q8_K` integer K-quant helpers (`quantize_q8_k_row`, `dot_q4_k_q8_k_row_f32`, `dot_q5_k_q8_k_row_f32`, `dot_q6_k_q8_k_row_f32`), strided `TensorView` (`reshape`, `permute`, `read_f32_bytes`, `write_f32_bytes`), and 47 pure-Xu forward/training primitives (`src/tensor/ops.xu`); `--tensor-fusion` / `XU_TENSOR_FUSION=1` (with optional `--tensor-fast-math`) lowers pure-Xu tensor loops to ARM64 NEON/SDOT and x86-64 SSE2/SSSE3 kernels (including K-quant SIMD); `examples/llm_engine/main.xu` (modularized into `models`/`vision`/`gbnf`/`quantize`) runs multi-threaded CPU inference (`--threads N`), Multimodal VLM (`mmproj.gguf` F32/F16/BF16 & SafeTensors + PNG/JPEG/PPM/BMP + inline ``), HuggingFace/SafeTensors & GGUF (`F32`/`F16`/`BF16`/`FP8`/`Q4_0`/`Q4_1`/`Q5_0`/`Q5_1`/`Q8_0`/`Q2_K`โ€“`Q8_K`), `VocabIndex` Trie + `GbnfMaskCache` (`--grammar` / `--json-schema` supporting `$ref`/`$defs`/`allOf`/`pattern` + `--gbnf-max-branches`), PEFT LoRA + `merge-lora`, `quantize`, `perplexity`, pure-Xu `train-lora`/`train-dpo`/`train-grpo`/`train-rlvr`/`train-distill`, lossless `--draft` speculative decode, Mamba SSM & Hybrid Attention+SSM GGUF, DeepSeek MLA, MoE, YaRN RoPE, and multi-slot continuous-batching HTTP `serve` (`/v1/*`, `/v1/messages`, `/api/*`, `/health`, `/metrics`); and standalone `github.com/xulang-org/packages` (`v1.17.0`, 50 packages) provides multi-backend GPU (`gpu`, `llm_metal`, `metal`/`metal_native` 176 symbols + K-quant SIMD GEMV, pure-Xu `dlopen` `cuda_native`, pure-Xu `dlopen` + SPIR-V `vulkan_native`) alongside `synth`, `openai` (11 presets), `cohere`, `gateway` (Redis distributed state + `ProviderPassthrough`), `prompt`, `anthropic`, `gemini`, `mcp` (`2025-03-26`), `a2a` (API key/hook auth + SQLite store + SSE), `agent` (4-runtime parity, cross-provider `AgentSwarm`, SQLite memory/checkpoints, `SKILL.md`, parallel HITL `StateGraph`, OTLP/Prometheus), `guardrails` (`strict_policy`, `normalize_for_detection`), `eval` (`evaluate_json_schema_raw`, `pass_at_k`, Ragas triad, LLM judges), `rag` (`PgVectorPool`, `PgVectorClient`, cached `SqliteVectorStore`, `QdrantVectorStore`, GraphRAG), `postgres`, `sqlite`, `qdrant`, `milvus`, and `chroma`. See https://xulang.org/docs/ai/. Known AI limitations and caveats: `examples/llm_engine` runs multi-threaded CPU (`--threads N`) rather than dispatching directly to Metal or CUDA (use `packages/llm_metal` for Apple Silicon GPU Transformer inference or `packages/gpu` for multi-backend GPU kernels); GGUF supports K-quants (`Q2_K`โ€“`Q8_K`) and `Q4_1`/`Q5_1`, while imatrix `IQ1`โ€“`IQ4` are unsupported; image decoding covers PNG/JPEG/PPM/24-bit BMP only; training targets single-node `f32` LoRA fine-tuning; since `Xu 0.14.3`, `xu build` embeds Mach-O `LC_CODE_SIGNATURE` ad-hoc signatures automatically (no manual `codesign` needed); `rag.SqliteVectorStore` scans loaded rows in memory ($O(N)$ exact search, best under ~10k chunks; use `PgVectorPool` or `QdrantVectorStore` at scale); `gateway` SSE failover applies before the first chunk arrives; terminate TLS/RBAC in front of `a2a`; and pair `guardrails.strict_policy` with `check_safety_openai` against adversarial evasion. See https://xulang.org/docs/ai/#limitations. XACP documentation describes the language repository's development branch, separately from the selected released SDK. The implementation includes stdio and loopback TCP control. With a registered Screen, `ui.record` performs bounded XAR1 sampling within one request and returns `mode`, `records`, `bytes`, `truncated`, and quoted `payload`. It requires positive `win` and `mode: events|frames`, with optional `max_bytes`, `max_records`, and `duration_ms`. Clients pull successive segments by repeating requests, with one response per request, sequence numbers restarting at 1, and no persistent recorder or continuation cursor. `events` observes current `window/canvas/generation/open` state with `state=true`, without an input event log; `frames` exports dimensions only with `redacted=true`, without pixels. Sampling does not inject input or pump the application's event loop. `stream_required` is reserved for adapters without a sink/sampling capability; the supplied Screen sampling path does not return it. CLI `xu xacp record` captures stdout, separately from `ui.record`. See https://xulang.org/api/xacp/#ui-record and the authoritative dev protocol ยง7 at https://github.com/xulang-org/xu/blob/dev/examples/xacp/PROTOCOL.md#7-screenshots-mutations-and-recording. `xu xacp debug` inspects and launches a program; source debugging uses `xu debug`. ## Benchmark evidence The published dashboard contains 102 display groups with 121 measured workload variants across 6 platforms, measured with Xu 0.16.0 on 2026-11-29. Each algorithm and input size retains its own source and results; display groups do not combine measurements. The measurement identity is independent of the selected SDK. See https://xulang.org/benchmarks/ and the source CI run: https://github.com/xulang-org/bench/actions/runs/46208668702. Consult the dashboard's per-platform results and methodology rather than infer a universal speedup. ## Documentation index - Documentation hub: https://xulang.org/docs/ - Getting started: https://xulang.org/docs/start/ - Installation: https://xulang.org/docs/install/ - Language syntax: https://xulang.org/docs/lang/syntax/ - Ownership and memory: https://xulang.org/docs/lang/memory/ - Concurrency: https://xulang.org/docs/lang/concurrency/ - Types: https://xulang.org/docs/lang/types/ - Grammar: https://xulang.org/docs/lang/ebnf/ - CLI: https://xulang.org/docs/cli/ - Modules: https://xulang.org/docs/modules/ - External packages: https://xulang.org/docs/packages/ - Native modules: https://xulang.org/docs/native/ - Operating system development: https://xulang.org/docs/os/ - Local AI inference: https://xulang.org/docs/ai/ - VS Code / Cursor: https://xulang.org/docs/vscode/ - Tutorials (run commands from the separate examples repository root): https://xulang.org/docs/tutorial/01/ - Standard library and package API: https://xulang.org/api/ - FAQ: https://xulang.org/docs/faq/ - Release notes: https://xulang.org/blog/ - Expanded LLM reference: https://xulang.org/llms-full.txt