# Vex documentation snapshot Documentation target: 0.4.0. Source order is deterministic. Each document is identified by its canonical Markdown URL. Read /llms.txt first when working within a limited context. --- Source: https://vex-lang.org/docs/architecture/compiler-pipeline.md # Compiler Pipeline This page describes the main compilation flow from source text to native code or SIR-backed execution. ## End-to-End Flow ```text source (.vx) -> lexer -> parser / syntax tree -> HIR lowering -> comptime generator discovery and canonical CTFE -> sealed source/generated HIR snapshot -> type inference + borrow analysis + semantic checks -> typed known/residual staging -> codegen selection -> LLVM/native path -> SIR graph path -> link / subprocess execution ``` ## Front-End Stages ### Lexer `vex-lexer` tokenizes source text. ### Parser `vex-parser` constructs the syntax tree and keeps enough recovery behavior for diagnostics and tooling. ### Syntax Layer `vex-syntax` defines the syntax node model used by the parser and later lowering passes. ## HIR and Semantic Analysis `vex-hir` is where syntax becomes semantically meaningful program structure. Key responsibilities include: - name resolution - type inference - pattern lowering - contract-related checks - borrow and move analysis - enum, `Option`, and `Result` behavior ## Comptime and expansion Canonical CTFE runs on HIR before backend codegen. It evaluates strict `#` boundaries and eligible ordinary `const fn` calls, expands authorized typed `DeclSet` module generators, and produces one sealed source/generated semantic snapshot for compiler, diagnostics, lint, and LSP. Staging classifies work as known, typed residual HIR, or an error. Runtime effects and runtime-dependent values remain in the ordinary pipeline; strict compile-time consumers never receive a runtime fallback. Generated declarations are not printed or reparsed and do not cross a separate bitcode boundary. Their typed HIR remains visible to monomorphization, VUMM, fusion, ABI lowering, and dead-code elimination. See [Comptime Pipeline](docs/architecture/comptime-pipeline.md) for the full flow. ## Memory-Safety Analysis The repository describes the borrow system as a multi-phase analysis model. The high-level responsibilities are: 1. immutability and `let` vs `let!` enforcement 2. move tracking 3. borrow rule validation 4. lifetime-oriented validation This is the part of the compiler that enforces the memory model documented in the guide. ## Two Main Lowering Paths ### Native LLVM Path `vex-compiler` lowers checked HIR into LLVM IR and then into object code, linked executables. This path is the default for ordinary systems code. #### Callable and alias contracts First-class functions and closures have one internal representation: `{ code, context }`. The context is always a valid non-null pointer; a capture-free callable uses a private sentinel without a heap allocation. Direct calls, indirect calls, callable fields and error-rescue handlers share the same physical ABI decisions for hidden return storage, aggregate parameters, references, alignment and capture guarantees. Because a true indirect call has no visible declaration to inherit from, its sealed HIR function type publishes those facts at the call site too: initialized scalar, aggregate and SIMD results retain `noundef`, while `Box` and reference results retain `nonnull noundef`. Ownership alone never invents allocator-style return `noalias`. O3 indirect-call promotion is proof-carrying. It consumes only the exact target identities sealed by semantic lowering in standard LLVM `!callees` metadata; it never guesses candidates by scanning for the same opaque-pointer signature. Without that proof the call stays indirect. Before rewriting, the pass also requires an exact function type, calling convention and ABI-attribute match. Variadic calls, `tail`/`musttail`, invokes and unknown call metadata fail closed, while operand bundles, `notail`, attributes, fast-math flags, debug locations and the indirect fallback are preserved. LLVM alias information is emitted only from sealed semantic facts. Alias-scope domains are operation-distinct even after separately compiled modules are linked. TBAA describes the storage actually accessed: pointer slots are pointer storage, whole aggregates and byte views remain conservative, and scalar field identities include the exact nominal owner and generic specialization. Missing owner or layout information removes the optimization claim instead of guessing from a source name. Call coercions follow the same rule. Direct calls, function values and Vex source-variadic packing consume the typed HIR coercion plan before physical ABI transport is selected. LLVM bit widths alone never decide a language conversion or signedness; an unsealed conversion fails before IR emission. Memory alignment follows pointer provenance as well. A SIMD value's preferred register/ABI width is not treated as proof that an array or slice address has the same alignment. Generic vector memory operations are conservative; optimized paths publish stronger alignment only from the element type, Vex's allocator/entry-alloca guarantee, or immutable global storage. This keeps the same source valid on NEON, AVX2 and AVX-512 without sacrificing vectorized O3 code. Allocator-backed closure fields use their exact TargetData offset, while array and Vec stores are bounded by the storage base and element ABI. Repeated SIMD stores also include their byte stride in the proof, so a strongly aligned first address cannot overstate later iterations. Pointer-transported aggregate copies use the destination alloca's exact guarantee and the source type's target ABI alignment; no fixed alignment is guessed for closure or contract-default arguments. Program-lifetime `invariant.load` metadata is likewise restricted to real loads from true constant globals, never ordinary immutable borrows. The cooperative async-local allocator is also a proven 16-byte source: its page, bump, size-class and private-header layout preserve that boundary, so its LLVM return declaration publishes the fact directly. Pointer-backed aggregate values are not all equivalent, however. Stack storage, general/async allocation, RC/ARC payloads and user pointers have different guarantees; aggregate copies must carry storage provenance before the compiler strengthens their alignment. Runtime function attributes also describe the intersection of all target implementations, not the most favorable backend. Arena and region accessors may release a losing first-use runtime-state allocation, while standard-stream wrappers can cross a libc `FILE*` boundary on macOS. Those functions therefore keep their proven control-flow facts but do not advertise `nofree` to LLVM. Bounds facts preserve the source integer contract. Signed and unsigned indices are widened differently, and 128-bit indices keep all of their high bits until the bounds decision; the backend never truncates first and then mistakes a wrapped value for a valid address. SIMD chunk loops prove `width <= length - index` before publishing any no-wrap increment. Thus the check itself remains defined even for adversarial maximum-size inputs, while the guarded hot loop still gives LLVM the strong fact it needs. Allocation optimizations use exact LLVM def-use identity rather than pointer names or a search for one direct `free`. Consecutive allocations may be merged only when every derived use stays local and no derived pointer is freed; zero-size and overflowing size calculations are rejected. Heap-to-stack and SBO promotion share the same rule. Pointer casts and GEPs preserve one root, but PHI/select nodes are not assumed to do so because they may combine distinct allocation lifetimes. Heap-to-stack replacement preserves Vex's 16-byte allocator alignment and never turns a failing zero-size allocation into live stack storage. Coroutine frames additionally require an explicit non-owning wrapper proof; the optimizer does not mutate shared async wrapper or cleanup functions to erase frees. Arena-loop hoisting mirrors the runtime's physical layout. It specializes only exact constant positive loops, preserves signed induction widening, and uses a 16-byte stride per allocation. All trip/span arithmetic is checked, nested allocations belong to the innermost loop, and one batch cannot exceed an ordinary arena chunk. Dynamic or unrepresentable cases retain the original allocator calls. Small constant `memcpy` lowering is equally provenance-aware. Byte-pointer inputs are scalarized only for non-volatile copies and the generated accesses remain conservatively aligned to one byte unless an independent provenance proof strengthens them. Bounds-check reuse requires the exact normalized index and length SSA values plus dominance by a previous successful check; the optimizer never erases aggregate-field identity or signedness casts to invent a shared proof. CPU/GPU UMA barrier removal is proof-carrying. A pointer that is only read by the CPU is not enough: the read may follow a GPU write and require coherence. The optimizer removes a barrier only when semantic Valence lowering seals an exact proof covering transition direction, producer completion and the full alias set. Missing proof keeps the barrier live, and exception-capable `invoke` sites are never rewritten as plain branches. Constant string-slice folding preserves the language-level `usize` domain as well. High-bit indices remain unsigned and clamp to the view length exactly as the runtime operator does; the LLVM folder never reinterprets them as negative signed offsets. Receiver and result layouts are validated before constructing constant pointers or VexStr values. SSO concatenation folds only after validating its complete physical result layout. Unknown or stale layouts keep the original call, and pointer payloads retain their declared address space. Diverging direct calls terminate in `unreachable`; pruning their stale normal continuation also repairs successor PHI predecessors before LLVM sees the CFG. Inlining uses two levels of evidence. HIR can attach positive hints from typed semantic shape, and a post-lowering budget checks the concrete body after specialization, ownership lowering and Vex-specific simplification. Bodies over the configured instruction ceiling lose only automatic positive hints; the compiler does not turn size into a blanket `noinline` contract. Explicit source `inline fn` declarations and genuine semantic/cold boundaries remain authoritative, while LLVM's target-aware cost model decides otherwise unhinted call sites. Opt-in module profiling reports the top-five body concentration so cold outlining is introduced from measured evidence rather than source size. ### SIR Path When the program shape is suitable for data-parallel lowering, Vex can form SIR graphs that later target SIMD and selected accelerator backends. This path is the basis for: - vector-style arithmetic - tensor and mask operations - fusion and graph rewrites - backend-specific kernel generation ## Driver Layer The user usually interacts with the compiler through `vex-cli`, which wraps compilation, linking, execution, and test discovery. That means the operational pipeline is often: ```text vex run / vex compile / vex test -> compiler driver -> embedded VRI selection + semantic fusion -> explicit target/native link plan -> execution or test reporting ``` ## Related Pages - [SIR & Backends](docs/architecture/sir-and-backends.md) - [Comptime Pipeline](docs/architecture/comptime-pipeline.md) - [Runtime & Tooling](docs/architecture/runtime-and-tooling.md) - [CLI Reference](docs/references/vex-cli-reference.md) --- Source: https://vex-lang.org/docs/architecture/comptime-pipeline.md # Comptime Pipeline Architecture Vex comptime is a semantic HIR stage shared by the compiler, diagnostics, lint, and LSP. LLVM is a consumer of the result, not the evaluator and not the source of compile-time truth. ## End-to-end flow ```text source + target + tracked build inputs -> parse and lower source HIR -> discover eager module generators -> canonical CTFE under one metered expansion session -> seal source + generated declaration snapshot -> inference, contracts, ownership, borrow and layout validation -> effect classification and typed staging -> Known(value) -> Residual(typed HIR) -> Error(diagnostic) -> compiler / diagnostics / lint / LSP consume the same snapshot -> normal monomorphization, Valence/VUMM, fusion and backend lowering ``` This ordering prevents two historical failure modes: 1. a codegen-only evaluator making semantic decisions after analysis; and 2. generated source or bitcode losing identities, generic substitutions, provenance, ownership facts, or target facts at a serialization boundary. ## One canonical evaluator Canonical CTFE operates on Vex HIR values and semantic IDs. It does not depend on `CodegenContext`, LLVM values, symbol names, or host pointers. The value model covers target-aware fixed-width integers, bools, floats, text, typed aggregates, enums, sequences, insertion-ordered maps, references, reflection records, callable handles, and invocation-bound declaration plans. Every evaluation runs with explicit context: - source and expansion provenance; - exact generic type and const arguments; - selected target facts; - effect capabilities; - tracked environment/source inputs; - step, recursion, allocation, byte, collection, diagnostic, and expansion budgets. Required-comptime evaluation has only two terminal outcomes: a value/expansion or an error. It never silently asks codegen to execute the operation at runtime. ## Effect model Functions are classified from their semantic body and reachable calls. The important distinction is whether an operation is legal and deterministic in the current compile-time context—not whether it comes from user code, std, or VexArch. Pure arithmetic, exact reflection, deterministic collection operations, and tracked source/target queries may execute during CTFE. Runtime I/O, clocks, untracked external state, unsupported FFI, and runtime-only effects remain residual or are rejected by a strict boundary. Effects are transitive. A wrapper around a runtime-only call is not considered pure merely because its own body contains no direct intrinsic. ## Typed staging and residualization Staging reports a typed result: ```text StageResult = Known(T) | Residual(ResidualHIR) | Error(Diagnostic) ``` The rewrite is transactional. A candidate is committed only after the known subgraph evaluates, the replacement is well typed, and consumer-visible semantics remain valid. Otherwise the original HIR is preserved or a strict boundary emits a diagnostic. The accepted V2 frontier folds maximal known: - primitive binary operations; - primitive unary operations; - casts; and - exact function/method call islands. Runtime-dependent parents remain ordinary HIR. Overloaded operators with an exact callable fact are excluded from the primitive path until canonical CTFE can dispatch that callable directly. ## Collections and runtime materialization Compile-time allocations live in metered compiler storage. Host addresses are never Vex values and cannot escape. When a known text, sequence, map, struct, or enum must enter runtime HIR, CTFE produces a typed construction recipe. That recipe is lowered through the ordinary ownership path: ```text known CTFE value -> typed materialization recipe -> ordinary residual Vex HIR -> borrow/move/drop validation -> Valence/VUMM allocation and ownership selection -> fusion and backend codegen ``` There is no comptime-specific runtime allocator, object header, reference count, drop path, or hidden map representation. ## Structural declaration expansion An eager module generator is a top-level, non-generic, parameterless `const fn` returning `DeclSet`. Discovery creates a request containing its exact function identity, module owner, stable site key, lexical anchor, target, and budgets. The generator returns compiler-owned structural plans. Expansion: 1. reserves stable identity ranges for every invocation; 2. executes all generators under one cumulative metered session; 3. validates declaration roles, types, constraints, bodies, patterns, hygiene, and ownership; 4. remints generic type and const binders for the generated owner; 5. seals one combined source/generated scope and inference snapshot; and 6. exposes that same snapshot to compiler and tooling consumers. Generated native functions cross a dedicated typed boundary containing their signature, HIR body, provenance, and frozen inference result. They are not converted into source text, a synthetic parser tree, or a separate `.bc` module. ## Fusion and VexArch Known values are embedded into ordinary HIR before backend lowering. Residual user, std, and VexArch calls stay semantically visible in the same module and monomorphization graph. This allows normal inlining, reachability analysis, runtime fusion, ABI selection, and dead-code removal to operate across the boundary. Comptime does not bypass VexArch. It can execute eligible VexArch `const fn` logic, but runtime VexArch work remains in the same fused runtime path as handwritten user code. ## Persistent cache Persistent entries are semantic query results, not snapshots of host memory. Their keys include the compiler/language semantic version, target identity, generic instantiation, source dependencies, tracked environment/embed inputs, and effect policy. Deserialization validates the entire recursive wire envelope. Current hard limits are: | Limit | Value | | --- | ---: | | Semantic nodes | 100,000 | | Semantic payload | 64 MiB | | Recursive depth | 256 | The stack-safe validator meters value nodes, type arguments, nominal fields, and promoted projections. Corrupt, stale, too-deep, oversized, or target-incompatible entries become cache misses. Invocation-bound declaration values and compiler-storage addresses are never published as ordinary persistent constants. ## Target portability Layout, pointer width, integer domains, and target-specific intrinsic choices come from the exact semantic target key. Backend lowering checks that its LLVM target agrees with that key and fails closed on drift. For example, PDEP/PEXT may select LLVM x86 BMI2 intrinsics only for an exact `x86_64 +bmi2` target. Generic x86_64, i686, AArch64, and PowerPC64 use the deterministic software lowering. A host CPU feature cannot leak into a cross-compiled artifact. ## Consumer parity Compiler, diagnostics-only analysis, lint, and LSP use the same expansion and staging queries. The parity harness checks: - known/residual/error classification; - values and diagnostics; - generated identity and provenance; - target-sensitive behavior; - no-artifact analysis without LLVM; - native lowering of the same sealed HIR. The current V2 closure gates include full HIR and native suites, architecture invariants, HIR/CLI parity, persistent-cache envelope tests, and a semantic performance fixture. ### Staging policy and rollback The current CLI defaults to `apply-known` for native compile, run, and IR commands. Choose a mode explicitly when comparing behavior across builds: ```bash vex compile --comptime-staging apply-known app.vx vex compile --comptime-staging analyze app.vx vex compile --comptime-staging disabled app.vx ``` `apply-known` transactionally substitutes materialization-ready known islands in eligible user-source HIR. The current native adapter preserves sealed compiler-owned prelude/VexArch, standard-library and authoritative frozen package bodies. Source-fallback packages remain eligible when their source is the codegen authority. Runtime effects and unsupported values remain typed HIR; a failed optional rewrite keeps the original accepted body. `analyze` records staging observations while preserving the codegen body. `disabled` switches off optional staging. Neither setting disables required `#const`, `#if` or reflection evaluation: a failed required boundary remains a diagnostic, even when optional rewrites are disabled. Lint and test retain the observation-only `--analyze-comptime` option; test mode forwards it to generated test and benchmark compilation. LSP uses the default-false `analyzeComptime` setting in initialization options or `vex.lsp` configuration. These tooling controls cannot select `ApplyKnown`. Lint writes its aggregate semantic summary to stderr; test and benchmark runners forward the compiler summary; LSP retains only the latest summary per URI and clears it when the setting is disabled. For compiler telemetry, combine a non-disabled compile/run staging mode with `--comptime-telemetry FILE`. The versioned `vex.ctfe-staging` schema v5 includes stable semantic decisions, cache status, VRI inventory, VexArch fusion and capability reasons, backend phases, object/link timing, and separate host-side policy discovery plus persistent-cache lookup, decode, semantic-validation, installation, and publication clocks. Missing phases are `null`, not zero. These clocks never enter semantic query identity. Telemetry cannot implicitly turn staging on. Returning to `disabled` selects the original typed HIR snapshot for optional staging. `tools/run_apply_known_canary.sh` defines native parity, custom-drop, known-island IR and differential checks. Its presence is a test entry point, not evidence that a particular release passed those checks. The CLI default is defined by `ComptimeStagingMode` in `tools/vex-cli/src/cli_commands.rs`; the source-authority boundary is in `crates/vex-compiler/src/codegen_hir/staging.rs`. ## Measuring Staging Cost Measure analysis overhead separately from known-root evaluation. Compare cold and warm runs with the same compiler, source, target, flags and cache state. The staging telemetry separates policy discovery, cache work, evaluation and backend/link phases; a faster known-root lookup need not make the whole build faster when inference or native linking dominates. Use a representative package workload and retained per-phase observations when comparing build time. Include parsing, inference, native code generation, and linking in an end-to-end measurement. ## Deliberate post-V2 extensions The architecture keeps the following out of the accepted V2 contract: - cyclic persistent values; - arbitrary boolean constraint algebra; - unknown-slot aggregate residual graphs; - unproven scalable/GPU/foreign vector ABI layouts; - token/procedural macro compatibility layers. Future work must extend the canonical identity, effect, ownership, target, cache, and parity contracts. It must not add a second evaluator or a codegen-only semantic fallback. ## Related - [Compile-Time Evaluation](docs/guide/advanced/comptime.md) - [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md) - [Compiler Pipeline](docs/architecture/compiler-pipeline.md) - [Runtime Architecture](docs/architecture/runtime-architecture.md) - [VUMM](docs/guide/memory/vumm.md) --- Source: https://vex-lang.org/docs/architecture/index.md # Architecture This section explains how Vex source moves through the compiler and where the major subsystems live in the repository. Source paths refer to the development implementation reviewed for the 0.4.0 documentation. They explain ownership of behavior; the [verification evidence](docs/guide/verification-evidence.md) records executable checks and their actual compiler identities. Diagrams are conceptual, not source excerpts. ## Pipeline Overview ```text source (.vx) -> lexer -> parser / syntax tree -> HIR lowering -> comptime declaration expansion + canonical CTFE -> sealed source/generated HIR snapshot -> type inference + borrow analysis + semantic checks + typed staging -> codegen path selection -> LLVM/native path -> SIR path for data-parallel graphs -> link / run / test integration ``` The important split is that Vex has both: - a native LLVM-oriented path for ordinary systems code - a SIR path for tensor-, SIMD-, and graph-oriented lowering ## Major Crates ```text crates/ vex-lexer tokenization vex-parser syntax parsing and recovery vex-syntax syntax node definitions vex-hir semantic IR, inference, borrow checking vex-sir Silicon IR graphs and backend lowering vex-diagnostics diagnostics formatting and reporting vex-compiler main codegen pipeline and prelude/runtime integration ``` ## Front End ### `vex-lexer` Responsible for turning source text into tokens. ### `vex-parser` Builds the syntax tree and handles recovery from malformed input well enough to support diagnostics and tooling. ### `vex-hir` This is where most language semantics become concrete: - name resolution - type inference - pattern handling - borrow and move analysis - enum/result/option semantics ## Native Codegen Path The native path in `vex-compiler` lowers checked HIR into LLVM IR and from there into object code and linked executables. This path is used for ordinary systems programming, CLI tools, servers, runtime code, and general application code. ## SIR Path `vex-sir` handles data-parallel graph lowering for tensor- and array-oriented computation. It is the basis for: - SIMD-friendly expression lowering - graph fusion - compute backends such as SPIR-V, WGSL, and Metal - graph/runtime dispatch decisions for heterogeneous execution If you are working on vectorized operators, tensors, masks, or GPU-facing computation, this is the path to understand. ## Runtime and Tooling Outside the language crates, the repository also includes: - runtime support under `lib/runtime/` - CLI tooling under `tools/vex-cli/` - editor/LSP tooling under `tools/vex-lsp/` - formatter and supporting developer tools under `tools/` ## Where to Start Reading - Start in [Guide](docs/guide/introduction.md) if you want language semantics. - Start in [CLI Reference](docs/references/vex-cli-reference.md) if you want execution and command behavior. - Start in [GPU & SIR](docs/guide/gpu/index.md) and [SIMD](docs/guide/simd/index.md) if you care about the graph path. ## Architecture Pages - [Compiler Pipeline](docs/architecture/compiler-pipeline.md): source to HIR to native/SIR lowering - [Comptime Pipeline](docs/architecture/comptime-pipeline.md): CTFE, typed residualization, declaration expansion, caching, and fusion - [SIR & Backends](docs/architecture/sir-and-backends.md): graph path, backend maturity, and acceleration routing - [Runtime & Tooling](docs/architecture/runtime-and-tooling.md): runtime model, CLI, tests, docs, and editor tooling ## Lexer (vex-lexer) The lexer uses [Logos](https://github.com/maciejhirsz/logos) for high-performance tokenization. ### Token Types The actual token definitions are Rust source in `crates/vex-lexer/src/lib.rs` (`Token`). Check that file for current variants; simplified examples are not a token inventory. ### Automatic Semicolon Insertion Automatic semicolon insertion is implemented in `crates/vex-lexer/src/asi.rs`; consult the source and tests for the current rules. ## Parser (vex-parser) Built on Rowan for lossless syntax trees with error recovery. ### Syntax Kinds `SyntaxKind` is represented in `crates/vex-syntax/src/syntax_kind/mod.rs`, with parser implementation under `crates/vex-parser/src/`. It is not the Rust enum previously sketched on this page. ### Error Recovery Parser recovery is implementation-specific; start with `crates/vex-parser/src/` and its syntax tests rather than treating an illustrative parser loop as source code. ## HIR (vex-hir) High-level IR with semantic information, powered by Salsa for incremental computation. ### Type System The actual Rust `Ty` definition is in `crates/vex-hir/src/ir/types/definition.rs`. Its variants and representations evolve with the compiler. ### Borrow Checker The borrow checker contains non-lexical lifetime (NLL) analysis. Its exact algorithms and guarantees must be read from the current implementation and tests. The implementation lives under `crates/vex-hir/src/borrow_check/`, including the `nll` subtree; the previous `BorrowChecker` structure was a schematic, not an API. #### Four-Phase Analysis The following are conceptual categories, not a claim that the implementation runs four fixed sequential phases: 1. **Immutability Check**: Verify `let` vs `let!` usage 2. **Move Analysis**: Track ownership transfers 3. **Borrow Analysis**: Verify borrowing rules 4. **Lifetime Analysis**: NLL region inference ### VUMM (Vex Unified Memory Model) VUMM analyzes memory and ownership behavior; decisions depend on the exact program and compiler build. The actual `BoxKind` definition is in `crates/vex-hir/src/vumm/kind.rs`; inspect its current variants and analysis in `crates/vex-hir/src/vumm/` rather than assuming a fixed sequence of passes. ## SIR (Silicon IR) Intermediate representation for data-parallel computation, with CPU and accelerator paths when supported. ### Node Types The actual `SirNode` enum is in `crates/vex-sir/src/graph/node/mod.rs`. SIR represents supported computations; the presence of a node does not prove that every backend can emit it. ### Backends Backend implementations live under `crates/vex-sir/src/codegen/backends/`. Their APIs, target availability, and supported operations differ; they do not imply a universal `Backend` interface or successful execution on every device. ### Automatic Differentiation Autograd-related structures exist in the source tree, but presence alone does not establish that automatic differentiation is part of the active graph pipeline. See [SIR Pipeline](docs/guide/simd/sir-pipeline.md) for the status and validate the intended path. ## Runtime ### VexArch Runtime Layer ```text lib/runtime/ ├── VexArch/ │ ├── src/ │ │ ├── async/ # Scheduler, channels, poller integration │ │ ├── io/ # Runtime I/O services │ │ ├── mem/ # Allocation and memory primitives │ │ ├── sync/ # Synchronization primitives │ │ └── unwind/ # Panic and unwind support │ └── native/ # Explicit platform/native artifacts └── src/ # Optional Rust runtime-core integration ``` VexArch is the production runtime written in Vex. Target-specific `.vxc` selection follows `os.arch → os → arch → generic`, so public modules do not hard-code a platform backend. Imported symbols use explicit `LIBC`, `SYSTEM`, `VEX`, or `NATIVE` providers; a freestanding build does not gain a hidden libc dependency merely by importing a standard-library module. See [Runtime Architecture](docs/architecture/runtime-architecture.md) for the provider model, memory boundary, scheduler, and link-plan rules. ## Diagnostics (vex-diagnostics) Rich error reporting with source locations. The actual Rust diagnostic data and engine live in `crates/vex-diagnostics/src/types.rs` and `crates/vex-diagnostics/src/engine.rs`; this is not a Vex language API. ### Example Output The following is illustrative pseudodiagnostic text, not a captured Vex compiler result. Diagnostic codes and wording can differ by build. ```text error[E0382]: borrow of moved value: `data` --> src/main.vx:10:20 | 8 | let data = vec![1, 2, 3]; | ---- move occurs because `data` has type `Vec` 9 | consume(data); | ---- value moved here 10 | println(data); | ^^^^ value borrowed here after move | help: consider cloning the value if you need to use it again | 9 | consume(data.clone()); | ++++++++ ``` ## Build System Integration ### Incremental Compilation The compiler uses Salsa-backed queries in its HIR implementation. Consult `crates/vex-hir/src/lib.rs` and the relevant query implementation for current cache and invalidation behavior. ### Parallel Compilation Parallelism and incremental behavior vary by stage and build configuration. The old `compile_crate` fragment was pseudocode, not a guaranteed scheduling algorithm; measure the exact workload. ## Next Steps - [Language Guide](docs/guide/introduction.md) - Language syntax and semantics - [Contributing](docs/guide/contributing.md) - How to contribute - [Reference](docs/references/index.md) - CLI, test, package, and documentation tools --- Source: https://vex-lang.org/docs/architecture/runtime-and-tooling.md # Runtime and Tooling The Vex repository is more than a compiler. The runtime and tools layer determines how code is linked, executed, tested, formatted, and surfaced in editors. ## Runtime Layer Runtime support lives primarily under `lib/runtime/`. This layer includes infrastructure for: - allocation and heap management - async and task runtime support - scheduler state - runtime symbols used by CLI execution paths - platform integration for native execution ## Execution Model Vex compiles to native code ahead-of-time (AOT). Both `vex run` and `vex compile` produce native binaries via LLVM. `vex run` compiles to a temporary executable and runs it as a subprocess; `vex compile` produces a standalone binary. VexArch is rehydrated from the compiler's embedded VRI and lowered into the same backend module as user and prelude code. Release packages do not carry a VexArch bitcode module or static/dynamic runtime library. A tiny target-selected native support object may be materialized for irreducible assembly. The macOS build also has a native Objective-C CoreML bridge; that platform integration is distinct from VexArch semantic runtime code. System and package-native dependencies remain explicit in the final link plan. ## CLI Tooling `tools/vex-cli/` is the main developer-facing entry point. Important commands: - `vex run` - `vex compile` - `vex test` The CLI owns orchestration around: - dependency resolution - compiler-driver invocation - embedded VRI target selection and semantic fusion - linking - execution model selection - test discovery and execution ## Other Tooling The repository also contains: - `tools/vex-lsp/` for editor integration - formatter tooling - docs tooling and site generation These tools matter because they all depend on the same semantic model staying aligned with the compiler. ## Why This Layer Matters Many user-facing “language” issues are actually toolchain or runtime issues: - requested-target ABI and native-support selection - reachable provider/link-plan differences - fused runtime reachability constraints - test-runner discovery assumptions - editor/compiler semantic drift Understanding this layer makes debugging much faster. ## Related Pages - [CLI Reference](docs/references/vex-cli-reference.md) - [Test Reference](docs/references/vex-test-reference.md) - [Compiler Pipeline](docs/architecture/compiler-pipeline.md) --- Source: https://vex-lang.org/docs/architecture/runtime-architecture.md # Runtime Architecture VexArch is the target-routed runtime implemented in Vex under `lib/runtime/VexArch`. It provides allocation, ownership support, async scheduling, channels, I/O, networking integration, panic paths, and platform ABI adapters without making libc an implicit language dependency. The separately packaged `vex-runtime-core` Rust artifact is a hosted compatibility option. It is not folded into the freestanding VexArch object, bitcode, or archive. ## Runtime Layer Map ```text +------------------------------------------------------+ | Vex application and lib/std public APIs | +------------------------------------------------------+ | v +------------------------------------------------------+ | Compiler HIR/ABI lowering and generated code | +------------------------------------------------------+ | v +------------------------------------------------------+ | VexArch | | mem | async | channel | io | unwind | platform glue | +------------------------------------------------------+ | | v v +---------------------------+ +------------------------+ | Explicit OS system ABI | | Manifest-owned native | | SYSTEM / selected LIBC | | NATIVE feature | +---------------------------+ +------------------------+ ``` There is no universal `extern "C"` import bucket. Every imported symbol states its owner: | Provider | Meaning | | --- | --- | | `extern "LIBC"` | An intentional hosted C-library dependency | | `extern "SYSTEM" from "library"` | A named operating-system DLL, dylib, or framework | | `extern "VEX"` | Compiler/runtime-owned ABI; reserved for VexArch, prelude, and standard-library internals | | `extern "NATIVE" from "feature"` | A package native feature whose artifacts are declared in `vex.json` | `export "C" fn` is different: it defines an unmangled outbound C-ABI symbol. It does not select an import provider or add a library dependency. See the [FFI guide](docs/guide/ffi.md) for the complete provider contract. ## Target-Routed Sources Vex source files can select an OS and architecture directly. For an import of `native.vx`, resolution uses the first file that exists: 1. `native...vx` 2. `native..vx` 3. `native..vx` 4. `native.vx` The same rule applies to `.vxc`. Source routing uses OS/architecture names; package native artifacts prefer exact target triples before explicit OS/architecture, OS/environment, OS and `all` fallbacks. These are intentionally separate mechanisms. ## Memory and Freestanding Boundary The active memory implementation lives under `VexArch/src/mem`: - `arena.vx` owns arena state, region tokens, and runtime state; - `alloc.vx` owns slab, heap, realloc, and compatibility allocation entry points; - `vumm.vx` implements Vex Unified Memory Model routing; - `raw_pages.*.vx` and `compat.*.vx` provide target-specific page, thread, and process primitives. VexArch does not require a hosted `malloc/free` allocator. Target code may call explicit system APIs, direct kernel interfaces, or selected hosted facilities, but such dependencies remain visible through the provider and final link plan. A freestanding link rejects activated `LIBC` requirements. Prelude types such as `Box`, `Vec`, `string`, and `Mem` use the reserved VEX ABI internally. Application code consumes their public APIs instead of declaring raw allocator symbols. ## Async Runtime and Channels The scheduler and async state machine support live under `VexArch/src/async`: - `async.vx` owns worker/task scheduling and lifecycle; - `channel.vx` implements channel state and waiter coordination; - `timer_wheel.vx` tracks timed wakeups; - `poller..vx` integrates the target event mechanism. Reachable async code is capability-specialized. Straight-line `async fn` and `await` graphs use a single-owner cooperative FIFO without materializing worker, timer, channel, or poller machinery. Because that mode has no external wake source, live tasks with an empty runnable FIFO are reported immediately as a cooperative deadlock instead of consuming a core in finalization. Full async graphs retain provider-aware parking because an empty runnable set can be waiting legitimately on I/O, timers, or channels. Background worker bootstrap is also ownership-checked. A native thread enters the scheduler only after its thread-local async state is attached to the exact shared runtime that spawned it. If attachment fails, the worker cleans up and acknowledges exit instead of constructing a second scheduler and leaving the original runtime blocked during shutdown. Target files select the appropriate implementation at compile time. Runtime modules import concrete Vex implementations directly where possible. A small number of reserved VEX ABI edges remain where two core runtime modules form a deliberate dependency cycle or where a native bootstrap shim supplies the symbol. ## I/O and Networking VexArch owns stream state and exposes runtime I/O entry points. Target-specific files such as `io/native.macos.vx`, `io/native.linux.vx`, and `io/native.windows.vx` bind to the relevant system surface without exposing C `FILE` layout as Vex ABI. `lib/std/io`, `lib/std/fs`, and `lib/std/net` build public, typed APIs over this boundary. Their low-level target files use explicit `SYSTEM`, `LIBC`, `VEX`, or `NATIVE` declarations according to the actual symbol owner. Optional native codecs, database drivers, or TLS implementations are package features rather than hidden global linker inputs. ## Extern Activation and Linking Parsing an extern declaration alone has no link effect. Codegen records the providers required by emitted uses, and the CLI constructs a deterministic native link plan from those activated requirements. Important failures are reported before native linking: - an activated `LIBC` provider is rejected in freestanding mode; - an unresolved `VEX` provider is rejected when `--no-runtime` is selected; - a `NATIVE` feature must resolve to artifacts owned by the package manifest; - system libraries are deduplicated deterministically. Provider requirements are preserved beside warm prelude cache entries, so a warm compile cannot silently lose an FFI dependency. ## Runtime Semantic Image and Fusion VexArch is not shipped or linked as a separate LLVM bitcode, object, static archive, or shared library. Cargo validates the VexArch package and embeds a deterministic, versioned Vex Runtime Image (VRI) in the compiler. The image contains lossless pre-parsed syntax, stable package/source identities, provenance and target selectors. For each user compilation the compiler rehydrates the selected VRI sources without invoking the parser. User code, the prelude and VexArch then enter one semantic graph. Exact `DefId` reachability, monomorphization and callback address-taking decide which runtime bodies are materialized in the same backend module as user code. This keeps cross-boundary inlining and eliminates unused runtime code before backend DCE. Architecture-specific assembly is allowed only for operations that cannot be expressed in Vex. Cargo assembles this tiny target pack once and embeds it in the compiler; the CLI materializes the content-addressed object only because native linkers require a filesystem input. It carries no Vex semantics. This assembly pack is not the entire native support inventory: the macOS CLI build separately compiles an Objective-C CoreML bridge for the platform framework boundary. ## Safety Rules - Foreign calls require an audited `unsafe` boundary. - A concrete local definition or explicit import owns its name over an ambient prelude extern declaration. - Raw VEX ABI declarations are runtime/standard-library internals, not the application-facing API. - Provider choice describes ownership; it is not inferred from a filename or platform convention. - Outbound `export "C" fn` definitions must expose explicitly ABI-safe types. ## Related Pages - [FFI](docs/guide/ffi.md) -- provider syntax and link behavior - [FFI Deep Dive](docs/guide/ffi-deep-dive.md) -- ownership and ABI design - [Freestanding Vex](docs/guide/freestanding.md) -- hosted and freestanding boundaries - [VUMM](docs/guide/memory/vumm.md) -- Vex Unified Memory Model - [Concurrency Deep Dive](docs/guide/concurrency/deep-dive.md) -- scheduler behavior --- Source: https://vex-lang.org/docs/architecture/sir-and-backends.md # SIR and Backends SIR, short for Silicon IR, is the graph-oriented lowering path used for Vex's data-parallel execution model. ## What SIR Is For SIR is the part of the architecture that turns array-, tensor-, and graph-friendly computation into backend-specific execution plans. Typical features routed through or associated with this layer include: - tensor and mask lowering - fused arithmetic graphs - reductions and SIMD-oriented ops - backend-specific code generation ## Main Idea ```text Vex source -> HIR -> SIR graph -> optimization / fusion / lowering -> backend codegen ``` ## Code Generation and Execution Each route needs several independently implemented pieces: 1. HIR lowering for the operation, type and shape. 2. A legal SIR graph and backend emitter. 3. A compatible kernel representation, such as MSL, PTX or SPIR-V. 4. A runtime executor and compiler bridge using the same buffer/entry contract. 5. A compatible device, installed provider and numerical validation. An emitter producing text proves only one step. For example, ROCm HIP source is not a loadable HSACO code object; a WebGPU runtime executor does not by itself make every legacy compiler-generated GPU call ABI compatible. The [backend reference](docs/architecture/sir-backends-reference.md) separates these routes. ## Routing and Fallbacks The architecture includes runtime/backend selection and fallback logic. That means a graph may: - stay on SIMD/CPU - route to a specific backend - fall back depending on capability, shape, or runtime constraints This is part of why backend maturity and runtime availability both matter. ## Where to Read Next - [SIMD Overview](docs/guide/simd/index.md) - [GPU Programming](docs/guide/gpu/index.md) - [Fusion Graph](docs/guide/fusion/graph.md) - [Runtime & Tooling](docs/architecture/runtime-and-tooling.md) --- Source: https://vex-lang.org/docs/architecture/sir-backends-reference.md # SIR Backend Reference Silicon IR (SIR) describes computations independently of a particular device. A backend translates supported graph nodes to a target representation. An executor must then load that representation, bind buffers, dispatch work, and return results. These are separate capabilities: a generated shader is not proof that an application can execute it on a selected device. ## Backend Overview The following is an implementation map for the 0.4.0 documentation. Support must be checked for the actual operations, element types, shapes, build features and runtime device. It is not an all-operations compatibility table. | Backend family | Generated representation or role | Execution boundary | | --- | --- | --- | | Metal | Metal Shading Language | The native Metal executor requires a macOS build with Metal support and an available device. | | CUDA | PTX | The CUDA executor requires the compiled CUDA feature, driver/device support and compatible generated PTX. | | ROCm | HIP source; native execution consumes HSACO | HIP text is not an executable code object. The direct graph execution path rejects attempts to use it without the required compilation step. | | SPIR-V / Vulkan | SPIR-V modules and Vulkan-oriented generation | Module features must match the selected adapter, including subgroup operations. | | WGSL / WebGPU | WGSL generation and a separate WebGPU runtime path | Native WebGPU, browser integration, shader generation and the compiler call bridge have distinct requirements. | | OpenCL | OpenCL-oriented generation | Inspect the selected runtime integration; backend presence does not establish a driver or executor. | | CoreML | CoreML model generation and an optional NPU dispatch path | Requires the macOS CoreML feature and a model supported by the runtime. The framework chooses device placement. | | OpenVINO | Inference-oriented generation | Check model/operator support and runtime integration separately. | | CPU SIMD / scalar | LLVM vector or scalar lowering | A CPU route must support the graph too; an unsupported GPU graph is not automatically executable on every CPU path. | See [SIMD/SIMT execution contracts](docs/guide/simd/simd-simt-contract.md) for the operation-specific mask, subgroup and compiler/runtime boundaries. ## Metal Backend The Metal generator emits MSL for supported SIR nodes. Buffer layout, resource binding, dtype support and synchronization are part of the generated-kernel contract. Apple Silicon unified memory does not eliminate allocation, resource wrapping, synchronization or possible copies in the actual integration. Metal does not provide a native `f64` lane type. Some development generator paths narrow `F64` nodes while others reject them. Use an explicitly supported dtype and validate numerical error; do not treat CPU `f64` results as the implicit semantics of a Metal `float` computation. ## CUDA Backend PTX generation and CUDA execution are separate steps. Instruction selection also depends on GPU capabilities and graph shape. A matrix expression does not promise Tensor Core use, a particular tile size, or a cuBLAS call. Inspect the emitted artifact and measure the actual workload before making such claims. ## ROCm Backend The source contains a HIP generator and a native module executor that consumes HSACO. The direct `execute_sir_graph` path explicitly rejects ROCm execution when only generated HIP text is available. A deployment needs a compatible compiled code object and its corresponding launch descriptor; renaming source text to a binary artifact cannot supply that boundary. ## SPIR-V Backend SPIR-V is an intermediate representation. A generated module must declare only the capabilities available on the selected executor. Subgroup ballot, arithmetic, barriers and width assumptions are checked separately. Driver acceptance and output correctness remain device-level checks. ## WGSL Backend WGSL generation does not imply that a Vex executable automatically runs inside a browser. A WebGPU integration must arrange adapter/device creation, buffer transfer, shader compilation and dispatch. Limits such as workgroup size and shared-memory capacity come from the actual device, not a universal constant in a tutorial. ## Other Targets Vulkan, OpenCL, OpenVINO and CoreML have distinct adapters and supported operation subsets. Select the target from evidence for the intended workload, including conversion cost and output precision. A compiler build containing a generator is not a declaration that every runtime integration is complete. ## CPU SIMD Backend (Fallback) LLVM can lower supported vector operations to target instructions or scalar sequences. Vector width, instruction count and math-library calls depend on the target features and optimization settings. Keep a known-correct CPU implementation available for result comparison; that reference may be a normal loop rather than the same graph routed through another backend. ## Backend Selection ### Automatic Selection Dispatch considers graph support, estimated work, build configuration and runtime capability. There is no documented universal ranking such as “Metal, then CUDA, then every other backend”, and no stable `launch ... with threads` syntax taught by this guide. Start with the complete [graph-function example](docs/guide/fusion/graph.md#quick-start). ### Selection and capability checks Compile-time `#Target.os()` and `#Target.arch()` describe the requested binary target. They do not probe a GPU installed on a user's machine. Runtime backend selection and compiler call-bridge selection must agree on the actual artifact and ABI. Environment overrides are development controls, with route-specific meanings; see [Runtime Controls](docs/guide/gpu/index.md#runtime-controls). ## SIR Optimization Passes Fusion, simplification, layout selection, tiling, dead-code elimination and other passes operate on graphs they support. Their presence does not imply that every pass runs for every program. Fusion may reduce intermediate work, while tiling can change temporary memory and synchronization requirements. Precision-changing transformations require an explicit numerical contract. ## Validation Workflow 1. Define input shapes, dtypes, aliasing and ownership requirements. 2. Compare with a reference using small, empty and boundary-sized inputs. 3. Record the actual selected route, device, driver and compiler identity. 4. Exercise the production shape range, including tails and exceptional values. 5. Measure transfer, compilation, warm execution and synchronization separately. The owning implementation areas are `crates/vex-sir/src/codegen/backends/`, `crates/vex-sir/src/runtime/gpu_executor/factory.rs`, `crates/vex-sir/src/dispatch/policy.rs` and the compiler call bridges under `crates/vex-compiler/src/codegen_hir/`. Consult the matching source revision when diagnosing a boundary failure. ## Related Pages - [SIR and Backends](docs/architecture/sir-and-backends.md) - [SIR Passes Deep Dive](docs/architecture/sir-passes-deep-dive.md) - [GPU Programming](docs/guide/gpu/index.md) - [Graph Functions](docs/guide/fusion/graph.md) --- Source: https://vex-lang.org/docs/architecture/sir-passes-deep-dive.md # SIR Optimization Passes SIR optimization transforms a data-parallel graph and produces analysis hints for a selected backend. A graph rewrite, an allocation plan and an executed GPU kernel are different outcomes. This page follows the function bodies in `crates/vex-sir/src/passes/pipeline.rs`; backend emission and runtime dispatch remain separate stages. ## Pass Pipeline Order | SIR level | Ordered work in the shared optimizer | | --- | --- | | O0 | Legalization | | O1 | Legalization → simplify → layout rewrite → dead-code elimination | | O2 | Legalization → simplify → layout rewrite → fusion → dead-code elimination → analysis | | O3 | Legalization → simplify → layout rewrite → fusion with a larger chain limit → simplify → layout rewrite → dead-code elimination → analysis | The O2/O3 analysis stage computes tiling strategies, matrix blocking, a memory plan and device-routing decisions. These are metadata in `SirOptResult` and `SirOptHints`; a backend must consume them before they can affect generated work. The selected level does not establish a launch count, register count or measured speedup. Legalization still runs at O0. The `optimize_sir_for_metal` entry currently delegates to `optimize_sir`. Its name does not imply that a separate automatic NHWC conversion runs. ## 1. Simplify Pass Simplification folds constants, recognizes common subexpressions and removes eligible redundant operations. For example, an expression containing constant `2.0 + 3.0` may use `5.0` in the residual graph. It need not have executed the addition at runtime before optimization. Algebraic identities require the operation's actual numeric rules. For floating point, `x * 0` and `x - x` do not universally equal positive zero: NaN, infinity and signed zero matter. A list of rewrite patterns is not permission for an application to discard those cases. Compare optimized output with a reference under the precision policy used by the selected backend. ## 2. Fusion Pass Fusion can represent a compatible chain of element-wise operations as one `FusedKernel`, reducing intermediate values that would otherwise be materialized. The operations normally **do** depend on each other: a producer's result feeds a consumer. Other uses of that producer and operation constraints affect the fusion decision. For an affine transform followed by clamping, the conceptual expression is: ```text input → add bias → multiply scale → clamp below at zero → output ``` A fused representation can compute each output lane without storing every intermediate array. It does not automatically promise one hardware launch. There is no public `thread.x` or `threadgroup` syntax implied by this diagram. A reduction followed by normalization has a whole-input dependency: the normalization cannot use a complete sum until that sum exists. Combining the expressions into one graph does not remove that dependency or make a workgroup-local barrier a device-wide barrier. See the [graph guide](docs/guide/fusion/graph.md) for an executable starting point. ## 3. Layout Pass The wired `LayoutRewritePass` removes identity permutations and inverse permutation chains. It does not universally convert convolutions to NHWC or matrix operations to tiled storage merely because a device is a GPU. Shape and layout are distinct: reshaping changes the logical dimensions; permuting dimensions may require a different access pattern or materialization. A consumer must interpret the resulting strides/layout consistently with its producer. Source-level flat storage alone does not encode a matrix shape. ## 4. Tiling Pass Tiling analysis chooses strategies for working on bounded portions of a tensor. It can improve locality when emitted code reuses those portions. The number of tiles is not the number of kernel launches: one launch may contain many workgroups, and one workgroup may iterate over several tiles. Edge tiles require bounds checks, including an incomplete reduction dimension. If a GPU implementation uses shared storage, all participating lanes must obey the barrier protocol. The [tiled reference model](docs/guide/gpu/graph-functions.md) explains these dependencies with non-multiple dimensions. ## 5. MatMul Pass `MatMulTilingPass.analyze` produces blocking metadata. The existence of this analysis does not establish automatic Tensor Core, AMX or SME instruction use. That requires a compatible emitter, device, element type and matrix shape. Precision conversion is a separate numerical decision. An `f32` matrix operation is not permission to silently approximate it with integer or half-precision multiplication. Validate the exact input/output and accumulation types, as well as exceptional values and error tolerance. ## 6. Memory Pass `MemoryPlanningPass.plan` analyzes buffer lifetimes and reuse. Two temporary buffers can share storage only when their live ranges and layout requirements permit it. A reusable-buffer plan is not itself a guarantee that all runtime allocations disappeared. Memory planning should not be described as universally inserting prefetches, rewriting thread coordinates or removing GPU bank conflicts. Those are distinct backend transformations requiring their own emitted-code evidence. ## 7. Quantize Pass The repository contains a `QuantizationPass` type, but the shared pipeline does not call it. There is no documented `#[quantize(f16)]` switch or `--sir-quantize` option that enables an automatic quantization workflow here. A deliberately quantized representation needs its own format, calibration and numerical acceptance criteria. ## 8. DCE (Dead Code Elimination) Dead-code elimination removes graph nodes not needed by the outputs. It is particularly useful after fusion or simplification disconnects intermediate nodes. This graph reasoning does not authorize deleting arbitrary Vex function calls whose return values are unused: such functions may perform I/O or mutate observable state. ## 9. Legalize Pass Legalization adapts operations and types to target capabilities. It runs before simplification and fusion so subsequent stages see the legalized graph. A backend may need casts or decomposed operations; some cases remain unsupported. Narrowing is not numerically transparent. In particular, supported source `f64` types do not prove preserved double precision on Metal or WGSL routes. See the [backend reference](docs/architecture/sir-backends-reference.md) and [SIMD/SIMT contract](docs/guide/simd/simd-simt-contract.md) for the concrete boundaries. ## 10. Autograd Pass The shared SIR pipeline does not invoke its `AutogradPass` type. A plain forward `graph fn` does not automatically generate the training backward graph shown in older versions of this page. Vex's documented [forward-mode autograd](docs/guide/advanced/autograd.md) uses explicit `@param`, `@val`, `@grad` and `@detach` transforms; it is a separate surface. ## Pass Configuration and Verification Use documented compiler options, starting with `vex compile --help` and the [CLI reference](docs/references/vex-cli-reference.md). For a native comparison: ```sh vex compile graph-add.vx -O0 --emit-llvm -o graph-add-o0 vex compile graph-add.vx -O2 --emit-llvm -o graph-add-o2 ``` The `graph-add.vx` source is provided in the [graph quick start](docs/guide/fusion/graph.md#quick-start). Compare output before examining IR for a performance claim. LLVM output describes the native module; it alone does not prove that a device kernel ran. For development builds, `VEX_FUSION_DEBUG=1` can expose graph/plan diagnostics. Record the compiler identity, environment, target and observed route alongside those diagnostics. Internal trace text is not a stable machine-readable API. The previously documented `--sir-disable-fusion`, `--sir-disable-quantize`, `--sir-tile-size` and `--sir-profile` flags are not the CLI surface. ## Related Pages - [SIR and Backends](docs/architecture/sir-and-backends.md) - [SIR Backends Reference](docs/architecture/sir-backends-reference.md) - [Fusion Graph](docs/guide/fusion/graph.md) --- Source: https://vex-lang.org/docs/guide/advanced/assembly.md # Inline Assembly Vex supports `asm!(...)` expressions for low-level and freestanding code. The current parser accepts the builtin-style operand helpers shown on this page. ## Current Syntax ```vex unsafe { asm!("nop") } ``` Operands and options are passed as builtin-style helpers inside the `asm!(...)` call. ## Operand Helpers The parser currently recognizes these forms: - `$asmIn("constraint", value)` - `$asmOut("constraint", place)` - `$asmLateOut("constraint", place)` - `$asmInOut("constraint", place)` - `$asmInLateOut("constraint", place)` - `$asmOpt("pure", "nomem", ...)` - `$asmClobber("memory", "cc", ...)` ## Basic Example This no-op example is intended for targets whose assembler accepts `nop`, such as the tested AArch64 host. It declares no outputs and changes no application value: ```vex [asm-nop.vx] fn main(): i32 { unsafe { asm!("nop"); } $println("continued"); return 0; } ``` Run `vex run asm-nop.vx` on a compatible target. Expected stdout is `continued`, with exit status 0. The example demonstrates the assembly boundary; it is not a portable delay, memory barrier or synchronization primitive. ## Outputs and Wildcards An output constraint promises that the assembly writes the selected output. The instruction must actually define it on every path. A `nop` with an output constraint does not produce a valid result merely because a destination was provided. `_` discards a result but does not repair a false output contract. Use target-specific instruction syntax and the matching register constraints. A register operand is not automatically a pointer of the width or alignment required by an instruction. ## Clobbers and Options Options and clobbers are assertions consumed by code generation. Declare every register, flag or memory effect the assembly actually has. Do not combine a claim of no memory effects with a memory effect, or mark a side-effecting instruction as pure to encourage optimization. Incorrect declarations can miscompile surrounding code even when the assembler accepts the instruction. Accepted constraints and option combinations depend on the backend and target. For a real hardware operation, retain the emitted assembly and test the surrounding optimized code. Prefer an existing intrinsic or target abstraction when it already expresses the required effect. ## Legacy Syntax Note Older `in(...)`, `out(...)`, and similar Rust-style operand forms are no longer the documented surface here. Use the `$asmIn` and `$asmOut` family instead. ## Guidance 1. Keep `asm!` inside `unsafe` blocks. 2. Prefer higher-level intrinsics or stdlib APIs when they exist. 3. Use the narrowest possible constraints and the fewest clobbers needed. 4. Treat inline assembly as target-specific code, not portable application logic. ## Related - [Freestanding](docs/guide/freestanding.md) - [Unsafe](docs/guide/advanced/unsafe.md) - [Builtins](docs/guide/advanced/builtins.md) --- Source: https://vex-lang.org/docs/guide/advanced/autograd.md # Automatic Differentiation Vex currently exposes forward-mode automatic differentiation through an autograd block and four intrinsic helpers: - `@param(expr)` seeds a value with gradient `1` - `@val(dual)` reads the primal value - `@grad(dual)` reads the tangent - `@detach(dual)` clears gradient tracking The `@{ ... }` block is still part of the language surface. It evaluates the block and returns the final autograd value. ## Core Example ```vex [autograd-polynomial.vx] fn main(): i32 { let result = @{ let x = @param(3.0) x * x + 2.0 * x + 1.0 } $println("value = ", @val(result)) $println("grad = ", @grad(result)) return 0 } ``` Save as `autograd-polynomial.vx` and run `vex run autograd-polynomial.vx`. The primal value is `16` and the derivative is `8` (printed with floating-point formatting). This is a scalar forward-mode example, not a backward tensor training graph. ## Direct Intrinsic Use You can also use the intrinsics directly without wrapping everything in a larger block: ```vex fn main(): i32 { let x = @param(2.0) let y = Math.sin(x) $println("sin(2.0) = ", @val(y)) $println("d/dx sin(2.0) = ", @grad(y)) return 0 } ``` Current examples and compiler paths use the `Math.*` namespace for trig and transcendental functions rather than `$sin`, `$cos`, `$exp`, or `$log`. ## Supported Pattern Today The implementation is forward-mode dual-number AD. ```vex let x = @param(2.0) let y = @param(3.0) let z = x * y $println("value = ", @val(z)) $println("grad = ", @grad(z)) ``` When more than one input is seeded with `@param`, the current surface returns the directional derivative along the seeded tangent vector. In the example above, `@grad(z)` is `5`, not a pair of separate partial derivatives. If you need separate partials, run separate passes and seed one input at a time. ## Sensitivity of a calibration loss Suppose a sensor model predicts `gain * input + bias`. With input `3`, target `10`, gain `2`, and bias `1`, its prediction is `7` and squared error is `9`. Two forward passes isolate the effect of changing gain and bias: ```vex [autograd-sensitivity.vx] fn main(): i32 { let gainPass = @{ let gain = @param(2.0); let bias = 1.0; let prediction = gain * 3.0 + bias; let error = prediction - 10.0; error * error }; let biasPass = @{ let gain = 2.0; let bias = @param(1.0); let prediction = gain * 3.0 + bias; let error = prediction - 10.0; error * error }; $println(@val(gainPass)); $println(@grad(gainPass)); $println(@grad(biasPass)); if @val(gainPass) != 9.0 || @grad(gainPass) != -18.0 || @grad(biasPass) != -6.0 { return 1; } return 0; } ``` Run `vex run autograd-sensitivity.vx`. Expected output: ```text 9.000000 -18.000000 -6.000000 ``` For `loss = (gain * input + bias - target)^2`, the gain derivative is `2 * error * input = -18`; the bias derivative is `2 * error = -6`. Only one parameter is seeded in each pass. Seeding both together would measure the directional derivative for changing both by the same amount, rather than returning these two partial derivatives separately. The program calculates local sensitivities. A training loop must separately choose an update rule, step size, stopping condition, and handling of nondifferentiable points; forward-mode differentiation does not choose those for the application. ## Detaching Values `@detach` preserves the value and clears the gradient component. ```vex fn main(): i32 { let x = @param(3.0) let frozen = @detach(x) $println("value = ", @val(frozen)) $println("grad = ", @grad(frozen)) return 0 } ``` ## Math Functions The current examples and compiler support autograd through ordinary arithmetic plus the math namespace. ```vex fn main(): i32 { let result = @{ let x = @param(4.0) Math.sqrt(x) + Math.log(x) + Math.exp(x) } $println("value = ", @val(result)) $println("grad = ", @grad(result)) return 0 } ``` Common working paths in the current tree include: - `Math.sin` - `Math.cos` - `Math.exp` - `Math.log` - `Math.sqrt` ## What To Rely On Use this page as the current contract for non-stdlib autograd syntax: - Prefer `@param`, `@val`, `@grad`, and `@detach` - Do not use legacy `$` spellings; autograd transforms use the `@` phase - Use `Math.*` calls for differentiable math operations - Keep autograd scopes small and explicit so the seeded derivative path is obvious ## Related - [SIMD](docs/guide/simd/index.md) - [GPU Programming](docs/guide/gpu/index.md) - [Builtins](docs/guide/advanced/builtins.md) --- Source: https://vex-lang.org/docs/guide/advanced/builtins.md # Builtins and Intrinsics Vex intrinsic names expose two properties directly in source: **when** an operation runs and **which subsystem** owns it. This is a language contract, not a naming convention. ## Phase prefixes | Prefix | Phase | Runtime cost | Examples | | --- | --- | --- | --- | | `#` | compile time | none | `#Type.sizeOf()`, `#Target.os()` | | `$` | runtime | possible | `$println(value)`, `$monotonicNow()` | | `@` | compiler transform / autograd | generated program dependent | `@param(x)`, `@grad(y)` | Compile-time intrinsics use an UpperCamel namespace and lowerCamel member, with the sigil written once: `#Type.sizeOf`, `#Reflect.getField`, `#Diag.compileError`. Runtime and autograd builtins use lowerCamel names. Legacy flat, PascalCase, and snake_case spellings are not aliases. > **warning Phase is semantic** An operation that emits a runtime load, store, allocation, clock read, or I/O cannot become compile-time merely by receiving a `#` name. The prefix describes the operation's real execution phase. ## Access levels Not every compiler primitive is a public language API. | Access | Who may call it? | Purpose | | --- | --- | --- | | Public | normal Vex source | public intrinsic surface | | Prelude-only | embedded VexArch prelude | implements `Ptr`, `Span`, `RawBuf`, and ownership helpers | | Compiler-only | compiler transforms | values or operations that source code cannot spell | | Syntax-only | dedicated syntax | operands inside constructs such as `asm!` | Raw load/store, pointer-offset, pointer-to-slice, and ownership primitives are prelude-only. Application and library code should use the typed prelude APIs; this keeps unsafe invariants in one audited layer and leaves the compiler free to improve their lowering. ## Public runtime core ### I/O, formatting, and debugging ```vex $print("partial line") $println("done") $eprint("warning: ") $eprintln("bad state") let rendered = $format("{0}:{1}", host, port) let value = $dbg(rendered) ``` `$format` is a runtime operation. The compiler may pre-parse a constant format string, but producing a result from runtime arguments still has runtime semantics. ### Control and assertions ```vex $assert(index < length) $assertEq(actual, expected) $panic("fatal error") $todo("finish this branch") $unreachable() ``` `$panic`, `$todo`, and `$unreachable` return `never`. Use `$unreachable` only when reaching the path would be a program bug; a false claim can invalidate optimizer assumptions. ### Timing ```vex let start = $monotonicNow() work() let elapsed = $monotonicNow() - start ``` `$monotonicNow()` is the canonical high-resolution monotonic clock builtin. Wall-clock/calendar time belongs to the standard library, not this intrinsic. ### Runtime shape, math, and bit operations Runtime-dependent values use the `$` family: - shape: `$len`, `$rank`, `$shape` - math: `$pow`, `$abs`, `$min`, `$max`, `$clamp`, `$log2`, `$sqrt` - transcendental: `$cos`, `$sin`, `$tanh`, `$exp`, `$exp2`, `$log` - bits: `$bitCount`, `$leadingZeros`, `$trailingZeros`, `$isPowerOfTwo`, `$nextPowerOfTwo`, `$byteSwap` For ordinary arithmetic, prefer the documented `Math.*` and typed value methods where available; they also make source examples easier to compose. The `$` names above are present in the intrinsic registry, not removed aliases. Use the equivalent `#Math` or `#Bit` operation only when the input is required to be evaluated at compile time. ## Public compile-time namespaces | Namespace | Responsibility | Examples | | --- | --- | --- | | `#Type` | layout, integer domains, type identity, predicates | `sizeOf`, `minValue`, `maxValue`, `info`, `isCopy` | | `#Reflect` | field and variant reflection | `getField`, `setField`, `hasVariant` | | `#Value` | default and zeroed values | `default`, `zeroed` | | `#Text` | compile-time text/source conversion | `concat`, `stringify`, `concatIdents` | | `#Build` | build environment | `env` | | `#Target` | target triple properties | `os`, `arch`, `endian`, `pointerWidth` | | `#Source` | current source location | `line`, `column`, `fileName`, `module` | | `#Embed` | compile-time file embedding | `string`, `bytes` | | `#Diag` | compile-time diagnostics | `staticAssert`, `compileError`, `compileWarning` | | `#Const` | forced constant evaluation | `eval` | | `#Math` | compile-time arithmetic | `pow`, `abs`, `gcd`, `sqrt` | | `#Bit` | compile-time bit operations | `count`, `isPowerOfTwo`, `byteSwap` | | `#DeclSet` | invocation-authorized declarations | `empty`, `addFunction`, `addStruct`, `addContractImpl` | | `#DeclExpr` | typed generated expression plans | `value`, `param`, `call`, `matchPattern` | | `#DeclPattern` | typed generated pattern plans | `value`, `tuple`, `variant`, `anyOf` | | `#DeclConstraint` | exact generated requirements | `contract` | ```vex let bytes = #Type.sizeOf
() let largest = #Type.maxValue() let target = #Target.os() let mask = #Bit.nextPowerOfTwo(17) #Diag.staticAssert( #Type.fieldCount
() > 0, "Header must not be empty" ) ``` See [Compile-Time Evaluation](docs/guide/advanced/comptime.md) for the complete namespace reference and structured reflection examples. The declaration namespaces are public only inside an authorized module generator invocation. See [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md). ## Memory and explicit destruction The public low-level boundary is method based: ```vex let! p = Ptr.allocWith(42) if !p.isNull() { let value = unsafe { p.read() } unsafe { p.free() } } Mem.drop(ownedValue) ``` - Prefer references and owned containers for ordinary code. - Use `Span` for bounds-aware non-owning views. - Use `Ptr` for typed raw handles. - Use `RawBuf` for byte-oriented layouts. - Use `Mem.drop(value)` only for intentional early destruction; normal RAII destruction remains automatic. The compiler-owned primitives beneath these APIs are intentionally unavailable to normal developer code. ## Autograd transforms ```vex let x = @param(2.0) let y = Math.sin(x) $println(@val(y)) $println(@grad(y)) let constant = @detach(y) ``` The public autograd transform family is `@param`, `@val`, `@grad`, and `@detach`. ## Guidance 1. Choose ordinary language or prelude APIs before reaching for an intrinsic. 2. Treat the prefix as a phase guarantee, not decoration. 3. Do not depend on legacy spellings; there are no compatibility aliases. 4. Keep raw memory access behind `Ptr`, `Span`, `RawBuf`, or `Mem`. 5. Remove `$dbg` and `$todo` from production paths. ## Related - [Compile-Time Evaluation](docs/guide/advanced/comptime.md) - [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md) - [Pointers and Low-Level Memory](docs/guide/advanced/pointers.md) - [Memory Prelude](docs/guide/memory/mem-prelude.md) - [Assembly](docs/guide/advanced/assembly.md) - [Unsafe](docs/guide/advanced/unsafe.md) --- Source: https://vex-lang.org/docs/guide/advanced/compiler-directives.md # Compiler Directives Vex compiler directives are source constructs evaluated during parsing, semantic analysis, or compile-time expansion. The stable surface consists of compile-time control flow, namespaced compile-time intrinsics, `export`, and `extern` declarations. > **warning About attribute-style examples** Rust-style optimizer attributes such as `#[inline]`, `#[cold]`, and `#[target_feature]` are not part of Vex's stable source API. Vex computes inlining and target lowering from semantic analysis and the selected target. Do not use those spellings in portable Vex code. ## Inlining syntax `inline fn` is a function modifier in the source grammar. It is distinct from Rust-style `#[inline]` attributes. Explicit inline intent participates in the compiler's lowering policy; automatic inlining also depends on the specialized body and backend cost model. Inspect emitted code when call overhead matters. ## Compile-time conditional expansion Use `#if`, `#elif`, and `#else` with a compile-time expression. Branches use normal braces; there is no `#endif` terminator. ```vex #if #Target.os() == "macos" { fn platformName(): str { "Darwin" } } #elif #Target.os() == "linux" { fn platformName(): str { "Linux" } } #elif #Target.os() == "windows" { fn platformName(): str { "Windows" } } #else { #Diag.compileError("unsupported operating system") } ``` Target queries are compile-time values: | Query | Typical results | | --- | --- | | `#Target.os()` | `"macos"`, `"linux"`, `"windows"` | | `#Target.arch()` | `"aarch64"`, `"x86_64"` | | `#Target.endian()` | `"little"`, `"big"` | | `#Target.pointerWidth()` | `64`, `32` | Use these queries instead of unbound names such as `target_os` or `target_arch`. ## Compile-time iteration and evaluation ```vex #for field in #Type.info().fields { $println(field.name) } let headerSize = #const { #Type.sizeOf() } let folded = #Const.eval(6 * 7) ``` `#for` expands its body from compile-time-known metadata. `#const` evaluates a block at compile time. `#Const.eval` requires an expression that the compiler can fold and produces no runtime call. These are strict boundaries: an unknown value is a compile error. Runtime effects inside a branch selected by `#if` or a body expanded by `#for` remain ordinary runtime HIR; selecting the body does not execute its I/O or allocation during compilation. A top-level, parameterless, non-generic `const fn` returning `DeclSet` is a structural module generator. See [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md) for the typed builder surface and invocation rules. ## Diagnostics ```vex #Diag.staticAssert( #Type.sizeOf() == 16, "PacketHeader ABI changed" ) #if #Target.pointerWidth() != 64 { #Diag.compileError("this implementation requires a 64-bit target") } #Diag.compileWarning("experimental implementation selected") ``` - `#Diag.staticAssert(condition, message)` checks a compile-time invariant. - `#Diag.compileError(message)` stops compilation. - `#Diag.compileWarning(message)` emits a compiler and LSP diagnostic. - `#Diag.debugExpr(expression)` and `#Diag.debugType()` assist metaprogram development. ## Layout, embedding, and source location ```vex let size = #Type.sizeOf() let alignment = #Type.alignOf() let payloadOffset = #Type.offsetOf("payload") let schema = #Embed.string("schema.json") let table = #Embed.bytes("lookup.bin") $eprintln( "{}:{}", #Source.fileName(), #Source.line() ) ``` Embedding reads the file during compilation and makes it an input to the binary. It performs no runtime file I/O. `#Source` reports the expansion's source location. ## Exported and foreign symbols Use `export` for declarations that must be visible outside their module and an `extern` provider at a foreign boundary. Put the import declaration below in a `.vxc` boundary module: ```vex export "C" fn vexAdd(a: i32, b: i32): i32 { return a + b } extern "NATIVE" from "host_api" { fn hostWrite(data: Ptr, length: usize): i32; } ``` Keep ABI declarations at a narrow wrapper boundary. Convert raw pointers to typed Vex abstractions inside the wrapper, and keep ownership rules explicit. See [FFI](docs/guide/ffi.md) for ABI and native-module details. ## Best practices 1. Use canonical namespaced intrinsics; legacy flat aliases are unsupported. 2. Encode ABI and layout assumptions with `#Diag.staticAssert`. 3. Keep `#if` conditions target- or type-derived and compile-time evaluable. 4. Let the optimizer choose inlining unless Vex exposes a documented stable directive for the use case. 5. Treat embedded files and build environment values as build-cache inputs. ## Related - [Compile-Time Evaluation](docs/guide/advanced/comptime.md) - [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md) - [Builtins and Intrinsics](docs/guide/advanced/builtins.md) - [FFI](docs/guide/ffi.md) - [Platform Support](docs/guide/platform-support.md) --- Source: https://vex-lang.org/docs/guide/advanced/comptime-declarations.md # Structural Declaration Generation Vex can generate declarations without generating source text. A module generator returns compiler-owned `DeclSet` data composed from typed `DeclExpr`, `DeclPattern`, and `DeclConstraint` plans. The compiler lowers those plans directly to ordinary HIR. This is the supported alternative to token streams, textual templates, synthetic ASTs, and Rust-style procedural macros. ## Generator trigger A top-level function is an eager module generator when it is: - declared `const`; - non-generic; - parameterless; and - declared to return `DeclSet`. Parameterized or generic functions returning `DeclSet` may be called as helpers, but they are not discovered as module roots. ```vex [generated-classify.vx] const fn deriveModule(): DeclSet { let input = #DeclExpr.param("classify.input", "input", 0) let body = #DeclExpr.matchValue( input, [#DeclExpr.value(0), #DeclExpr.value(1)], [#DeclExpr.value(10), #DeclExpr.value(20)], #DeclExpr.add(input, #DeclExpr.value(40)), ) return #DeclSet.addFunction( #DeclSet.empty(), "classify.function", "generatedClassify", body, false, ) } fn main(): i32 { if generatedClassify(0) != 10 { return 1; } if generatedClassify(1) != 20 { return 2; } if generatedClassify(2) != 42 { return 3; } $println(generatedClassify(2)); return 0; } ``` Save as `generated-classify.vx` and run `vex run generated-classify.vx`. Expected stdout is `42`, with exit status 0. The three checks exercise both explicit match arms and the generated fallback expression. `generatedClassify` is available to ordinary name resolution, inference, linting, LSP analysis, monomorphization, fusion, and native codegen after the module expansion snapshot is sealed. ## Stable role and presentation name Every generated declaration or local has two different names: - **role** is its stable structural identity inside the generator invocation; - **name** is the spelling presented to Vex source and diagnostics. ```vex #DeclSet.addFunction( set, "codec.decode.function", // stable role "decodeUser", // presentation name body, true, ) ``` Changing a presentation name does not redefine structural identity. Reusing a role for two different declarations in one invocation is rejected. Roles should be deterministic and derived from semantic structure, not iteration addresses, hash-map order, or host-global counters. ## Declaration builders The current accepted surface can emit: | Family | Builders | | --- | --- | | Functions and constants | `addConstFunction`, `addConst`, `addFunction`, `addFunctionWhere` | | Types | `addTypeAlias`, `addStruct`, `addGenericStruct`, `addEnum`, `addGenericEnum` | | Methods | `addValueMethod`, `addRefMethod`, `addRefMutMethod`, `addStaticMethod`, plus their `Where` forms | | Conformance | `addContractImpl`, `addAssociatedTypeImpl` | The returned `DeclSet` is immutable: each builder accepts a set and returns the extended set. A declaration is committed only after its exact types, constraints, body, ownership behavior, and structural identity validate. ## Expression plans `DeclExpr` is a closed typed expression algebra, not a string builder. | Purpose | Builders | | --- | --- | | Values and parameters | `value`, `param`, `paramType` | | Locals | `local`, `localMut`, `bind`, `assign` | | Scalar/control | `add`, `lessThan`, `ifElse`, `block` | | Loops | `whileLoop`, `forEach`, `breakLoop`, `continueLoop` | | Matching | `matchValue`, `matchPattern` | | Calls and results | `call`, `returnValue` | | Aggregates | `aggregate` | Each plan carries an exact Vex type. Builders reject unresolved types, missing fields, invalid calls, out-of-scope locals, illegal mutation, result-type drift, and ownership-invalid paths before native codegen. Mutable generated locals must be explicit: ```vex let counter = #DeclExpr.localMut("counter.local", "counter") let initialize = #DeclExpr.bind(counter, #DeclExpr.value(0i64), body) ``` `#DeclExpr.assign` accepts only a local created with mutation capability and only while that hygienic local is in scope. ## Typed patterns `DeclPattern` supports exact scalar, enum, tuple, struct, reference, binding, and or-pattern construction: ```vex enum Choice { First, Second, Other } const fn deriveChoiceMatcher(): DeclSet { let input = #DeclExpr.param("choice.input", "input", 0) let variants = #Type.info().variants let accepted = #DeclPattern.anyOf([ #DeclPattern.variantUnit(variants[0]), #DeclPattern.variantUnit(variants[1]), ]) let body = #DeclExpr.matchPattern( input, [accepted], [#DeclExpr.value(true)], #DeclExpr.value(false), ) return #DeclSet.addFunction( #DeclSet.empty(), "choice.accepted.function", "isGeneratedChoiceAccepted", body, false, ) } ``` Available pattern builders are `wildcard`, `value`, `bind`, `ref`, `refMut`, `tuple`, `structFields`, `variantUnit`, `variant`, `variantStruct`, and `anyOf`. Important invariants: - literal patterns preserve their exact signed/unsigned integer or bool type; - enum variants and fields use reflected semantic identity, not their names; - `anyOf` requires at least two refutable alternatives of one exact type; - every or-pattern alternative must expose the same hygienic binding contract; - moved payloads, borrowed payloads, and remainder cleanup use ordinary Vex ownership rules. ## Generate an enum classification function An enum-based classifier shows how reflected variants and generated patterns work together. The declared order here is `Inspect`, `List`, `Update`, `Delete`; the generator groups the first two variants as read-only actions. The result is an ordinary boolean function, and `main` checks all four cases. ```vex [generated-read-policy.vx] enum Action { Inspect, List, Update, Delete } const fn deriveReadPolicy(): DeclSet { let variants = #Type.info().variants; let input = #DeclExpr.param("read-policy.input", "action", 0); let readOnly = #DeclPattern.anyOf([ #DeclPattern.variantUnit(variants[0]), #DeclPattern.variantUnit(variants[1]), ]); let body = #DeclExpr.matchPattern(input, [readOnly], [#DeclExpr.value(true)], #DeclExpr.value(false)); return #DeclSet.addFunction(#DeclSet.empty(), "read-policy.function", "isReadOnly", body, false); } fn main(): i32 { if !isReadOnly(Action.Inspect) || !isReadOnly(Action.List) { return 1; } if isReadOnly(Action.Update) || isReadOnly(Action.Delete) { return 2; } $println("read policy: PASS"); return 0; } ``` Run `vex run generated-read-policy.vx`. Expected output is `read policy: PASS` and exit status 0. `variants[0]` and `variants[1]` supply typed variant identities to the pattern builder; their array positions are an explicit policy in this small example. If the enum is reordered, update the selection and its cases together. This function classifies an action; authorization still requires the application's user, resource, and permission checks. The parameter plan has slot zero, its `Action` type, and a stable role. The match body returns `true` for the combined pattern and `false` for the fallback. No generated source file, text substitution, or runtime reflection table is needed. The `false` argument to `addFunction` keeps the generated declaration non-public; it is unrelated to the function's boolean result. ## Generic constraints Generated generic callables can attach exact contract requirements with `#DeclConstraint.contract` and a `Where` builder. ```vex let marker = #DeclConstraint.contract>(parameter.ty) let stable = #DeclConstraint.contract(parameter.ty) return #DeclSet.addFunctionWhere( #DeclSet.empty(), "generated.checked.function", "generatedChecked", body, false, [marker, stable], ) ``` Requirements retain contract identity and generic arguments. Duplicate exact requirements are idempotent. Ordinary Vex conformance inference decides whether a concrete type satisfies them. Conjunctions of exact requirements are supported. Arbitrary disjunction, negation, compound-subject predicates, and user-defined type-set algebra are not part of the accepted V2 surface. ## Identity, hygiene, and provenance Generated identities are derived from the generator, invocation owner, stable module site, structural role, and declaration ordinal. They do not depend on a backend symbol spelling. The compiler preserves: - the generator definition and invocation ancestry; - exact source and reflected declaration identities; - reminted generic type and const binders; - hygienic local roles and lexical scope; - sealed inference and ownership facts used by every consumer. Diagnostics, lint, LSP, and native compilation consume the same expansion snapshot. A declaration accepted by one consumer cannot be reconstructed from names differently by another. ## Invocation authority `DeclSet`, `DeclExpr`, `DeclPattern`, and `DeclConstraint` are compiler-owned semantic values. `#DeclSet.empty()` and the transform builders work only while the compiler is executing an authorized module generator. Ordinary const evaluation cannot manufacture or persist a declaration set. Helper functions called by the active generator inherit that exact invocation authority. Their generated values remain bound to the invocation and cannot be published through an unrelated persistent const result. ## Codegen and fusion Generated functions are not printed, reparsed, or compiled into a side bitcode file. Their typed HIR and sealed inference facts enter the normal callable registry directly. Consequently: - source and generated calls share monomorphization; - VexArch and std calls remain visible to whole-module fusion and inlining; - generated allocations and drops use the normal VUMM/Valence path; - normal reachability and dead-code elimination remove unused generated work; - ABI and target checks are identical to handwritten declarations. ## Fail-closed rules A generator fails compilation when it attempts to: - use transform builders outside an authorized invocation; - duplicate or drift a stable structural role; - construct unresolved, semantic-only, or target-unavailable runtime types; - refer to a field, variant, method, or contract by a mismatched identity; - leak a generated local outside its lexical scope; - violate mutability, borrow, move, drop, or result-type rules; - create an or-pattern with incompatible bindings; - introduce a generator cycle or exceed evaluation/expansion quotas. There is no source-string fallback and no best-effort declaration emission. ## Related - [Compile-Time Recipes](docs/guide/advanced/comptime-recipes.md) - [Compile-Time Evaluation](docs/guide/advanced/comptime.md) - [Builtins and Intrinsics](docs/guide/advanced/builtins.md) - [Generics](docs/guide/types/generics.md) - [Contracts](docs/guide/types/contracts.md) - [Pattern Matching](docs/guide/types/pattern-matching.md) - [Comptime Pipeline Architecture](docs/architecture/comptime-pipeline.md) --- Source: https://vex-lang.org/docs/guide/advanced/comptime-recipes.md # Compile-Time Recipes Use compile-time evaluation to make a decision once, then keep the resulting application code ordinary Vex. These recipes cover a bounded configuration calculation and a field traversal driven by typed reflection. For generated functions and types, continue with [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md). ## Calculate a bounded retry schedule Suppose a client starts with a 25 ms delay, doubles it for each retry, and caps it at 400 ms. The policy below clamps the exponent before multiplication, so a large attempt count cannot overflow the calculation or create a long loop. Negative attempt counts use the initial delay. ```vex [comptime-backoff.vx] const fn retryDelay(attempt: i32): i32 { let! steps = attempt; if steps < 0 { steps = 0; } if steps > 4 { steps = 4; } let! delay = 25; while steps > 0 { delay *= 2; steps -= 1; } return delay; } fn main(): i32 { let initial = #const { retryDelay(0) }; let later = #const { retryDelay(3) }; let capped = #const { retryDelay(20) }; #Diag.staticAssert(retryDelay(20) == 400, "retry cap changed"); $println(initial); $println(later); $println(capped); if initial != 25 || later != 200 || capped != 400 { return 1; } return 0; } ``` Run `vex run comptime-backoff.vx`. Expected output: ```text 25 200 400 ``` `const fn` makes the algorithm available to the compile-time evaluator. Each `#const { ... }` requires its result during compilation; `staticAssert` checks that the cap agrees with the policy. The resulting values can be passed to a runtime timer without evaluating the loop again at runtime. The function describes a delay, not an automatic retry mechanism. The caller still decides which errors are retryable, when to stop, and whether repeating an operation is safe. Keep clocks, sleeping, network calls, and runtime state outside this required-comptime calculation. The same function can also accept a runtime attempt count in an ordinary call. ## Select fields by their exact type A metrics record can contain counters and a sequence identifier. This example sums and clears only `i32` fields; the `i64` sequence stays intact. Both helpers are generic, and the reflected field access is checked for each concrete type. ```vex [comptime-counters.vx] struct Counters: Copy { accepted: i32, retried: i32, sequence: i64 } fn counterTotal(value: T): i32 { let! total = 0; #for field in #Type.info().fields { #if #Reflect.fieldIs(field) { total += #Reflect.getField(value, field); } } return total; } fn clearCounters(target: &T!) { #for field in #Type.info().fields { #if #Reflect.fieldIs(field) { #Reflect.setField(target, field, 0); } } } fn main(): i32 { let! counters = Counters { accepted: 7, retried: 2, sequence: 100i64 }; let before = counterTotal(counters); clearCounters(&counters); let after = counterTotal(counters); $println(before); $println(after); $println(counters.sequence); if before != 9 || after != 0 || counters.sequence != 100i64 { return 1; } return 0; } ``` Run `vex run comptime-counters.vx`. Expected output: ```text 9 0 100 ``` The three lines are the original counter sum, the sum after clearing, and the unchanged sequence identifier. During expansion, `#for` visits the metadata fields of `T`. The typed predicate `#Reflect.fieldIs(field)` decides which body to keep. Each retained `getField` or `setField` becomes access to that exact field, so the generated program does not search a dictionary of field names. The integer values being summed or changed are still runtime data. `Counters: Copy` allows the summing helper to take a value while the caller retains its record. Clearing instead takes a mutable reference: it changes the original record and requires exclusive access. The unused `i64` field is neither converted nor reset. Type selection expresses a policy, not a universal meaning of `i32`. If a record also uses `i32` for an identifier that must survive clearing, use a separate counter record or an explicit field/tag policy. For heterogeneous serialization, inspect each field's type and metadata instead of assuming all fields support one arithmetic operation. ## Choose the right compile-time boundary | Need | Mechanism | Runtime behavior | | --- | --- | --- | | A value must be known while compiling | `#const { ... }` or `#Const.eval(...)` | Uses the evaluated value. | | Select code for a target or reflected type | `#if` | The selected body can still contain runtime work. | | Repeat a field-specific body | `#for field in #Type.info().fields` | Executes the expanded, typed operations. | | Define new named functions or types | An authorized `DeclSet` module generator | Uses generated declarations through normal name resolution and calls. | A useful separation is to compute **structure** at compile time and process **data** at runtime. A serializer can choose fields during compilation while reading a particular message's contents at runtime; a target-specific wrapper can select an implementation during compilation while accepting ordinary runtime arguments. ## Next steps - [Compile-Time Evaluation](docs/guide/advanced/comptime.md) - [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md) - [Compiler Directives](docs/guide/advanced/compiler-directives.md) - [Comptime Pipeline](docs/architecture/comptime-pipeline.md) --- Source: https://vex-lang.org/docs/guide/advanced/comptime.md # Compile-Time Evaluation Vex comptime is ordinary typed Vex evaluated before native or SIR codegen. It is not a token-macro language, a second interpreter-facing dialect, or a runtime fallback mechanism. The compiler evaluates the same HIR used by user code, the standard library, and VexArch, then keeps any runtime-dependent work as ordinary typed HIR. This page describes the typed comptime surface used by the 0.4.0 documentation. Pin the compiler version when publishing metaprogramming APIs; a version label alone does not identify the exact compiler binary or its validation results. ## V2 feature and limit table This table is the frozen user-facing V2 contract. “Accepted” means the feature uses canonical typed HIR semantics and fails closed outside its supported domain. The staging policy is a separate compiler option, described below. | Area | V2 status | Contract | | --- | --- | --- | | Required boundaries | Accepted | `#const`, required intrinsics, `#if`, `#for`, and `#while` must resolve at compile time or diagnose. | | Ordinary `const fn` CTFE | Accepted | User, std, prelude, and VexArch calls use the same typed callable/effect model. | | Typed residualization | Accepted | Runtime-dependent work remains ordinary typed HIR and uses normal Valence/VUMM/fusion. | | Type/target/source reflection | Accepted | Results retain exact semantic identity, requested-target facts, and source provenance. | | Scalars and aggregates | Accepted subset | Scalars, text, bytes, arrays, tuples, structs, enums, references, sequences, and insertion-ordered maps are quota-bounded. | | Structural declarations | Accepted subset | Typed functions, methods, structs, enums, constants, aliases, conformances, constraints, and patterns enter the sealed HIR snapshot without generated source or bitcode. | | Persistent CTFE cache | Accepted subset | Only the closed semantic wire subset is stored; target/source/compiler drift or malformed data is a cache miss. Host addresses and session-local IDs cannot persist. | | Opportunistic staging | Default `apply-known` policy | Compile, run, and IR commands apply eligible known-value rewrites. `analyze` observes without replacing HIR; `disabled` disables optional staging. Required `#` evaluation remains active in every mode. | | Cyclic values and custom map policy | Outside V2 | No cyclic persistent graph or arbitrary user-defined compile-time map policy. | | Constraint boolean algebra | Outside V2 | Arbitrary `AND`/`OR`/`NOT` composition is not accepted. | | Unknown aggregate slots | Outside V2 | Residual aggregate value graphs with unknown interior slots remain runtime HIR. | | Scalable/GPU/foreign vector ABI | Outside V2 | Only explicitly proven target layouts are generated. | | Token/source/procedural macros | Outside V2 | V2 does not expose token streams, source templates, or Rust-style procedural macros. | ## The three ways code becomes compile time | Form | Meaning | If the result is not known | | --- | --- | --- | | `#Namespace.operation(...)` | Required compile-time intrinsic | Compilation fails | | `#const { ... }` | Required compile-time block | Compilation fails | | `const fn` called from a compile-time context | Ordinary Vex function eligible for CTFE | Compilation fails at a required boundary | ```vex const fn addOne(value: i32): i32 { return value + 1 } let answer = #const { addOne(41) } #Diag.staticAssert(answer == 42, "constant evaluation failed") ``` Public intrinsic names use an UpperCamel namespace with a lowerCamel member, such as `#Type.sizeOf` and `#Diag.staticAssert`. The `#` prefix is a semantic phase requirement, not decoration: a required-comptime expression cannot silently turn into a runtime call. ## Strict boundaries and residual runtime code Vex distinguishes a required compile-time result from a body selected or expanded at compile time. ```vex #if #Target.os() == "macos" { // The branch is chosen at compile time. // This call remains an ordinary runtime effect. $println("running on Darwin") } ``` The condition of `#if` must be known. The selected body may still contain runtime values, allocations, calls, I/O, and ownership operations. Those operations remain typed residual HIR and enter the normal Valence, VUMM, fusion, and backend pipeline. By contrast, runtime-dependent data cannot cross a strict boundary: ```vex fn invalid(value: i32): i32 { // Compile error: value is not known at this required-comptime boundary. return #Const.eval(value + 1) } ``` There is no hidden "try CTFE, then execute at runtime" behavior for `#const`, `#Const.eval`, `#if` conditions, reflection requests, or compile-time intrinsics. A result is either known, valid residual HIR where the surrounding construct permits it, or a diagnostic. ## Partial evaluation of ordinary Vex The staging pass can fold known scalar and call islands while preserving their runtime-dependent parents. ```vex const fn headerBytes(): usize { return #Type.sizeOf
() } fn totalBytes(payloadBytes: usize): usize { // headerBytes() is known; payloadBytes remains runtime data. return headerBytes() + payloadBytes } ``` Primitive binary, unary, cast, and exact call islands can be folded. Calls with runtime effects remain runtime calls. Overloaded operators are not folded as primitive scalar islands merely because their operands look constant; their exact callable semantics must be supported by canonical CTFE first. Package origin does not grant special powers. User functions, standard-library functions, and VexArch functions are classified by the same effect and target rules. ## Compile-time control flow ```vex #if #Type.fieldCount() > 0 { #Diag.compileWarning("User has fields") } #elif #Type.fieldCount() == 0 { #Diag.compileWarning("User is empty") } #else { #Diag.compileError("unreachable compile-time branch") } #for field in #Type.info().fields { $println(field.name) } let four = #const { 2 + 2 } ``` `#if`, `#elif`, `#else`, `#for`, and `#while` make their control decision at compile time. Conditions and iteration sources must be compile-time evaluable. Evaluation is quota-bounded; an unbounded compile-time loop is a compiler diagnostic, not an infinite build. ## Exact type and target reflection ```vex let size = #Type.sizeOf() let alignment = #Type.alignOf() let fieldOffset = #Type.offsetOf("y") let smallest = #Type.minValue() let largestIndex = #Type.maxValue() let name = #Type.name>() let baseName = #Type.baseName>() let expressionType = #Type.of(value) ``` | Intrinsic | Result | | --- | --- | | `#Type.sizeOf()` | target size of `T` in bytes | | `#Type.alignOf()` | target alignment of `T` | | `#Type.offsetOf(field)` | target byte offset of a named field | | `#Type.minValue()` | minimum value of integer `T` | | `#Type.maxValue()` | maximum value of integer `T` | | `#Type.of(value)` | exact type of an expression | | `#Type.name()` | fully qualified display name | | `#Type.baseName()` | display name without generic arguments | | `#Type.info()` | structured typed metadata | | `#Type.contractInfo()` | structured contract metadata | | `#Type.fieldCount()` | number of fields | | `#Type.tupleLen()` | number of tuple elements | | `#Type.tupleFields()` | structured tuple-field metadata | | `#Type.arrayLen()` | fixed array length | | `#Type.elementType()` | element type of a supported aggregate | | `#Type.variantCount()` | number of enum variants | | `#Type.implements()` | whether `T` implements contract `C` | `minValue` and `maxValue` preserve the exact integer type, including `i128` and `u128`. `isize`, `usize`, layout, and offsets use the selected target—not the compiler host. If semantic target facts and backend target facts disagree, compilation fails closed. Type predicates include: - representation: `isStruct`, `isEnum`, `isPrimitive`, `isInteger`, `isFloat`, `isSigned`, `isPointer`, `isArray`, `isTuple`, `isReference`, `isSlice`; - ownership: `isCopy`, `needsDrop`, `hasDefault`; - standard shapes: `isOption`, `isResult`, `isFunction`, `isGeneric`; - compute types: `isTensor`, `isDynTensor`, `isMask`, `isDynMask`; - identity: `same`. Names such as `typeName` are presentation data. Use typed metadata handles and `#Type.same` for semantic decisions instead of comparing display strings. ## Structured reflection `#Type.info()` keeps field, variant, method, contract, visibility, generic, and ownership metadata attached to compiler identities. ```vex struct User { id: i32 `json:"user_id" db:"primary_key"`, name: string `json:"username"`, } fn dumpUserFields(user: User) { #for field in #Type.info().fields { $println("field: ", field.name, " type: ", field.typeName) #for tag in field.tags { $println(" ", tag.key, " = ", tag.value) } let value = #Reflect.getField(user, field) $println(" value = ", value) } } ``` Direct reflection operations include: - fields: `fieldType`, `fieldTag`, `hasField`, `hasFieldTag`; - variants: `variantDiscriminant`, `variantPayload`, `variantHasPayload`, `hasVariant`; - values: `getField`, `setField`. `#Reflect.setField` requires a mutable target. Reflected access uses the exact field identity; it is not a runtime hash-map lookup. ## Values, collections, and memory Canonical CTFE supports exact scalar values, text, sequences, insertion-ordered maps, tuples, structs, enums, references, and supported ordinary `Vec`/`Map` operations. Const functions can call ordinary user, std, and VexArch code when its effects are valid in the current compile-time context. Compile-time storage is compiler-owned and quota-bounded. Its addresses never escape into the program. When a supported compile-time collection must become a runtime value, the compiler emits an ordinary typed construction recipe; the result then uses the same VUMM/Valence ownership and allocation hierarchy as handwritten runtime code. Comptime does not introduce a second runtime memory model. `#Value.zeroed()` is a low-level operation. Use it only when the all-zero bit pattern is valid for `T`; prefer `#Value.default()` for semantic defaults. ## Text, environment, embedding, and diagnostics ```vex let joined = #Text.concat("hello", " ", "vex") let source = #Text.stringify(User { id: 1, name: "A" }) let ident = #Text.concatIdents(http, Client) let profile = #Build.env("VEX_PROFILE") let config = #Embed.string("config.json") let bytes = #Embed.bytes("blob.bin") #Diag.staticAssert( #Type.fieldCount() == 2, "User layout changed" ) ``` `#Build.env` and `#Embed` are tracked build inputs. `#Source` reports the original source/expansion provenance through `line`, `column`, `fileName`, and `module`. Diagnostics preserve the CTFE call stack and expansion ancestry. Persistent CTFE entries include compiler/language versions, target facts, tracked source/environment inputs, and semantic dependencies. Malformed, oversized, stale, or target-incompatible entries are cache misses; they do not weaken semantic checks. ## Arithmetic and bit operations ```vex let folded = #Const.eval(10 + 20) let power = #Math.pow(2, 10) let divisor = #Math.gcd(48, 18) let population = #Bit.count(0b1010101) let swapped = #Bit.byteSwap(0x12345678) ``` Use ordinary namespace operations such as `Math.pow` for runtime-dependent data; see the [math guide](docs/guide/math.md) and [bit guide](docs/guide/bit.md). The same target-identity rule applies to backend-selected ordinary operations: for example, runtime `Bit.pdep`/`Bit.pext` use BMI2 only on an `x86_64` target with `+bmi2`; supported generic targets use the portable implementation. ## Structural declaration generation An eager, top-level, parameterless `const fn` returning `DeclSet` can generate typed declarations for its module. `DeclSet`, `DeclExpr`, `DeclPattern`, and `DeclConstraint` build semantic HIR directly—never source strings, tokens, synthetic AST, or a generated bitcode module. Generated declarations receive stable identity and provenance, pass ordinary inference/ownership validation, and enter the same monomorphization, fusion, VUMM, ABI, and native codegen pipeline as source declarations. See [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md) for the trigger, builders, constraints, patterns, and safety rules. ## Current controlled limits The following are deliberately outside the accepted V2 contract: - cyclic compile-time values and arbitrary user-defined map policies; - arbitrary boolean algebra over declaration constraints; - unknown-slot aggregate value graphs during residualization; - scalable/GPU/foreign vector ABI generation beyond explicitly supported target layouts; - token streams, source-template macros, and Rust-style procedural macros. Unsupported cases fail closed or remain ordinary runtime HIR. They are not approximated with string matching or hidden runtime fallback. ## Practical guidance 1. Use `#const` or `#Const.eval` only when the result is semantically required during compilation. 2. Prefer typed `#Type.info()` metadata over names and parallel string lists. 3. Keep I/O, clocks, nondeterministic state, and runtime allocation outside required-comptime expressions. 4. Treat environment variables and embedded files as explicit build inputs. 5. Use stable structural roles—not presentation names—for generated items. 6. Let known ordinary code fold naturally; do not duplicate runtime algorithms in a comptime-only dialect. ## Related - [Compile-Time Recipes](docs/guide/advanced/comptime-recipes.md) - [Structural Declaration Generation](docs/guide/advanced/comptime-declarations.md) - [Compiler Directives](docs/guide/advanced/compiler-directives.md) - [Builtins and Intrinsics](docs/guide/advanced/builtins.md) - [Comptime Pipeline Architecture](docs/architecture/comptime-pipeline.md) - [Policies](docs/guide/types/policies.md) - [Generics](docs/guide/types/generics.md) --- Source: https://vex-lang.org/docs/guide/advanced/methods.md # Methods and Constructors Vex supports instance methods, static methods (constructors), and method chaining using explicit receiver and type-qualified syntax. ## Method Syntax Overview Vex has two primary method levels: 1. **Instance methods**: `fn (self: &T) method()` - Associated with an instance. 2. **Static methods**: `fn T.method()` - Associated with the type name. ## Instance Methods Instance methods take `self` as the first parameter with an explicit type: ```vex struct Counter { value: i32, } // Immutable receiver: read-only access fn (self: &Counter) get(): i32 { return self.value } // Mutable receiver: allows modification fn (self: &Counter!) increment() { self.value = self.value + 1 } // By-value receiver: takes ownership fn (self: Counter) into_value(): i32 { return self.value } ``` ## Static Methods (Constructors) Static methods use `Type.method` syntax and are commonly used as constructors: ```vex struct Point { x: f64, y: f64, } // Constructor: Point.new() fn Point.new(x: f64, y: f64): Point { return Point { x, y } } // Specific constructor: Point.origin() fn Point.origin(): Point { return Point { x: 0.0, y: 0.0 } } ``` ## Method and Constructor Overloading Vex supports overloading for: - **Constructors**: `fn Type(...)` - **Static methods**: `fn Type.method(...)` - **Instance methods**: `fn (self: &Type) method(...)` ```vex struct Point { x: f64, y: f64, } fn Point(): Point { return Point { x: 0.0, y: 0.0 } } fn Point(v: f64): Point { return Point { x: v, y: v } } fn Point.new(x: f64, y: f64): Point { return Point { x, y } } fn (self: &Point) distance(): f64 { return (self.x * self.x + self.y * self.y).sqrt() } fn (self: &Point) distance(other: Point): f64 { let dx = self.x - other.x let dy = self.y - other.y return (dx * dx + dy * dy).sqrt() } ``` ### Overload Selection Make overloads distinguishable by their parameter types and arity. Use an explicit numeric type when an unsuffixed literal would fit several candidates. Static and instance calls have different lookup contexts; sharing a name does not make their receiver conventions interchangeable. The source fixtures under `tests/03_functions/overloading/` exercise constructor, static and instance lookup. A fixture for one signature does not settle every combination of generic methods, default arguments and variadic parameters. Keep an integration test for the concrete call shapes your API exports. ## Generic Methods Methods can be generic over one or more types: ```vex struct Holder { value: T, } fn Holder.new(val: T): Holder { return Holder { value: val } } fn (self: &Holder) get(): &T { return &self.value } ``` ## Method Chaining (Fluent API) Methods can be chained when they return `Self` or the receiver type: ```vex struct Builder { count: i32, } fn (self: Builder) add(n: i32): Builder { return Builder { count: self.count + n } } let result = Builder { count: 0 }.add(1).add(10).count // 11 ``` ## Methods with Contracts Methods are the primary way to implement contract behavior: ```vex contract Display { toString(): string; } struct Point: Display { x: f64, y: f64 } fn (self: &Point) toString(): string { return f"({self.x}, {self.y})" } ``` ## Extension Methods Vex allows adding methods to existing types, including primitives: ```vex // Extend string with a custom method fn (self: &string) excited(): string { return self + "!!!" } $println("Hello".excited()) // "Hello!!!" ``` ## Best Practices 1. **Use `Type.new` for primary constructors**: Follow the standard library convention. 2. **Prefer references (`&self`)**: Unless you explicitly need to consume the object. 3. **Use `&self!` for mutation**: Make it clear when a method modifies internal state. 4. **Separate logic from data**: Group methods separately from the struct definition for better modularity. ## Next Steps - [Structs](docs/guide/types/structs.md) - Defining data structures - [Contracts](docs/guide/types/contracts.md) - Defining shared behavior - [Generics](docs/guide/types/generics.md) - Generic methods and types --- Source: https://vex-lang.org/docs/guide/advanced/operators-reference.md # Operators -- Complete Reference This page summarizes common operators, their source syntax and numeric behavior. Contract names in tables describe the conventional operation family; a user type needs an applicable operator callable. See [operator methods](docs/guide/advanced/operators.md) for complete examples. ## Arithmetic Operators | Operator | Syntax | Contract | Description | | -------------- | ------- | -------- | ------------------------------------------- | | Addition | `a + b` | `Add` | Element-wise or numeric addition | | Subtraction | `a - b` | `Sub` | Element-wise or numeric subtraction | | Multiplication | `a * b` | `Mul` | Element-wise or numeric multiplication | | Division | `a / b` | `Div` | Element-wise or numeric division | | Modulo | `a % b` | `Mod` | Remainder (integers) or element-wise modulo | | Negation | `-a` | `Neg` | Unary minus | ```vex let sum = 10 + 5 // 15 let diff = 10 - 5 // 5 let prod = 10 * 5 // 50 let quot = 10 / 3 // 3 (integer division) let rem = 10 % 3 // 1 let neg = -42 // -42 // Floating point let f_div = 10.0 / 3.0 // 3.333... ``` ### Scalar numeric operands and borrows A primitive numeric borrow participates through its referent's value type: comparing an `&i64` with zero is a signed numeric comparison, not an address comparison. Numeric widening preserves the source's signedness. Arithmetic uses its inferred result type; comparisons select a common numeric operand type before producing `bool`. Mixed integer operands need a lossless implicit conversion to one operand's type. Integer/float operations use the existing numeric promotion to the selected float type. Required compile-time evaluation follows these same rules; this does not introduce an implicit float-to-integer conversion. For `a >> b`, the value type of `a` determines arithmetic versus logical right shift. An unsigned shift count does not turn a signed value unsigned. Raw pointers are not implicitly loaded by these numeric rules. ### Compound Assignment | Operator | Equivalent | | -------- | ----------- | | `a += b` | `a = a + b` | | `a -= b` | `a = a - b` | | `a *= b` | `a = a * b` | | `a /= b` | `a = a / b` | | `a %= b` | `a = a % b` | ```vex let! x = 10 x += 5 // x = 15 x -= 3 // x = 12 x *= 2 // x = 24 x /= 4 // x = 6 x %= 4 // x = 2 ``` ## Bitwise Operators | Operator | Syntax | Contract | Description | | ----------- | -------- | --------- | -------------------------- | | AND | `a & b` | `BitAnd` | Bitwise AND | | OR | `a \| b` | `BitOr` | Bitwise OR | | XOR | `a ^ b` | `BitXor` | Bitwise XOR | | NOT | `~a` | `BitNot` | Bitwise complement (unary) | | Left Shift | `a << b` | `Shl` | Shift left by b bits | | Right Shift | `a >> b` | `Shr` | Shift right by b bits | ```vex let a: u8 = 0b1100_1010 let b: u8 = 0b1010_0110 let and_val = a & b // 0b1000_0010 let or_val = a | b // 0b1110_1110 let xor_val = a ^ b // 0b0110_1100 let not_a = ~a // 0b0011_0101 let shifted = a << 2 // 0b0010_1000 (left shift) let right = a >> 3 // 0b0001_1001 (right shift) ``` ### Compound Bitwise Assignment | Operator | Equivalent | | --------- | ------------ | | `a &= b` | `a = a & b` | | `a \|= b` | `a = a \| b` | | `a ^= b` | `a = a ^ b` | | `a <<= b` | `a = a << b` | | `a >>= b` | `a = a >> b` | ## Comparison Operators | Operator | Syntax | Contract | Description | | ---------------- | -------- | -------- | ---------------------------- | | Equal | `a == b` | `Eq` | Returns true if equal | | Not Equal | `a != b` | `Eq` | Returns true if not equal | | Less Than | `a < b` | `Ord` | Returns true if a is less | | Greater Than | `a > b` | `Ord` | Returns true if a is greater | | Less or Equal | `a <= b` | `Ord` | Returns true if a <= b | | Greater or Equal | `a >= b` | `Ord` | Returns true if a >= b | ```vex let same = (5 == 5) // true let diff = (5 != 3) // true let less = (3 < 5) // true let greater = (10 > 5) // true let le = (5 <= 5) // true let ge = (10 >= 5) // true ``` ## Logical Operators | Operator | Syntax | Contract | Description | | -------- | ---------- | -------- | ------------------------- | | AND | `a && b` | — | Short-circuit logical AND | | OR | `a \|\| b` | — | Short-circuit logical OR | | NOT | `!a` | `Not` | Logical negation | ```vex let t = true let f = false let and_val = t && f // false (short-circuit: f not evaluated if t were false) let or_val = t || f // true let not_val = !t // false // With &&, the right-hand expression is evaluated only if the left is true. ``` Short-circuit evaluation does not make raw pointer access safe: a non-null address may still be dangling, misaligned, uninitialized, or out of bounds. Raw reads need an unsafe context and a valid live pointee. See [Memory Safety](docs/guide/memory/safety.md). `&&` and `||` also accept `&bool` operands: they read the referenced boolean, not whether its address is non-null. Mixing `bool` and `&bool` preserves the same left-to-right, once-only evaluation and short-circuit rules, including inside `#const`: ```vex const fn both(left: &bool, right: &bool): bool { return left && right; } let enabled = false; let ready = true; let result = both(&enabled, &ready); // false ``` Binary operators automatically dereference one reference layer. For nested references, dereference the outer layer explicitly (for example, `*left && *right` for `& &bool` parameters). This does not grant logical operators an implicit raw-pointer dereference or change unary `!` rules; use `!*reference` to negate a referenced boolean. ## Indexing Operator | Operator | Syntax | Contract | Description | | -------- | ------ | -------- | ----------------------- | | Index | `a[i]` | `Index` | Element access by index | ```vex let arr = [10, 20, 30] let second = arr[1] // 20 let map = Map.new() map["key"] = 42 // indexed assignment; distinct from a read let val = map["key"] // 42 ``` ## Range Operators | Operator | Syntax | Description | | --------------- | ------- | ----------------------------------- | | Exclusive Range | `a..b` | From a (inclusive) to b (exclusive) | | Inclusive Range | `a..=b` | From a (inclusive) to b (inclusive) | | From | `a..` | From a to infinity | | To Exclusive | `..b` | From start to b (exclusive) | | To Inclusive | `..=b` | From start to b (inclusive) | | Full Range | `..` | Everything | ```vex for i in 0..5 { } // 0, 1, 2, 3, 4 for i in 0..=5 { } // 0, 1, 2, 3, 4, 5 let slice = data[1..4] // elements at indices 1, 2, 3 let with_end = data[1..=4] // elements at indices 1, 2, 3, 4 let from_start = data[..3] // elements at indices 0, 1, 2 let to_end = data[2..] // elements from index 2 to end ``` ## Reference and Pointer Operators | Operator | Syntax | Description | | ---------------- | -------- | ---------------------------------------------- | | Immutable Borrow | `&expr` | Creates an immutable reference | | Mutable Borrow | `&expr!` | Creates a mutable reference | | Dereference | `*expr` | Dereferences a reference or pointer; raw-pointer access requires an unsafe context | ```vex [references.vx] fn observe(counter: &i32!): bool { *counter = *counter + 1; return true; } fn main(): i32 { let x = 42; let ref_x: &i32 = &x; let! y = 10; let mut_ref: &i32! = &y!; *mut_ref = *mut_ref + 5; let! calls = 0; let result = false && observe(&calls!); if result || calls != 0 { return 1; } $println(*ref_x); $println(y); $println(calls); return 0; } ``` Expected output is `42`, `15`, and `0`, followed by exit status 0. The zero demonstrates that the right side of `false && ...` was not called. ## Error Handling Operators | Operator | Syntax | Description | | ------------- | ------------------ | ------------------------------------------------------------------------------------------ | | Null-coalesce | `expr ?? fallback` | If `expr` is `None`/`Err`, evaluates and returns `fallback`; otherwise returns the contained value | | Rescue | `expr !> fallback` | If `expr` is `None`/`Err`, returns `fallback` (lazy with `\|\|`, error-aware with `\|e\|`) | | Try | `expr?` | Propagates `None`/`Err` from the enclosing function | ### Null-Coalescing Operator (`??`) The right-hand expression is evaluated only if the left side is `None` or `Err`. A normal `.or(fallback())` method call evaluates its argument before calling the method; `.orElse` takes a callback instead. ```vex let opt: Option = None let val = opt ?? 0 // 0 let res: Result = Err("fail") let val = res ?? 42 // 42 // expensiveFunction() runs only if opt is None: let val = opt ?? expensiveFunction() ``` For a Result fallback that needs the error value, use the error-aware `!>` closure or `orElse`; `??` discards the error. ### Rescue Operator (`!>`) The `!>` operator extracts a value from `Option` or `Result`, providing a fallback on failure. The error value is passed to the fallback closure when recovering from `Err`. #### Three Forms ```vex // 1. Direct value fallback (error DISCARDED): let val = result !> 0 // 2. Lazy closure, error DISCARDED: let val = result !> || computeDefault() // 3. Lazy closure, error PASSED to closure: let val = result !> |err| { $eprintln(f"Recovering from: {err}") fallbackFromError(err) } ``` #### On `Result` ```vex let res: Result = Err(404) // Error passed to closure -- |e| receives the 404 let val = res !> |err_code| { $println(f"Failed with code: {err_code}") err_code // use error as fallback value } // val = 404 // Ok values pass through without calling closure let ok: Result = Ok(42) let val = ok !> |e| { $println("Never called") 0 } // val = 42, closure not evaluated ``` #### On `Option` ```vex let opt: Option = None // Option uses || form (no error value to pass): let val = opt !> || { $println("Was None, computing default") 99 } // val = 99 ``` The fallback is **only evaluated when the value is `None`/`Err`**. This is the idiomatic Vex alternative to `.unwrap()` (which does not exist in Vex). ### Try Operator (`?`) Propagates errors from `Option` or `Result`: ```vex fn process(): Result { let file = File.open("data.txt")? // propagates Err let parsed = parse(file.readAll()?)? // propagates Err return Ok(parsed) } ``` ## Channel Operators | Operator | Syntax | Description | | -------- | ------------- | -------------------------------------- | | Send | `ch <- value` | Moves a value into the channel; blocks while full | | Receive | `<-ch` | Blocks for `T`; returns zero `T` when closed and drained | ```vex let! ch = Channel.new(10) ch <- 42 // send value let received = <-ch // receive value (blocking) // Select-like pattern with try operations if let Some(val) = ch.tryRecv() { process(val) } ``` Use `recv()`, `recvResult()`, or `tryRecv()` instead of `<-ch` when the program must distinguish a closed or not-ready channel from a valid zero value. ## Ternary Operator | Operator | Syntax | Description | | -------- | -------------- | --------------------------------- | | Ternary | `cond ? a : b` | Returns a if cond is true, else b | ```vex let max = a > b ? a : b let status = code == 200 ? "OK" : "ERROR" // Nested ternaries (use sparingly for readability) let category = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F" ``` ## Type Operators | Operator | Syntax | Description | | --------- | -------------- | ------------------------------- | | Type Cast | `expr as Type` | Safe or unsafe type conversion | | Type Test | (not in Vex) | Use `match` or `if let` instead | ```vex let x: i32 = 42 let y: f64 = x as f64 // safe: widening cast 42.0 let z: u8 = 300 as u8 // safe: truncating cast (wraps) let ptr_val: Ptr = Ptr.null() let addr: usize = ptr_val.addr() // address-sized integer ``` ## SIMD-Specific Operators Availability depends on element type, shape and lowering path. Fixed arrays have dedicated lowering; they do not all become owned tensors. See [SIMD operations](docs/guide/simd/simd-operations.md) for numerical and backend limits. ### SIMD Arithmetic | Operator | Syntax | Description | | ------------------- | --------- | -------------------------------------------- | | Saturating Add | `a +\| b` | Addition with saturation (clamp on overflow) | | Saturating Sub | `a -\| b` | Subtraction with saturation | | Saturating Mul | `a *\| b` | Multiplication with saturation | | Min | `a ? b` | Element-wise maximum | | Multiply-add token | `a *+ b` | Parser token; not a complete three-operand FMA recipe | | Carry-less Multiply | `a *^ b` | CLMUL (cryptographic) | ```vex let a = [100u8, 200u8, 50u8] let b = [100u8, 100u8, 200u8] let sat_add = a +| b // [200, 255, 250] -- 200+100=300 clamped to 255 let sat_sub = a -| b // [0, 100, 0] -- 50-200=0 (clamped) let min_vals = a ? b // [100, 200, 200] ``` ### SIMD Rotation | Operator | Syntax | Description | | ------------ | --------- | --------------------------- | | Rotate Left | `a <<< b` | Circular left bit rotation | | Rotate Right | `a >>> b` | Circular right bit rotation | ```vex let x: u8 = 0b1000_0001 let rot_left = x <<< 1 // 0b0000_0011 (bit 7 wraps to bit 0) let rot_right = x >>> 1 // 0b1100_0000 (bit 0 wraps to bit 7) ``` ### Horizontal Reductions (Prefix Operators) Reductions collapse lanes to a scalar. Use the prefix reduction forms: | Operator | Syntax | Description | | --- | --- | --- | | Sum | `<+ values` | Add lanes | | Product | `<* values` | Multiply lanes | | AND | `<& values` | Bitwise/logical AND | | OR | `<\|> values` | Bitwise/logical OR | | Minimum | `?\| values` | Maximum lane | ```vex let values: [i32; 4] = [1, 2, 3, 4]; let total = <+ values; // 10 let product = <* values; // 24 ``` Floating-point accumulation order, empty inputs and special values need the operation's actual contract. A parallel reduction need not reproduce the low bits of a sequential loop. ### Matrix Operations | Operator | Syntax | Intended operation | | --- | --- | --- | | Matrix multiply | `a <*> b` | Multiply compatible matrix shapes | | Matrix power | `a <^> n` | Repeated square-matrix multiplication | | Linear solve | `a <\> b` | Solve a linear system on a supporting route | A flat `[f64; 4]` does not declare a 2×2 matrix. The operation requires shape information or an explicit overload that defines it. Parser recognition does not prove support for arbitrary rank, dtype or backend. Use the [shape and matrix guidance](docs/guide/simd/simd-operations.md#matrix-operations) before relying on these forms. ## Operator Precedence The table follows the parser's infix binding powers, strongest first. Postfix call/index/member access, prefix unary operations and casts are handled separately; parenthesize mixed forms when the intended grouping is not obvious. | Group | Operators | | --- | --- | | Cast | `as` | | Powers | `**` (right-associative), then `<^>` | | Multiplicative | `*`, `/`, `%`, `*\|`, `*^`, `*+` | | Additive | `+`, `-`, `+\|`, `-\|` | | Concatenation | `++` | | Shift/rotate | `<<`, `>>`, `<<<`, `>>>` | | Bitwise AND, XOR, OR | `&`, then `^`, then `\|` | | Coalescing | `??` | | Relational/min/max | `<`, `<=`, `>`, `>=`, `?` | | Equality | `==`, `!=` | | Logical AND, OR | `&&`, then `\|\|` | | Matrix multiply/solve | `<*>`, `<\>` | | Ranges | `..`, `..=` | | Pipelines | `\|>`, `<\|` | | Assignment/send | `=`, compound assignment, `<-` (right-associative) | | Rescue | `!>` | | Ternary | `condition ? yes : no` | For example, `x & 1 == 1` groups as `(x & 1) == 1`, and `a ?? b + 1` groups as `a ?? (b + 1)`. Prefix reduction operands should be parenthesized when reducing an expression: `<+ (a * b)`. ## Best Practices 1. Use parentheses to clarify precedence in complex expressions, even when you know the rules. 2. Prefer `if`/`else` over nested ternary operators for readability. 3. Use compound assignment operators (`+=`, `*=`, etc.) for concise mutation. 4. For SIMD operations, inspect the emitted route when vectorization matters. 5. When overloading operators, define domain-appropriate laws; concatenation is a useful noncommutative `+`. 6. Implement `Eq` and `Ord` as a pair when your type has a natural ordering. --- Source: https://vex-lang.org/docs/guide/advanced/operators.md # Operator Overloading Operator methods give a user-defined type a meaning for an operation such as addition or indexing. Contracts can state the required operator signatures. Define the receiver, argument and result types explicitly; the same spelling does not make two different domain operations interchangeable. ## A Complete Addition Example This example defines component-wise addition. The receiver is borrowed and the result is a new value: ```vex [point-add.vx] contract AddPoints { op+(other: Self): Self; } struct Point: AddPoints { x: i32, y: i32, } fn (self: &Point) op+(other: Point): Point { return Point { x: self.x + other.x, y: self.y + other.y }; } fn main(): i32 { let first = Point { x: 1, y: 2 }; let second = Point { x: 3, y: 4 }; let sum = first + second; if sum.x != 4 || sum.y != 6 { return 1; } $println(sum.x); $println(sum.y); return 0; } ``` Save it as `point-add.vx` and run `vex run point-add.vx`. Expected output is `4` then `6`, with exit status 0. The method is declared outside the struct, using the same receiver syntax as ordinary [methods](docs/guide/advanced/methods.md). The contract name has no `$` prefix. ## Signatures and Contracts An operator method has the same ownership obligations as an ordinary call: - `self: &T` borrows the receiver for observation; - `self: &T!` requests mutable access; - `self: T` receives the value according to its move/copy behavior; - a returned reference must remain tied to valid storage. A contract declaration and its implementation must agree on receiver mutability, parameters and return type. Merely using a familiar name such as `Add` or `Index` does not establish that agreement. See [Contracts](docs/guide/types/contracts.md) for an example that calls through a bound. ## Operator Method Forms | Source operation | Method spelling | Design question | | --- | --- | --- | | `left + right` | `op+` | Does addition return the same type or another domain value? | | `left - right` | `op-` with an operand | Is subtraction meaningful for every pair? | | `-value` | Unary `op-` | How are overflow and signedness handled? | | `left * right` | `op*` | Is this scaling, component-wise multiplication or composition? | | `left == right` | `op==` | What equality law does the type promise? | | `value[index]` | `op[]` | Is the result a value or a reference, and how are bounds checked? | | `value[index] = replacement` | Mutable indexing / setter path | Does the selected callable return a mutable reference or accept a replacement? | The compiler selects an applicable callable using the actual receiver and operand types. Cross-type right operands are possible; make overload selection clear with explicit numeric types when otherwise ambiguous. Do not infer an operation or an automatic conversion merely from a table of conventional contract names. ## Index Operators An index reader can borrow storage owned by the receiver; a separate `op[]=` method defines assignment. The following example checks assignment and subsequent reads: ```vex [indexed-buffer.vx] struct Buffer { data: [i32; 3], } fn (self: &Buffer) op[](index: i32): &i32 { return &self.data[index]; } fn (self: &Buffer!) op[]=(index: i32, value: i32) { self.data[index] = value; } fn main(): i32 { let! buffer = Buffer { data: [10, 20, 30] }; buffer[1] = 42; if buffer[0] != 10 || buffer[1] != 42 || buffer[2] != 30 { return 1; } $println(buffer[1]); return 0; } ``` Save as `indexed-buffer.vx` and run `vex run indexed-buffer.vx`. Expected output is `42`, with exit status 0. The method delegates bounds checking to the array access. It does not make arbitrary indices valid, and it must not return a reference to a temporary or unrelated local. Indexing uses the selected source callable. Prelude containers and user-defined types share this path; their names do not prove contiguous storage. Intrinsic array, slice, pointer and tensor forms have separate structural lowering. ## Equality and Ordering Define what comparison means for the domain before adding operators. For a version number, lexicographic comparison of `(major, minor)` is different from comparing only `major`. For floating-point fields, NaN can make an apparently simple ordering partial. The compiler accepting the method does not prove reflexivity, transitivity or consistency between equality and ordering. Test equal values, different values and boundary cases. Keep all supplied comparison operators consistent; do not assume missing methods are derived unless the selected contract explicitly provides them. ## Mutation and Compound Assignment Operations that mutate a receiver need the corresponding mutable receiver contract. A mutable local binding alone does not change an immutable method's signature. For a compound assignment, verify which overload is selected and whether the right operand is moved, copied or borrowed. Avoid placeholder setters that silently do nothing. If an operation can fail, choose an API that can report that failure instead of disguising it behind an operator whose callers expect an ordinary result. ## Cross-Type Operations Scaling a vector by a scalar and multiplying two vectors are separate signatures. Give each an intentional result type and document its units. A named method is often clearer when the meaning is unusual or the operation needs configuration, error handling or more than one argument. ## Validation and Implementation Notes The repository contains operator and indexing fixtures under `tests/07_contracts/operators/`, including `complex_arith_001.vx`, `index_001.vx` and `index_mut_001.vx`. Those sources describe test cases; their presence alone does not certify every generic, variadic or cross-target combination. Validate the overloads used by a public API with the actual compiler and deployment targets. ## Related Pages - [Methods](docs/guide/advanced/methods.md) - [Contracts](docs/guide/types/contracts.md) - [Operators Reference](docs/guide/advanced/operators-reference.md) - [Ownership](docs/guide/memory/ownership.md) --- Source: https://vex-lang.org/docs/guide/advanced/pointers.md # Pointers and Low-Level Memory Vex exposes raw pointers for FFI, allocators, runtimes, and memory-mapped I/O. Most code should use ownership, references, and bounds-aware views instead. ## Choose the narrowest abstraction | Tool | Bounds | Ownership | Use it for | | --- | --- | --- | --- | | `&T` / `&T!` | one valid value | borrowed | ordinary safe access | | `Span` | checked extent | borrowed | contiguous views and slicing | | `Ptr` | unchecked | non-owning raw handle | typed FFI and allocator work | | `RawBuf` | unchecked byte offsets | non-owning raw handle | binary layouts and runtime internals | | `Ptr` | unchecked | non-owning raw handle | opaque C object-pointer boundaries | `Ptr` and `RawBuf` do not make invalid memory safe. They make units, mutability, and intent explicit. `Ptr` is represented as a target pointer; that representation alone says nothing about the cost of allocation, copying or a particular access pattern. ## Raw pointer forms - `Ptr` is a readable raw pointer to `T`. - `Ptr` carries writable-pointee capability. - `Ptr` is an opaque object pointer, similar to C's `void*`. Legacy Vex spellings `*T`, `*T!`, and `ptr` are rejected by normal semantic analysis. Existing source can be migrated with `vex lint --fix --only pointer_migration`. Dereference requires an unsafe boundary: ```vex let value = 10 let raw = &value as Ptr let loaded = unsafe { raw.read() } ``` The programmer must prove non-nullness, alignment, initialization, lifetime, aliasing validity, and sufficient allocation extent. ## Typed raw access with `Ptr` Save the following as `raw-values.vx`. It checks allocation, initializes all three elements, reads them while the storage is live, and frees it once: ```vex [raw-values.vx] fn main(): i32 { let values = Ptr.allocN(3); if values == Ptr.nullMut() { return 1; } let result = unsafe { values.writeAt(0, 10); values.writeAt(1, 20); values.writeAt(2, 30); let value = (values as Ptr).readAt(1); values.freeN(3); value }; $println(result); return if result == 20 { 0 } else { 2 }; } ``` Run `vex run raw-values.vx`. Expected output is `20`, with exit status 0. Allocation failure returns 1 before any access. The example uses integers; raw allocation of a type with a destructor also requires a deliberate initialization and destruction protocol. Pointer arithmetic is element-based: `values.add(2)` advances by two `i32` elements, not two bytes. The raw handle carries no allocation extent or lifetime. After `freeN`, every pointer or view into that allocation is invalid. ## Bounds-aware views with `Span` Construct a raw span only while its backing storage is live and initialized. All uses of the span and references obtained from it must end before the storage is freed, reallocated or incompatibly mutated. Prefer a container's `asSpan()` when the container already owns the storage. The complete [Span example](docs/guide/memory/span-t.md) demonstrates this relationship without manual deallocation. ## Byte-oriented access with `RawBuf` `RawBuf` is a non-owning byte-addressed accessor. Its `load(offset)` and `store(offset, value)` use byte offsets; the `loadAt`/`storeAt` forms use element strides. Wrapping a pointer does not validate its extent, initialization or aliasing. A mutable `RawBuf` binding alone does not prove exclusive write access to the memory. Use the complete [raw allocation example](docs/guide/memory/safety.md#raw-allocation-example) for allocation, access and cleanup in one scope. Do not reuse a pointer from an earlier example after that example has freed it. ## Compiler-owned memory primitives The embedded VexArch prelude implements these APIs using a small set of compiler-owned runtime primitives. Those primitives are **prelude-only** and normal Vex source must not call them directly. This boundary is deliberate: - application code receives typed, reviewable APIs; - ownership-sensitive writes stay centralized; - the compiler can change lowering without expanding the public surface; - unsafe code does not become a collection of unstructured intrinsic calls. If a missing operation seems to require direct compiler access, extend the appropriate prelude abstraction instead of bypassing it. ## FFI example Foreign declarations belong in a `.vxc` boundary in user packages. The [first native bridge](docs/guide/ffi-first-native.md) gives a complete `.vxc`/`.vx` example with null checks, explicit ownership and cleanup on both success and failure. It also shows the C implementation and manifest used in its test. Do not call `Ptr.free()` for memory owned by a foreign allocator unless that allocator is explicitly compatible with Vex's allocator. The allocator that creates a block must also destroy it. ## Practical rules 1. Use references and owned containers in ordinary code. 2. Use `Span` when an extent is known. 3. Use `Ptr` for typed raw handles and element offsets. 4. Use `RawBuf` for byte layouts. 5. Keep raw pointers and allocator pairing at the boundary. 6. Never manufacture addresses through integer arithmetic when a typed prelude operation expresses the same intent. ## See also - [`Ptr`](docs/guide/memory/ptr-t.md) - [`Span`](docs/guide/memory/span-t.md) - [RawBuf](docs/guide/memory/rawbuf.md) - [Memory Prelude](docs/guide/memory/mem-prelude.md) - [FFI](docs/guide/ffi.md) - [Unsafe](docs/guide/advanced/unsafe.md) --- Source: https://vex-lang.org/docs/guide/advanced/unsafe.md # Unsafe Code `unsafe` marks a boundary where the caller must establish memory or foreign-API preconditions that the compiler cannot prove. It does not disable type checking or make an invalid operation valid. > **warning** Unsafe code can cause memory corruption, undefined behavior, and security vulnerabilities. Always wrap unsafe code in safe abstractions. ## Unsafe Blocks The `unsafe { }` block allows operations that the compiler cannot verify as safe: ```vex fn main() { let value: i64 = 42 let ptr = &value as Ptr // Unsafe block for raw pointer dereference let read_val = unsafe { ptr.read() } $println(f"Value: {read_val}") } ``` ### What Requires Unsafe? | Operation | Why Unsafe? | |-----------|-------------| | Raw pointer read/write | Pointer may be null or dangling | | Calling `unsafe fn` | Function has manual safety requirements | | Foreign calls (`LIBC`/`SYSTEM`/`NATIVE`) | No safety guarantees for foreign code | | Mutable global access | Risk of data races | ## Unsafe Functions Declare functions with the `unsafe` keyword to signal manual safety requirements: ```vex // Caller must supply a live, aligned pointer to an initialized i64, // readable for this call and compatible with all outstanding aliases. unsafe fn rawRead(ptr: Ptr): i64 { return ptr.read() } fn main() { let val = 100 let ptr = &val as Ptr // Must call within unsafe block let result = unsafe { rawRead(ptr) } } ``` ## Raw Pointers Vex distinguishes between references (`&T`) and canonical raw pointers (`Ptr` and `Ptr`). ### Creating Raw Pointers ```vex let x = 42 let ptr = &x as Ptr // Readable raw pointer let! y = 100 let ptrMut = &y! as Ptr // Writable-pointee capability ``` ### Dereferencing Dereferencing a raw pointer is always `unsafe`: ```vex let x = 42 let ptr = &x as Ptr let val = unsafe { ptr.read() } let! y = 100 let ptrMut = &y! as Ptr unsafe { ptrMut.write(200) } ``` ## Mutable Global Variables Accessing mutable global variables requires `unsafe` due to potential data races: ```vex let! COUNTER: i32 = 0 fn increment() { unsafe { COUNTER += 1 } } fn get_count(): i32 { return unsafe { COUNTER } } ``` ## Best Practices 1. **Minimize Unsafe Scope**: Keep `unsafe` blocks as small as possible. 2. **Safe Wrappers**: Always prefer wrapping unsafe modules in a clean, safe Vex API. 3. **Prove the full memory contract**: Null and bounds checks are necessary in many APIs, but do not prove alignment, initialization, lifetime or aliasing validity. 4. **Pair ownership and cleanup**: Release each allocation through its owning allocator, and do not use pointers or views after release. 5. **Document the caller obligation**: A public `unsafe fn` must state what storage is valid, for how long, and whether another thread may access it. ## Next Steps - [FFI](docs/guide/ffi.md) - Calling C functions - [Raw Pointers](docs/guide/advanced/pointers.md) - Pointer arithmetic and details - [Freestanding](docs/guide/freestanding.md) - Using unsafe for OS kernels --- Source: https://vex-lang.org/docs/guide/advanced/vxm-native-module-linking.md # VXM Native Module Linking Architecture VXM carries package declarations and semantic information between a producer and its consumers. VRI embeds the runtime semantic image used by the compiler. They solve different distribution problems, and each has its own identity and compatibility checks. ## The Problem Reusable packages need a way to supply declarations and implementation information to a consumer without requiring every build to repeat all work. An artifact format must also identify the compiler and semantic compatibility assumptions under which it can be consumed. ## The VXM Solution VXM V2 package images expose a semantic inventory that the CLI can inspect and verify. A consumer needs an image compatible with its compiler, target, and package dependencies. An image is a typed package artifact, not a promise that every consumer skips analysis or receives one pre-optimized bitcode file. ### Phase 1: Library Mode Compilation A producer publishes an image for an identified package and compiler context. Keep its locator, identity, dependency information, and verification material together. Use `vex vxm --help` for the publication options exposed by the producer toolchain; standard-library publication uses `publish-std`. ### Phase 2: Transparent Consumer Linking Inspect and verify an image with a compatible compiler toolchain. The `vex vxm` command group includes `publish-std`, `install-std`, `inspect`, `verify`, `size`, `attach-origins`, and `attach-validations`. The first two manage the standard-library distribution; the inspection commands let a consumer examine an image before incorporating it into a build. For an existing image-bearing package, inspect and validate without publishing: ```sh vex vxm inspect ./package --json vex vxm verify ./package --json vex vxm size ./package ``` Replace `./package` with the package root, source, locator or immutable image path supplied by the producer. `inspect` decodes inventory; `verify` must succeed before the image is treated as structurally and semantically valid. Publisher authentication additionally needs the trusted key/key-id inputs shown by `vex vxm verify --help`; receiving an image does not itself establish trust in its publisher. Compatibility with a concrete consumer still needs that consumer's compile and behavior checks. `attach-origins` and `attach-validations` enrich an image using consumer compilations. They are not substitutes for compiler/target identity checks or blanket proof for future consumers and flags. ### Link-Time Optimization (LTO) Integration Do not assume that VXM implies LTO, cross-module inlining, a particular linker, a zero runtime cost, or a fixed LLVM version. A workspace LLVM dependency does not establish the backend version bundled with a published release. Confirm compatibility and performance with that release's build metadata and a representative workload. ## Local Workspaces and Standard Library Standard-library image publication and installation are separate operations from runtime embedding. VRI embeds VexArch semantic sources into the compiler for the path described in [Runtime Architecture](docs/architecture/runtime-architecture.md#runtime-semantic-image-and-fusion). Inspect the selected package to learn which artifacts its distribution carries. | Artifact | Role | Consumer responsibility | | --- | --- | --- | | VXM V2 package image | Portable package and semantic inventory; `.vxm/package.vxm2` appears as a package locator | Package-specific publication, validation, and source-free consumption need their own tests. | | VRI runtime image | Embedded VexArch runtime semantic source image | Separate from a package image or a linked bitcode library; see the runtime architecture page. | | Native object or final executable | Target-specific code produced and linked by a build | Target, linker, features, and release packaging must be verified separately. | For implementation details, start with `tools/vex-cli/src/commands/vxm.rs`, `crates/vex-vir/src/`, and `tools/vex-cli/src/runtime_image.rs` in the matching source checkout. Match those source paths to the toolchain whose artifacts you are inspecting. --- Source: https://vex-lang.org/docs/guide/agent-workflow.md # Vex agent workflow Use this workflow when writing, porting, debugging or reviewing Vex `.vx` code. Vex is a separate systems language. Start from its documented syntax and APIs even when the task resembles Rust, Go, C++ or TypeScript. ## Establish the project Read the project's instructions, `vex.json` and nearby working code. Check `vex --version` before choosing commands or interpreting diagnostics. Keep the user's requested target and dependency constraints. The documentation targets 0.4.0; recorded example checks identify their actual compiler separately in [verification evidence](docs/guide/verification-evidence.md). For a new project, follow [the first-project walkthrough](docs/guide/first-project.md). For an existing project, reuse its layout and test entry points. Finish this step with an identified entry file, compiler version and relevant test command. ## Read for the task Read only the references needed for the change. Start with the corresponding row, then follow a package link for its exact imports, signatures and ownership. | Task | Read | | --- | --- | | Write or translate a function | [Syntax](docs/guide/basics/syntax.md), [variables](docs/guide/basics/variables.md), [functions](docs/guide/basics/functions.md) | | Work with records or variants | [Structs](docs/guide/types/structs.md), [enums](docs/guide/types/enums.md), [error handling](docs/guide/error-handling.md) | | Return, retain or mutate data | [Ownership workflows](docs/guide/memory/ownership-workflows.md) | | Choose a package or parse input | [Standard-library entry path](docs/guide/stdlib-start.md), [package map](docs/std/index.md), then the selected API guide | | Validate JSON configuration | [Checked fields and a complete tested program](docs/std/serde/json.md) | | Add a regression or benchmark | [Testing](docs/std/testing.md) and the project's existing tests | | Coordinate async work | [Concurrency overview](docs/guide/concurrency/overview.md), then the relevant channel/task recipe | | Call a native library | [First native integration](docs/guide/ffi-first-native.md) | | Generate declarations | [Comptime recipes](docs/guide/advanced/comptime-recipes.md) | | Use tensors, graphs or devices | [Capability map](docs/guide/language-status.md), then the specific execution guide | ## Use Vex contracts - Bind with `let`; use `let!` when rebinding or mutation is required. Read the receiver signature before choosing a shared or mutable borrow. - Use `fn name(...): ReturnType` and the documented `import { Name } from "module";` form. Prelude types such as `Vec`, `Map`, `Option` and `Result` need no invented package import. Package names such as `"fs"` and `"serde/json"` come from their guides. - Use `$println` and `$format` for builtin formatting. Builtin namespaces `Math`, `Bit` and `Crypto` are distinct from imported packages. - Distinguish owning `string` from borrowed `str`. Keep owners alive while retaining views, spans or pointers; use the package's owning conversion when data must outlive its input. Follow [ownership workflows](docs/guide/memory/ownership-workflows.md) for return values, collections, callbacks and async boundaries. - Preserve `Option` absence and `Result` errors. Use `?` only where the enclosing return type supports propagation. Select the actual return type from the reference instead of adding `.unwrap()` by analogy. - For external data, select a checked parser with explicit resource limits where available. Wire-format validation and application-schema validation are separate steps. The [serde guide](docs/std/serde/index.md) describes the dynamic parse and field/type/range checks used at input boundaries. Before using an unfamiliar API, locate its declaration or current reference. If the installed version differs, preserve the diagnostic and resolve that specific mismatch against its source or versioned documentation. ## Make the change verifiable Use the smallest complete program or existing test that exercises the desired behavior. Keep imports, setup and expected output with the example. Distinguish copyable programs from fragments that depend on surrounding bindings. Run the relevant check, program or test with the identified compiler. For parsers, include a malformed input; for an owning/borrowed conversion, exercise the intended lifetime; for concurrency, check completion and shutdown. Choose checks that establish the requested behavior rather than reproducing the implementation line by line. When execution is unavailable, report what was source-checked and what remains unexecuted. Passing a CPU example does not qualify a GPU path, a parser example does not qualify a protocol session, and successful compilation does not prove native-library interoperability. Report the files changed, the command and observed result, and any remaining task-relevant limitation. --- Source: https://vex-lang.org/docs/guide/ai-tools.md # Use Vex with AI tools Give an assistant a short route into the documentation, then let it read the pages relevant to your task. The same maintained Markdown sources power this website, the machine-readable pages and the downloadable skill. ## Choose a format | Resource | Use it for | | --- | --- | | [llms.txt](https://vex-lang.org/llms.txt) | A compact entry point with selected language, library and toolchain links | | [Documentation catalogue](https://vex-lang.org/llms-index.md) | Finding every published Markdown page by section | | [Vex skill ZIP](https://vex-lang.org/skills/vex-language.zip) | An agent workflow with a small set of local references for compatible skill hosts | | [SKILL.md](https://vex-lang.org/skills/vex-language/SKILL.md) | Inspecting the skill instructions before installation | | [llms-full.txt](https://vex-lang.org/llms-full.txt) | The full public documentation snapshot for offline indexing | | [Artifact manifest](https://vex-lang.org/ai-docs-manifest.json) | Source identities, byte sizes and SHA-256 hashes for a reproducible snapshot | The six generated standard-library API inventories are filtered through their public package re-exports, including the documented HTTP submodules. Internal and test declarations are omitted from the Markdown exports and full snapshot. References use readable anchors and relative documentation links. Signatures retain their ownership and error types; redundant parameter tables are omitted. The full snapshot is much larger than the entry point. Load a specific page first; use the full export when your retrieval/indexing workflow needs it. These resources supply context at use time. They do not train a model or guarantee that every assistant discovers the files automatically. ## Start without installing anything Give a browsing-capable assistant this prompt, followed by your task: ```text Use https://vex-lang.org/llms.txt to find the Vex documentation for this task. Read the relevant language and package pages before choosing syntax or APIs. Follow the project's instructions and report the compiler version and checks you actually ran. My task is: ... ``` Each documentation page also has a plain Markdown form. For example, `/docs/guide/first-project` has `/docs/guide/first-project.md`, and `/docs/std/` has `/docs/std/index.md`. HTML pages advertise their Markdown alternate and the documentation entry point through link metadata. ## Install the skill Download the ZIP, inspect `vex-language/SKILL.md`, and extract the complete `vex-language` directory into the skill directory supported by your agent. Preserve its `references` directory. Use your host's skill discovery or reload mechanism, then select `vex-language` or ask it to work on a Vex program. The package follows the [Agent Skills format](https://agentskills.io/specification). Installation paths and activation controls vary by host; this archive does not install extensions, execute a setup script or grant extra tool permissions. Its essential references work locally; specialist links use the published Markdown documentation when network access is available. The [agent workflow](docs/guide/agent-workflow.md) is also readable as an ordinary guide. The skill is generated from that page, so fixes to the workflow propagate to the download during the site build. ## Keep the version visible The documentation targets 0.4.0. Use `vex --version` to identify your installed compiler, and consult [verification evidence](docs/guide/verification-evidence.md) for the actual executable used for recorded examples. A refreshed documentation archive is not evidence that a new compiler package has been released. The [llms.txt proposal](https://llmstxt.org/) defines the discovery file. Source changes regenerate the Markdown exports, catalogue, skill and manifest together; stale generated outputs fail the repository's check command. --- Source: https://vex-lang.org/docs/guide/basics/control-flow.md # Control Flow Vex provides conditional expressions, pattern matching, and several loop forms. The compiler's current surface favors readable block-based control flow. Complete programs on this page print their computed values and return `0` for successful execution. Printed output and process exit status are separate: returning `42` from `main(): i32` would report a nonzero process status, not print the number. Fragments without `main` belong inside a program. ## if, elif, and else ~~~vex fn classify(value: i32): i32 { if value < 0 { return -1; } elif value == 0 { return 0; } else { return 1; } } fn main(): i32 { $println(classify(12)); return 0; } ~~~ An if expression can produce a value when both branches have compatible types: ~~~vex fn main(): i32 { let left = 20; let right = 22; let larger = if left > right { left } else { right }; $println(larger); return 0; } ~~~ A branch block can contain statements followed by its result expression. `return` inside a branch exits the enclosing function; it is not merely a way to yield the value of the `if` expression. ## match match is an exhaustive expression for selecting between patterns: ~~~vex fn label(value: i32): i32 { return match value { 0 => 100, 1 | 2 | 3 => 200, _ => 300, }; } fn main(): i32 { $println(label(2)); return 0; } ~~~ Constructor patterns bind enum payloads: ~~~vex enum State { Ready, Failed(i32), } fn state_code(state: State): i32 { return match state { State.Ready => 0, State.Failed(code) => code, }; } fn main(): i32 { $println(state_code(State.Failed(7))); return 0; } ~~~ Use a wildcard only when all remaining values truly share the same behavior. A wildcard can hide a newly added enum variant from review. ## for loops The range form is the normal counted loop: ~~~vex fn main(): i32 { let! total = 0; for value in 0..10 { total += value; } $println(total); return 0; } ~~~ The upper bound of 0..10 is exclusive. Use 0..=10 when the upper bound is inclusive. Collection iteration uses the same in form: ~~~text for item in values { process(item) } ~~~ C-style for loops are not part of the supported Vex syntax. Use a range, collection iteration, or while loop. For a source-defined iterable, `for` uses the exact `IntoIterator.iter()` and `Iterator.next()` implementations selected by type checking. The source expression is evaluated once, and the iterator's `Item` determines whether the body receives a value or a reference. Prelude collections follow the same rule: for example, `Deque` yields borrowed elements in logical front-to-back order, including when its ring buffer wraps. Physical field names or backing-array order do not override the source iterator. Optimizations must preserve these semantics; source iterator calls can inline and vectorize without a per-type compiler implementation. ## while loops Use while when the next iteration depends on mutable state: ~~~vex fn sum_to(limit: i32): i32 { let! current = 0; let! total = 0; while current <= limit { total += current; current += 1; } return total; } fn main(): i32 { $println(sum_to(10)); return 0; } ~~~ Make progress toward the loop condition explicit. The compiler can check types and ownership, but it cannot prove that an arbitrary loop terminates. ## loop, break, and continue loop creates an unbounded loop. break exits it and continue starts the next iteration: ~~~vex fn first_multiple_of_seven(limit: i32): i32 { let! value = 1; loop { if value > limit { break; } if value % 7 == 0 { return value; } value += 1; continue; } return -1; } fn main(): i32 { $println(first_multiple_of_seven(50)); return 0; } ~~~ ## defer defer schedules a cleanup expression for the current scope. It is useful for resource-management code, but the exact runtime behavior depends on the resource type and backend. Keep the deferred expression simple and use the standard-library resource APIs described by their own documentation. ~~~text fn process() { let resource = acquire() defer resource.close() use(resource) } ~~~ The fragment is intentionally shown as text because acquire, use, and close are library-specific names. ## Next steps - [Loops and Labels](docs/guide/basics/loops.md) - [Pattern Matching](docs/guide/types/pattern-matching.md) - [Error Handling](docs/guide/error-handling.md) - [Concurrency Overview](docs/guide/concurrency/overview.md) --- Source: https://vex-lang.org/docs/guide/basics/functions.md # Functions Functions are the main unit of reuse in Vex. A function has a name, typed parameters, an optional return type, and a block body. Complete programs on this page print their computed values and return `0` for successful execution. Printed output and process exit status are separate: returning `42` from `main(): i32` would report a nonzero process status, not print the number. Fragments without `main` belong inside a program. ## Declaration The basic form is: ~~~text fn name(parameter: Type): ReturnType { ... } ~~~ A return type can be omitted for a function that returns unit. Use an explicit return type for public functions and for code where the interface matters. ~~~vex fn add(left: i32, right: i32): i32 { return left + right; } fn main(): i32 { let answer = add(20, 22); $println(answer); return 0; } ~~~ Vex accepts automatic statement boundaries at line breaks. Explicit semicolons are still useful when several statements share a line or when a boundary would be ambiguous. ## Parameters and mutation Parameters are immutable by default. Use the mutable marker when a function must reassign a parameter: ~~~vex fn increment(value: i32!): i32 { value += 1; return value; } fn main(): i32 { $println(increment(41)); return 0; } ~~~ Mutation of a caller-owned value normally requires a mutable binding and a mutable reference. The full rules are covered in [Ownership](docs/guide/memory/ownership.md) and [Borrowing](docs/guide/memory/borrowing.md). ~~~text fn inspect(value: &Point): i32 { ... } fn update(value: &Point!): i32 { ... } ~~~ Use immutable references for read-only access. A mutable reference is exclusive for the duration of the borrow; the checker rejects conflicting mutable and immutable borrows. ## Return values Use `return expression` for an explicit return. A final expression without a terminating semicolon can also supply the function result, for example `fn double(value: i32): i32 { value * 2 }`. This guide uses explicit returns when they make control flow clearer. Tuples are the direct way to return more than one value: ~~~vex fn divide_with_remainder(left: i32, right: i32): (i32, i32) { return (left / right, left % right); } fn main(): i32 { let (quotient, remainder) = divide_with_remainder(10, 3); $println(quotient); $println(remainder); return 0; } ~~~ Use an enum such as Result when a function can fail; do not use a magic integer unless the calling contract explicitly requires one. ## Generic functions Generic functions declare type parameters after the function name: ~~~vex fn identity(value: T): T { return value; } fn main(): i32 { let value = identity(42); $println(value); return 0; } ~~~ Generic structs use the same angle-bracket syntax. Add a contract bound when the function needs operations beyond those available for every type. See [Generics](docs/guide/types/generics.md) for type and const parameters, and [Contracts](docs/guide/types/contracts.md) for constrained APIs. For a homogeneous variable-length argument list, use a trailing `values: ...T` parameter. [Typed variadic packs](docs/guide/types/variadics.md) describe ownership, borrowed iteration and supported compile-time calls. ## Methods and associated functions Methods are declared outside the struct with a receiver. The receiver type determines which value owns the method: ~~~vex struct Point { public: x: i32, y: i32, } fn (point: &Point) sum(): i32 { return point.x + point.y; } fn Point.origin(): Point { return Point { x: 0, y: 0 }; } fn main(): i32 { let point = Point.origin(); $println(point.sum()); return 0; } ~~~ The receiver is written as an ordinary parameter inside parentheses. A call such as point.sum() supplies the receiver automatically. Methods can be immutable or mutable; mutable receiver methods require the corresponding mutable reference rules. ## Closures Closures use pipe delimiters around their parameters: ~~~vex fn apply(operation: fn(i32): i32, value: i32): i32 { return operation(value); } fn main(): i32 { let double = |value: i32| value * 2; $println(apply(double, 21)); return 0; } ~~~ A closure can capture values from its surrounding scope. Capture behavior is checked by the ownership and escape analyses, especially when the closure is passed to a go block or stored for later execution. ## Explicit inlining Use `inline fn` for a small, bounded function whose body must remain visible to the optimizer at every legal call site: ~~~vex inline fn isAscii(value: u8): bool { return value < 128 as u8; } ~~~ This is a semantic code-generation contract, not a spelling-based compiler special case. Vex carries it through HIR and emits the corresponding backend attribute. It can override ordinary size and loop profitability heuristics, but it cannot override a semantic prohibition such as a function that the compiler has proven unsafe to inline. Prefer ordinary `fn` by default. Use `inline fn` for short dispatchers, fixed-width primitives, and similar boundaries where caller constants remove most of the body. Keep large loops in a separate ordinary function and call it from the inline dispatcher; this preserves specialization without duplicating the loop at every call site. ## Overloading Vex supports functions with the same name when their parameter signatures are distinct: ~~~vex fn measure(value: i32): i32 { return value; } fn measure(value: f64): f64 { return value; } fn main(): i32 { $println(measure(42)); return 0; } ~~~ Resolution considers exact matches, compatible numeric coercions, and generic candidates. Ambiguous calls should be made explicit with an annotation or a type conversion. ## Async functions Async functions are declared with async fn. Await is valid inside an async function or async execution context: ~~~vex async fn get_value(): i32 { return 42; } async fn main(): i32 { let value = await get_value(); $println(value); return 0; } ~~~ `await` suspends the current async computation until its result is available. Keep borrowed data valid across that suspension and use the owning API's cancellation and cleanup rules. See [Async](docs/guide/concurrency/async.md) for task execution and synchronization. An ordinary synchronous function cannot use `await`. ## Choosing a callable shape - Use a named function for reusable behavior without a captured environment. - Use a method when the operation belongs to a receiver; declare it with `fn (self: &Type)` or `fn (self: &Type!)` rather than an `impl` block. - Use a closure when the operation needs values from its surrounding scope. - Use `fn(Args): R` for a callback parameter and `async fn` for a computation that can suspend. - Use a [typed variadic pack](docs/guide/types/variadics.md) for a varying number of arguments of one element type; use a `Span` to borrow an existing sequence. ## Next steps - [Control Flow](docs/guide/basics/control-flow.md) - [Structs](docs/guide/types/structs.md) - [Generics](docs/guide/types/generics.md) - [Contracts](docs/guide/types/contracts.md) - [Closures](docs/guide/types/closures.md) - [Async](docs/guide/concurrency/async.md) --- Source: https://vex-lang.org/docs/guide/basics/loops.md # Loops -- Expressions and Labels A value-producing `loop` can return a value through `break`. `for` and `while` are statement loops: use a bare `break` to exit them. The snippets below illustrate individual constructs. A snippet referring to application names such as `generateNext`, `process`, or `Token` is a fragment, not a standalone program. For complete counted-loop examples, see [Integer ranges](docs/guide/types/range.md). ## Loops as Expressions A value-producing `loop` can yield a value via `break`: ### `loop` with Break Value ```vex // loop is the primary way to compute with early exit let result = loop { let candidate = generateNext() if isGood(candidate) { break candidate // loop returns this value } if attempts > 1000 { break defaultValue // fallback return } } // result is the value from whichever break executed ``` ### `for` and `while` are statement loops Use `break` without a value in a `for` or `while`. The current type checker rejects `break value` in a statement loop. To retain a result from a search, store it in a mutable `Option` and break without a value, or return from the function. A statement loop does not implicitly produce `Some` or `None`. ## Labeled Blocks Labels allow naming a block or loop so `break` and `continue` can target a specific scope: ### Labeled Block Expressions ```vex let value = 'outer: { let x = compute() if x < 0 { break 'outer 0 // break out of 'outer with value 0 } let y = 'inner: { if x > 100 { break 'inner x / 2 } break 'inner x * 2 } break 'outer y + 1 } ``` ### Labeled Loops ```vex 'search: for row in 0..gridHeight { for col in 0..gridWidth { if grid[row][col] == target { $println(f"Found at ({row}, {col})") break 'search // breaks the OUTER loop, not just the inner } } } ``` ### `continue` with Labels ```vex 'outer: for i in 0..10 { for j in 0..10 { if i * j > 50 { continue 'outer // skip rest of inner loop AND advance outer loop } process(i, j) } } ``` ## Loop Forms Reference ### `for` -- Iteration ```vex for index in 0..10 { } // 0 through 9 for index in 0..=10 { } // 0 through 10 let! index = 0; while index < 10 { $println(index); // 0, 2, 4, 6, 8 index += 2; } ``` Iteration follows the selected `IntoIterator.iter()` and `Iterator.next()` contract. Do not infer element ownership from the absence of an `&` before the collection. For example, the prelude's `Vec` iterator yields `&T`: ```vex let! values = Vec.new(); values.push(10); values.push(20); for value in values { $println(*value); } $println(values.len()); // the vector still owns its two elements ``` A mutable borrow uses `&values!`, not `&!values`. The ability to borrow a collection mutably does not itself establish that it has a mutable iterator. Use the collection's documented mutable accessors when changing elements. Map iteration similarly follows its declared item type, typically borrowed key/value pairs; do not assume a generic `enumerate()` adapter exists. ### `while` -- Condition-Based ```vex while condition { // body } // While-let pattern while let Some(item) = queue.pop() { process(item) } ``` ### `loop` -- Infinite Loop ```vex loop { // runs until break, return, or panic if done { break } } ``` ## Loop Control Flow | Expression | Behavior | | -------------------- | ---------------------------------------------- | | `break` | Exit the innermost loop immediately | | `break value` | Exit a value-producing `loop` with a value | | `break 'label` | Exit the named loop | | `break 'label value` | Yield from a value-producing loop or labelled block | | `continue` | Skip to next iteration of innermost loop | | `continue 'label` | Skip to next iteration of named loop | ## Loop Return Types A value-producing `loop` takes its result type from its compatible break values and its surrounding type context. `for` and `while` are statement loops, so do not use `break value` to produce an `Option` from them. ```vex let answer: i32 = loop { break 5 } ``` ## Common Patterns ### Find First Match For a bounded search, keep an explicit `Option` or return from a function on a match. If the loop finishes without finding a match, return `None` explicitly. This makes the no-match path visible rather than relying on an implicit loop result. ### Bounded Retry Count attempts separately from any delay policy. This helper makes at most `maxAttempts` calls, returns immediately after success, and preserves the last operation error on exhaustion: ```vex fn retry(operation: fn(): Result, maxAttempts: i32): Option> { if maxAttempts <= 0 { return None; } let! attempt = 0; loop { attempt += 1; match operation() { Ok(value) => { return Some(Ok(value)); }, Err(error) => { if attempt == maxAttempts { return Some(Err(error)); } }, }; } } ``` This is a helper definition: supply the operation at the call site. `None` means no attempt was allowed. If a real operation has side effects, retry it only when its contract permits repetition. Backoff, cancellation, and a total deadline are separate policies; comparing an exponentially increasing delay to an attempt limit does not count retries correctly. ### State Machine with Labeled Blocks ```vex fn parseStateMachine(tokens: Span): Result { let! state = State.Initial return 'parse: { for token in tokens { state = match (state, token) { (Initial, OpenBrace) => InBlock, (InBlock, Identifier(name)) => { // ... handle identifier InBlock }, (InBlock, CloseBrace) => break 'parse Ok(ast), (_, unexpected) => break 'parse Err(ParseError.new(unexpected)), } } break 'parse Err(ParseError.new("Unexpected end of input")) } } ``` ## Best Practices 1. Use `loop` with `break value` for complex initialization or search logic that doesn't fit a `for` or `while`. 2. Use labeled blocks for multi-level control flow instead of boolean flags or deeply nested conditionals. 3. For linear searches, use an explicit optional result or return on a match. 4. Label outer loops clearly when nested -- `'search`, `'parse`, `'retry` are better than `'outer`, `'a`. 5. Avoid `loop` with `break` when a simpler `while` or `for` expresses the intent more clearly. --- Source: https://vex-lang.org/docs/guide/basics/syntax.md # Syntax This page introduces the syntax shared by most Vex programs. It focuses on forms accepted by the current compiler. Advanced operators, compiler directives, and backend-specific constructs have their own reference pages. Complete programs on this page print their computed values and return `0` for successful execution. Printed output and process exit status are separate: returning `42` from `main(): i32` would report a nonzero process status, not print the number. Fragments without `main` belong inside a program. ## Source files and comments Vex source files use the .vx extension. Comments use // for a line and /* ... */ for a block. Documentation comments use /// and are consumed by the documentation tool when attached to a public item. ~~~text // A line comment /* A block comment */ /// Documentation for the next public item ~~~ ## Statements and automatic semicolons Vex accepts explicit semicolons and also inserts statement boundaries at suitable line breaks. Use one statement per line in normal code; add a semicolon when placing multiple statements on one line or when the grammar needs an unambiguous boundary. ~~~vex fn main(): i32 { let first = 10 let second = 20; let total = first + second $println(total); return 0; } ~~~ Automatic insertion is intentionally conservative around operators, delimiters, and struct literals. Do not split an expression after an infix operator just because the line is long. ## Declarations The core declaration forms are: ~~~text fn name(parameter: Type): ReturnType { ... } struct Name { ... } enum Name { ... } contract Name { ... } const NAME: Type = value let name = value let! mutable_name = value ~~~ Bindings are covered in [Variables](docs/guide/basics/variables.md). Functions, methods, generics, and closures are covered in [Functions](docs/guide/basics/functions.md). ## Identifiers Identifiers are case-sensitive. They normally begin with a letter or underscore and may contain letters, digits, and underscores. Keep type names distinct from value names; Vex uses the spelling and context of a path to resolve types, functions, constructors, and fields. ~~~text counter user_name Point3 _temporary ~~~ The language reserves keywords such as fn, let, struct, enum, contract, if, else, elif, for, while, loop, match, return, break, continue, defer, go, async, await, import, export, unsafe, extern, self, true, false, and nil. ## Literals Vex supports integer, floating-point, boolean, string, character, and null literals. ~~~vex fn main(): i32 { let decimal: i32 = 42; let hexadecimal: i32 = 0x2a; let binary: i32 = 0b101010; let ratio: f64 = 3.5; let enabled: bool = true; let greeting = "hello"; $println(greeting); if enabled && decimal == hexadecimal + binary - 42 { return 0; } return 1; } ~~~ Unsuffixed integer literals default to i32 when there is no expected type. An expected parameter or return type can guide inference. Add an explicit annotation when the width is part of the program's meaning or ABI. Numeric suffixes and the complete primitive type list are documented in [Primitive Types](docs/guide/types/primitives.md). ## Strings and formatting Normal strings use double quotes and support escape sequences. Vex also has formatted string literals with an f prefix: ~~~vex fn main(): i32 { let name = "Vex"; let message = f"Hello, {name}!"; $println(message); return 0; } ~~~ Backtick template literals and compile-time rendering are separate features. Read [Template Literals](docs/guide/basics/template-literals.md) before using them in generated output; the feature is still evolving. ## Arrays, tuples, and blocks Array and tuple literals are expressions. A block can be used as the body of a control-flow construct or function; use return when the value must be returned from the enclosing function. ~~~vex fn first_pair(): (i32, i32) { let values: [i32; 2] = [3, 4]; let pair = (values[0], values[1]); return pair; } fn main(): i32 { let (left, right) = first_pair(); $println(left + right); return 0; } ~~~ See [Arrays](docs/guide/types/arrays.md) and [Tuples](docs/guide/types/tuples.md) for indexing, repetition, and ownership behavior. ## Operators The core operator groups are: | Group | Operators | | --- | --- | | Arithmetic | +, -, *, /, % | | Comparison | ==, !=, <, <=, >, >= | | Boolean | `&&`, `\|\|`, `!` | | Bitwise | `&`, `\|`, `^`, `~`, `<<`, `>>` | | Assignment | `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `\|=`, `^=`, `<<=`, `>>=` | | Access | ., [], function call () | | Range | .., ..= | | Error flow | ?, ??, and !> where supported by the Result/Option APIs | SIMD-oriented operators are documented separately because their type rules depend on arrays, masks, tensors, or SIR lowering. Do not assume that a scalar operator is automatically vectorized. ## Expressions and control flow if, match, and loops can appear inside functions. if and match can produce values when every branch has a compatible result: ~~~vex fn label(value: i32): i32 { return match value { 0 => 100, 1 | 2 => 200, _ => 300, }; } fn main(): i32 { let result = if label(1) == 200 { 1 } else { 0 }; $println(result); return 0; } ~~~ For detailed grammar and semantics, continue with [Control Flow](docs/guide/basics/control-flow.md), [Loops](docs/guide/basics/loops.md), and [Pattern Matching](docs/guide/types/pattern-matching.md). --- Source: https://vex-lang.org/docs/guide/basics/template-literals.md # Template Literals Template literals use backticks and embed normal Vex expressions with {{ ... }}. They are useful for HTML, config files, text reports, prompts, and generated source. ```vex let name = "Vex Developer"; let basic = `Hello {{ name }}`; $println(basic); ``` ## Basic interpolation Anything inside {{ ... }} is evaluated as Vex code: ```vex let name = "Vex Developer"; let active = true; let html = `

Hello World

Welcome, {{ name }}!

Status: {{ if active { "Active!" } else { "Inactive." } }}
`; ``` If an interpolated value is not already text, the compiler uses the normal string conversion path, so `.toString()` remains the mental model to keep in mind. ## Control flow blocks Template literals also support block-style control flow with {{ if ... }}, {{ else }}, {{ for ... in ... }}, and {{ end }}. ```vex struct User { public: name: string, age: i32, admin: bool, } let users = [ User { name: "Alice", age: 30, admin: true }, User { name: "Bob", age: 25, admin: false } ]; let page = `
    {{ for u in users }} {{ if u.admin }}
  • Admin: {{ u.name }}
  • {{ else }}
  • User: {{ u.name }}
  • {{ end }} {{ end }}
`; ``` This is the syntax used by the current repository examples. ## What templates are good for - HTML fragments - CLI reports and status pages - Generated config or source text - Structured logs with readable formatting Interpolated text is ordinary text construction. When producing HTML, SQL, or another structured language, apply that domain's escaping or parameterization at its boundary; a template literal does not establish that the result is safe for every destination. ## Compile-time checking Template literals are parsed by the compiler, not by a separate runtime template engine. That means unknown names or invalid expressions fail like normal Vex code during compilation. ## Escaping To output a literal {{, escape it with a backslash: ```vex let example = `Escaped example: \{{ not_parsed \}}`; ``` ## Notes - Backticks preserve multi-line layout. - You can mix plain text, inline expressions, loops, and branches in one template. - Template literals are a text-construction feature, not a replacement for module-level code generation or macros. --- Source: https://vex-lang.org/docs/guide/basics/variables.md # Variables and Constants Vex makes mutation explicit. A binding created with let cannot be reassigned; use let! when the binding itself must change. Constants use const and require a type annotation. Complete programs on this page print their computed values and return `0` for successful execution. Printed output and process exit status are separate: returning `42` from `main(): i32` would report a nonzero process status, not print the number. Fragments without `main` belong inside a program. ## Immutable bindings ~~~vex fn main(): i32 { let count = 42; let name = "Vex"; $println(name); $println(count); return 0; } ~~~ Reassigning count or name would be a compiler error. Immutability applies to the binding; it does not mean that every value reachable through a reference is immutable. ## Mutable bindings ~~~vex fn main(): i32 { let! total = 0; total += 10; total += 32; $println(total); return 0; } ~~~ The exclamation mark is part of the declaration syntax. It is not a general mut keyword. ## Constants Constants are declared at module scope with an explicit type: ~~~vex const MAX_RETRIES: i32 = 3; fn main(): i32 { $println(MAX_RETRIES); return 0; } ~~~ Use a constant for a named value that should be available without allocating a mutable binding. Keep runtime configuration in ordinary bindings or in a configuration type. ## Type annotations and inference An annotation follows the binding name: ~~~vex fn main(): i32 { let inferred = 42; let explicit: i64 = 42; let ratio: f64 = 3.5; let enabled: bool = true; $println(inferred); return 0; } ~~~ Unsuffixed integer literals default to i32 when there is no expected type. Function parameters, return types, field declarations, and explicit annotations can provide that expected type. Use an annotation when numeric width or ABI compatibility matters. An admitted widening conversion also applies when the initializer is another immutable local. For example, `let small: i8 = -7; let wide: i64 = small;` preserves `-7` whether evaluated at runtime or folded at compile time. Constant folding must retain the destination's exact type; it does not make narrowing or signed-to-unsigned conversions implicit. ## Shadowing A later let can introduce a new binding with the same name. The new binding hides the old one in the current scope: ~~~vex fn main(): i32 { let value = 10; let value = value + 5; $println(value); return 0; } ~~~ Shadowing is useful when a value changes representation during a sequence of transformations. Use distinct names when shadowing would obscure ownership or lifetime behavior. ## Destructuring Tuple patterns can bind several values at once: ~~~vex fn pair(): (i32, i32) { return (3, 4); } fn main(): i32 { let (left, right) = pair(); $println(left + right); return 0; } ~~~ Struct patterns can select exposed fields in `match` arms: ~~~text struct Point { public: x: i32, y: i32, } let point = Point { x: 3, y: 4 } let total = match point { Point { x, y } => x + y } ~~~ `let` also accepts struct and array destructuring through the shared pattern grammar. For example, `let Point { x, y } = point;` names the two fields. Nested tuple patterns are supported; successive bindings can still make a complicated shape easier to read. Use `match` when success depends on a variant or a condition rather than only on a fixed shape. Patterns participate in ownership and visibility checks just like ordinary bindings. See [Pattern Matching](docs/guide/types/pattern-matching.md) for match arms and [Ownership](docs/guide/memory/ownership.md) for move behavior. ## Scope A binding is visible from its declaration to the end of its enclosing block, subject to shadowing: ~~~vex fn main(): i32 { let outer = 10; let inner = { let nested = 32; outer + nested }; $println(inner); return 0; } ~~~ Use narrow scopes for temporary values. This makes the lifetime of owned data easier to see and gives the checker more opportunities to end a borrow before the next operation. ## Common mistakes - Use let! only for a binding that will actually be reassigned. - Do not assume that a mutable binding makes a value passed by reference mutable; the reference type must also allow mutation. - Add explicit types at FFI boundaries and for platform-sized values. - Do not use an integer sentinel where Option or Result communicates the state directly. - Check examples against the same compiler version used by your project. ## Next steps - [Primitive Types](docs/guide/types/primitives.md) - [Functions](docs/guide/basics/functions.md) - [Ownership](docs/guide/memory/ownership.md) - [Borrowing](docs/guide/memory/borrowing.md) --- Source: https://vex-lang.org/docs/guide/benchmarks.md # Benchmarks Use the compiler-owned benchmark runner instead of a hand-written timer. The following is an integration fragment: `Input`, `makeInput`, and `hash` belong to the application being measured. Put it in a benchmark test file alongside those definitions or imports. ```vex import { BenchCtx } from "testing"; fn bench_hash(b: &BenchCtx!) { let! input = makeInput(); b.setBytes(input.len() as i64); b.iterMut(&input!, |data: &Input!| hash(data)); } ``` ```bash vex test --bench -O3 --benchtime 1s --count 5 --benchmem tests/bench.test.vx ``` Independent benchmark files compile in a bounded parallel pool. Their binaries then execute serially so concurrent workloads cannot contaminate timing. A selected file is compiled once; `--count 5` reuses that exact artifact for all five measurement rounds. `BenchCtx.iter` centralizes adaptive clock batching, compiler barriers and an isolated child allocation region. Temporary allocations are reclaimed every 128 operations, and the caller's prior region and arena mode are restored. `iterMut` evolves caller-owned state; `iterString` consumes owned string results exactly once. Use `blackBox` in manual `b.n` loops. Timer control uses `resetTimer`, `startTimer` and `stopTimer`; resumed intervals accumulate. Do not benchmark a loop whose complete result is a compile-time constant. LLVM may legally replace it with the closed-form result. Seed work from runtime state and keep the result observable through `iter`, `iterMut` or `blackBox`. For reproducible comparisons record the Vex revision, target CPU/GPU, input distribution, optimization level, benchmark duration, iteration count, median and spread. Compare equivalent algorithms and observable outputs—never source size, estimates or one fastest sample as a substitute for measurements. --- Source: https://vex-lang.org/docs/guide/bit.md # Bit Namespace `Bit.pext` and `Bit.pdep` extract and deposit bits using a mask. They are builtin operations; the current source declares scalar `(u64, u64) -> u64` signatures. Do not assume a scalar call accepts arrays, spans, or tensors, or that it emits a single SIMD instruction. ## Quick Example Save this complete program as `bit-example.vx`: ```vex [bit-example.vx] fn main(): i32 { let source: u64 = 0b10100110; let sparse: u64 = 0b10100110; let mixed: u64 = 0b10000010; let full: u64 = 0xffffffffffffffff; $println(Bit.pext(source, 0 as u64)); $println(Bit.pext(source, full)); $println(Bit.pext(source, sparse)); $println(Bit.pext(mixed, sparse)); let deposited = Bit.pdep(0b1011 as u64, sparse); $println(deposited); $println(Bit.pext(deposited, sparse)); $println(Bit.pdep(Bit.pext(mixed, sparse), sparse)); return 0; } ``` A local macOS arm64 development build printed `0`, `166`, `15`, `9`, `134`, `11`, and `130`, each on its own line. These cover an empty mask, a full 64-bit mask, source equal to a sparse mask, a sparse selection containing zeros, and both directions of a masked round trip. ## Parallel Bit Deposit ### How PDEP Works Deposit the least-significant source bit into the least-significant set mask position, then advance through set mask positions from least to most significant. With source `0b1011` and mask `0b1010_0110`, source bits `1, 1, 0, 1` go to mask positions `1, 2, 5, 7`; the result is `0b1000_0110` (134). ## Parallel Bit Extract ### How PEXT Works Extract mask-selected source bits in ascending position order, packing the first selected bit into result bit 0. With `source = mask = 0b1010_0110`, positions `1, 2, 5, 7` are all set, producing `0b1111` (15). With source `0b1000_0010` and the same mask, selected bits are `1, 0, 0, 1`, producing `0b1001` (9). For a mask with `n` set bits, `pext(pdep(x, mask), mask)` keeps the low `n` bits of `x`; `pdep(pext(x, mask), mask)` equals `x & mask`. Bits outside the mask cannot be recovered. ## Hardware Support In the current compiler source, x86-64 targets with `+bmi2` select LLVM PEXT/PDEP intrinsics; other targets use software lowering. CPU support, compiler target settings, optimization, and generated machine code determine the actual path. No throughput or latency is promised here; benchmark the specific binary on your target. ## Related - [Math bit operations](docs/guide/math.md#bit-operations) - [Crypto Namespace](docs/guide/crypto.md) - [SIMD](docs/guide/simd/index.md) --- Source: https://vex-lang.org/docs/guide/concurrency/async-internals.md # Async Functions -- Internals This page covers how `async fn` and `await` work under the hood: the state machine lowering, suspension mechanics, and runtime interaction. ## The Async State Machine When you write an `async fn`, the Vex compiler lowers it into a **stackless coroutine** -- a state machine that can suspend and resume. Potential suspension points determine the saved state; an immediately ready await can continue inline. ### Source Code ```vex async fn fetchAndProcess(url: string): Result { let response = await http.get(url)? let parsed = await parse(response)? return Ok(parsed) } ``` ### What the Compiler Does The compiler: 1. Identifies all `await` points in the function body. 2. Partitions the code into **basic blocks** between `await` points. 3. Generates a state machine that saves/restores live variables at each boundary. 4. Generates a **resume function** that jumps to the correct state and continues execution. Conceptually (not actual generated code): ```vex // The compiler creates: // - A struct holding all live variables across await points // - A state enum tracking which await point is next // - A resume function with a jump table to each state ``` ## Suspension Mechanics ### What Happens at `await` ```vex let result = await someAsyncFn() ``` If the awaited operation is not ready: 1. The current function's state (live variables, program counter) is saved. 2. Control returns to the runtime scheduler. 3. The runtime polls the awaited operation. 4. When the operation completes, the runtime re-queues the task. 5. On resume, the state machine restores live variables and continues from the next instruction. ### Creating a Future is not awaiting it An `async { ... }` expression captures its inputs and constructs a Future. Its body does not run at that point, and constructing it does not suspend the enclosing function. Suspension begins only when the Future is awaited or scheduled: ```vex let pending = async { return await loadRecord(id) } // Construction above did not run loadRecord or yield this task. let record = await pending ``` The Future owns or borrows its captures according to the normal ownership rules, so those inputs remain live for as long as the Future may use them. At `await`, the compiler transports the exact Future value through the suspension boundary and preserves any reference provenance carried by its result. This prevents an awaited view or reference from outliving the storage that produced it. ### Suspension Safety Borrow safety depends on origin, lifetime, mutability, and owner storage. A value kept across `await` must remain valid when the coroutine resumes. Neither `&T` nor `&T!` can be classified solely by its spelling. | Case | Ownership obligation | | --- | --- | | Mutable reference to a local owner in an async frame | The owner and reference must remain valid in the frame; no conflicting access may occur while the mutable borrow is live. | | Reference returned from an awaited call | The reference cannot escape the lifetime of the owner that backs it. Awaiting does not extend that owner's lifetime. | | Reference backed by a caller-owned parameter | The caller must retain the owner for the entire borrow, including suspension and use of the result. | | Detached task capture | The captured owner or reference must outlive every use by the independently scheduled task. | The following function updates a frame-local record through a mutable reference and returns an owned integer result: ```vex [async-mutable-frame.vx] struct Cell { value: i32 } async fn update(): i32 { let! cell = Cell { value: 41 }; let reference = &cell!; await sleep(1); reference.value = reference.value + 1; return reference.value; } fn main(): i32 { let out: Channel = Channel.new(1); go { out.send(await update()); }; return match out.recv() { Some(42) => { $println("mutable frame: PASS"); 0 }, _ => 1, }; } ``` Expected output is `mutable frame: PASS`, with exit status 0. The `go` block communicates through a channel, and the parent waits for its result. Whether a particular await actually suspends depends on readiness; the owner must be valid on both the immediate and suspended paths. The following is an intentionally invalid lifetime example: `local` belongs to `bad`, so returning a reference to it would leave a dangling reference once `bad` finishes. Passing that reference through `await` does not make it valid: ```vex [async-escape.vx] async fn borrow(input: &i32): &i32 { return input; } async fn bad(): &i32 { let local = 42; return await borrow(&local); } fn main(): i32 { return 0; } ``` ### `SuspendSafe` Contract Suspension analysis uses compiler ownership and storage information. A type or marker name alone is not proof that a particular reference, view, or detached capture remains valid. Check the exact compiler and target; do not use pinning to bypass a lifetime or exclusivity error. ## Pin and Async An async frame can require address stability for values or references retained across a suspension. `Pin` is an address-stability mechanism, not a guarantee that arbitrary self-references are accepted or live long enough. For the tested examples and current limits, see [Pin](docs/guide/memory/pin.md#async-frames). ## Runtime Integration ### How the Scheduler Runs Async Tasks ``` User code: async fn myTask() { ... } | v Compiler: State machine struct + resume function | v Runtime: Task pushed to worker's local deque Worker picks up task Calls resume function | +-------+-------+ | | Completes Hits await | | Task done Save state Register with I/O poller Yield to scheduler | I/O completes | Re-queue task on worker | Resume from saved state ``` ### Key Runtime Functions The generated state machine cooperates with VexArch at each suspending `await` boundary. A ready await may continue inline; suspension saves state and hands the task back to the scheduler. The exact ABI is compiler/runtime-internal: | Concept | Purpose | |---------|---------| | Task spawn | Push a new task to the scheduler | | Task yield | Suspend current task, return to scheduler | | Task resume | Re-queue a suspended task | | Timer wait | Register an exact deadline in the hierarchical timer wheel | | Poller wait | Block on I/O events (kqueue/epoll/IOCP) | The full scheduler tracks an exact earliest timer deadline even when timers are stored in coarse wheel buckets. Workers reject future-deadline scans before contending on the wheel lock, ignore stale clock snapshots, and preserve chronological expiration across the internal millisecond-counter wrap. These are runtime representation guarantees, not application-visible timer APIs. Long waits are not limited by the wheel's compact 32-bit bucket key. Vex keeps the exact saturating i64 monotonic deadline inside the active task and schedules bounded modular chunks. Expiration, cascade, and long scheduler pauses re-arm the next chunk without resuming user code; only the exact final deadline wakes the coroutine. This requires no extra task bytes or per-wait allocation. > **Implementation detail:** See `lib/runtime/VexArch/src/async/` for the runtime > implementation. Its reserved `extern "VEX"` ABI is not application API. ## Async Function Rules ### Lifetime and ownership rules Use the [suspension safety table](docs/guide/concurrency/async-internals.md#suspension-safety) above for the tested examples. Do not generalize from either shared or mutable references alone. Keep owners alive, preserve exclusivity, and test the exact compiler, target, and operation. Avoid holding a lock across a suspension unless its locking protocol explicitly supports it. FFI export and recursive async support also need their own target-specific validation. ### Implicit suspension points `await` is the explicit suspension form. Potentially blocking channel syntax is also a suspension point when it appears in a coroutine: channel send, channel receive, and a `select` without a `default` arm split the generated state machine. A `select` with `default` is non-blocking and therefore does not suspend. The same channel operations inside an ordinary synchronous function may block the current OS thread, but they do not manufacture a coroutine frame or a synthetic `yield`. Borrow checking follows this distinction rather than treating every channel operation as async. ## Async with `?` Operator An awaited `Result` can use `?` to propagate a compatible error type. This fragment assumes the awaited calls return `AppError`; it does not establish automatic conversion from unrelated error enums: ```vex async fn processRequest(req: Request): Result { let user = await auth.verify(req.token)? // propagates AppError let data = await db.query(user.id)? // propagates AppError let result = await compute(data)? // propagates AppError return Ok(Response.new(result)) } ``` ## Comparison: Vex vs Rust Async | Concept | Rust | Vex | | ------------------ | --------------------------- | ------------------------------------- | | `await` syntax | Postfix: `expr.await` | Prefix: `await expr` | | State machine type | `impl Future` with `poll()` | Compiler-generated struct + resume fn | | Waker mechanism | `std::task::Waker` | Runtime-internal, not exposed | | Trait | `Future` trait | No trait -- compiler intrinsic | | Executor | External (tokio, async-std) | Built-in M:N scheduler | | Pin requirement | Manual for self-referential | Compiler-detected in supported cases; validate the exact build | ## Performance Characteristics | Metric | Approximate | Notes | | ----------------------- | ------------------------------------ | --------------------------------- | | State machine size | Sum of live vars across await points | Compiler optimizes dead stores | | Runtime task cell | 64 bytes | One cache line; frame is separate | | Ready `await` | No OS context switch | Continues through generated state | | Suspended `await` | Provider and workload dependent | Saves state and resumes later | Straight-line async graphs use a compiler-selected cooperative-local scheduler. That mode has no external wake source. If live tasks remain after its runnable FIFO becomes empty, Vex reports a deterministic cooperative deadlock instead of spinning during program finalization. Full async graphs are different: an empty runnable set may be waiting on channels, timers, or native I/O, so their scheduler uses provider-aware parking and cancellation rather than this local terminal check. The full scheduler becomes visible only after its native poller, global queue, and timer wheel have all initialized. These resources form one construction transaction: a failure releases every completed prefix and publishes no partial scheduler. Likewise, cooperative-local state can promote only before any task, frame, queue entry, or scheduler work exists. Live local frames can contain allocator and coroutine-context pointers, so Vex rejects a late promotion instead of copying an unsafe ownership graph; capability selection must choose the full scheduler before task publication. Timer suspension verifies its provider before marking the task waiting, preventing an allocation failure from turning into an invisible permanent suspension. Task publication follows the same fail-closed rule. If scheduler/task storage, an inline reservation token, or queue ownership is unavailable, Vex emits an allocation-free runtime diagnostic and terminates before publication. It never reports success after silently dropping a `go` task or leaves an active task count with no reachable queue entry. Cooperative-local frames use a thread-local VexArch allocator rather than libc `malloc`/`free`. Small blocks are reused from aligned size classes backed by raw 64 KiB pages; large frames use page-rounded direct extents. Bounds are checked before extent tagging and rounding, and cleanup is idempotent for both pooled and direct storage. Linux uses the target mmap/syscall provider, macOS uses the system VM provider, and Windows uses `VirtualAlloc`; this does not add a libc allocator dependency to freestanding runtime storage. ## Best Practices 1. Keep async functions focused -- each `await` point adds to the state machine. 2. Keep borrowed owners alive across suspension; clone only when independent ownership is needed. 3. Don't hold locks across `await` -- restructure to acquire-release around suspension. 4. Use `go` to schedule independent work and define completion and shutdown explicitly. 5. Be explicit about error types -- `Result` composes well with `?`. 6. Avoid deep async call stacks -- each level adds state. ## Related Pages - [Concurrency Overview](docs/guide/concurrency/overview.md) -- goroutines and M:N scheduler - [Async](docs/guide/concurrency/async.md) -- async/await basics - [Channels](docs/guide/concurrency/channels.md) -- message passing between tasks - [Runtime Architecture](docs/architecture/runtime-architecture.md) -- VUMM, event loop, channel internals - [Operators Reference](docs/guide/advanced/operators-reference.md) -- channel send/receive operators --- Source: https://vex-lang.org/docs/guide/concurrency/async.md # Async/Await and `go {}` Use `async fn` and prefix `await` to express dependencies that may suspend. Use `go {}` to schedule work independently. Channels connect the two styles and provide an explicit way for the caller to wait for results or completion. ## A Complete Async Workflow This example starts an async calculation inside a task and waits for its result before returning from `main`: ```vex [async-result.vx] async fn twice(value: i32): i32 { return value * 2; } async fn answer(): i32 { return (await twice(21)) + 1; } fn main(): i32 { let result = Channel.new(1); go { result.send(await answer()); result.close(); }; return match result.recv() { Some(value) => { $println(value); if value == 43 { 0 } else { 1 } }, None => 2, }; } ``` Save as `async-result.vx` and run `vex run async-result.vx`. Expected stdout is `43`, with exit status 0. These async functions compute immediately; the example demonstrates awaiting and result ownership, not a timer, network I/O or a measured scheduler suspension. ## Prefix `await` Write `await work()` rather than `work().await`. Awaiting a dependency obtains its result before the enclosing expression continues. Parentheses make the order clear in a larger expression: ```vex let first = await left(); let second = await right(); let total = first + second; ``` This fragment is sequential. Two awaited calls are not automatically concurrent; independent progress requires a scheduling operation and a completion protocol. An `async { ... }` expression constructs a future and captures its inputs; that construction does not itself execute the body or suspend the enclosing task. ## `go {}` Blocks A `go` block schedules work. It does not return its block value to the caller. When the caller needs a result, use a channel as in the complete example. When a task is intentionally detached, establish who owns its inputs, how it reports failures and what happens during application shutdown. Do not teach a program that schedules a task and immediately returns from `main` as a reliable way to observe that task's output. Explicit completion makes examples and applications independent of incidental shutdown timing. ## Suspension and Borrowing An `await` can suspend. Values needed after that point must remain valid in the coroutine frame, including the owners behind references. Whether a particular borrow is accepted depends on its origin, storage, lifetime and mutability; there is no general rule that every reference is forbidden across `await`. See [Async Internals](docs/guide/concurrency/async-internals.md#suspension-safety) for positive and negative borrow examples. Pinning addresses an address-stability requirement; it does not repair a dangling reference or an exclusivity error. ## Channels, Errors and Shutdown `recv()` distinguishes a received value from a closed, drained channel. This matters when zero is legitimate data. For fallible work, design a result message with success and error variants and ensure every terminal path notifies the receiver. A task that exits without sending or closing can leave a consumer waiting indefinitely. Bounded channels introduce backpressure. Decide whether cancellation closes a channel, sends an explicit message, or uses a library's documented cancellation protocol. Then wait for worker completion before releasing shared resources. The [fan-in guide](docs/guide/concurrency/fan-in.md) shows a multi-worker lifecycle. ## When to Use Which | Need | Mechanism | | --- | --- | | Sequence dependent async operations | `async fn` and `await` | | Start independent work | `go {}` | | Transfer results and report completion | `Channel` | | Distinguish closure from a zero-valued message | `recv()` or a documented result API | | Coordinate multiple producers | Explicit owner of output closure and worker completion | ## Next Steps - [Collecting Fallible Task Results](docs/guide/concurrency/batch-results.md) - [Concurrency Overview](docs/guide/concurrency/overview.md) - [Channels](docs/guide/concurrency/channels.md) - [Fan-in and Shutdown](docs/guide/concurrency/fan-in.md) - [Async Internals](docs/guide/concurrency/async-internals.md) --- Source: https://vex-lang.org/docs/guide/concurrency/batch-results.md # Collecting Fallible Task Results Independent tasks can complete in any order. Give each reply an identifier and an explicit success or error value, then let one collector own aggregation. This keeps the result protocol separate from scheduling order. ## A complete two-job batch The first job doubles a nonnegative input. The second rejects a negative input. Both send a `Reply`, so the collector receives two terminal outcomes instead of waiting forever for a failed job to send a successful value. ```vex [async-batch-results.vx] enum JobError { NegativeInput } struct Reply { id: i32, result: Result } async fn evaluate(value: i32): Result { if value < 0 { return Err(JobError.NegativeInput); } return Ok(value * 2); } async fn sendReply(id: i32, value: i32, output: Channel) { let result = await evaluate(value); output.send(Reply { id: id, result: result }); } fn main(): i32 { let output = Channel.new(1); go { await sendReply(0, 21, output); }; go { await sendReply(1, -3, output); }; let! received = 0; let! success = 0; let! rejected = 0; while received < 2 { match output.recv() { Some(reply) => { received += 1; match reply.result { Ok(value) => { if reply.id != 0 || value != 42 { return 1; } success += 1; }, Err(JobError.NegativeInput) => { if reply.id != 1 { return 2; } rejected += 1; }, }; }, None => { return 3; }, }; } output.close(); $println(success); $println(rejected); if success != 1 || rejected != 1 { return 4; } return 0; } ``` Save as `async-batch-results.vx` and run `vex run async-batch-results.vx`. Expected output is one successful result and one rejected input: ```text 1 1 ``` The two workers can send in either order. `reply.id` lets the collector check which input produced each result; the printed totals are order-independent. The `Result` payload owns either the calculated value or the error enum. `None` from `recv()` has a different meaning: the channel closed and drained before all expected replies arrived. The calculation completes immediately, but the protocol also explains where an operation that suspends belongs: inside `evaluate`, awaited before its reply is sent. Marking a function `async` does not make the two calls run in parallel; the two `go` blocks are the scheduling operations. ## Backpressure and closure ownership The output capacity is one. A sender may wait while the previous reply occupies that slot; the collector creates space by receiving. Only the collector closes the output, after consuming both expected replies. A worker must not close the shared output after its own send because the other worker may still be using it. This is a fixed batch: exactly two launched jobs each produce exactly one terminal reply. For a variable-size stream, use a producer-completion protocol such as [fan-in and shutdown](docs/guide/concurrency/fan-in.md), then drain until closure. A count of expected replies is not a cancellation or timeout policy. The early returns in `main` are checks for this teaching example. In a service, a collector that stops early must notify producers, handle unsuccessful `send` results, and wait for their completion before releasing shared resources. A panic, process termination, or worker that never sends is not converted into an `Err` automatically. ## Preserve input order when needed Carry an input index in each reply, as `id` does here. A single collector can place each successful value or error into an indexed result collection. Emit that collection in input order only after every expected index is complete. For untrusted or retrying producers, also reject duplicate and out-of-range indices; counting messages alone would not establish a complete batch. Keep task-local calculations and result transfer separate from mutations of a shared aggregate. The collector can own its counters or result storage without introducing a lock around every worker update. ## Next steps - [Async/Await and go](docs/guide/concurrency/async.md) - [Channels](docs/guide/concurrency/channels.md) - [Fan-in and channel shutdown](docs/guide/concurrency/fan-in.md) - [Result API](docs/guide/types/result-api.md) --- Source: https://vex-lang.org/docs/guide/concurrency/channels.md # Channels Channels provide typed communication between Vex tasks. A channel can be bounded, which makes the amount of queued work explicit and gives the producer a natural backpressure point. The compiler, Prelude, and runtime share one typed message ownership protocol. A value accepted by a channel belongs to the receiver; rejected sends destroy the moved value exactly once. ## Create and use a channel The constructor form is the simplest current example: ~~~vex fn main(): i32 { let! channel: Channel = Channel(3); go { channel.send(42); channel.send(100); channel.send(999); }; let first = <-channel; let second = <-channel; let third = <-channel; if first != 42 { return 1; } if second != 100 { return 2; } if third != 999 { return 3; } return 0; } ~~~ The channel type carries the element type. Sending a value of another type is a semantic error. `Channel()` and `Channel(capacity)` are source-defined Prelude constructor overloads that delegate to `Channel.new`. Their defaults and initialization belong to that Vex source, not a second constructor implementation in the compiler. The no-argument overload currently selects capacity 16. ## Capacity The integer passed to Channel is the buffer capacity: ~~~text Channel(1) Channel(16) ~~~ A capacity of one is useful for hand-off or small bursts. A larger capacity allows a producer to get ahead temporarily, but it does not remove the need for a shutdown policy. ## Receive syntax The receive operator is written `<-channel` and is intended for a blocking receive: ~~~text let value = <-channel ~~~ `<-channel` returns `T` directly. If the channel is closed and fully drained, it returns `T`'s zero value, matching the single-value Go-style receive rule. Use the explicit APIs when closure must remain observable: ~~~vex let maybe: Option = channel.recv() let result: Result = channel.recvResult() let ready: Option = channel.tryRecv() ~~~ ## Closing and shutdown A producer should close a channel only when it has finished sending. Consumers need a clear way to stop; otherwise a worker can wait forever for data that will never arrive. `close()` rejects future sends while allowing receivers to drain values that were already accepted. `recv()` returns `None` after the closed queue is drained; `recvResult()` returns `Err`; and `tryRecv()` returns `None` when no value is immediately available. An accepted send is never discarded merely because `close()` races its final publication. Close and producer reservation are ordered by the same atomic cursor. If the producer reserved first, receivers wait for that payload and then reach the drained terminal state. This also applies when many ordinary or `select` receivers are already blocked: each wait generation is claimed at most once, and the final accepted publication cannot leave surplus receivers parked on a permanently drained channel. `trySend(value)` is the symmetric non-blocking publication operation. It returns `false` immediately when the bounded queue is full or closed; because it takes ownership just like `send`, a rejected value is destroyed exactly once. Use it for fail-closed completion inboxes and native event-loop bridges where blocking a scheduler participant would violate the subsystem contract. ## Ownership and captures A channel does not make arbitrary captured state safe to share. Values sent through a channel and values captured by a go block still follow Vex's ownership and escape rules: ~~~text let! queue: Channel = Channel(8) let message = Message.Work go { queue.send(message) } ~~~ Whether this is accepted depends on whether the captured message is moved or borrowed safely. Prefer transferring ownership of a value that will no longer be used by the sender, or define a small message type that makes the transfer explicit. Channel operations observe the channel through a shared handle; sending does not consume that handle. The payload is different: a successful or pending send transfers ownership of the value to the channel operation, and the caller must not use the moved value afterward. ## Blocking and suspension In an ordinary `fn`, a blocking send or receive waits on the current OS thread. It is not a coroutine suspension point. In an `async fn` or `go` body, direct send and receive syntax may park the current task, so the compiler retains the receiver and payload in the coroutine frame until the operation completes. A `select` without `default` follows the same async rule because it may wait for one case to become ready. A `default` arm makes `select` non-blocking and does not add a suspension point. ## Waiter fairness Blocked senders, blocked receivers, and parked `select` cases are registered in arrival-order intrusive FIFOs. The runtime represents each queue as a circular list with one tail pointer, so fairness does not enlarge the channel object or add allocation. Ordinary and `select` waiter classes alternate when both are present; close detaches each waiter exactly once before publishing wakeups. FIFO order applies to completed waiter registration, not source-level spawn order. With multiple scheduler workers, two tasks may reach the same channel in a different order from the order in which their `go` statements were issued. ## A practical design For a producer-consumer pipeline: 1. Choose the element type and capacity. 2. Decide who owns the sending side. 3. Define how the consumer learns that production is complete. 4. Decide how errors are returned, usually through a Result value or a second channel. 5. Test the shutdown path as carefully as the successful path. ## Select ownership and readiness Blocking `select` is event-driven: each case owns an independent waiter, one atomic winner commits the operation, and losing waiters are removed before their storage is reused. Ready cases begin at a rotating per-thread index so a permanently-ready first case cannot starve later cases. A `default` arm makes the operation non-blocking. Every channel and payload expression in a `select` is evaluated exactly once, in source order, before readiness is resolved. Send candidates are moved into compiler-owned transports during that preparation; losing a case does not restore its source value. Channel handles remain usable because selection only borrows them. Case-local reservations are released before the selected case body begins. A readiness decision applies to the committed operation, not to every other operation on that channel. Another task may consume the next value or fill the next slot. Design the selected branch around the value it received or the send it completed, and give channel closure an explicit meaning in the protocol. ## Next steps - [Fan-in and channel shutdown](docs/guide/concurrency/fan-in.md) - [Concurrency Overview](docs/guide/concurrency/overview.md) - [Async](docs/guide/concurrency/async.md) - [Borrowing](docs/guide/memory/borrowing.md) - [Error Handling](docs/guide/error-handling.md) --- Source: https://vex-lang.org/docs/guide/concurrency/deep-dive.md # Concurrency -- Deep Dive This page covers advanced concurrency features: the M:N scheduler, synchronization primitives, and channel patterns. This page separates public task/channel behavior from runtime implementation notes. The complete [async workflow](docs/guide/concurrency/async.md) and [fan-in example](docs/guide/concurrency/fan-in.md) are the starting points for application code. Internal scheduler and synchronization types are not public imports. ## M:N Scheduler Architecture Vex uses an M:N user-space scheduler: M coroutines multiplexed onto N operating system threads. This is the same model as Go's runtime, but Vex's scheduler is designed for both throughput and latency-sensitive workloads. ### Architecture Overview ```text User tasks → compiler-selected scheduler variant → owner-local queues / shared work distribution → worker execution and bounded stealing ↔ channel wakeups / timer deadlines / native I/O provider ``` This is a responsibility map, not a fixed object layout. The compiler can select a cooperative-local runtime for a graph that needs no external wake provider; the full M:N runtime has different initialization and shutdown rules. ### Worker Threads The development M:N runtime derives a worker ceiling from CPU discovery and caps its default at 32. Embedders and compiler-selected runtime variants can use different configurations. A CPU count query is not a scheduler introspection API, and this guide does not prescribe a `VEX_WORKERS` environment variable or a `vex.toml` key without an implementation that consumes it. ### Work-Stealing Algorithm Each worker maintains a **local deque** (double-ended queue) of tasks: 1. **Push/pop from local end** -- The owning worker pushes new tasks to the back and pops from the back (LIFO, cache-friendly). 2. **Steal from remote end** -- Idle workers steal from the front of another worker's deque (FIFO from that end; task age does not establish task size). 3. **Global queue fallback** -- If all deques are empty, workers check the global queue. The runtime contains a Chase-Lev-style deque. Its atomic publication and steal protocol are implementation details; FIFO/LIFO endpoints do not promise application-level task order or a latency bound. ``` Worker A's deque: [task1, task2, task3, task4] ^ ^ | | Steal (FIFO) Push/Pop (LIFO) ``` ### Task Lifecycle ``` Created --> Queued --> Running --> Complete | | | +--> Suspended (await) --> Queued | +--> Stolen (migrated to another worker) ``` ## `go` Blocks -- Deep Semantics ### Capture Semantics `go` capture analysis selects ownership behavior from the value and how it is used. An owned value can move into the task; some shared owners use their documented sharing protocol. A borrowed reference must not outlive its owner: ```vex fn spawnTasks(data: Vec) { // data is moved into the go block -- cannot be used after go { for item in data { process(item) } } // data is inaccessible here -- compile error } ``` For mutable coordination, use `Channel`. Immutable owned data may be captured through `Box`; VUMM recognizes the cross-task escape and selects the required thread-safe representation internally. Vex does not expose `Arc`, `Rc`, reference counts, or thread-ownership bookkeeping to application code: The owner and immutable captures must remain valid until every task completes. A function that starts two tasks and returns without a completion protocol is not a useful proof of shared ownership. Use separate result/completion messages as in the [fan-in example](docs/guide/concurrency/fan-in.md), and validate any custom sharing protocol's final drop behavior. ### `go` with Return Values `go` blocks do not return values directly. Use channels or shared state: ```vex fn computeAsync(): Channel { let! ch = Channel.new(1) go { let result = expensiveComputation() ch <- result // send result through channel } return ch // caller receives the channel } fn main() { let resultCh = computeAsync() // ... do other work ... let result = <-resultCh // blocks until result is ready $println(f"Result: {result}") } ``` ### Capture and Lifetime Boundaries A spelling such as `&T` or `&T!` alone does not determine every accepted capture. The compiler checks origin, lifetime, storage and mutation. Moving a pointer is not the same as transferring ownership of what it points to. Keep borrowed views within the lifetime of their storage; use an owning value or explicit communication when work may outlive its caller. ### Exact detached batches and automatic fanout When a detached integer-range group has an exact small task count, a non-suspending body, and a capture layout whose ownership can be completed before publication, the compiler may lower the source operation as one private batch. This is a physical optimization only: it does not change iteration values, ownership, completion, or source-visible concurrency semantics. The compiler chooses producer-local or 2/4/8-way publication from the target, the exact task population, and a transitive typed-HIR cost. Calls are followed by resolved semantic identity and exact generic instantiation, never by a function-name match. Recursion, indirect calls, dynamic control flow, unsupported targets, or incomplete inference retain the ordinary scheduler path. Suspension uses a separate persistent-frame admission path described below; it never uses transient inline capture storage. Automatic fanout is also subordinate to the runtime's configured worker ceiling. For example, an eight-way compiler request in a four-worker embedder uses at most four execution contexts; it never silently expands the pool. This keeps scheduler tuning and host resource ownership under application control while allowing zero-source-noise batching where the proof is complete. Exact owned indexed sources participate in the same physical optimization. Copy arrays move into one generation-owned aggregate, while `Vec` and `Deque` move one owning container and yield immutable `&T` items to the lane tasks. A Deque remains a ring: the compiler transports its semantic head and capacity and maps logical indices directly to wrapped physical slots without linearizing or copying it. The final lane releases compiler-generated drop glue exactly once. Borrowed Slice/Span views intentionally keep the ordinary path, because a view alone does not prove that its backing owner outlives detached execution. Read-only shared captures may also use this exact batch path when ownership can be completed before reservation. Today that proof is available for the exact `Channel` language item and for `Box` sites that VUMM has selected as thread-safe shared owners. `Box` remains the public API; no Arc type or manual thread-aware ownership leaks into user code. Retains may be combined into one same-owner multiplicity operation before private task reservation. The compiler passes the exact owner and lane count directly; no pointer array is materialized, and VexArch performs one RC update or one uncontended CAS. Channel and VUMM ownership remain distinct internally, so this optimization cannot accidentally apply VUMM release or permanence rules to Channel storage. Owned strings and arbitrary user containers remain fail-closed because their clone operation may allocate or otherwise fail. Suspending Array, Vec, and Deque bodies retain the same ownership model rather than falling back to one universal coroutine. One allocation owns the single source value and exactly N persistent lane frames. Array/Vec frames carry only `data`, `length`, and a logical cursor; Deque adds `head` and `capacity` so every lane can address the ring directly. Generic iterator state is omitted. Vec/Deque drop glue runs exactly once after the final lane reaches terminal completion, including lane-local `break`; Copy arrays need no owner destructor. The parent evaluates the source once, even when the `go` is nested in an async function. For an integer-range body that can suspend, `go(cpu: N) for` likewise creates exactly N persistent coroutine lanes rather than one universal task. The parent evaluates range bounds or a trusted first-class `Range` once, allocates one aggregate frame generation, initializes every private lane, and publishes the group once. Lane `i` visits offsets `i, i + N, ...` from a widened frame field. Empty lanes finish normally, and inclusive integer maxima cannot wrap at the source width. Transient inline captures remain DONE-only. Aggregate coroutine frames instead survive YIELDED/WAIT returns and are released only after terminal DONE and drop glue. The final lane reclaims the shared allocation. Resume blocks reload bounds and offsets from the frame, so no entry-state SSA value is reused across a suspension edge. Admission is based on exact HIR identities and repeat-safe capture ownership; unsupported owners retain the single-coroutine fallback. Borrowed views and non-Copy arrays stay on that fallback until backing lifetime and exact-once element destruction can be proven. Generic iterator lane batching additionally requires a semantic partition capability: sharing one mutable `next()` cursor across lanes would race, while calling `iter()` once per lane could repeat user-visible conversion effects. This fallback is not limited to integer ranges. An inference-sealed custom `Iterator` keeps its normalized source value in the coroutine frame, and a custom `IntoIterator` keeps the converted iterator in a separate exact frame field when its type or ABI differs from the source. `iter`, `next`, and `Option` are selected by semantic identity rather than spelling. Mutable receivers are reloaded after resume, and converted iterator drop glue runs exactly once on exhaustion, `break`, return, or terminal cleanup. Re-entering the same source loop reinitializes the persistent field and its ownership flag without reusing stale state. Ordered results require an explicit collection protocol: include an input index in each result and let a single collector place it in the corresponding slot. Launch order does not establish completion or arrival order. The `ordered` modifier is reserved; use indexed results or channels for this behavior. ## Channel `select` `select` chooses among channel operations. A `default` case gives a non-blocking path; without it the operation may wait. The order in which tasks are spawned does not establish arrival order or the winning case. Selection alone does not define shutdown. A single-value receive from a closed, drained channel can produce the element type's zero value. An endless loop can therefore confuse closure with data. Use the explicit [receive and close contracts](docs/guide/concurrency/channels.md) and the complete [fan-in lifecycle](docs/guide/concurrency/fan-in.md). A timeout is an application protocol, not just an arbitrary `after 5.seconds()` clause copied from another language. Use the timer or context API provided by the selected runtime/library and arrange cancellation and cleanup for every contender. The previous `sync`, `sync/atomic`, Mutex, RwLock and WaitGroup import examples were API sketches, not verified public packages; this guide does not present them as copyable current Vex code. ## Synchronization and Shared State Choose the smallest protocol that states who may change each value: | Need | Design requirement | | --- | --- | | Work distribution | Bound the queue; define overflow/backpressure and shutdown. | | Completion | Count actual terminal workers; notify exactly once on success and error. | | Shared mutable state | Use a supported synchronization API or transfer mutation to one owning task. | | Cancellation | Wake blocked senders and receivers; release resources after workers finish. | | Reusable initialization | Define ownership, error propagation and whether failure can be retried. | The runtime contains internal locks and atomics. Their presence does not expose an application package or a stable set of memory-order defaults. When using a supported atomic API, derive ordering from a concrete communication relation; “relaxed is fastest” or “sequential consistency is safest” is not a correctness argument for a compound algorithm. Thread-local state belongs to an operating-system thread. A task that can suspend or migrate must not use thread-local state as if it were task-local state. Prefer explicit state ownership when that distinction matters. ## Concurrency Safety Contracts `ConcurrentSafe` and `SuspendSafe` are compiler-recognized capabilities. They complement storage and lifetime analysis; merely naming a capability does not establish that every reference or capture is safe. `$Send` and `$Sync` are not the Vex contract spellings. See [ownership at concurrency boundaries](docs/guide/concurrency/overview.md#ownership-at-concurrency-boundaries). ## Debugging Concurrency Issues Use a small deterministic protocol test before stress or performance testing. Record how many messages were accepted, which workers completed, and whether closure was observed after draining. Apply a deadline to the test harness so that a failed shutdown produces an actionable failure instead of an endless run. ### Thread Sanitizer `vex compile --sanitize thread` selects sanitizer instrumentation where the compiler, runtime libraries and target support it. Instrumented compilation is not proof that all runtime code is instrumented or that no race exists. Check the selected build and run the actual concurrent paths. ### Deadlock Detection The compiler-selected cooperative-local runtime has no external wake source. It therefore reports a deterministic deadlock when live tasks remain but its runnable FIFO is empty. No environment flag is required. The full M:N runtime cannot infer a general wait cycle from an empty runnable set: tasks may be waiting legitimately on I/O, timers, channels, cancellation, or a remote worker publication. Use bounded contexts/timeouts for application protocols. General cross-provider wait-cycle diagnostics are not currently a documented runtime guarantee. ## Performance Characteristics | Operation | Latency | Notes | | ------------------------- | --------------------- | ---------------------------------------- | | `go { }` spawn | target-dependent | Measure with the bounded benchmark matrix | | Channel send | target-dependent | Bounded MPMC ring; no direct handoff claim | | Mutex lock | target-dependent | Contention and provider policy dominate | | Work stealing | target-dependent | Runs only on the scheduler's idle path | Vex keeps the common task cell to one 64-byte cache line and uses owner-local queues plus bounded stealing. Competitive numbers must come from the repository's bounded benchmark matrix on the target host; these rows are architecture notes, not fixed nanosecond promises. ## Best Practices 1. Make ownership, errors, cancellation and completion visible in each protocol. 2. Use bounded queues where producers can outpace consumers. 3. Separate task completion from the arrival of an intermediate result. 4. Test empty/full queues and shutdown while work is pending. 5. Use `go` for independent work, including CPU work where appropriate; use `graph fn` for supported data-parallel computations rather than as a universal replacement for CPU tasks. 6. Measure scheduling and communication overhead on the deployment target. ## Related Pages - [Concurrency Overview](docs/guide/concurrency/overview.md) -- goroutines and M:N scheduler - [Async](docs/guide/concurrency/async.md) -- async/await basics - [Channels](docs/guide/concurrency/channels.md) -- message passing between tasks - [Runtime Architecture](docs/architecture/runtime-architecture.md) -- VUMM, event loop, channel internals - [Operators Reference](docs/guide/advanced/operators-reference.md) -- channel send/receive operators --- Source: https://vex-lang.org/docs/guide/concurrency/fan-in.md # Fan-in and channel shutdown This example forwards values from two input channels into one bounded output. Each worker uses `recv()` so `Some(0)` is data and `None` means the source is closed and drained. One coordinator waits for both workers before closing the output. The consumer drains until `None` and then waits for the coordinator. Save the following as `fan-in.vx`: ```vex [fan-in.vx] fn forward(source: Channel, output: Channel, finished: Channel) { loop { match source.recv() { Some(value) => { if !output.send(value) { break; } }, None => { break; }, } } finished.send(1); } fn fanIn(left: Channel, right: Channel): (Channel, Channel) { let output = Channel.new(1); let workersDone = Channel.new(2); let finished = Channel.new(1); go { forward(left, output, workersDone); }; go { forward(right, output, workersDone); }; go { let _ = workersDone.recv(); let _ = workersDone.recv(); output.close(); finished.send(1); }; return (output, finished); } fn main(): i32 { let left = Channel.new(1); let right = Channel.new(1); left.send(0); left.close(); let (output, finished) = fanIn(left, right.clone()); right.send(7); right.close(); let! count = 0; let! sum = 0; let! zero = 0; let! seven = 0; loop { match output.recv() { Some(value) => { count += 1; sum += value; if value == 0 { zero += 1; } if value == 7 { seven += 1; } }, None => { break; }, } } let _ = finished.recv(); $println(count); $println(sum); $println(zero); $println(seven); if count != 2 || sum != 7 || zero != 1 || seven != 1 { return 1; } return 0; } ``` Run `vex run fan-in.vx`. The result is independent of which worker sends first: ```text 2 7 1 1 ``` The lines are total messages, their sum, number of zero values, and number of seven values. The left input closes before the right input sends; the right remains usable and both are drained before the output closes. The checks in `main` return a nonzero status if those counts differ. ## Cancellation and bounded queues The output buffer has capacity one, so a forwarding worker can wait when the consumer stops reading. In a design where the caller owns cancellation, close the output to wake or reject blocked sends, and coordinate the input owners so they stop producing and close the inputs to wake blocked receives. A producer whose `send` returns `false` must stop; closing an input while another owner still intends to send changes that producer's outcome. Wait for `finished` before treating the forwarding tasks as finished. Cancellation can discard values the consumer chose not to drain. Cancellation needs its own notification or context-aware protocol. Decide whether outstanding messages are drained or discarded, notify every blocked participant, and wait for its completion acknowledgement. Arrival order can differ between producers; attach a source identifier or sequence number when the consumer needs to reconstruct that order. `select` receives that return only `T` do not by themselves distinguish a closed channel from a valid zero value. Do not repeatedly select such a closed input as if every zero were a message. See [Channels](docs/guide/concurrency/channels.md) for receive and close semantics. ## Related workflow For a fixed number of jobs whose replies may succeed or fail, see [Collecting Fallible Task Results](docs/guide/concurrency/batch-results.md). --- Source: https://vex-lang.org/docs/guide/concurrency/overview.md # Concurrency Overview Vex has two concurrency surfaces: 1. go blocks for detached or background work; 2. async functions and await for suspension-based workflows. Channels provide typed communication between tasks. The runtime uses bounded multiple-producer, multiple-consumer queues, cooperative blocking progress, and event-driven multi-channel `select`. Channel capacity controls how far producers can advance before a consumer makes space. ## Choose a model | Model | Use it for | Main syntax | | --- | --- | --- | | go block | Scheduling a block of work | go { ... } | | async function | A function that may suspend | async fn | | await | Waiting for an async result | await expression | | channel | Typed communication and backpressure | `Channel`, `<-channel` | Start with synchronous code. Add concurrency when the ownership boundary and shutdown behavior are clear. ## go blocks A go block schedules its body independently of the current statement sequence: ~~~vex fn main(): i32 { let done = Channel.new(1); go { $println("background work"); done.send(1); }; $println("main continues"); let _ = done.recv(); return 0; } ~~~ The two messages can appear in either order. The final receive makes task completion explicit before `main` returns. The block does not make a synchronous function return a value. If the caller needs a result, use a channel or an explicit task handle provided by the relevant runtime API. Captured values still go through ownership and escape analysis. A borrowed local cannot be moved into a detached block if that would leave a dangling reference or create an unsafe shared mutation. ## Channels Channels are typed queues. A bounded channel makes the producer and consumer relationship explicit: ~~~vex fn main(): i32 { let! channel: Channel = Channel(1); go { channel.send(42); }; let value = <-channel; $println(value); return 0; } ~~~ The receive operator is blocking and returns the element type directly. A drained closed channel produces that type's zero value. Use `recv()`, `recvResult()`, or `tryRecv()` when the caller must distinguish closure or non-readiness. See [Channels](docs/guide/concurrency/channels.md). ## async and await An async function can be awaited from another async context: ~~~vex async fn fetch_value(): i32 { return 42; } async fn main(): i32 { let value = await fetch_value(); $println(value); return 0; } ~~~ Await is not valid in an ordinary synchronous function. An async function's runtime behavior depends on the runtime support available for the target and the operation being awaited. ## Ownership at concurrency boundaries Concurrency does not disable the ownership model. The compiler checks captures at a go or async boundary: ~~~text let! values = Vec.new() let borrowed = &values go { use(borrowed) } ~~~ Whether a capture is accepted depends on the lifetime and capture kind. Prefer moving an owned value into a task, borrowing only when the task is guaranteed to remain within the borrow's lifetime, and communicating results through a channel. For bounded iteration such as `go(cpu: 4) for item in bundle.items { ... }`, an independently owned source field can move into the task without moving `bundle.label`. This also covers nested generic fields and user-defined iterators; it is not a special privilege of `Vec`. An iterator call such as `bundle.items.iter()` stays inside the task, after its source owner is transferred, so it cannot leave a borrow pointing into the spawning function's storage. This precise source transfer does not permit reading the moved field again or moving it while a live borrow exists. A custom destructor or sharing protocol on an enclosing aggregate, an indexed/borrowed source place, or use of the same root inside the loop body retains the existing whole-root capture rules. It is not a promise of field-by-field capture for every closure or `go { ... }` block. ## Designing for the runtime A producer can wait when its bounded queue is full; a receiver can wait when that queue is empty. Give every wait an owner responsible for making progress or initiating shutdown. Close a channel only after its final producer is done, and drain the buffered values when delivery matters. For portability, consult [Platform Support](docs/guide/platform-support.md). Measure throughput and latency with the workload and runtime configuration you intend to deploy; queue capacity and task count are application choices. ## Next steps - [Collecting Fallible Task Results](docs/guide/concurrency/batch-results.md) - [Channels](docs/guide/concurrency/channels.md) - [Async](docs/guide/concurrency/async.md) - [Borrowing](docs/guide/memory/borrowing.md) - [Language Status](docs/guide/language-status.md) --- Source: https://vex-lang.org/docs/guide/contributing.md # Contributing to Vex A useful contribution connects an observable behavior to a focused change and its verification. Language and standard-library changes should update the public examples that teach that behavior as well as the implementation tests. ## Building from Source Use a source checkout you can access. Compiler packages are distributed through the [official release repository](https://github.com/vex-org/releases/releases); that repository is not itself a compiler source checkout. Check the source revision's build instructions before installing dependencies. ### Prerequisites | Component | Requirement for the inspected 0.4.0 source line | | --- | --- | | Rust and Cargo | Rust 2024 edition support; the release workflow selects the stable Rust toolchain. No lower minimum Rust version is declared here. | | LLVM | LLVM 23.1, matching `llvm-sys` 231 and the configured LLVM backend. | | Native toolchain | A C compiler, linker, SDK or development headers appropriate to the host and target. | | Git | Access to the checkout and its required submodules or local dependency forks. | `Cargo.toml` owns compiler dependency selection. `.github/workflows/release.yml` records the concrete release build environments. A distribution package called `llvm` may install a different major version; inspect `llvm-config --version` from the selected installation rather than assuming the package name is enough. ### Select LLVM Set `LLVM_SYS_231_PREFIX` to the LLVM 23.1 installation directory, not its `bin` subdirectory. For example, in a POSIX shell: ```bash export LLVM_SYS_231_PREFIX=/absolute/path/to/llvm-23.1 export PATH="$LLVM_SYS_231_PREFIX/bin:$PATH" llvm-config --version clang --version rustc --version cargo --version ``` The macOS release workflow uses Homebrew's `llvm@23` and the platform SDK. The Linux workflow installs versioned LLVM/Clang 23 development packages. The Windows workflow uses an identified LLVM 23.1 toolchain and the Windows native build environment. These are build recipes, not evidence that an arbitrary host or cross target has passed the release tests. ### Build the command-line tools From the checkout root: ```bash cargo build -p vex-cli --target-dir target target/debug/vex --version cargo build --release -p vex-cli --target-dir target target/release/vex --version ``` Use `.exe` on Windows. The explicit target directory keeps these paths predictable; without it the checkout currently defaults to `.vex/cargo-target` and an environment override may select another location. Keep separate build directories when working in multiple checkouts. For editor integration, build `vex-lsp` with the same toolchain. A debug profile may be configured without debug symbols in this checkout; inspect the selected Cargo profile before relying on source-level debugger information. ## Project Structure | Path | Responsibility | | --- | --- | | `crates/vex-lexer`, `vex-parser`, `vex-syntax` | Tokens, concrete syntax, and syntax-tree APIs. | | `crates/vex-hir` | Typed representation, inference, ownership, borrowing, and compile-time semantics. | | `crates/vex-sir` | Data-parallel representation, transformations, and backend lowering. | | `crates/vex-compiler` | Compilation orchestration and code generation. | | `lib/runtime/VexArch` | Runtime and prelude sources used by the compiler. | | `lib/std` | Standard-library packages and their tests. | | `tools/vex-cli` | User-facing commands and their execution paths. | | `tools/vex-pm`, `vex-doc`, `vex-lsp` | Package management, API documentation, and editor services. | | `web/documentation/docs` | Public language, library, and tooling documentation. | | `tests`, `examples`, `docs` | Integration/regression cases, examples, and internal design records. | ## Running Tests Begin with the component that owns the behavior. For example: ```bash cargo test -p vex-parser --target-dir target cargo test -p vex-hir --target-dir target test_name cargo test -p vex-compiler --target-dir target test_name -- --nocapture ``` Replace `test_name` with the relevant Rust test filter and inspect how many tests actually ran. A filtered command that selects zero tests is not a passing regression check. For Vex test files, use the compiled CLI: ```bash target/release/vex test --run '^test_add_bonus$' tests/lib_test.vx ``` This command illustrates path selection and test-name filtering; use an actual file in the checkout or the example from [Your first project](docs/guide/first-project.md). The [testing guide](docs/guide/tooling/testing.md) explains assertions, context tests, timeouts, and result reporting. Broaden testing according to the change: syntax changes affect parser and semantic users; ownership changes need accepted and rejected examples; code-generation changes need native execution; platform changes need the actual target. Consult the current repository checks rather than a fixed historical test count. ## Debugging the Compiler Keep the smallest input that preserves the behavior and record the phase that fails: analysis, object generation, linking, or program execution. ```bash target/debug/vex lint problematic.vx target/debug/vex compile --emit-llvm problematic.vx RUST_BACKTRACE=1 target/debug/vex run problematic.vx ``` The last environment-assignment form is for POSIX shells. Set the equivalent environment variable in your shell on other platforms. Backtraces describe the compiler process; they do not replace a debugger or runtime diagnostic for the compiled Vex program. ## Contribution Workflow 1. Reproduce the behavior on an identified source revision and compiler. 2. Agree on the expected language or API contract using the relevant tests and design record. Record ambiguity before changing observable behavior. 3. Keep the change focused and preserve unrelated work in the checkout. 4. Add a regression that distinguishes the old behavior from the intended one. 5. Run the affected checks and report their scope, including any untested targets or blocked commands. 6. Update the public examples and reference text affected by the change. 7. Submit a description of the problem, resulting behavior, and validation. Follow the checked-out repository's contribution and `AGENTS.md` instructions for style and workflow. A public tutorial does not override those local rules. ## Documentation The [public documentation repository](https://github.com/vex-org/documentation) contains the website and these guides. Use it for documentation changes; compiler source access is separate from this repository and the binary release repository. A complete example should say where its files go, which directory commands run from, what stdout and exit status to expect, and which inputs or failure paths it demonstrates. Mark schematic fragments before the code block and identify application-provided names. Do not label Rust or pseudocode as executable Vex. From `web/documentation`, the website provides these existing checks: ```bash bun run docs:bundle:check bun run build bun run docs:fragments:check ``` The build regenerates documentation output and checks generated local page and fragment targets. It does not establish native example behavior or external link availability. The website README lists the focused example checks; the [verification guide](docs/guide/verification-evidence.md) explains how to retain their compiler identity and results. ## Reporting a problem Include the source or a minimal reproduction, exact command, compiler version, source revision when available, operating system and architecture, and complete stdout/stderr. For a website issue, include the page URL, fragment, and the navigation path that failed. For documentation and website problems, search the [documentation issue tracker](https://github.com/vex-org/documentation/issues) before opening a report. Include the incorrect text or example, its expected behavior, and any compiler result that helped identify the discrepancy. For compiler, runtime, or library implementation problems, use the issue or feedback channel supplied with the relevant release or source access. The documentation repository is not presented as the compiler's issue tracker. --- Source: https://vex-lang.org/docs/guide/crypto.md # Crypto Namespace The `Crypto` namespace provides portable semantic cryptographic micro-helpers. The compiler selects a target instruction only when the target capability is proven; otherwise it emits the constant-flow portable lowering. > **No import needed.** `Crypto.*` is a builtin namespace available everywhere. > **These are building blocks, not full algorithms.** For complete crypto implementations (AES-256-GCM, SHA-256, ChaCha20, etc.), see the [`crypto` standard library package](docs/std/crypto/index.md). ## Fixed-block contract ```vex let state: [u8; 16] = [0; 16] let key: [u8; 16] = getRoundKey() let encrypted = Crypto.aesEncRound(state, key) ``` AES round operations currently accept exactly one `[u8;16]` state and one `[u8;16]` round key. They do not implicitly map over slices, tensors, `[u8;64]`, or nested arrays. Multi-block algorithms expose parallelism by scheduling multiple exact block operations; aggregate AES-round types require a separate semantic contract and are not inferred from storage shape. ## Quick Example This complete program computes the standard CRC-32C check value for the ASCII bytes `123456789`: ```vex [crc32c-example.vx] fn crc32c(data: &[u8; N]): u32 { let! crc: u32 = 0xffffffff; let! i: usize = 0; while i < N { crc = Crypto.crc32c(crc, data[i]); i = i + 1; } return crc ^ 0xffffffff; } fn main(): i32 { let input: [u8; 9] = [49, 50, 51, 52, 53, 54, 55, 56, 57]; if crc32c(&input) != (0xe3069283 as u32) { return 1; } $println("CRC-32C: PASS"); return 0; } ``` Expected output is `CRC-32C: PASS`, exit status 0. CRC detects accidental corruption; it is not a message-authentication code. ## AES Round Operations Single AES round instructions — the core building block of AES-128/192/256. | Function | Signature | Description | | -------------------------------- | ------------------------------ | ----------------------------------------------- | | `Crypto.aesEncRound(state, key)` | `([u8;16], [u8;16]) → [u8;16]` | SubBytes → ShiftRows → MixColumns → AddRoundKey | | `Crypto.aesDecRound(state, key)` | `([u8;16], [u8;16]) → [u8;16]` | Inverse AES round | | `Crypto.aesEncLast(state, key)` | `([u8;16], [u8;16]) → [u8;16]` | Final round (no MixColumns) | | `Crypto.aesDecLast(state, key)` | `([u8;16], [u8;16]) → [u8;16]` | Final inverse round | ### Platform Mapping | Vex Function | x86 (AES-NI) | ARM (Crypto Ext.) | | ------------- | ------------------ | --------------------------- | | `aesEncRound` | `AESENC` | `AESE` + `AESMC` | | `aesDecRound` | `AESDEC` | `AESD` + `AESIMC` | | `aesEncLast` | `AESENCLAST` | `AESE` | | `aesDecLast` | `AESDECLAST` | `AESD` | The exact lowering is target-dependent. Inspect emitted assembly and benchmark the complete construction; instruction latency alone is not an algorithm-level performance guarantee. ### Usage: AES-256 Encrypt Block This algorithm fragment assumes a correctly expanded 15-round-key schedule and an `xorBlocks` helper performing bytewise XOR. It is one block-cipher operation, not authenticated encryption or a full key schedule. Use a checked AEAD facade for application records. ```vex fn aes256EncryptHW(block: [u8;16], roundKeys: &[[u8;16]; 15]): [u8;16] { // XOR initial round key let! state = xorBlocks(block, roundKeys[0]); // Rounds 1-13 let! r = 1; while r <= 13 { state = Crypto.aesEncRound(state, roundKeys[r]); r = r + 1; } // Final round (no MixColumns) state = Crypto.aesEncLast(state, roundKeys[14]); return state; } ``` ## SHA-256 Hardware Acceleration These operations have target-independent SHA-256 semantics. The compiler selects native instructions when the exact target proves them and otherwise emits the portable fixed-flow implementation. | Function | Signature | Description | | --- | --- | --- | | `Crypto.sha256Rounds4(abcd, efgh, wk)` | `([u32;4], [u32;4], [u32;4]) → [u32;8]` | Four rounds; returns the complete `A..H` state | | `Crypto.sha256Schedule4(w0, w1, w2, w3)` | `([u32;4], [u32;4], [u32;4], [u32;4]) → [u32;4]` | Produces the next four schedule words | | `Crypto.sha256H(cdgh, abef, wk)` | `([u32;4], [u32;4], [u32;4]) → [u32;4]` | Low-level SHA-NI two-round contract | | `Crypto.sha256Msg0(msg0, msg1)` | `([u32;4], [u32;4]) → [u32;4]` | Low-level SHA256MSG1 stage | | `Crypto.sha256Msg1(msg, prev)` | `([u32;4], [u32;4]) → [u32;4]` | Low-level SHA256MSG2 stage | ### Platform Mapping | Vex Function | AArch64 with SHA2 | x86 with SHA-NI | Portable fallback | | --- | --- | --- | --- | | `sha256Rounds4` | `SHA256H` + `SHA256H2` | fixed-flow lowering | fixed-flow lowering | | `sha256Schedule4` | `SHA256SU0` + `SHA256SU1` | fixed-flow lowering | fixed-flow lowering | | `sha256H` | fixed-flow lowering | `SHA256RNDS2` | fixed-flow lowering | | `sha256Msg0` | fixed-flow lowering | `SHA256MSG1` | fixed-flow lowering | | `sha256Msg1` | fixed-flow lowering | `SHA256MSG2` | fixed-flow lowering | `crypto` uses the complete-state four-round API so the source remains identical across targets. Architecture selection is a compiler/backend responsibility. ## Carry-Less Multiply 64×64→128 bit polynomial multiplication — essential for GCM (GHASH) and CRC computations. | Function | Signature | Description | | -------------------- | ---------------------- | ---------------------------------------- | | `Crypto.clmul(a, b)` | `(u64, u64) → [u64;2]` | Carry-less multiply, result = `[lo, hi]` | ### Platform Mapping | x86 | ARM | | ------------------------ | -------------------- | | `PCLMULQDQ` | `PMULL` | The standard-library GHASH implementation uses this operation with Karatsuba multiplication, reflected register state and four-block aggregation. Targets without PCLMUL/PMULL use the portable constant-flow lowering. ```vex // 64×64 carry-less product; a complete GHASH step also needs field reduction. let result = Crypto.clmul(a, b); let lo = result[0]; // Lower 64 bits let hi = result[1]; // Upper 64 bits ``` ## CRC-32 and CRC-32C `Crypto.crc32` implements the reflected IEEE polynomial used by Gzip, while `Crypto.crc32c` implements Castagnoli CRC used by networking and storage. Both operations accept an exact unsigned chunk width, so one semantic source can consume 1, 2, 4 or 8 bytes per update without architecture-specific code. | Function | Signature | Description | | --- | --- | --- | | `Crypto.crc32(crc, chunk)` | `(u32, u8\|u16\|u32\|u64) → u32` | IEEE CRC update | | `Crypto.crc32c(crc, chunk)` | `(u32, u8\|u16\|u32\|u64) → u32` | Castagnoli CRC update | ### Platform Mapping | Operation | x86 | AArch64 | | --- | --- | --- | | IEEE CRC-32 | portable slicing fallback | `CRC32B/H/W/X` | | CRC-32C | SSE4.2 where the exact width is legal; otherwise portable | `CRC32CB/CH/CW/CX` | The compiler owns target selection and the constant table fallback. Vex source sees only polynomial and chunk-width semantics. The `compress` package builds its dependency-broken large-buffer CRC pipeline from this operation. For chunked input, preserve the running CRC state between chunks and apply the initial/final XOR exactly once for the complete message. Multi-byte chunks must represent the intended byte order; use the package's checked hash/codec APIs when you do not already own a proven raw-buffer range. The byte-at-a-time program above avoids alignment and tail-read assumptions. ## Secure Random Cryptographically secure random number generation using the operating system's CSPRNG capability. | Function | Signature | Description | | --------------------- | --------- | ------------------- | | `Crypto.secureRand()` | `→ u64` | 64-bit CSPRNG value | ### Platform Mapping | Platform | Entropy boundary | | --- | --- | | Linux | Direct `getrandom` syscall with EINTR/short-read handling; no libc dependency | | macOS | Supported libSystem `arc4random_buf` API | | Windows | `BCryptGenRandom` with the system-preferred provider | The operation fails closed if the OS cannot supply all 64 bits. It never falls back to time, PID, pointer addresses, or a predictable PRNG. > For non-cryptographic randomness (games, simulations), use [`Math.random()`](docs/guide/math.md#random-numbers) for non-security-sensitive work, or use an explicit [`rand.Rng`](docs/std/rand.md) stream when replay and distribution control matter. ```vex fn generateKey(): [u8; 32] { let! key: [u8; 32] = [0; 32]; let! wordIndex: usize = 0; while wordIndex < 4 { let word = Crypto.secureRand(); let! byteIndex: usize = 0; while byteIndex < 8 { key[wordIndex * 8 + byteIndex] = ((word >> (byteIndex * 8)) & 255 as u64) as u8; byteIndex = byteIndex + 1; } wordIndex = wordIndex + 1; } return key; } ``` This fills the array without an aligned `u64` store into byte storage. The caller still owns secure storage, distribution and destruction of the key. Nonce allocation is a separate policy; see [AEAD nonce lifecycle](docs/std/crypto/encryption.md#nonce-and-key-lifecycle). ## Hardware Support Instruction-oriented `Crypto.*` functions select a legal hardware lowering when target features prove support. Operations with a software implementation, such as CRC-32C, remain portable. `Crypto.secureRand()` uses the OS CSPRNG and does not depend on CPU `RDRAND`. | Feature | x86 | ARM | Apple Silicon | | ---------- | ----------------- | ---------------- | ------------- | | AES rounds | AES-NI (2010+) | ARMv8 Crypto | Yes M1+ | | SHA-256 complete-state helpers | portable fixed-flow path | SHA2 when enabled for the target | SHA2 when enabled for the target | | SHA-NI-style helpers | SHA-NI when enabled for the target | portable fixed-flow path | portable fixed-flow path | | CLMUL | PCLMULQDQ (2010+) | PMULL (ARMv8) | Yes M1+ | | CRC-32/32C | CRC-32C via SSE4.2; IEEE portable | CRC32 extension | Yes M1+ | | Secure RNG | OS CSPRNG | OS CSPRNG | OS CSPRNG | > Cryptographic algorithms still need portable implementations or explicit > target-feature handling where no legal hardware lowering exists. ## Next Steps - [Math Namespace](docs/guide/math.md) — Mathematical functions and constants - [Bit Namespace](docs/guide/bit.md) — Parallel bit manipulation - [Crypto Library](docs/std/crypto/index.md) — Full crypto algorithms (AES-GCM, SHA-256, etc.) --- Source: https://vex-lang.org/docs/guide/error-handling.md # Error Handling Vex represents recoverable failure and absence as values. Use the prelude `Result` when an operation can fail with a meaningful error, and `Option` when a value may simply be absent. Neither requires an import. ## Return an error the caller can inspect An error enum gives callers stable cases to match. Keep diagnostic text at the boundary that presents the failure: ```vex [division.vx] enum DivisionError { ZeroDivisor, Overflow } fn divide(left: i32, right: i32): Result { if right == 0 { return Err(DivisionError.ZeroDivisor); } if left == (-2147483647 - 1) && right == -1 { return Err(DivisionError.Overflow); } return Ok(left / right); } fn main(): i32 { match divide(20, 4) { Ok(value) => { $println(value); }, Err(DivisionError.ZeroDivisor) => { $println("cannot divide by zero"); return 1; }, Err(DivisionError.Overflow) => { $println("quotient is outside i32"); return 1; }, }; return 0; } ``` Save this as `division.vx` and run `vex run division.vx`. It prints `5` and exits with status 0. Returning the quotient from `main` would instead use it as the process exit status. Integer division truncates the fractional part; this function handles both zero division and the signed minimum divided by -1. ## Represent ordinary absence with Option ```vex [first-even.vx] fn firstEven(left: i32, right: i32): Option { if left % 2 == 0 { return Some(left); } if right % 2 == 0 { return Some(right); } return None; } fn main(): i32 { match firstEven(3, 8) { Some(value) => { $println(value); }, None => { $println("no even value"); }, }; return 0; } ``` This complete example prints `8` and exits 0. `None` is a typed absence, not an integer sentinel or a null raw pointer. See the [Option API](docs/guide/types/option-api.md) for borrowing, mapping, and extraction. ## Propagate failure with `?` `?` extracts a success payload or returns the unsuccessful branch from the current function. The enclosing return type must support that propagation. For example, using `divide` and `DivisionError` from above: ```vex fn calculate(): Result { let first = divide(20, 4)?; let second = divide(first, 2)?; return Ok(second + 1); } ``` The successful result is `Ok(3)`. If either division fails, the following statements are skipped and its error is returned. `?` does not print an error, terminate the process, or provide a fallback. Keep the error type the same or convert it explicitly before propagation; see [Result](docs/guide/types/result-api.md) for `mapErr` and conversion guidance. Option-returning functions can likewise propagate absence: ```vex fn incrementEven(left: i32, right: i32): Option { let value = firstEven(left, right)?; return Some(value + 1); } ``` ## Choose fallback or early return deliberately A `match` makes fallback evaluation and early return explicit: ```vex fn requirePresent(value: Option): Result { let inner = match value { Some(inner) => inner, None => return Err("missing value"), }; return Ok(inner + 1); } ``` The prelude also provides `??` and `!>` operators. Follow the operand and callback signatures on the [Option](docs/guide/types/option-api.md) and [Result](docs/guide/types/result-api.md) pages. `??` supplies a fallback value; `!>` invokes a handler for the unsuccessful branch. Do not assume an ordinary fallback expression is lazy. An `!>` handler supplies a replacement success payload. Its `return` exits the **handler closure**, not the enclosing function. For example, `missing !> || { return 7; }` produces `7` for an absent `Option`. A handler containing only `return;` returns unit and cannot initialize an `i32`. Use an outer `match` when failure must return from the caller. ## Ownership is part of error handling Matching or mapping a value can transfer its payload. Do not assume an owned `Result` remains usable after a consuming helper call. Check whether a method receives `self` by value or by reference. The API pages spell out those receiver contracts; `Copy` examples alone do not establish how an owning payload behaves. The prelude does not provide `unwrap` or `expect` on these types. When an invariant violation should stop execution, use an explicit panic branch. Handle expected user input and I/O failures as values. Error propagation still follows normal scope cleanup for owned values. ## Null pointers belong at foreign boundaries Use typed pointer constructors and `isNull()` at an FFI boundary. The following is a declaration sketch, not a complete allocation wrapper: ```text extern "LIBC" { fn malloc(size: usize): Ptr } let pointer = malloc(64) if pointer.isNull() { return 1 } ``` A non-null result does not establish alignment, initialization, ownership, or how to free it. Keep those obligations together in a small wrapper and return an `Option` or `Result` to ordinary application code. See [FFI](docs/guide/ffi.md) and [Raw Pointers](docs/guide/types/raw-pointers.md). ## Choosing a representation | Situation | Prefer | | --- | --- | | Success or a meaningful failure | `Result` | | An ordinary missing value | `Option` | | Return a compatible failure from the caller | `?` | | Distinct recovery for different errors | `match` | | Supply a default success value | `??` or an explicit `match` | | A raw null pointer crosses a foreign ABI | `Ptr.isNull()` at the boundary | Handle an error where the program can make a useful decision. Lower layers should preserve enough information for that decision; the outer application can select an exit status, report the problem, or retry under a bounded policy. ## Next steps - [Enums](docs/guide/types/enums.md) - [Pattern Matching](docs/guide/types/pattern-matching.md) - [Option API](docs/guide/types/option-api.md) - [Result API](docs/guide/types/result-api.md) ## Ownership in practice - [Ownership workflows](docs/guide/memory/ownership-workflows.md) — complete borrowed-parser and owned-report examples --- Source: https://vex-lang.org/docs/guide/examples.md # Learn Vex through examples Choose a task, then follow the linked program and the API contracts around it. The examples cover data modeling, resource ownership, concurrent work, compile-time programming, numerical code and application libraries. Complete programs identify their filename, run command and expected behavior. Library fragments show a component to embed in a larger application; keep the surrounding imports, owners and error handling when adapting them. ## Start with a small application | Task | What you practice | Example | | --- | --- | --- | | Build a two-file library and its tests | Exported interfaces, imports, immutable/mutable values and test discovery | [Your first project](docs/guide/first-project.md) | | Calculate a credit with rejected inputs | A domain contract, typed failures and positive/negative tests | [Testing and benchmarking](docs/guide/tooling/testing.md) | | Return either a value or a useful error | Result, match, early return and exit status | [Introduction](docs/guide/introduction.md#explicit-failure-values), [error handling](docs/guide/error-handling.md) | | Build a command-line interface | Commands, flags, arguments and help text | [CLI library](docs/std/cli.md) | | Read structured configuration | Owning parsed values, lookup and conversion errors | [JSON](docs/std/serde/json.md), [TOML](docs/std/serde/toml.md), [YAML](docs/std/serde/yaml.md) | ## Make ownership visible | Task | What you practice | Example | | --- | --- | --- | | Validate a packet and return a borrowed payload | Bounded views, error paths and keeping the owner alive | [Ownership workflows](docs/guide/memory/ownership-workflows.md) | | Build an independently owned report | Borrowed input, transformation and owned return values | [Ownership workflows](docs/guide/memory/ownership-workflows.md) | | Call a small C function | A native header/provider, ABI selection and one cleanup owner | [Your first native call](docs/guide/ffi-first-native.md) | | Work with file contents or mapped regions | I/O errors, resource cleanup, bytes and filesystem paths | [Files](docs/std/fs/file.md), [filesystem API](docs/std/fs/reference.md) | | Protect and authenticate a message | Key and nonce lifecycle, byte lengths and authentication failure | [Encryption](docs/std/crypto/encryption.md) | ## Coordinate independent work | Task | What you practice | Example | | --- | --- | --- | | Collect a batch containing successes and failures | Async jobs, tagged replies, Result and bounded channels | [Fallible task results](docs/guide/concurrency/batch-results.md) | | Merge producers and shut down cleanly | Fan-in, completion counts, channel ownership and cancellation | [Fan-in](docs/guide/concurrency/fan-in.md) | | Serve HTTP requests | Request/response ownership, routes, middleware and body limits | [Fiber service](docs/std/http/fiber.md), [middleware](docs/std/http/middleware.md) | | Store and query application state | Connection/statement lifetimes, parameter binding and transaction scope | [Database connections](docs/std/db/connection.md), [ORM](docs/std/db/orm.md) | ## Move work into the compiler | Task | What you practice | Example | | --- | --- | --- | | Calculate a bounded retry schedule | Const functions, strict compile-time values and overflow checks | [Compile-time recipes](docs/guide/advanced/comptime-recipes.md) | | Process fields selected by their exact type | Typed reflection and statically checked field access | [Compile-time recipes](docs/guide/advanced/comptime-recipes.md) | | Generate repeated declarations from a typed description | DeclSet, generated methods/types and semantic checking | [Structural generation](docs/guide/advanced/comptime-declarations.md) | | Share serialization metadata across models | Named policies, field tags, overrides and reflection | [Policies](docs/guide/types/policies.md) | ## Work with numbers, images and protocols | Task | What you practice | Example | | --- | --- | --- | | Calibrate a batch of sensor values | Multiple graph inputs, elementwise arithmetic, masks and reduction | [Graph functions](docs/guide/gpu/graph-functions.md) | | Differentiate a numerical expression | Primal computation, forward-mode derivatives and sensitivities | [Autograd](docs/guide/advanced/autograd.md) | | Process a tile and its boundary | Shape/index arithmetic and a scalar reference | [Fusion and tiled work](docs/guide/fusion/graph.md) | | Measure a geographic journey or region | Coordinate order, units, distance and containment | [Geographic coordinates](docs/std/geo.md) | | Transform an image in memory | Pixel layout, owning images and deterministic transforms | [Image processing](docs/std/vips.md) | | Create PCM and describe it with a WAV header | Sample layout, buffer sizes and container metadata | [Media components](docs/std/media.md) | | Inspect and reconstruct an RTP packet | Checked parsing, network byte order and packet bounds | [Real-time protocols](docs/std/webrtc.md) | | Model a FIFO | Capacity, occupancy, simultaneous operations and parameter widths | [Hardware examples](docs/hdl/design-examples.md) | The hardware example belongs to the companion VexHDL project. GPU execution, native libraries and network peers each introduce their own environment; follow the linked page's setup and ownership contract. ## Build a language tool The [language-tooling guide](docs/guide/tooling/language-tools.md) includes complete tokenizer and width-sensitive layout programs, a lossless syntax-tree fragment, and a map of the ten IDE library families. Extend those building blocks with grammar rules, source-labelled diagnostics, query metadata or editor messages. When a compiler change needs a regression, use [compiler testing tools](docs/references/compiler-testing-tools.md) to retain and replay generated cases. Application benchmarks and compiler-phase benchmarks measure different workloads; keep their inputs and results separate. ## Adapt an example without losing its contract Change one dimension at a time: input size, error case, ownership boundary, concurrency or target. Keep an expected result for each change. For a parser, include empty/truncated input; for a pipeline, include shutdown; for a numerical operation, compare to a reference with an explicit tolerance. The [capability map](docs/guide/language-status.md) shows the broader language surface. The [verification guide](docs/guide/verification-evidence.md) explains how to retain the command, compiler identity and result for your adaptation. --- Source: https://vex-lang.org/docs/guide/faq.md # Frequently Asked Questions ## General ### What is Vex? Vex is a systems programming language with explicit ownership, borrowing, native compilation, and language-level concurrency. This documentation targets 0.4.0. Specialist pages explain the available SIMD, GPU, FFI, and library surfaces and the boundaries that matter when using them. ### Is Vex ready for production? Evaluate the 0.4.0 release against the features and deployment targets your application needs. Experimental backends and partially implemented library APIs do not become fully supported merely because the compiler has a release version. Use the release notes, [language status](docs/guide/language-status.md), and package-specific guides to identify the supported path; then run your application's integration and failure-path tests on its deployment targets. ### What platforms does Vex support? macOS ARM64 is the primary development platform for this checkout. Other targets are experimental until their compiler, runtime, linker, and native-library paths have been validated together. See [Platform Support](docs/guide/platform-support.md). ### What license is Vex under? The inspected compiler workspace metadata declares `MIT OR Apache-2.0`. Consult the license text distributed with the exact compiler, library, or tool you use; bundled dependencies and HDL Studio can carry separate terms. Workspace metadata alone does not identify every redistributed component's license. ## Language design ### Why does Vex use `let!`? `let` creates an immutable binding. `let!` makes local mutation explicit. Mutable references use the corresponding `!` form. This convention makes mutation visible in code and diagnostics. ### Does Vex have a garbage collector? Vex's core model is ownership and borrowing rather than a tracing garbage collector. Heap abstractions and runtime-managed values are still subject to the implementation status of the selected library and target. ### How are errors represented? Use enum-shaped `Option` and `Result` values, pattern matching, and the supported propagation operators. See [Enums](docs/guide/types/enums.md) and [Error Handling](docs/guide/error-handling.md). ## Compilation ### What is the difference between `vex lint`, `vex run`, and `vex compile`? `vex lint` performs correctness analysis and configured semantic lints without requiring a final executable. `vex run` builds a temporary executable and launches it. `vex compile` produces a persistent artifact. Runtime compilation and linking can fail even when source analysis succeeds. ### Can I cross-compile? The compiler exposes target-related options, but cross-compilation is not automatically a supported runtime configuration. Validate the target's runtime, linker, native dependencies, and standard library before relying on it. ### Why should I use `vex lint` during development? It gives fast feedback about syntax, types, ownership, and borrowing without requiring the full runtime and native-linking path. Use `vex run` only after checking the target-specific execution path. ## Memory and safety ### What are `Box`, `Ptr`, and raw pointers? - `Box` is an owning heap abstraction. - `Ptr` is a typed pointer abstraction for lower-level operations. - Raw pointers are unsafe boundary tools for FFI and specialized systems code. Ownership and borrowing still apply around all three. Keep raw operations inside small, tested boundaries. ### What should I do when the borrow checker rejects code? Reduce the lifetime of the borrow, make the ownership transfer explicit, or restructure the operation so mutable and immutable access do not overlap. Do not bypass the checker until the boundary and safety invariant are documented. ## Concurrency ### Are `go`, channels, `async`, and `await` stable? They are implemented language surfaces, but runtime behavior is experimental and platform-dependent. Channels and detached work also require an explicit shutdown and ownership design. See [Concurrency Overview](docs/guide/concurrency/overview.md) and [Channels](docs/guide/concurrency/channels.md). ### Can a channel deadlock? Yes. Capacity, send/receive ordering, task shutdown, and ownership transfers all matter. Start with a small checked example and test the runtime behavior on the target platform. ## Tooling and libraries ### Does Vex have a package manager? The repository contains package-management commands and documentation, but the package surface is still partial. Verify the exact command and manifest fields with `vex --help` and the [package manager reference](docs/references/vex-pm-reference.md). ### Can I call C libraries from Vex? FFI syntax exists, but ABI, linking, ownership, and platform support must be checked for the selected provider and target. Start with the [FFI guide](docs/guide/ffi.md). ### Where should I report an internal compiler error? Record the source, compiler version, repository revision, platform, command, and full diagnostic in the repository issue tracker. If the problem is already reproduced locally, link the relevant compiler issue report from the documentation. ## Getting help - Read the [installation guide](docs/guide/installation.md) and [language status](docs/guide/language-status.md). - Use `vex --help` and `vex --help` for the binary you actually built. - Include the exact compiler version and platform in bug reports. --- Source: https://vex-lang.org/docs/guide/ffi-deep-dive.md # FFI — Deep Dive This page covers ABI, symbol export, callbacks, and ownership across a foreign boundary. See the shorter [FFI guide](docs/guide/ffi.md) for basic imports. ## Scalar type mapping Use fixed-width types whenever the foreign ABI permits it. | Vex | C | | --- | --- | | `i8`, `u8` | `int8_t`, `uint8_t` | | `i16`, `u16` | `int16_t`, `uint16_t` | | `i32`, `u32` | `int32_t`, `uint32_t` | | `i64`, `u64` | `int64_t`, `uint64_t` | | `f32`, `f64` | `float`, `double` | | `bool` | `_Bool` / `bool` when ABI-compatible | | `char` | 32-bit Vex Unicode scalar; map explicitly, usually to `uint32_t` | | `Ptr` | `void*` | | `Ptr`, `Ptr` | `const T*`, `T*` by capability contract | | `()` return | `void` | Pointer width depends on the target. Use `usize` only for C `size_t`-like parameters and verify the target ABI. ## Importing foreign functions Place these declarations in a `.vxc` boundary module. The fragments below show individual ABI and ownership decisions; the [first native bridge](docs/guide/ffi-first-native.md) provides a complete buildable project. ```vex extern "LIBC" { fn malloc(size: usize): Ptr fn free(memory: Ptr) fn memcpy(dst: Ptr, src: Ptr, size: usize): Ptr } ``` Extern calls are unsafe by default: ```vex let memory = unsafe { malloc(128) } if !memory.isNull() { unsafe { free(memory) } } ``` The provider belongs to the extern block. `LIBC` identifies the owner; it is not a generic spelling for every function that happens to use the C calling convention. Use `SYSTEM from "library"` for an OS library and `NATIVE from "feature"` for a package-owned artifact. ## Exporting a C ABI symbol The stable spelling for a defined, unmangled C ABI export is `export "C" fn`: ```vex export "C" fn vexAdd(a: i32, b: i32): i32 { return a + b } ``` ```c extern int32_t vexAdd(int32_t a, int32_t b); ``` This scalar example performs no pointer access. For a pointer-taking export, a null/length check cannot prove that foreign memory is live, aligned or accessible; state those caller obligations in the exported ABI contract. Rust-style `#[no_mangle]` is not Vex syntax and is not needed. The export ABI spelling controls the unmangled wrapper symbol. ## Aggregate layout Do not assume that a normal Vex struct or enum automatically matches a C aggregate. For a stable boundary: 1. prefer scalar parameters and opaque handles; 2. use fixed-width fields; 3. verify size, alignment, and offsets with compile-time assertions; 4. test the layout from both languages for every supported target. The following checks deliberately describe one 64-bit layout expectation; they should fail on an incompatible target rather than silently change the ABI. Matching these two checks alone does not prove an entire foreign struct contract. ```vex struct CHeader { version: u32, flags: u32, payload: Ptr, } #Diag.staticAssert(#Type.sizeOf() == 16, "CHeader size mismatch") #Diag.staticAssert(#Type.offsetOf("payload") == 8, "payload offset mismatch") ``` Attribute spellings such as `#[repr(C)]` are not part of the stable Vex source surface. If the verified native layout is insufficient, use explicit serialization or an opaque C-owned object. ## Callbacks A native Vex callable carries a code pointer and an environment/context pointer in the current implementation. A C library may expect a single raw function pointer with a different calling convention; writing `fn(...)` in a declaration does not by itself establish that boundary. A top-level Vex function has no local captures, but that alone does not prove C ABI compatibility. For a callback API, establish the exact foreign signature and use an adapter whose generated entry point and call path have been verified for the target. If the foreign API supplies a separate context pointer, its owner must keep it valid until callbacks can no longer occur, and account for callback threads, reentrancy and deregistration. A context pointer is necessary for carrying state in such APIs but is not by itself proof that a Vex closure can be passed directly. Never discard a captured environment by casting a callable to a raw pointer. Keep the adapter's calling convention and context lifetime explicit in the foreign API contract. ## Allocation ownership Allocator identity must cross the boundary with the pointer contract. ```vex extern "NATIVE" from "foreign_objects" { fn foreignCreate(): Ptr fn foreignDestroy(value: Ptr) } let foreign = unsafe { foreignCreate() } if !foreign.isNull() { // Use the live foreign object before destroying it. unsafe { foreignDestroy(foreign) } } let size = 256 as usize let vexMemory = Mem.alloc(size) // Foreign code may borrow vexMemory, but Vex retains ownership. unsafe { Mem.free(vexMemory, size) } ``` If ownership is transferred, export a matching destroy function instead of asking the other language to guess the allocator: ```vex // Foreign caller contract: the exact live pointer and allocation size returned // by the matching Vex allocation API, passed once after all borrowers finish. export "C" fn vexBufferDestroy(memory: Ptr, size: usize) { unsafe { Mem.free(memory, size) } } ``` ## Linking Native libraries are selected by the feature named in `extern "NATIVE" from "..."`. The owning `vex.json` maps that feature to target-specific `static`, `dynamic`, or `bitcode` artifacts. Only features reached by codegen contribute link arguments or runtime files. On freestanding targets, activated `LIBC` uses are rejected before linking. With `--no-runtime`, an activated `VEX` symbol must have a local VexArch implementation; Vex reports `E0FFI36` instead of deferring the problem to an undefined-symbol linker error. If an activated static native artifact still leaves known libc/TLS symbols undefined, Vex reports that exact active feature instead of silently producing a hosted binary. ## Safety checklist 1. Match ABI, scalar width, pointer mutability, and variadic signatures exactly. 2. Treat every extern call and returned pointer as unsafe until validated. 3. Define nullability, ownership, allocator, lifetime, and thread rules. 4. Keep exported wrappers thin; convert to safe Vex types immediately inside. 5. Verify aggregate layout on every target, or use opaque handles. 6. Test both success and failure paths with sanitizers where available. ## Related - [FFI](docs/guide/ffi.md) - [Raw Pointers](docs/guide/types/raw-pointers.md) - [Memory Prelude](docs/guide/memory/mem-prelude.md) - [Freestanding](docs/guide/freestanding.md) - [Native Module Linking](docs/guide/advanced/vxm-native-module-linking.md) --- Source: https://vex-lang.org/docs/guide/ffi-first-native.md # First native bridge This example calls a small C library through a `.vxc` boundary, then exercises success and two failure paths. It has two Vex files, a C source file and a manifest. It uses `cc` and an object file built for the same target as the Vex program. The example makes allocation ownership and cleanup visible at the foreign boundary. Create an empty directory and put all four files in it. This teaching fixture uses global unsynchronized counters: call it only from one thread, with no concurrent bridge operations. The `unsafe` boundary reflects that requirement. The numeric `-1` and `-2` values are fixture statuses, not universal C errors. ## C implementation The handle is either null or an allocated, initialized byte. `bridge_read` requires a live, non-null handle returned by `bridge_open`; reading after `bridge_close`, passing another pointer, or closing twice violates its contract. ```c [bridge.c] #include #include static int32_t opened = 0; static int32_t closed = 0; void bridge_reset(void) { opened = 0; closed = 0; } void *bridge_open(int32_t fail) { if (fail) return NULL; uint8_t *p = malloc(1); if (!p) return NULL; *p = 42; opened++; return p; } int32_t bridge_read(const void *p) { return *(const uint8_t *)p; } void bridge_close(void *p) { if (p) { closed++; free(p); } } int32_t bridge_opened(void) { return opened; } int32_t bridge_closed(void) { return closed; } ``` ## Native feature manifest `all` selects the local object in this teaching fixture. Build the object for the actual target; the manifest does not make one object portable. ```json [vex.json] {"name":"ffi-demo","version":"0.1.0","main":"main.vx","native":{"features":{"bridge":{"all":{"path":"bridge.o","type":"static"}}}}} ``` ## Vex boundary The boundary owns the handle during `runCase`: null exits before any read or close; after a successful open, each branch calls `bridge_close` exactly once. No raw handle escapes to the caller. The counter functions are unsafe because the C fixture uses unsynchronized global state. ```vex [native.vxc] extern "NATIVE" from "bridge" { fn bridge_reset(); fn bridge_open(fail: i32): Ptr; fn bridge_read(handle: Ptr): i32; fn bridge_close(handle: Ptr); fn bridge_opened(): i32; fn bridge_closed(): i32; } export unsafe fn runCase(failOpen: bool, failAfterOpen: bool): i32 { unsafe { bridge_reset(); } let handle = unsafe { bridge_open(if failOpen { 1 } else { 0 }) }; if handle == Ptr.nullMut() { return -1; } if failAfterOpen { unsafe { bridge_close(handle); } return -2; } let value = unsafe { bridge_read(handle as Ptr) }; unsafe { bridge_close(handle); } return value; } export unsafe fn opened(): i32 { return unsafe { bridge_opened() }; } export unsafe fn closed(): i32 { return unsafe { bridge_closed() }; } ``` ## Vex caller The caller obeys the single-threaded fixture contract. Each group of three lines reports the case result, successful opens, and closes. ```vex [main.vx] import { runCase, opened, closed } from "./native.vxc"; fn main(): i32 { $println(unsafe { runCase(false, false) }); $println(unsafe { opened() }); $println(unsafe { closed() }); $println(unsafe { runCase(false, true) }); $println(unsafe { opened() }); $println(unsafe { closed() }); $println(unsafe { runCase(true, false) }); $println(unsafe { opened() }); $println(unsafe { closed() }); return 0; } ``` ## Build and run From the directory containing these files, using a C compiler for the same host target as Vex: ```bash cc -std=c11 -c bridge.c -o bridge.o vex lint main.vx vex run main.vx ``` Expected stdout: ```text 42 1 1 -2 1 1 -1 0 0 ``` The successful read and the simulated error after opening each have one open and one close. The simulated open failure has neither. These counters cover only this fixture and these paths; they are not a proof of behavior under allocation failure, asynchronous cancellation, concurrent calls, or a different foreign library. Production wrappers must define those contracts explicitly. See [Native FFI pipeline](docs/references/vex-pm-native-ffi.md) for artifact selection and [FFI](docs/guide/ffi.md) for provider and pointer rules. --- Source: https://vex-lang.org/docs/guide/ffi.md # Foreign Function Interface (FFI) Vex makes the owner of every imported symbol explicit. Import declarations use one of four providers; the old all-in-one `extern "C"` import syntax is not supported. | Provider | Use it for | |---|---| | `LIBC` | The target C runtime | | `SYSTEM from "library"` | An operating-system library or framework | | `NATIVE from "feature"` | A package-owned native artifact selected by `vex.json` | | `VEX` | The private compiler/runtime ABI | An extern declaration has no link or deployment cost by itself. Vex activates its provider only when reachable code calls the function or takes its address. ## Boundary modules Put user-package extern declarations in a `.vxc` boundary module. A wrapper accepting an arbitrary raw pointer must expose its own safety contract: ```vex [native.vxc] // native.vxc extern "LIBC" { fn strlen(value: Ptr): usize; } // Caller must supply a non-null, readable NUL-terminated byte sequence. export unsafe fn byteLength(value: Ptr): usize { return unsafe { strlen(value) }; } ``` ```vex [text.vx] // text.vx import { byteLength } from "./native.vxc"; fn main(): i32 { let bytes: [u8; 4] = [86, 101, 120, 0]; let count = unsafe { byteLength(&bytes[0] as Ptr) }; $println(count); // 3 return 0; } ``` Extern blocks in ordinary user `.vx` files are rejected. Compiler-owned prelude, standard-library, and runtime modules have a private exception for their internal boundaries. The caller must keep the bytes readable for the call, include a terminator within that readable allocation, and obey the foreign function's platform contract. `unsafe` does not check those preconditions. For a complete native ownership and cleanup example, see [First native bridge](docs/guide/ffi-first-native.md). ## Calling libc Use `LIBC` only for symbols owned by the target C runtime: ```vex extern "LIBC" { fn memcpy(destination: Ptr, source: Ptr, size: usize): Ptr; fn free(memory: Ptr); } ``` `LIBC` does not accept a `from` clause. A reachable libc call is rejected in a freestanding build; an unused declaration does not create a libc dependency. ## Calling operating-system libraries Use `SYSTEM` for an OS-owned dylib, DLL, or framework: ```vex // native.windows.vxc extern "SYSTEM" from "kernel32" { fn GetLastError(): u32; } ``` ```vex // native.macos.vxc extern "SYSTEM" from "framework:Metal" { fn MTLCreateSystemDefaultDevice(): Ptr; } ``` The library name is required. Duplicate requests are deduplicated in a deterministic link plan. ## Calling package-native code Use `NATIVE` for a package feature whose artifact differs by target: ```vex extern "NATIVE" from "codec" { fn codec_decode(input: Ptr, length: usize): i32; } ``` The nearest owning `vex.json` selects static, dynamic, or bitcode artifacts: ```json { "name": "image-codec", "version": "0.1.0", "native": { "features": { "codec": { "x86_64-unknown-linux-gnu": { "path": "native/libcodec.a", "type": "static" }, "aarch64-apple-darwin": { "path": "native/libcodec.dylib", "type": "dynamic" }, "x86_64-pc-windows-msvc": { "path": "native/codec.dll", "type": "dynamic", "importLib": "native/codec.lib" } } } } } ``` Only a feature reached by codegen is resolved, staged, and linked. Prefer exact target triples when ABI environments differ. Fallback selectors are matched after the exact triple; a broad `linux` or `all` entry does not make an artifact compatible with both GNU and musl targets. ## The private Vex runtime provider `extern "VEX"` is reserved for compiler-owned prelude, standard-library, and VexArch modules. Application code uses the public prelude API instead of calling raw `vex_*` symbols. `VEX` is not an implicit runtime injection. With `--no-runtime`, an activated symbol must be implemented locally by VexArch; otherwise compilation stops with `E0FFI36` before the linker is invoked. ## Exporting Vex to C Import providers and exports are separate concepts. `export "C" fn` remains the stable spelling for an unmangled C-ABI definition: ```vex export "C" fn pluginInit(api: Ptr): i32 { return 0; } ``` ```c extern int32_t pluginInit(void *api); ``` ## Pointer and scalar mapping | Vex | Typical C mapping | |---|---| | `i32`, `u32` | `int32_t`, `uint32_t` | | `i64`, `u64` | `int64_t`, `uint64_t` | | `usize` | `size_t` | | `Ptr` | `void *` | | `Ptr` | borrowed/read-only `const T *` contract | | `Ptr` | writable-pointee `T *` contract | Always match the target ABI exactly. C `long`, `wchar_t`, handles, and structure layout vary by platform. ## Unsafe calls and safe wrappers Foreign code is outside Vex's safety guarantees: ```vex let result = unsafe { codec_decode(dataPtr, dataLength) }; ``` A public wrapper should validate nullability, lengths, ownership, thread rules, and errors before translating the result into normal Vex types. ## Target-aware bindings Both `.vx` and `.vxc` imports support target suffixes. Resolution prefers the most specific available file: ```text native...vxc native..vxc native..vxc native.vxc ``` Use file routing to select the OS/architecture binding or API implementation and manifest routing to select the exact target binary artifact. Source routing does not guess an ABI environment such as `gnu`, `musl`, or `msvc`. ## Removed import spellings These legacy forms are errors: ```vex extern "C" { ... } extern "static" from "foo" { ... } extern "dylib" from "foo" { ... } ``` Choose the symbol owner instead: `LIBC`, `SYSTEM`, `VEX`, or `NATIVE`. ## Related - [FFI Deep Dive](docs/guide/ffi-deep-dive.md) - [Freestanding](docs/guide/freestanding.md) - [Platform Support](docs/guide/platform-support.md) - [vex-pm Native FFI](docs/references/vex-pm-native-ffi.md) --- Source: https://vex-lang.org/docs/guide/first-project.md # Your first project Create a small project, move a function into a second source file, and test it. This guide is part of the Vex 0.4.0 documentation. Check the version of the compiler you actually run; the [evidence guide](docs/guide/verification-evidence.md) identifies the compiler used to check these examples. ## Before you start Install or build the CLI using the [installation guide](docs/guide/installation.md). Put the **directory containing** the `vex` executable on your `PATH`. For example, in a POSIX shell, replace the path below with your real directory: ```bash export PATH="/absolute/path/to/vex-directory:$PATH" command -v vex vex --version ``` If `command -v` prints nothing, fix the path first. If the executable fails to start because of a missing shared library, follow the installation guide's troubleshooting section before continuing. ## Create the project From a directory where `greetings` does not already exist: ```bash vex new greetings cd greetings ``` All remaining commands in this guide run **from inside `greetings/`**. The scaffold creates `vex.json`, `src/lib.vx`, and `tests/lib_test.vx`. ## Try a mutation error Temporarily replace `src/lib.vx` with this program: ```vex [try-immutable.vx] fn main(): i32 { let score = 32; score = score + 10; return 0; } ``` Run `vex lint src/lib.vx`. The compiler rejects the assignment because `let` creates an immutable binding; its diagnostic suggests `let!` for a mutable one. Changing the declaration to `let! score = 32;` permits reassignment. See [Variables](docs/guide/basics/variables.md) for the distinction. ## Split the program into two files Create `src/score.vx`: ```vex [src/score.vx] export fn add_bonus(score: i32): i32 { return score + 10; } ``` Replace `src/lib.vx` with: ```vex [src/lib.vx] import { add_bonus } from "./score.vx"; fn main(): i32 { $println(add_bonus(32)); return 0; } ``` The relative import is resolved from the importing file. `export` makes `add_bonus` available to another module. Without it, lint reports that the requested symbol is not exported. The [modules guide](docs/guide/modules.md) covers other import and export forms. Check and run the program: ```bash vex lint src/lib.vx vex run src/lib.vx ``` The program's stdout is: ```text 42 ``` Lint checks the program; `run` also builds, links and starts it. Native build or runtime diagnostics can appear separately from stdout. ## Add a test Replace the generated `tests/lib_test.vx` with: ```vex [tests/lib_test.vx] import { add_bonus } from "../src/score.vx"; fn test_add_bonus(): bool { return add_bonus(32) == 42; } ``` The resulting tree is: ```text greetings/ ├── vex.json ├── src/ │ ├── lib.vx │ └── score.vx └── tests/ └── lib_test.vx ``` Run the test directory, or select a file and a test name separately: ```bash vex test tests/ vex test --run test_add_bonus tests/lib_test.vx ``` Both commands should report one passing `test_add_bonus` test. A file path selects where tests are discovered; `--run` filters test names within that selection. If the name filter selects nothing, the current runner reports no test functions and can exit successfully: inspect the reported test count, not just the process exit code. See [Testing](docs/guide/tooling/testing.md) for discovery, glob, and selection rules. ## What you have built The manifest identifies the project, `score.vx` exposes a small reusable API, `lib.vx` chooses how to present its result, and the test checks the API without depending on console output. Keep that separation as the program grows: business logic belongs in importable functions, while the entry point handles arguments, output, and process exit status. The example uses small `i32` values. A real score API should define its allowed range and overflow behavior before accepting untrusted values. Add tests at those boundaries and for each failure path; one successful arithmetic case does not define the application's complete contract. Continue with [Modules](docs/guide/modules.md), [Error handling](docs/guide/error-handling.md), and [Testing](docs/guide/tooling/testing.md). --- Source: https://vex-lang.org/docs/guide/freestanding.md # Freestanding and No-Runtime Builds Vex can compile without an implicit libc/CRT edge and can omit VexArch runtime memory-management and scheduling hooks. Freestanding mode is selected by `--no-runtime` or by `native.useSystemLibC: false` in the owning `vex.json`. It is not a source-level `no_std`, `no_main`, or global-allocator directive. ```bash vex compile --no-runtime --target x86_64-unknown-none kernel.vx ``` Target and linker support still determine whether the final artifact is truly bare-metal. `--no-runtime` removes the normal Vex runtime edge; it does not magically supply an entry point, linker script, platform services, allocator, panic transport, or device I/O. ## What changes No-runtime mode: - does not link the normal VexArch memory/scheduler runtime; - does not install the hosted `main` runtime setup path; - disables runtime ownership strategies that require shared reference counting; - makes runtime-only async/scheduler symbols unavailable; - requires every referenced platform/allocator symbol to be supplied by the program, target support layer, or link inputs. Language primitives, compile-time intrinsics, stack values, raw pointers, and inline assembly remain available. Standard-library modules that depend on OS or VexArch services are not freestanding merely because they type-check. ## Entry point Export the symbol expected by the target ABI: ```vex export "C" fn _start(): never { // Initialize hardware and platform state. loop {} } ``` The exact name and signature are target-specific. UEFI, an ELF kernel, a microcontroller image, and a hosted process do not share one universal entry contract. ## Memory Stack/static code needs no allocator: ```vex let! buffer: [u8; 4096] = [0; 4096] let! counter: u32 = 0 ``` Heap-using code must supply the allocation ABI required by the generated program. VexArch itself provides freestanding implementations of compiler- required memory routines when building the runtime artifacts; an independent no-runtime target must provide an equivalent target layer or avoid those paths. Do not call host `malloc/free` merely to satisfy the linker. That turns a supposedly freestanding artifact back into a hosted libc-dependent program. ## Panic and termination Code that can panic needs a target-appropriate termination/reporting path. A minimal bare target may halt: ```vex fn halt(): never { loop {} } ``` Production firmware or kernels usually provide architecture-specific panic logging before halting. Do not assume stderr, process exit, unwinding, or a filesystem exists. In normal runtime builds, compiler-generated fail-fast paths call the VexArch `vex_sys_abort` ABI. VexArch selects the native target implementation (for example direct Linux system calls, Windows system services, or Apple's system ABI); the compiler does not inject a hidden libc `abort` dependency. A `--no-runtime` target that can reach such a path must provide `vex_sys_abort` itself or prove the path unreachable. ## Hardware access Memory-mapped I/O requires a target-specific access contract: register address, access width, alignment, byte order, device memory mapping and any required ordering barriers. An ordinary store through `Ptr` does not express a volatile device access. `unsafe` assigns responsibility for those preconditions; it does not add volatility or a hardware barrier. Use a board or platform abstraction that defines the required volatile reads and writes. For registers with write-one-to-clear bits, read-modify-write may be incorrect even when each individual access is volatile. Verify the device manual's operation, not only the pointer type. `Mem.secureZero` is a memory clearing API and is not a general MMIO interface. Use `asm!` when the target operation requires it, with accurate operands and clobbers as described in [Assembly](docs/guide/advanced/assembly.md). Inspect the final optimized code and validate the access on the selected device or emulator. ## Link validation Extern providers remain explicit: | Provider | Freestanding behavior | |---|---| | `LIBC` | A reachable call is rejected before linking | | `SYSTEM from "library"` | Allowed when the target OS provides that ABI | | `NATIVE from "feature"` | Allowed when the selected artifact is freestanding-compatible | | `VEX` | Available only through the selected compiler/runtime configuration | Freestanding does not mean “no system dylib or DLL.” An OS may define its stable ABI through `libSystem`, `kernel32`, or another system library without making the program libc-hosted. The forbidden behavior is a hidden, unavoidable libc/CRT dependency. WASM rejects dynamic native artifacts. Other targets may use dynamic `SYSTEM` or `NATIVE` providers when the target supports them. Native-link diagnostics identify known libc and TLS dependencies from the exact activated static feature; unused manifest entries cannot affect the result. Treat these as architecture errors to remove, not symbols to paper over with compatibility stubs. When using clang, freestanding linking passes `-nostdlib`. The Linux direct-LLD path likewise omits automatic CRT objects, dynamic-loader selection, libc, libm, and libgcc inputs. The program must supply its own entry and required target support. ## Verification checklist 1. Compile with `--no-runtime` for the exact target triple. 2. Provide the correct entry symbol and linker script/format. 3. Inspect undefined symbols; no accidental libc, TLS, or Vex scheduler edge should remain. 4. Verify compiler-required memory operations are supplied by freestanding code. 5. Test the produced artifact on the real target or an accurate emulator. 6. Keep target-specific services beneath portable Vex ownership and container APIs. ## Related - [Assembly](docs/guide/advanced/assembly.md) - [FFI Deep Dive](docs/guide/ffi-deep-dive.md) - [Memory Prelude](docs/guide/memory/mem-prelude.md) - [Platform Support](docs/guide/platform-support.md) - [Unsafe](docs/guide/advanced/unsafe.md) --- Source: https://vex-lang.org/docs/guide/fusion/graph.md # Graph Functions A `graph fn` describes a computation the compiler can lower to a Silicon IR (SIR) graph. Depending on the supported operations, compiler build, and runtime environment, it may optimize that graph and select an execution path. Neither GPU execution nor fusion is guaranteed by the keyword. ## Quick Start Save this complete example as `graph-add.vx`: ```vex [graph-add.vx] graph fn add(a: [i32; 4], b: [i32; 4]): [i32; 4] { return a + b; } fn main(): i32 { let x: [i32; 4] = [1, 2, 3, 4]; let y: [i32; 4] = [5, 6, 7, 8]; let result = add(x, y); $println(result[0]); $println(result[1]); $println(result[2]); $println(result[3]); return 0; } ``` ```sh VEX_NO_GPU=1 vex run graph-add.vx ``` Expected standard output: ```text 6 8 10 12 ``` `VEX_NO_GPU=1` requests CPU-only routing for this run. The source expresses four independent additions; the chosen scalar or vector implementation is a compiler decision. Inspect the generated plan when the execution route matters. ## Calibrating a batch A sensor batch often needs more than one arithmetic operation. This graph subtracts a baseline and applies a per-lane gain. The caller then summarizes those calibrated values with an ordinary reduction and threshold mask: ```vex [graph-calibration.vx] graph fn calibrate(raw: [i32; 4], baseline: [i32; 4], gain: [i32; 4]): [i32; 4] { return (raw - baseline) * gain; } fn main(): i32 { let raw: [i32; 4] = [12, 13, 14, 15]; let baseline: [i32; 4] = [10, 10, 10, 10]; let gain: [i32; 4] = [10, 10, 10, 10]; let calibrated = calibrate(raw, baseline, gain); let total = <+ calibrated; let high = calibrated > 35; $println(calibrated[0]); $println(calibrated[3]); $println(total); $println(high.countBits()); if calibrated[0] != 20 || calibrated[3] != 50 || total != 140 || high.countBits() != 2 { return 1; } return 0; } ``` Run `VEX_NO_GPU=1 vex run graph-calibration.vx`. Expected output: ```text 20 50 140 2 ``` The four calibrated lanes are `[20, 30, 40, 50]`. Their total is `140`, and two lanes exceed `35`. The fixed array types require the raw values, baselines, and gains to have matching extents. A per-lane gain allows different sensor calibration coefficients without changing the graph structure. The graph returns application data; the caller decides how to classify and report it. Keeping that boundary explicit also gives a straightforward reference calculation: lane `i` should equal `(raw[i] - baseline[i]) * gain[i]`. Use values whose intermediate results fit the selected integer type. For floating-point calibration, specify acceptable error and rounding behavior. The expression exposes subtraction and multiplication together to SIR, which can optimize supported combinations. It does not promise a specific number of instructions, allocations, or launches. For a small fixed batch, compare the ordinary array expression with the graph form before choosing a performance strategy. ## Why Graph Functions? A graph gives the optimizer an opportunity to analyze operations together. Compatible operations may be fused to avoid intermediate work, but the number of loops, allocations, or kernel launches depends on the actual lowering and chosen backend. Measure the compiled program rather than assuming a speedup. ## Supported Operations Graph operations preserve their element types and shapes. A computation can be planned only when its operations have a compatible lowering and backend. Keep allocation, I/O, reporting, and application control flow outside the graph unless their graph semantics are explicitly supported. This creates a useful boundary between a numerical transformation and the code that consumes it. ## Nested Graph Functions Calls and cross-function optimization depend on the compiler's current lowering support. Check your actual program rather than assuming every graph call is inlined or fused. ## Hardware Dispatch SIR has dispatch policies for different execution paths. Backend availability and support for a particular graph affect the plan; input size alone does not guarantee a particular GPU or SIMD route. `VEX_NO_GPU=1` requests CPU-only routing; selecting a GPU-capable host alone does not determine how a particular graph executes. ## Analytical Fusion & DAG Compilation Pipeline ### The Lowering Flow For supported graph bodies, the compiler lowers operations into an SIR graph, applies available optimization passes, and plans a backend. A map followed by a reduction is a possible fusion candidate, not a promise that a given expression will lower or fuse. ### The `FusedKernel` Structure SIR represents some fused operations with a `FusedKernel` containing inputs and an operation chain. Backend support determines whether and how that representation can be emitted. See the [SIR pipeline](docs/guide/simd/sir-pipeline.md) for more context. ## Inline Fusion vs Graph Functions An expression and a graph function give the compiler different scopes to analyze. Both remain subject to the lowering and backend support of the operations involved. ## Debug For a development build, `VEX_FUSION_DEBUG=1 vex run graph-add.vx` can print graph and plan diagnostics. These diagnostics describe the observed build and run, and are not a stable API. The examples above use `VEX_NO_GPU=1` for CPU-only routing. For a conceptual tiled matrix multiplication and the distinction between a graph and a manual GPU kernel, see [Graph Functions and GPU Execution](docs/guide/gpu/graph-functions.md). --- Source: https://vex-lang.org/docs/guide/glossary.md # Glossary Key terms and concepts in the Vex ecosystem. ## A **AOT (Ahead-of-Time)** -- Compilation mode that produces a standalone native binary before execution. Vex is AOT-only. **Async Function** -- Function declared with `async fn` that can suspend at `await` points. Compiled to a state machine coroutine. **Autograd** -- Automatic differentiation system for computing gradients of tensor operations, used in machine learning. ## B **Borrowing** -- Creating a reference (`&T` or `&T!`) to a value without taking ownership. Governed by the borrow checker's NLL (Non-Lexical Lifetime) analysis. **Box\** — A handle that owns a heap payload through Vex's memory model. Sharing, mutation, and taking the payload have distinct rules; see [Box](docs/guide/memory/box.md). **Builtin** -- A compiler-provided operation or prelude item available without imports. `#Type.sizeOf()` is compile-time, while `$println(value)` has runtime semantics. ## C **Channel\** -- Multi-producer, multi-consumer bounded channel for communication between concurrent tasks. Use `ch <- val` to send and `<-ch` to receive. **Closure** -- Anonymous function that can capture variables from its enclosing scope. Syntax: `|params| expression`. **Comptime** -- Compile-time code execution. Functions and expressions evaluated at build time rather than runtime. **Contract** -- A trait-like interface defining shared behavior. Types implement contracts to gain capabilities. Syntax: `contract Name { method(); }`. **Copy Type** — A type whose values may be duplicated under the language's copy rules rather than transferring an exclusive ownership obligation. Copying a view does not copy or extend the lifetime of its backing storage. ## D **Defer** — A statement that schedules an action for scope exit. Use it to keep cleanup near resource acquisition; see [Error handling](docs/guide/error-handling.md). **Drop** — The cleanup contract used when an owned value is destroyed. Moving a value transfers the cleanup obligation rather than duplicating it. **DynMask** -- Compiler name for the runtime-sized source `Mask`. Its current packed host storage includes an owner; GPU transport is separate. See the [representation table](docs/guide/simd/simd-simt-contract.md#dynamic-mask-representation-in-the-development-implementation). **DynTensor** — An implementation term for runtime-sized tensor storage. The source-level form is `Tensor`; use the [tensor guide](docs/guide/simd/dynamic-tensors.md) for constructors, ownership, and indexing. ## E **Enum** -- Sum type (tagged union) that can hold one of several variants. Each variant can carry payload data. Syntax: `enum Option { Some(T), None }`. **Expression-Oriented** -- Most language constructs (if, match, loop, blocks) are expressions that return values, not just statements. ## F **FFI (Foreign Function Interface)** -- Mechanism for calling native functions from Vex and exporting Vex functions through a stable ABI. Imports use explicit `LIBC`, `SYSTEM`, `NATIVE`, or private `VEX` providers; outbound C ABI definitions use `export "C" fn`. **Freestanding** -- Build policy with no implicit libc/CRT dependency. It is selected with `--no-runtime` or `native.useSystemLibC: false`, not a `#![no_std]` attribute. **Fusion (SIR Fusion)** — Combining compatible operations into a shared execution plan or kernel to reduce intermediate work. Whether fusion occurs depends on dependencies and backend support. ## G **go Block** — A block scheduled as concurrent work, for example `go { ... }`. Design completion, cancellation, and captured-value lifetimes explicitly; see [Concurrency](docs/guide/concurrency/overview.md). **graph fn** — A function whose supported operations are represented through the graph/SIR pipeline. Execution backend and dispatch are governed by the [graph-function model](docs/guide/gpu/graph-functions.md), not by the keyword alone. ## H **HIR (High-Level IR)** -- The intermediate representation after parsing and type checking, before lowering to SIR or LLVM IR. **Horizontal Reduction** -- Collapsing a tensor/array to a scalar using an associative operation. Syntax: `<+ arr` (sum), `<* arr` (product), `?| arr` (max). ## I **Iterator** -- Contract for types that yield a sequence of values. Powers `for` loops. Method: `next(): Option`. ## L **LLVM** — The backend infrastructure used for native code generation. Its required version belongs to the selected compiler build; see [Installation](docs/guide/installation.md). **Lifetime** -- The span of execution during which a reference is valid. Vex uses NLL (Non-Lexical Lifetime) analysis to verify borrow safety. **LTO (Link-Time Optimization)** — Optimization that retains intermediate representation across the link boundary. Full LTO and ThinLTO have different compilation costs; measure the selected toolchain rather than assuming one always produces faster code. ## M **M:N Scheduler** -- User-space scheduler that multiplexes M coroutines onto N OS threads. Uses work-stealing for load balancing. **Mask\** -- Compile-time-sized SIMD boolean vector resulting from tensor comparisons. Supports bitwise operations and reduction queries. **Move Semantics** -- For non-Copy types, assignment transfers ownership. The source becomes inaccessible after a move. ## N **never** -- The bottom type with no possible values. Return type of diverging expressions such as `$panic` and infinite `loop`. Coerces to any type. **NLL (Non-Lexical Lifetimes)** -- The borrow checker algorithm that computes liveness based on actual usage rather than lexical scope boundaries. ## O **Operator Overloading** -- Defining custom behavior for operators (`+`, `==`, `[]`, etc.) by implementing the corresponding contract (`Add`, `Eq`, `Index`). **Option\** -- Type representing a value that may be absent. Variants: `Some(T)` or `None`. Safe alternative to null pointers. **OrderedMap\** -- Hash map that preserves insertion order. Combines O(1) lookup with predictable iteration. **Ownership** — The rules determining who is responsible for a value's lifetime and cleanup, when that responsibility moves, and what access a borrow permits. Shared handles and non-owning views must obey their own contracts. ## P **Pin** — A prelude marker contract that restricts moves which could invalidate self-references. It is not a `Pin` wrapper. Pinning does not by itself establish a valid lifetime or exclusive access; see [Pin](docs/guide/memory/pin.md). **Prelude** -- Set of types and functions always available without explicit import. Includes `Option`, `Result`, `Vec`, `Box`, `Ptr`, `Span`, `string`, etc. **Ptr\** — A typed pointer to storage. The element type alone does not establish validity, initialization, alignment, lifetime, or exclusivity; see [Typed pointers](docs/guide/memory/ptr-t.md). **Opaque pointer** — A pointer used without an exposed payload type, commonly `Ptr` at an interoperability boundary. Historical raw-pointer spellings are described in [Raw pointers](docs/guide/types/raw-pointers.md). ## R **Range** — A sequence or selection described by bounds. `0..10` excludes the upper bound and `0..=10` includes it. Omitted endpoints are context-dependent; see [Ranges](docs/guide/types/range.md). **RawBuf** — A byte-addressed view used for explicit typed loads and stores. It does not own storage or prove that a byte range is valid; see [RawBuf](docs/guide/memory/rawbuf.md). **Result\** -- Type representing either success (`Ok(T)`) or failure (`Err(E)`). Primary error handling mechanism with `?` operator for propagation and `!>` rescue operator for fallback values. **Rescue Operator (`!>`)** -- Infix operator that extracts a value from `Option` or `Result`, providing a fallback on `None`/`Err`. Syntax: `val !> fallback` or `val !> || { computeFallback() }`. The development prelude does not declare an `.unwrap()` method. ## S **SIMD (Single Instruction, Multiple Data)** — Machine operations that process several data lanes together. Vex exposes data-parallel intent through array/tensor operations; actual instruction selection depends on the target and optimization path. **SIR (Silicon IR)** — Vex's representation for data-parallel operations and their transformations. Backend support and operation coverage are described in [SIR and backends](docs/architecture/sir-and-backends.md). **Span\** — A non-owning view of contiguous elements. Bounds-checked access does not prove that the backing storage is alive or was constructed correctly; see [Span](docs/guide/memory/span-t.md). **str (VexStr)** — A borrowed string view. Its lifetime is tied to the storage it views; copying the view does not make an owned string. **string (VexString)** — An owned string abstraction. Encoding, indexing, and conversion behavior are described in [Strings](docs/guide/types/strings.md); do not infer a portable ABI from a particular host layout. **Struct** -- Composite data type with named fields. Can implement contracts, have methods, and define constructors. ## T **Tensor\** — A statically sized tensor form; `Tensor` has a runtime size. Shape and elementwise intent are separate from physical register placement; see [SIMD and tensors](docs/guide/simd/index.md). **Threadgroup Memory** — Storage shared by invocations in a GPU workgroup. Its capacity, synchronization rules, and use depend on the backend and kernel model. ## U **Unit Type (`()`)** -- Zero-size type with exactly one value: `()`. Default return type for functions without a meaningful return value. Not the same as C's `void`. **unsafe** — A boundary where the programmer must establish the preconditions of operations that the compiler cannot prove. It does not disable all checking or make invalid memory access correct. ## V **Vec\** — A growable, owning sequence of elements. Growth and mutation can affect borrowed views; see [Vec](docs/guide/types/vec.md). **VUMM** — The compiler/runtime memory model connecting ownership, sharing, and storage management. Representation choices do not remove application obligations around aliasing, mutation, synchronization, or borrowed lifetimes; see [VUMM](docs/guide/memory/vumm.md). ## W **Work-Stealing** -- Scheduling algorithm where idle worker threads "steal" tasks from busy workers' queues. Provides automatic load balancing for the M:N scheduler. --- Source: https://vex-lang.org/docs/guide/gpu/graph-functions.md # Graph Functions and GPU Execution A `graph fn` describes a computation graph candidate; it does not by itself define a manually launched GPU kernel or guarantee GPU execution. The compiler may lower a supported graph through SIR and choose an available path. See the [tested graph example](docs/guide/fusion/graph.md#quick-start). The thread coordinates, shared memory, and barriers below explain a **general GPU algorithm**. Vex expresses the computation through graph and tensor operations; these conceptual coordinates are not source-level launch syntax. Use the [calibration example](docs/guide/fusion/graph.md#calibrating-a-batch) to see a complete Vex graph surrounded by ordinary application code. ## Thread Hierarchy For a conceptual two-dimensional workgroup of side `T`, local coordinates `lx` and `ly` range from `0` to `T - 1`, while `bx` and `by` identify the workgroup. An output element is at `row = by * T + ly`, `col = bx * T + lx`. If an API instead supplies a *global* coordinate, use it directly: adding the workgroup offset again double-counts it. ## Shared Memory / Threadgroup Memory A tiled matrix multiplication can reuse two workgroup-local tiles. For matrices A with shape M×K and B with shape K×N, an implementation must: 1. Load each A and B tile with bounds checks on **both** dimensions, using zero for out-of-range elements, including the final partial K tile. 2. Synchronize every workgroup lane after loading and before computing, and again before overwriting the tiles for the next iteration. 3. Keep edge lanes participating in both barriers, even when their output row or column is out of range. Only the final C write is conditional on `row < M` and `col < N`. The following complete Python program models those stages sequentially. Its two stages model the data dependencies of the barriers; they do **not** exercise GPU synchronization, Vex kernel syntax, a GPU compiler, or a device. It checks the tiled result against an independent triple-loop reference, including multiple workgroups and dimensions that are not multiples of 16. ```python [tiled-reference.py] def tiled(a, b, m, n, k, tile=16): out = [[0 for _ in range(n)] for _ in range(m)] for by in range((m + tile - 1) // tile): for bx in range((n + tile - 1) // tile): sums = [[0 for _ in range(tile)] for _ in range(tile)] for base in range(0, k, tile): # All lanes finish these loads before any lane computes. a_tile = [[ a[by * tile + ly][base + lx] if by * tile + ly < m and base + lx < k else 0 for lx in range(tile)] for ly in range(tile)] b_tile = [[ b[base + ly][bx * tile + lx] if base + ly < k and bx * tile + lx < n else 0 for lx in range(tile)] for ly in range(tile)] for ly in range(tile): for lx in range(tile): for inner in range(tile): sums[ly][lx] += a_tile[ly][inner] * b_tile[inner][lx] # All lanes finish computing before either tile is replaced. for ly in range(tile): for lx in range(tile): row, col = by * tile + ly, bx * tile + lx if row < m and col < n: out[row][col] = sums[ly][lx] return out def reference(a, b, m, n, k): return [[sum(a[row][inner] * b[inner][col] for inner in range(k)) for col in range(n)] for row in range(m)] for m, n, k in [(1, 1, 1), (16, 16, 16), (17, 19, 23), (32, 17, 1), (33, 35, 37), (3, 5, 0)]: a = [[(row * 3 + inner) % 7 - 3 for inner in range(k)] for row in range(m)] b = [[(inner * 5 + col) % 11 - 5 for col in range(n)] for inner in range(k)] assert tiled(a, b, m, n, k) == reference(a, b, m, n, k) print(f"OK {m}x{n}x{k}") ``` Save it as `tiled-reference.py` and run `python3 tiled-reference.py`. Integer inputs allow exact comparison here; floating-point GPU results may require an appropriate tolerance and separate numerical validation. ## Graph Function Restrictions Graph lowering supports a subset of Vex, and restrictions depend on the compiler version and target. Do not assume that an arbitrary function, FFI call, or asynchronous body can be lowered as a graph. A graph function can return a value, as the [array addition example](docs/guide/fusion/graph.md#quick-start) demonstrates. ## SIR Pipeline for Graph Functions Supported graph bodies can be lowered from HIR to SIR and planned for an available backend. A backend's presence in the source tree does not establish that every operation or device is supported. Consult the [SIR pipeline](docs/guide/simd/sir-pipeline.md) and [backend reference](docs/architecture/sir-backends-reference.md), then validate the exact target. ## Best Practices Start with a verified graph example, check the compiler's diagnostics and the actual execution path, and compare output with a reference on your target. Measure performance only after correctness is established; tile sizes and memory behavior are device- and implementation-dependent. ## Related Pages - [GPU Overview](docs/guide/gpu/index.md) - [Fusion Graph](docs/guide/fusion/graph.md) - [SIR Pipeline](docs/guide/simd/sir-pipeline.md) - [SIR Backends Reference](docs/architecture/sir-backends-reference.md) --- Source: https://vex-lang.org/docs/guide/gpu/index.md # GPU and Compute with SIR Silicon IR (SIR) is Vex's graph representation for data-parallel computation. It separates the computation from backend generation and execution. Start with an algorithm whose shape, element type and expected results are clear, then validate the chosen device path. ## Graph-Based Compute Model A `graph fn` is a computation candidate. It is not a manually launched kernel, and it does not guarantee that a GPU will be selected. The complete [graph addition example](docs/guide/fusion/graph.md#quick-start) shows the source, command and expected output for a small CPU-only starting point. A multiply followed by a reduction can be represented as a map/reduce graph, but lowering depends on the exact source types and supported operations. In particular, converting a borrowed `Span` to an owning `Tensor` needs an owned materialization; do not hide that conversion in a performance example. See [Tensor ownership](docs/guide/simd/tensor-mask.md). ## Metal GPU Backend Architecture ### Types and Precision Metal generation emits MSL for supported SIR graphs. Metal has no native `f64` lane type: development generator paths can narrow some operations to `float`, while other operations reject the type. Select a supported dtype and compare results against a reference using an explicit tolerance. For floating-point workloads, include cancellation, NaN, infinity and signed zero when they matter to the application. Reduction order can change rounding because floating-point addition is not associative. A successful compile or a matching result on one input does not establish equivalence across backends. ### Reduction and Buffer Planning Some fused reductions use separate reduction and map passes with temporary scalar buffers. The number of passes, workgroup dimensions and buffer binding indices belong to the generated kernel and runtime descriptor. They are not fixed user-facing ABI rules. Do not hard-code internal buffer slots from an architecture diagram into a foreign integration. ### Shared Memory Unified physical memory can reduce transfer costs on Apple Silicon. It does not prove that a particular call is zero-copy: allocation, buffer wrapping, resource lifetime and synchronization still have costs. Measure the actual application boundary, including both cold and warm execution. ## Runtime Deferred Dispatch Runtime-sized work can use shape and cost information to choose among available routes. Selection requires more than an element-count threshold: - the graph's operations and dtypes must be supported; - the build must contain a compatible generator and call bridge; - the runtime must provide an executor and device; - the input and output layouts must match the execution descriptor. A cost-model estimate is not a speedup guarantee. Threshold constants are implementation details and may differ between dispatch paths. Neither clamping a length nor applying `noinline` makes an invalid or dangling span safe; callers must satisfy the memory contract before dispatch. ## Target Architectures and Backend Pipelines | Path | What to establish | | --- | --- | | CPU scalar / SIMD | Supported lowering, target features and a correct reference result. | | Metal | MSL support plus the native Metal runtime/device boundary. | | CUDA | PTX support plus the CUDA runtime/device boundary. | | ROCm | Compatible compiled HSACO; generated HIP text alone is insufficient. | | SPIR-V / WebGPU | Matching adapter capabilities, shader format and runtime bridge. | | CoreML and other inference paths | Supported model operations, conversion and actual runtime placement. | The [backend reference](docs/architecture/sir-backends-reference.md) distinguishes generation from execution. Operating-system names alone do not identify a working route, and a native WebGPU path is not evidence of browser deployment. ## Runtime Controls The development compiler recognizes presence-based routing switches: ```sh # Request CPU-only routing while compiling and running this program. VEX_NO_GPU=1 vex run graph-add.vx # Development diagnostic: request GPU consideration where supported. VEX_FORCE_GPU=1 vex run graph-add.vx ``` Unset these variables to restore default behavior; setting them to `0` is not equivalent to unsetting them in the inspected implementation. A force flag cannot install an absent executor or make unsupported operations valid. `VEX_GPU_BACKEND` is route-specific. The SIR policy recognizes values including `metal`, `cuda`, `rocm`, `spirv` and `wgsl`; the native compiler bridge separately recognizes `auto`, `metal` and `wgpu`/`webgpu`. Do not assume a value is a stable end-to-end backend selector. Retain the selected-route diagnostics when testing an override. `VEX_FUSION_DEBUG=1` can expose graph/plan diagnostics in development builds; their text is not a stable API. ## A Reliable Validation Sequence 1. Save the full input and expected output for a small reference case. 2. Test the same algorithm with the requested production dtype and shapes. 3. Include empty inputs and sizes around vector, tile and workgroup boundaries. 4. Record backend, device, compiler hash and relevant configuration. 5. Compare integer outputs exactly; define floating-point tolerances from the algorithm's requirements before measuring speed. 6. Measure device execution separately from allocation, transfer and cold shader/model compilation. ## Next Steps - [Graph Functions](docs/guide/fusion/graph.md) - [Graph Functions and GPU Execution](docs/guide/gpu/graph-functions.md) - [SIMD/SIMT Contract](docs/guide/simd/simd-simt-contract.md) - [Tensor and Mask Types](docs/guide/simd/tensor-mask.md) - [Verification Evidence](docs/guide/verification-evidence.md) --- Source: https://vex-lang.org/docs/guide/installation.md # Installation This guide targets Vex 0.4.0. Install the compiler package for your operating system and CPU architecture, then check the executable before creating a project. A release candidate such as `0.4.0-rc.39` is a different artifact from the final `0.4.0` package; see [Versioning](docs/guide/versioning.md). ## Install a compiler package 1. Open the [download page](https://www.vex-lang.org/download) or the [official release list](https://github.com/vex-org/releases/releases). 2. Select a **Vex compiler** release and the archive matching your machine. Vex HDL Studio is a separate application and does not replace the compiler package used in this guide. 3. Download the archive and its matching checksum file when provided. Compare the archive's SHA-256 with that file before extracting it. 4. Keep the extracted package together, including its bundled libraries and tools. Add the directory containing the `vex` executable to `PATH` using your shell's configuration. 5. Start a new shell and run: ```bash vex --version vex --help ``` The version should match the package you selected. If an older version appears, check which executable your shell resolves (`command -v vex` in a POSIX shell, or `Get-Command vex` in PowerShell). If no matching archive is listed, use a supported release target or the source-build route below; do not substitute an archive for a different CPU architecture. On macOS or Linux, a checksum file in the usual `SHA256 filename` format can be checked from the download directory with `shasum -a 256 -c filename.sha256` or `sha256sum -c filename.sha256`, respectively. Replace `filename.sha256` with the actual downloaded name. In PowerShell, use `Get-FileHash -Algorithm SHA256` on the archive and compare the result with the published digest. Continue with [Your first project](docs/guide/first-project.md) once the compiler starts successfully. The remaining build instructions are for contributors and users with access to a source checkout. ## Requirements for a source build To build the compiler from a checkout, you need: - a Rust toolchain with Cargo that supports the checkout's Rust 2024 edition; - the LLVM 23.1 toolchain selected by this checkout's `llvm-sys` 231 bindings, including the corresponding development libraries; - a native linker for your operating system; - Git to obtain the repository. The workspace manifest and release workflow define the dependency versions for a particular source revision. The current LLVM binding uses `LLVM_SYS_231_PREFIX` to locate an installed LLVM toolchain. Do not mix an LLVM 16, 21, or 22 installation with bindings configured for LLVM 23.1. See [Contributing](docs/guide/contributing.md) for the build environment and focused checks. ## Build from source This route requires an accessible source checkout and its dependencies. The previously listed repository URL is not confirmed to be publicly accessible; obtain access to the checkout from the project maintainer before using the commands below. From the checkout root: ~~~bash cargo build --release -p vex-cli --target-dir target ~~~ The explicit `--target-dir target` places the release binary at `target/release/vex` (`vex.exe` on Windows). Without this option, the checkout configuration currently uses `.vex/cargo-target`; `CARGO_TARGET_DIR` can also change the location. Confirm the build before using it: ~~~bash target/release/vex --version target/release/vex --help ~~~ For a faster edit-check cycle, use the debug build instead: ~~~bash cargo build -p vex-cli --target-dir target target/debug/vex lint examples/01_basics/hello_world.vx ~~~ ## Run a first program Create hello.vx: ~~~vex [hello.vx] fn main(): i32 { $println("Hello, Vex!"); return 0; } ~~~ Then check and run it: ~~~bash vex lint hello.vx vex run hello.vx ~~~ These commands assume the selected executable is on `PATH`; source-build users can use `target/release/vex` instead. The program prints `Hello, Vex!` and exits with status 0. Use `lint` while writing code: it performs correctness and configured lint analysis without creating a final executable. Use `run` to build a temporary executable and launch it. > **warning Native execution is a separate gate** `vex lint` does not emit an object, link, or execute the program. `vex run` uses the fused embedded VexArch image plus the requested target's native support and system ABI, so validate that path on the exact deployment target. ## Command-line tools The compiler currently exposes these high-level commands: | Command | Purpose | | --- | --- | | `vex lint [target]` | Run correctness analysis, semantic lints and verified fixes without code generation. | | `vex run ` | Compile and run a source file. | | `vex compile ` | Compile and link a persistent artifact. | | vex build | Build a Vex package or project. | | vex test | Discover and run Vex tests. | | vex format | Format Vex source. | | vex doc | Generate API documentation from Vex source. | | vex view | Inspect compiler representations and analyses. | | vex new / vex init | Create or initialize a project. | | vex mod / vex workspace | Manage module and workspace workflows. | | vex env / vex setup | Inspect or initialize the Vex environment. | Run `vex --help` for the options supported by the binary you built. The [CLI reference](docs/references/vex-cli-reference.md) describes the command surface in more detail. ## Project layout The current `vex new my-project` scaffold creates this layout: ~~~text my-project/ ├── vex.json ├── src/ │ └── lib.vx └── tests/ └── lib_test.vx ~~~ From the project directory, the scaffold's starter source can be selected with `vex run src/lib.vx`; `vex test` discovers the test file. The [first-project guide](docs/guide/first-project.md) develops and tests that scaffold with a second module. For manifest details, start with the [package manager reference](docs/references/vex-pm-reference.md). ## Editor support The repository includes an LSP implementation and a VS Code extension under editors/vscode. Build the LSP server with: ~~~bash cargo build --release -p vex-lsp --target-dir target ~~~ The resulting binary is target/release/vex-lsp. Configure your editor to start it for .vx files. LSP capabilities and editor integration are evolving alongside the compiler, so treat advanced refactoring features as experimental. ## Troubleshooting ### LLVM or Clang is not found Install the development packages for your operating system and ensure the compiler can find them through the environment used by Cargo. On macOS, the Xcode Command Line Tools are usually required. On Linux, install the distribution's LLVM, Clang, and development packages. ### The binary fails before printing its version A missing dynamic library can prevent a compiler binary from starting. Record the loader's missing library name and the binary's origin, then use a matching release/toolchain or rebuild from an accessible source checkout. This failure occurs before Vex can check your program. ### The compiler accepts a file but linking fails `lint` and `compile` exercise different parts of the toolchain. A successful lint run establishes that the source passed the selected analysis; it does not establish that target linking or native dependencies are available. Retain the full compiler output and the target triple when reporting the failure. ### An example does not match your checkout Check the compiler version first: ~~~bash target/release/vex --version git rev-parse --short HEAD ~~~ The documentation site follows the repository's current development line. Pin both the compiler revision and the documentation revision in CI when reproducibility matters. ## Next steps - [Introduction](docs/guide/introduction.md) - [Your first project](docs/guide/first-project.md) - [Language Status](docs/guide/language-status.md) - [Syntax](docs/guide/basics/syntax.md) - [Testing](docs/guide/tooling/testing.md) - [CLI Reference](docs/references/vex-cli-reference.md) --- Source: https://vex-lang.org/docs/guide/introduction.md # Introduction Vex is a systems programming language built around explicit memory ownership, concurrent execution, and data-parallel computation. This guide introduces the 0.4.0 programming model through complete programs and links to the more detailed language and library references. ## The basic idea Vex keeps ordinary systems code readable while making the important costs visible: - bindings are immutable unless mutation is written explicitly with let!; - values are moved or borrowed according to ownership rules; - go blocks, channels, async, and await are part of the language surface; - arrays and tensor-shaped operations can be lowered through Silicon IR (SIR); - FFI, typed pointers, spans, and raw buffers provide controlled low-level escape hatches. These parts are not equally mature. Core syntax, data types, ownership, and the checker have the strongest coverage. Concurrency, SIR, GPU backends, FFI, and platform-specific tooling are documented as experimental where their behavior is still being developed. See the [Language Status](docs/guide/language-status.md) page before choosing a feature for production work. ## A complete first program Create hello.vx: ~~~vex [hello.vx] fn main(): i32 { let language = "Vex"; $println("Hello from ", language); return 0; } ~~~ With the selected compiler on `PATH`, check and run it from the directory containing `hello.vx`: ~~~text vex lint hello.vx vex run hello.vx ~~~ The program prints `Hello from Vex` and exits with status 0. The compiler reports syntax and semantic errors before producing a program. The [installation guide](docs/guide/installation.md) covers compiler packages, source builds, and selecting the executable. ## A small data model Structs hold related fields. Methods are declared outside the struct with a receiver: ~~~vex [point.vx] struct Point { public: x: i32, y: i32, } fn (point: &Point) coordinate_sum(): i32 { return point.x + point.y; } fn main(): i32 { let positive = Point { x: 3, y: 4 }; let negative = Point { x: -3, y: 1 }; let origin = Point { x: 0, y: 0 }; $println(positive.coordinate_sum()); $println(negative.coordinate_sum()); $println(origin.coordinate_sum()); return 0; } ~~~ This prints `7`, `-2`, and `0` on separate lines and exits 0. `coordinate_sum` adds signed coordinates; it is not a distance function. `&Point` is an immutable borrow. A mutable receiver is written `&Point!`; mutation also requires the value at the call site to be held in a mutable binding. The complete rules are in [Ownership](docs/guide/memory/ownership.md) and [Borrowing](docs/guide/memory/borrowing.md). ## Explicit failure values Vex uses `Result` for recoverable failure. This example divides nonnegative quantities into a positive number of groups and propagates an invalid-input error with `?`: ~~~vex fn divide(left: i32, right: i32): Result { if left < 0 || right <= 0 { return Err(1); } return Ok(left / right); } fn calculate(): Result { let first = divide(20, 4)?; return Ok(first + 1); } fn main(): i32 { return match calculate() { Ok(value) => { $println(value); 0 }, Err(code) => code, }; } ~~~ This program prints `6` and exits 0. Replacing `divide(20, 4)` with `divide(20, 0)` propagates `Err(1)` and exits 1 without printing a successful value. Integer division truncates any remainder; this is a small integer example, not a decimal calculator. `Option` models an absent value. See [Enums](docs/guide/types/enums.md), [Option](docs/guide/types/option-api.md), [Result](docs/guide/types/result-api.md), and [Error Handling](docs/guide/error-handling.md). ## What makes Vex different ### Mutation is visible `let` is immutable. Use `let!` when a local must change: ~~~vex fn main(): i32 { let! total = 0; total += 2; total += 3; $println(total); return 0; } ~~~ The program prints `5` and exits 0. The numeric result is program output; `main`'s return value is the process status. Explicit mutation makes the places that can change state visible in the source. ### Concurrency is explicit A `go` block schedules work, while a channel provides a typed communication path: ~~~vex fn main(): i32 { let! channel: Channel = Channel(1); go { channel.send(42); }; let value = <-channel; $println(value); return 0; } ~~~ The channel connects the producer's value to the receiver. Capacity, input ownership and shutdown determine how a larger program coordinates its tasks. Continue with [Concurrency Overview](docs/guide/concurrency/overview.md), [Channels](docs/guide/concurrency/channels.md) and a [batch of fallible jobs](docs/guide/concurrency/batch-results.md). ### Data parallelism has a compiler path Vex includes operations intended to describe work over arrays and tensors. The SIR pipeline can lower eligible operations to target-specific code, but no source program should assume that every operation will be vectorized or that every GPU backend supports the same set of features. Read [SIMD](docs/guide/simd/index.md) and [GPU & SIR](docs/guide/gpu/index.md) together with the status notes on those pages. ## A practical learning path 1. [Install the compiler](docs/guide/installation.md). 2. Learn [syntax](docs/guide/basics/syntax.md), [variables](docs/guide/basics/variables.md), [functions](docs/guide/basics/functions.md), and [control flow](docs/guide/basics/control-flow.md). 3. Build data models with [primitive types](docs/guide/types/primitives.md), [structs](docs/guide/types/structs.md), [enums](docs/guide/types/enums.md), and [pattern matching](docs/guide/types/pattern-matching.md). 4. Learn the memory model through [ownership](docs/guide/memory/ownership.md), [borrowing](docs/guide/memory/borrowing.md), and [lifetimes](docs/guide/memory/lifetimes.md). 5. Add recoverable failure with [error handling](docs/guide/error-handling.md). 6. Explore [modules](docs/guide/modules.md), [testing](docs/guide/tooling/testing.md), and the [standard library](docs/guide/stdlib.md). 7. Combine those foundations with [async](docs/guide/concurrency/async.md), [SIR](docs/guide/simd/sir-pipeline.md), [GPU programming](docs/guide/gpu/index.md), [compile-time generation](docs/guide/advanced/comptime-recipes.md) or [FFI](docs/guide/ffi.md). 8. Use the [capability map](docs/guide/language-status.md) and [example collection](docs/guide/examples.md) to choose a practical next project. ## Source of truth The language guide describes the intended user-facing model. The compiler tests and checked examples determine what the current toolchain accepts. Design notes under the repository's docs/ directory can describe future work and should not be treated as stable syntax unless the corresponding guide page says that the feature is implemented. When reporting an example, include its page, exact command, source and compiler version through the [contribution guide](docs/guide/contributing.md#reporting-a-problem). --- Source: https://vex-lang.org/docs/guide/language-status.md # Vex capability map Vex combines application programming, explicit resource ownership, concurrency, compile-time programming and data-parallel computation. This map connects each part of the language to a guide, reference or complete example. Start with the [example collection](docs/guide/examples.md) when you prefer to learn through a task. ## Language and data modeling | Capability | What you can express | Read next | | --- | --- | --- | | Bindings, expressions and control flow | Immutable values, explicit mutation, conditions, loops and ranges | [Syntax](docs/guide/basics/syntax.md), [control flow](docs/guide/basics/control-flow.md), [loops](docs/guide/basics/loops.md) | | Functions and callable values | Named functions, overloads, closures and higher-order interfaces | [Functions](docs/guide/basics/functions.md), [closures](docs/guide/types/closures.md), [function types](docs/guide/types/function-types.md) | | Numeric and textual values | Explicit integer/float widths, booleans, characters, strings and complex numbers | [Primitives](docs/guide/types/primitives.md), [strings](docs/guide/types/strings.md), [complex](docs/guide/types/complex.md) | | Structured data | Structs, tuples, arrays, enums, unions and pattern matching | [Structs](docs/guide/types/structs.md), [enums](docs/guide/types/enums.md), [patterns](docs/guide/types/pattern-matching.md), [unions](docs/guide/types/unions.md) | | Reusable interfaces | Generic types/functions, contracts, associated types and receiver methods | [Generics](docs/guide/types/generics.md), [contracts](docs/guide/types/contracts.md), [methods](docs/guide/advanced/methods.md) | | Policies and operators | Reusable field-metadata policies, custom operator contracts and precedence | [Policies](docs/guide/types/policies.md), [operators](docs/guide/advanced/operators.md) | | Absence and failure | Typed Option/Result values, propagation, matching and compensation | [Option](docs/guide/types/option-api.md), [Result](docs/guide/types/result-api.md), [error handling](docs/guide/error-handling.md) | | Modules and packages | Explicit imports/exports, facade modules, package manifests and workspaces | [Modules](docs/guide/modules.md), [package manager](docs/references/vex-pm-reference.md) | | Template literals | Multiline text construction with interpolation and control structures | [Templates](docs/guide/basics/template-literals.md) | ## Ownership and resource control | Capability | Design purpose | Read next | | --- | --- | --- | | Moves and borrows | Make ownership transfer and temporary access part of interfaces | [Ownership](docs/guide/memory/ownership.md), [borrowing](docs/guide/memory/borrowing.md), [lifetimes](docs/guide/memory/lifetimes.md) | | Explicit mutable access | Distinguish a changing binding from permission to mutate a borrowed value | [Variables](docs/guide/basics/variables.md), [borrow rules](docs/guide/memory/borrowing.md) | | Owning containers | Store dynamic data with defined allocation, clone and drop behavior | [Vec](docs/guide/types/vec.md), [Box](docs/guide/memory/box.md), [maps and sets](docs/guide/types/map-set.md), [ordered maps](docs/guide/types/ordered-map.md) | | Borrowed views | Pass a bounded region without transferring or extending its ownership | [Span](docs/guide/memory/span-t.md), [raw buffers](docs/guide/memory/rawbuf.md) | | Typed low-level access | Express pointer/ABI obligations at a controlled unsafe boundary | [Ptr](docs/guide/memory/ptr-t.md), [unsafe](docs/guide/advanced/unsafe.md), [FFI](docs/guide/ffi.md) | | Runtime ownership model | Understand allocation regions, sharing and reference-counted values | [VUMM](docs/guide/memory/vumm.md), [memory prelude](docs/guide/memory/mem-prelude.md) | | Suspension-safe lifetimes | Keep task inputs and frame-bound references valid across await | [Pin](docs/guide/memory/pin.md), [async internals](docs/guide/concurrency/async-internals.md) | | Cleanup and context | Tie resources, cancellation and contextual values to an explicit lifetime | [Context](docs/std/context.md), [native cleanup](docs/guide/ffi-first-native.md) | ## Concurrency and compute | Capability | What it contributes | Read next | | --- | --- | --- | | Tasks and channels | Concurrent producers/consumers, bounded queues and result collection | [Concurrency](docs/guide/concurrency/overview.md), [channels](docs/guide/concurrency/channels.md), [fan-in](docs/guide/concurrency/fan-in.md) | | Async/await | Typed functions that can suspend while retaining owned state | [Async](docs/guide/concurrency/async.md), [fallible batches](docs/guide/concurrency/batch-results.md) | | SIMD and static tensors | Elementwise operations, shape-aware values and reductions | [SIMD](docs/guide/simd/index.md), [operations](docs/guide/simd/simd-operations.md), [masks](docs/guide/simd/tensor-mask.md) | | Dynamic tensors | Runtime dimensions and the matching tensor ownership model | [Dynamic tensors](docs/guide/simd/dynamic-tensors.md) | | Graph functions | Typed dataflow that can be analyzed and lowered through Silicon IR | [Graph functions](docs/guide/gpu/graph-functions.md), [fusion](docs/guide/fusion/graph.md) | | Accelerator paths | Backend-specific code generation, executor selection and host/device boundaries | [GPU](docs/guide/gpu/index.md), [SIMD/SIMT contract](docs/guide/simd/simd-simt-contract.md), [backends](docs/architecture/sir-and-backends.md) | | Automatic differentiation | Forward-mode derivatives of supported numerical expressions | [Autograd](docs/guide/advanced/autograd.md) | | Native and freestanding code | Foreign calls, target interfaces, inline assembly and controlled runtime dependencies | [First native call](docs/guide/ffi-first-native.md), [freestanding](docs/guide/freestanding.md), [assembly](docs/guide/advanced/assembly.md) | Shape, numeric precision, ownership, target ABI and available native providers are part of each API's contract. Selecting an operation and selecting its execution device are separate decisions; the specialist guides explain both. ## Compile-time programming | Capability | Typical use | Read next | | --- | --- | --- | | Strict compile-time evaluation | Compute constants and reject invalid configurations during compilation | [Comptime](docs/guide/advanced/comptime.md) | | Typed reflection | Inspect fields and types while retaining ordinary type checking | [Comptime recipes](docs/guide/advanced/comptime-recipes.md) | | Structural declaration generation | Generate typed functions, methods, types, aliases and conformances | [Declaration generation](docs/guide/advanced/comptime-declarations.md) | | Partial evaluation and residual staging | Apply proven values while retaining runtime expressions for dynamic work | [Comptime pipeline](docs/architecture/comptime-pipeline.md), [CLI modes](docs/references/vex-cli-reference.md#comptime-staging-modes) | | Builtins and directives | Access phase-specific operations and declared compilation controls | [Builtins](docs/guide/advanced/builtins.md), [directives](docs/guide/advanced/compiler-directives.md) | ## Libraries and tools The [standard-library directory](docs/std/index.md) covers files and paths, I/O, system services, text/Unicode, parsing and serialization, compression, hashing, cryptography, randomness, time, CLI applications, logging, testing, databases, network protocols, geometry, media, image processing, WebRTC, ML and inference. Each guide describes its public entry points and native dependencies. For source-processing programs, the [language-tooling libraries](docs/guide/tooling/language-tools.md) cover all ten IDE package families: Logos, Ungram, Rowan, Salsa, Ariadne, Pretty, Doc, LSP, DAP and VXIR. The [toolchain reference](docs/guide/tooling/full-toolchain.md) connects compiling, running, linting and verified fixes, formatting, testing, documentation, package/workspace operations, inspection and bundled native tools. [Compiler testing tools](docs/references/compiler-testing-tools.md) cover generated inputs, deterministic replay and compiler-phase benchmarks. [VexHDL and Studio](docs/hdl/index.md) are companion hardware-description and design tools. Their language, simulation/synthesis workflows and product releases are separate from the Vex systems-language compiler. ## Choose a workflow 1. Pick a concrete input, output and failure contract from the [example collection](docs/guide/examples.md). 2. Use the linked language and library guides to design the data and ownership boundaries. 3. Pin the compiler/package versions, then test the relevant execution target. 4. Retain example results using the [verification guide](docs/guide/verification-evidence.md). The [versioning policy](docs/guide/versioning.md) describes compatibility in the 0.x series. The [platform guide](docs/guide/platform-support.md) explains target and native library selection. Test records identify the program, compiler and target they cover; this feature map is navigation, not a claim that every combination has been run on every machine. --- Source: https://vex-lang.org/docs/guide/math.md # Math Namespace `Math` provides builtin numeric operations and constants without an import. Choose the operation and numeric width first; container support and backend lowering are separate considerations. ## Quick Examples This complete scalar example checks its results instead of relying on the printed spelling of floating-point values: ```vex [math-scalar.vx] fn main(): i32 { let root: f64 = Math.sqrt(144.0); let root32: f32 = Math.sqrtf(144.0 as f32); let angle: f64 = Math.PI / 4.0; let sine: f64 = Math.sin(angle); if root != 12.0 || root32 != (12.0 as f32) { return 1; } if Math.abs(sine - 0.7071067811865476) > 0.000000000001 { return 2; } if !Math.isFinite(sine) { return 3; } $println("scalar math: PASS"); return 0; } ``` Expected output is `scalar math: PASS` and exit status 0. The tolerance is specific to this example; select an error budget appropriate to an application's scale and algorithm. A `NaN` never compares equal to itself: use `Math.isNaN` when classifying a value. ## Scalar vs Vectorized Usage The scalar transcendental functions below use `f64`; the explicitly listed `f` variants use `f32`. `min`, `max`, `clamp`, `abs`, and integer bit operations have type-preserving forms. Do not infer a function's result width from the width of an untyped numeric literal. The compiler also has lifting rules for selected arrays and Tensor operations. Those rules do not make every scalar API available for every container. A `Span` is a borrowed view with a lifetime and length; it is not interchangeable with an owning Tensor. Consult the [SIMD/SIMT contract](docs/guide/simd/simd-simt-contract.md) for supported shapes and execution paths. Vectorizable source can lower to scalar work, LLVM vector operations, library calls or SIR operations. There is no blanket single-instruction `sin`, `exp` or `log` guarantee, and a `graph fn` does not by itself prove GPU execution. ## Trigonometric Angles use radians. Unary entries have scalar signature `(f64) -> f64`; `atan2` takes `(y: f64, x: f64)`. | Function | Meaning | | --- | --- | | `Math.sin(x)`, `Math.cos(x)`, `Math.tan(x)` | Sine, cosine and tangent | | `Math.asin(x)`, `Math.acos(x)` | Inverse sine/cosine; real-valued domain is `[-1, 1]` | | `Math.atan(x)` | Inverse tangent | | `Math.atan2(y, x)` | Angle using both coordinates to determine the quadrant | ## Hyperbolic `Math.sinh`, `cosh`, `tanh`, `asinh`, `acosh`, and `atanh` each take and return `f64`. Real-valued inverse domains differ: `acosh` requires `x >= 1` and `atanh` requires `-1 < x < 1` for a finite result. ## Exponential & Logarithmic | Function | Meaning | | --- | --- | | `Math.exp(x)`, `Math.exp2(x)` | `e^x`, `2^x` | | `Math.expm1(x)` | `exp(x) - 1`, avoiding cancellation near zero | | `Math.log(x)`, `Math.ln(x)` | Natural logarithm; `ln` is an alias | | `Math.log2(x)`, `Math.log10(x)` | Base-2 and base-10 logarithms | | `Math.log1p(x)` | `log(1 + x)`, retaining accuracy near zero | These scalar operations take and return `f64`. A finite real logarithm requires a positive argument (`x > -1` for `log1p`). These are numeric operations, not `Result`-returning input validators; validate application input before calling. ## Power & Root | Function | Scalar arguments | Meaning | | --- | --- | --- | | `Math.pow(base, exponent)` | Two `f64` values | Floating-point power | | `Math.sqrt(x)` | `f64` | Square root | | `Math.cbrt(x)` | `f64` | Cube root, including negative inputs | | `Math.rsqrt(x)` | `f64` | Reciprocal square root | | `Math.hypot(x, y)` | Two `f64` values | Euclidean magnitude | | `Math.copysign(x, y)` | Two `f64` values | Magnitude of `x` with the sign of `y` | | `Math.fmod(x, y)` | Two `f64` values | Floating-point remainder | Use `cbrt` when the mathematical operation is a real cube root; replacing it with a fractional `pow` changes behavior for negative inputs. ## Rounding | Function | Direction | | --- | --- | | `Math.floor(x)` | Toward negative infinity | | `Math.ceil(x)` | Toward positive infinity | | `Math.round(x)` | Nearest integral value; halfway cases away from zero | | `Math.trunc(x)` | Toward zero | | `Math.rint(x)` | Integral value according to the rounding mode used by its lowering | These return floating-point values. They do not perform an integer conversion. Validate finiteness and the destination range before converting to an integer. Do not use `rint` as an unconditional promise of banker's rounding across all execution environments. ## Comparison & Clamping `Math.min(a, b)`, `max(a, b)`, `clamp(x, lo, hi)`, `abs(x)` and `sign(x)` preserve the operand type on their scalar paths. Use matching argument types and an ordered interval (`lo <= hi`) for clamping. Integer absolute value cannot represent the positive magnitude of the minimum signed integer in that same type; do not use it as an overflow check. `Math.fmin` and `fmax` are floating-point comparisons. Their native LLVM lowering uses `minnum`/`maxnum`: a single NaN operand selects the other numeric operand. Neither call is a replacement for checking that both inputs satisfy an application's validity policy. `Math.isNaN`, `Math.isInf`, and `Math.isFinite` accept scalar `f32` or `f64` and return `bool`. The spelling is significant. ## Activation Functions (ML) `Math.relu(x)` computes `max(0, x)` and `Math.sigmoid(x)` expresses the logistic function; `Math.erf(x)` is the error function. The scalar family uses `f64`. For model-level normalization, softmax, attention and their shape contracts, see [`ml`](docs/std/ml.md). Mathematical names alone do not establish numerical stability for every magnitude, empty input or non-finite value. ## Bit Operations | Function | Scalar contract | | --- | --- | | `Math.popcount(x)` | Count set bits; preserves integer width/type | | `Math.clz(x)` / `Math.ctz(x)` | Leading/trailing zero count in the operand's width | | `Math.bswap(x)` | Reverse bytes without changing integer width | | `Math.nextPowerOf2(x)` / `Math.nextPow2(x)` | Width-preserving next power of two | For example, `Math.clz(4 as u32)` is `29`, while `Math.clz(4 as u64)` is `61`. Masked extraction/deposition live in the separate [Bit namespace](docs/guide/bit.md). ### Scalar next power of two at compile time Both spellings preserve the operand's integer type and bit width, including `usize`/`isize` on the compilation target and 128-bit integers. Known scalar operands can be evaluated in `#const` or a const function through the ordinary `Math` API; no separate intrinsic spelling is needed. ```vex let buckets: usize = #const { Math.nextPow2(1000001 as usize) }; // 1048576 let high: u128 = #const { Math.nextPowerOf2(((1 as u128) << 100) + 1 as u128) }; ``` This is a **wrapping bit-pattern operation**: zero returns zero, and a result outside the operand width wraps to zero. Signed inputs retain signedness and use their underlying bits; for example, `Math.nextPow2(127 as i8)` yields `-128`. For allocation sizes use unsigned inputs and checked `Layout`/collection APIs, which reject invalid extents. This scalar CTFE support does not imply array, Span, Tensor, or GPU next-power support. ## Float Bit Representation `Math.toBits` and `Math.fromBits` reinterpret a scalar's representation. They are not numeric casts and preserve signed zero and every NaN payload bit. | Function | Signature | Result | |---|---|---| | `Math.toBits(x)` | `f32 -> u32`, `f64 -> u64` | Same-width IEEE-754 bits | | `Math.fromBits(x)` | `u32 -> f32`, `u64 -> f64` | Same-width IEEE-754 value | ```vex let negativeZero = Math.fromBits(0x8000000000000000 as u64); let payload = Math.toBits(negativeZero); // exact same u64 ``` Both operations lower to one LLVM SSA `bitcast`. They perform no memory copy, allocation, libc call or FFI transition. Other integer widths and signed integer arguments are rejected rather than implicitly narrowed or re-signed. ## Angle Conversion `Math.degrees(x)` converts radians to degrees; `Math.radians(x)` converts degrees to radians. The unsuffixed scalar functions take/return `f64`; `degreesf` and `radiansf` are the `f32` forms. ```vex let degrees: f64 = Math.degrees(Math.PI); // approximately 180 let radians: f32 = Math.radiansf(90.0 as f32); ``` ## Random Numbers `Math.random()` takes no arguments and returns an `f64` in `[0, 1)`. It is not an array/Span/Tensor operation and is not a cryptographic randomness API. For reproducible simulations and unbiased integer ranges, prefer an explicit [`rand.Rng`](docs/std/rand.md) stream. Use [`Crypto.secureRand`](docs/guide/crypto.md#secure-random) for the OS-backed randomness primitive; it does not by itself implement a complete key-management or nonce-allocation policy. ## Constants The builtin constants are `f64` values: | Constant | Meaning | | --- | --- | | `Math.PI`, `Math.TAU` | π and 2π | | `Math.E` | Euler's number | | `Math.SQRT2` | Square root of 2 | | `Math.LN2`, `Math.LN10` | Natural logarithms of 2 and 10 | | `Math.LOG2E`, `Math.LOG10E` | Base-2/base-10 logarithms of e | | `Math.FRAC_PI_2`, `Math.FRAC_PI_4` | π/2 and π/4 | | `Math.FRAC_1_SQRT2` | Reciprocal square root of 2 | | `Math.PHI` | Golden ratio | | `Math.EPSILON` | The `f64` machine epsilon; not a universal comparison tolerance | | `Math.INF`, `Math.NAN` | Positive infinity and NaN | ## f32 Variants These explicit spellings select the `f32` scalar family: | Operation | `f32` spelling | | --- | --- | | Sine / cosine / hyperbolic tangent | `sinf`, `cosf`, `tanhf` | | Exponentials | `expf`, `exp2f` | | Logarithms | `logf`, `log2f`, `log10f` | | Square root / absolute value | `sqrtf`, `fabsf` | | Rounding | `floorf`, `ceilf`, `roundf`, `truncf`, `rintf` | | Power / copy sign | `powf`, `copysignf` | | Floating minimum/maximum | `fminf`, `fmaxf` | | Angle conversions | `degreesf`, `radiansf` | Prefix these names with `Math.`. There is no general rule that adding `f` to an arbitrary function name creates another overload. ## LLVM Backend The native backend uses operation-specific recipes. Some become LLVM intrinsics (such as `llvm.sqrt`); others call mathematical library functions (such as `atan2` or `expm1`). LLVM then selects legal instructions for the target. An LLVM intrinsic is not a hardware latency measurement. Inspect and benchmark the complete compiled workload if vectorization or throughput is a requirement. ## Next Steps - [Bit operations](docs/std/bit.md) - [SIMD and tensors](docs/guide/simd/index.md) - [Random streams](docs/std/rand.md) --- Source: https://vex-lang.org/docs/guide/memory/borrowing.md # Borrowing Borrowing lets a function or expression use a value without taking ownership. Vex's semantic checker tracks immutable and mutable references, moves, field access, and the lifetime of returned references. Complete programs on this page print their computed values and return `0` for successful execution. Printed output and process exit status are separate: returning `42` from `main(): i32` would report a nonzero process status, not print the number. Fragments without `main` belong inside a program. ## Immutable references An immutable reference uses &T: ~~~vex struct Point { public: x: i32, y: i32, } fn sum(point: &Point): i32 { return point.x + point.y; } fn main(): i32 { let point = Point { x: 3, y: 4 }; $println(sum(&point)); return 0; } ~~~ The callee can read through the reference, but it cannot mutate the borrowed value through an immutable reference. ## Mutable references A mutable reference uses &T!. The owner must be stored in a mutable binding: ~~~vex struct Counter { public: value: i32, } fn increment(counter: &Counter!): i32 { counter.value += 1; return counter.value; } fn main(): i32 { let! counter = Counter { value: 41 }; $println(increment(&counter!)); return 0; } ~~~ Use a mutable borrow only for the smallest operation that needs it. The exclamation mark at the call site makes the exclusive borrow visible. ## The borrowing rule At a point in the program, Vex permits several immutable borrows or one exclusive mutable borrow. An immutable and mutable borrow cannot conflict while both are live. ~~~text let! values = Vec.new() let read_only = &values use(read_only) let writable = &values! mutate(writable) ~~~ The checker uses non-lexical lifetime reasoning. In the example, the immutable borrow can end after its last use, allowing the later mutable borrow. ## References cannot outlive their source A function may return a reference derived from one of its input references: ~~~text fn choose(left: &string, right: &string): &string { if left.len() > right.len() { return left } return right } ~~~ A reference to a local value cannot be returned: ~~~text fn invalid(): &i32 { let value = 42 return &value } ~~~ The local value is destroyed when invalid returns, so the compiler rejects the dangling reference. ## Returning references through known callbacks A local function value can retain the declared function's return-source information. The result does not automatically borrow every argument: ~~~vex struct Record { value: i32 } fn first(left: &Record, right: &Record): &Record { return left; } fn selected(source: &Record): &Record { let local = Record { value: 719 }; let callback = first; return callback(source, &local); } ~~~ Here `first` returns `source`, so its result has the source owner's lifetime. Passing another reference to the callback does not itself make that argument the returned pointee. Keep the callback's declaration and reference-returning contract clear at the call site. This also works inside a generic forwarding function: ~~~vex fn firstGeneric(left: &T, right: &T): &T { return left; } fn forward(left: &T, right: &T): &T { let callback: fn(&T, &T): &T = firstGeneric; return callback(left, right); } ~~~ A generic forwarding function preserves the reference-source relationship; substituting a concrete `T` does not create a new owner. If a callback can return either input, both inputs must remain valid for every use of the result. A callback returning its second argument therefore cannot export the local `Record` from `selected` above. These are lifetime requirements on returned data, independent of how the callable is represented. ## Writing and returning a stored reference A stored reference refers to its pointee, not to the variable or field that holds the reference. Assigning a new reference changes the stored source: ~~~vex struct StoredRecord { value: i32 } struct StoredHolder { source: &StoredRecord } fn replace(output: &StoredHolder!, source: &StoredRecord): &StoredRecord { output.source = source; return output.source; } ~~~ The returned reference comes from `source`; it does not borrow the storage of `output`. The write still imposes its normal lifetime requirements on the stored reference. A definite overwrite replaces the previous source. A write on only one branch, a possibly zero-iteration loop or a possibly aliasing index must retain every possible source. A reference copied **before** an overwrite keeps its original pointee. ## Field-level access The checker can reason about disjoint fields for supported struct operations: ~~~text struct Point { public: x: i32, y: i32, } let! point = Point { x: 1, y: 2 } let x_ref = &point.x point.y = 10 use(x_ref) ~~~ Access to point.y does not overlap point.x. A write to point.x while x_ref is live would be rejected. A reference field's storage slot is distinct from the object it points to. Replacing `holder.source` does not mutate the old or new source object; ordinary scalar sibling updates and repeated field assignments use that same distinction. A live reference to the slot itself still prevents overwriting it. References stored behind a live alias remain observable even when the original holder variable is no longer directly used. Their source cannot be mutated or destroyed while that alias can still observe it. This follows selected fields: an alias to one subobject does not automatically keep unrelated sibling references live, and an alias whose last use has passed does not extend a borrow. The conservative call-side and implicit-effect boundaries described above still apply. Copying a reference out of caller-owned storage does not borrow its reference slot; borrowing the slot with `&holder.source` does. Unknown pointees and whole-owner operations remain conservative. ## Method receivers Methods use the same reference types as ordinary functions: ~~~text fn (point: &Point) sum(): i32 { return point.x + point.y } fn (point: &Point!) move_by(dx: i32, dy: i32) { point.x += dx point.y += dy } ~~~ The call-site value must satisfy the receiver's mutability requirement. ## Borrowing an indexed element For a source-defined index operator, exclusive use selects the declared mutable getter (`&Container! -> &Element!`). This applies to field assignment, an explicit mutable borrow, a contextually mutable reference argument, and a method whose selected receiver is `&Element!`: ~~~vex struct IndexedCounter { value: i32 } fn (self: &IndexedCounter!) increment() { self.value = self.value + 1; } fn update(counters: &Vec!) { counters[0 as usize].increment(); let counter = &counters[0 as usize]!; counter.increment(); } ~~~ The same rule applies to user-defined containers and nested index projections; it is not a special privilege of `Vec`. The getter must return a mutable reference to the value required by the consuming operation. A getter returning a different element type cannot replace the value underneath an already resolved method call. Selecting a mutable getter does not grant permission to mutate a shared owner, nor does it override a live conflicting borrow. A container with only a shared getter still cannot provide mutable element access. The selection is resolved at compile time and does not add runtime dispatch. A freshly written `&value` can also take its shared/exclusive reference type from its consuming field or parameter. This applies after generic literal inference too. The borrow checker uses that inferred capability: if the field requires `&T!`, a simultaneous shared borrow of the same live pointee is not allowed. This does not upgrade an already stored `&T` reference to `&T!`. ## Concurrency boundaries References cannot be captured by a detached task when the capture could dangle or introduce an unsafe race: ~~~text let! values = Vec.new() let borrowed = &values go { use(borrowed) } ~~~ Whether a capture is accepted depends on the lifetime and escape path. Prefer moving an owned value into a task or sending a value through a typed channel. ## Container and foreign boundaries An ordinary reference expresses a borrow. A raw pointer or foreign handle also needs its owning API's lifetime, invalidation, and synchronization rules. For example, a pointer into a Vec can be invalidated by growth, and a foreign callback may outlive the call that registered it. Keep such contracts at a small boundary and expose borrowed or owned Vex values to the rest of the program. ## Guidance - Prefer &T for read-only functions. - Use &T! only when mutation is required. - End borrows before taking a mutable borrow. - Keep returned references tied to input data. - Treat pointers, raw buffers, and FFI values as separate safety boundaries. ## Next steps - [Ownership workflows](docs/guide/memory/ownership-workflows.md) — complete borrowed-parser and owned-report examples - [Ownership](docs/guide/memory/ownership.md) - [Lifetimes](docs/guide/memory/lifetimes.md) - [Memory Safety](docs/guide/memory/safety.md) - [Concurrency Overview](docs/guide/concurrency/overview.md) --- Source: https://vex-lang.org/docs/guide/memory/box.md # `Box` `Box` owns a heap-allocated value through a managed handle. It is available from the prelude. Use it when a value needs indirection, when a recursive type would otherwise have an infinite layout, or when an owned value must outlive the stack frame that constructs it. A box handle and its payload are distinct. Moving a handle transfers ownership; cloning a box shares its payload. A clone is not an independent deep copy, and a mutable binding does not make a shared payload writable. ## Construction and reads ```vex fn main(): i32 { let number = Box.new(42); $println(number.get()); $println(*number.getRef()); return 0; } ``` Expected stdout is `42` on each of two lines, with exit status 0. `Box(42)` is also constructor syntax. `Box.new(value)` makes the type argument explicit and transfers an owning `value` into the allocation. Choose a read operation according to the result you need: | Operation | Result and effect | | --- | --- | | `get()` | Returns a value while leaving the box populated. The current prelude rejects payloads that need drop; use a borrow or an ownership transfer for them. | | `getRef()` | Returns `&T`; the box must be populated and remain alive while the reference is used. | | `getRefOpt()` | Returns `Option<&T>`; an empty box returns `None`. | | `isValid()` | Reports whether the handle is populated. It does not establish uniqueness or authorize raw-pointer access. | For example, inspect a `Box>` through `getRef()`; do not use `get()` to copy its owning vector out. To make independent data, use the payload type's explicit cloning or reconstruction operation and put that result in a new box. ## Exclusive mutation The mutable operations require an exclusive borrow of the handle. They also check whether another managed handle shares the payload: | Operation | Populated, sole handle | Empty or shared handle | | --- | --- | --- | | `getRefMut()` | Returns `&T!` | Shared payload panics; an empty handle is not a valid receiver. Prefer the optional form when emptiness is possible. | | `getRefMutOpt()` | Returns `Some(&T!)` | Returns `None`. | | `set(value)` | Drops the previous payload and replaces it | Panics. It is not a way to refill an empty box. | ```vex fn main(): i32 { let! number = Box.new(41); match number.getRefMutOpt() { Some(value) => { *value = *value + 1; }, None => { return 1; }, }; $println(number.get()); return 0; } ``` The intended output is `42`, exit status 0. If the optional borrow returns `None`, the program exits 1 instead of dereferencing an unavailable value. All normal borrow rules still apply: uniqueness of a box handle does not permit a write that conflicts with a live reference into its payload. Shared ownership provides lifetime management, not synchronized mutable access. Use channels, atomics, or an appropriate synchronization API for shared state; do not bypass the check with a raw pointer. ## Taking ownership out `take()` and `tryTake()` borrow the box mutably. On success they transfer the payload out and **leave the existing box handle empty**. They do not make the binding disappear. ```vex fn main(): i32 { let! number = Box.new(42); let value = number.take(); if number.isValid() { return 1; } if number.tryTake().isSome() { return 2; } $println(value); return 0; } ``` Expected stdout is `42`, exit status 0. The value is now owned by `value`. Dropping the empty box does not drop that value a second time. | Operation | Success | Failure | | --- | --- | --- | | `take()` | Returns `T`; leaves the box empty | Panics if empty or another handle shares the payload. | | `tryTake()` | Returns `Some(T)`; leaves the box empty | Returns `None` and leaves the box unchanged. | To reuse an empty binding, assign a newly constructed box. Do not call `getRef`, `get`, or `set` on the empty handle. ## Cloning, swapping, and cleanup `clone()` creates another managed handle to the same payload. While both handles exist, `getRefMutOpt()` and `tryTake()` return `None`. The panicking mutation and take forms refuse the same sharing condition. Releasing the other handles can restore uniqueness, subject to the ordinary borrow rules. This complete example observes sharing, releases one handle, then mutates through the remaining handle: ```vex [box-sharing.vx] fn main(): i32 { let! owner = Box.new(41); let! alias = owner.clone(); if owner.getRefMutOpt().isSome() { return 1; } if owner.tryTake().isSome() { return 2; } $println(*alias.getRef()); alias.drop(); match owner.getRefMutOpt() { Some(value) => { *value += 1; }, None => { return 3; }, }; $println(owner.get()); return 0; } ``` Expected stdout is `41` followed by `42`, with exit status 0. The optional operations leave the shared box unchanged. The explicit `alias.drop()` makes the end of that handle visible; scope cleanup is sufficient when an earlier release is unnecessary. `swap(&other!)` swaps the **handles**, including their empty or populated state; it does not mutate the two payloads in place. Each handle subsequently owns the allocation it received. Scope cleanup releases a handle. The payload is destroyed and its storage is reclaimed when the final owning handle is released. Explicit `drop()` also releases this handle and leaves it empty; normal scope-based cleanup is easier to reason about unless early release is needed. ## Recursive types Indirection makes a recursive representation finite: ```vex enum List { Cons(T, Box>), Nil, } ``` This is a type-definition fragment, not a full collection implementation. Traversal and updates must still respect borrowing and sharing. ## Raw addresses and implementation boundaries `asPtr()` borrows the address without transferring ownership. Do not free that address or keep using it after the box's allocation is released. A raw address also does not grant mutable access to a shared payload. The prelude implementation contains `fromRaw` and `intoRaw` helpers, but they are not exported as ordinary application API in the inspected source. Their presence in source is not a portable FFI ownership-transfer recipe. Prefer an explicitly documented foreign-resource wrapper; see [FFI](docs/guide/ffi.md). Representation, reference-count placement, and allocation elimination are compiler decisions. The public contract is ownership and access to the payload; it does not prescribe a binary layout or fixed allocation cost. ## See also - [Ownership](docs/guide/memory/ownership.md) - [Borrowing](docs/guide/memory/borrowing.md) - [VUMM](docs/guide/memory/vumm.md) - [Typed raw pointers](docs/guide/memory/ptr-t.md) - [Vectors](docs/guide/types/vec.md) --- Source: https://vex-lang.org/docs/guide/memory/lifetimes.md # Automatic Lifetime Management Unlike Rust, Vex does not expose explicit lifetime annotations in ordinary source code. The compiler performs lifetime and borrow analysis internally. > **tip Key Difference from Rust** In Rust, you write: `fn longest<'a>(x: &'a str, y: &'a str) -> &'a str` In Vex, you simply write: `fn longest(x: &string, y: &string): &string` Vex derives those reference-source relationships from the function and its callers. ## How It Works At a high level, the compiler tracks: 1. **Reference Origins** - Where each reference comes from 2. **Validity Ranges** - How long each reference is valid 3. **Conflicts** - When mutable and immutable borrows overlap ```vex fn longest(x: &string, y: &string): &string { if x.len() > y.len() { return x } return y } // The compiler understands that the returned reference // is tied to the borrowed inputs ``` ## Borrowing Rules Vex enforces safety rules through static analysis, without explicit annotations: ### Rule 1: One Mutable OR Multiple Immutable ```vex let! data = Vec.new() data.push(1) data.push(2) // Multiple immutable borrows - OK let a = &data let b = &data $println(f"{a.len()}, {b.len()}") // Mutable borrow - OK (immutable borrows no longer in use) let c = &data! c.push(3) // Rejected if included: d stays live across the mutation. // let d = &data // let e = &data! // e.push(4) // $println(d.len()) ``` ### Rule 2: References Cannot Outlive Data ```vex fn dangling(): &i32 { let x = 42 return &x // Rejected: x is destroyed when the function returns } // Return owned data instead fn not_dangling(): i32 { let x = 42 return x } ``` ### Rule 3: Respect concurrency and suspension boundaries A detached task must not retain a reference to stack storage that can disappear before the task finishes. Shared mutable state also needs the synchronization contract of its owning abstraction. Copying a handle or writing `go { ... }` does not itself establish either lifetime or synchronization. Use the [concurrency guide](docs/guide/concurrency/async.md) for task and suspension rules. The compiler checks captures, but these checks should not be described as a blanket proof for unchecked raw memory or arbitrary foreign callbacks. ## Common Patterns ### Borrowed Results from Temporary Owners A call may borrow an unnamed source value and return a view into it. When that view is consumed directly by another call, the source owner stays alive until the consuming expression finishes: ```vex // makeOwner() returns an owned value; view() borrows it; read() returns i32. let value = makeOwner().view().read(); ``` This applies to ordinary user-defined types, free functions and method chains; it is not a special rule for strings or collections. Scalar field and pointer dereference reads through a safe reference are evaluated before cleanup. Owners sharing a cleanup boundary are destroyed in reverse construction order. A scalar-returning call without a borrowed-result chain still cleans its own temporary operands immediately after that call. Do not assume the ordinary temporary-chain rule extends an owner across a binding, a block boundary, a return, a capture, or suspension. Coroutine lowering can retain particular owners in a frame when supported; that is a separate analysis. To keep a view, keep its owner explicitly: ```vex let owner = makeOwner(); let view = owner.view(); let value = view.read(); // Invalid when the view borrows the temporary owner's storage: // let dangling = makeOwner().view(); ``` This rule concerns borrowing existing source storage. Ownership-producing argument conversions have separate temporary/escape checks; a constructor conversion does not automatically make its borrowed result escapable. ### Temporaries Created by Argument Conversions A conversion that only borrows existing storage does not create a new owner. For example, `&string` (including nested references) can provide a `str` view of the original string's bytes. The view retains that owner's lifetime; it cannot outlive the string. This conversion is not an implicit clone. An argument conversion may create a new owner before borrowing it for the callee. For example, passing a `str` to an `&string` parameter constructs temporary owned storage. The source `str` and that new owner have different lifetimes, even when the source is a string literal. The converted owner is registered before later arguments are evaluated. Normal completion and early `return`, `break` or `continue` use the same cleanup mechanism. Variadic arguments follow the same sealed conversion and ownership rules as ordinary arguments. A callee cannot export this temporary's reference through an output field merely because its return type is `None`: ```vex struct View { source: &string } fn store(output: &View!, input: &string) { output.source = input; } fn invalid(initial: &string, text: str): &string { let! output = View { source: initial }; store(&output!, text); // A separate converted owner lives for this call. return output.source; // Rejected: that owner has already expired. } ``` Keep an owned value explicitly when the stored view must remain usable. Replacing an expired reference field with a valid reference before reading it is allowed; taking a direct field's address to overwrite it does not read its old reference value. Typed variadic calls follow the same rule. Every element in `...&T` contributes its own reference origins to the pack; later arguments cannot escape the check. An empty pack contributes no element references. The pack owns its element storage, but does not become the owner of external values referenced by those elements. Returning an element's reference can therefore be valid when its external owner remains alive; returning a borrow of the pack's own element storage is not. Native calls can borrow an owning pack through the shared Span API (`get`, `getUnchecked`, `slice`, `splitAt`). This does not convert the pack into an owned Span value or transfer its cleanup responsibility. A nested view must remain within the pack's lifetime. The descriptor view requires identical element types and does not admit an exclusive descriptor borrow. At compile time, a borrowed pack view still points into the original pack's storage; it does not copy or take ownership of the elements. The descriptor must remain within the pack's lifetime. A source method must also be const-capable before it can run during compile-time evaluation. See [Variadic Functions](docs/guide/types/variadics.md) for typed packs and CTFE. ### Named Values and Field Borrows The dot in `State.Ready` selects an enum value; it does not borrow a field from a runtime object named `State`. Passing that value to a reference parameter materializes temporary storage for the value. An explicit `&State.Ready` can also be used within its enclosing lifetime, but cannot be returned as a reference to permanent storage merely because the variant has a name. By contrast, `&object.field` borrows the object's existing field storage. A projection such as `&makeOwner().field` retains the complete temporary owner, not just an independently copied field. These rules follow resolved values and storage projections, not type names or prelude privileges. ### Reading a Value Through a Reference A contextual `&T` to `T` load does not transfer ownership from the referent. It can copy a `Copy` value, including a user-defined type with the appropriate contract. For a non-Copy owner, retain a reference or explicitly clone it when the type supports cloning. The same rule applies to pattern bindings, fields, indexed elements, function/method results, and block/branch results. ```vex enum Message { Text(string), Empty } fn copyText(message: &Message): string { return match message { Message.Text(text) => text.clone(), Message.Empty => "", }; } ``` Here `text` borrows the payload. Returning `text` directly as an owned `string` is rejected; returning its explicit clone leaves the original message intact. Matching an owned `Message` by value can instead transfer its payload normally. Serde's dynamic `asString()` getters follow the explicit-clone contract: their owned results remain valid after the source value is destroyed. Read-only views should be used when an independent owned result is unnecessary. ### Returning References from Functions A getter returning a reference reborrows existing storage; it does not move the referenced value. For example, `&*reference` remains a reborrow even when the pointee is a non-Copy generic type. Writing through a mutable getter's result uses that result's capability. Two separate live getter results do not become interchangeable permissions: a conflicting write is still rejected. Shared references can retain the lifetime of their mutable parent without gaining mutable access. These rules apply structurally to user-defined types and adapters, not just to prelude or standard-library getters. ```vex struct User { name: string, email: string } // Return reference to field - compiler tracks this fn (self: &User) get_name(): &string { return &self.name } // Usage let user = User { name: "Alice", email: "alice@example.com" } let name = user.get_name() $println(name) // OK: user still valid // Error case - would be caught at compile time fn bad_example(): &string { let user = User { name: "Bob", email: "bob@example.com" } return user.get_name() // Rejected: user is dropped, so the returned reference would dangle } ``` ### Structs Holding References ```vex // Struct can hold references struct Parser { input: &string, position: usize } fn Parser.new(input: &string): Parser { return Parser { input, position: 0 } } fn (self: &Parser!) advance() { self.position = self.position + 1 } // Usage let source = "let x = 42" let! parser = Parser.new(&source) parser.advance() // parser valid only while source is valid - compiler enforces this ``` ## Comparison: Vex vs Rust | Aspect | Rust | Vex | | -------------------- | ------------------------ | ------------------------------------- | | Lifetime annotations | Required when ambiguous | Never required | | `'a` syntax | Yes | No | | Borrow checking | Compile time | Compile time | | User-facing style | Explicit lifetime syntax | Automatic lifetime syntax | | Async references | Must remain valid across suspension | Depends on owner storage and lifetime; see the async guide | ### Equivalent Code **Rust:** ```rust fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } struct ImportantExcerpt<'a> { part: &'a str, } ``` **Vex:** ```vex fn longest(x: &string, y: &string): &string { if x.len() > y.len() { x } else { y } } struct ImportantExcerpt { part: &string } fn (self: &ImportantExcerpt) level(): i32 { return 3 } ``` ## Lifetimes across suspension A borrow crossing suspension requires an owner that remains alive until the borrow's last use. Storage retained by a coroutine frame and ordinary stack storage have different lifetimes. Address stability is a separate condition: retaining an owner does not authorize moving self-referential storage or reallocating a borrowed buffer. See [Pin](docs/guide/memory/pin.md) and the [suspension safety table](docs/guide/concurrency/async-internals.md#suspension-safety). ## Best Practices 1. **Return owned data when in doubt** - Simpler and avoids lifetime issues 2. **Use references for read-only access** - Efficient, no copying 3. **Use `&T!` for mutable operations** - Clear intent 4. **Use async and detached concurrency with the documented rules in mind** - especially around borrows that might cross `await` or `go {}` boundaries ## Next Steps - [VUMM Memory Model](docs/guide/memory/vumm.md) - Automatic memory management - [Ownership](docs/guide/memory/ownership.md) - Value ownership model - [Borrowing](docs/guide/memory/borrowing.md) - Reference borrowing details --- Source: https://vex-lang.org/docs/guide/memory/mem-prelude.md # Memory Prelude (`Mem`) `Mem` is VexArch's single prelude boundary for allocation, reallocation, byte movement, and explicit destruction. It is available without an import, but it is intended for runtime, standard-library, allocator, and data-structure code. Most applications should use `Box`, `Vec`, `string`, or another owning type. `Mem` does not make raw memory safe. Every caller remains responsible for allocation extent, alignment, initialization, aliasing, and allocator pairing. ## Core allocation API | Function | Purpose | | --- | --- | | `Mem.alloc(size: usize): Ptr` | allocate `size` bytes from the active region or persistent heap, 16-byte aligned | | `Mem.allocAligned(size: usize, align: usize): Ptr` | allocate from the active region or heap with a power-of-two alignment | | `Mem.realloc(p, oldSize, newSize): Ptr` | resize a block while preserving the common prefix | | `Mem.free(p, size): ()` | free a block with its exact allocation size | ```vex let size = 16 as usize // byte buffer, not an assumed struct layout let memory = Mem.alloc(size) let! header = RawBuf.of(memory) header.zero(size) header.store(0, 0x56455821) Mem.free(memory, size) ``` `Mem.allocAligned` is paired with `Mem.freeAligned`; the aligned pointer may carry a private prefix and must not be passed directly to `Mem.free`. `Mem.free` expects the exact allocation size. For `Ptr.allocN(count)`, use `Ptr.freeN(count)` so the element count is converted to the correct byte size. For checked dynamic layouts, `Layout` is also a prelude type and requires no package import. It validates size/alignment arithmetic but deliberately does not introduce a second allocator or ownership abstraction: low-level owners retain the `Layout` needed to pair their `Mem` allocation and release. ## Heap- and region-bound allocation VexArch distinguishes temporary arena allocation from storage that must survive an arena reset. | Function | Purpose | | --- | --- | | `Mem.heapAlloc(size)` | allocate from the persistent slab/large heap | | `Mem.heapRealloc(p, oldSize, newSize)` | resize persistent heap storage | | `Mem.currentRegion()` | return the active allocator region, or null | | `Mem.regionAlloc(region, size)` | allocate through a captured region; null selects heap behavior | | `Mem.regionRealloc(region, p, oldSize, newSize)` | resize through the same captured region | | `Mem.allocFor(size)` | active-region allocation preserving the exact target alignment of `T` | | `Mem.heapAllocFor(size)` | persistent-heap allocation preserving the exact target alignment of `T` | | `Mem.regionAllocFor(region, size)` | captured-region typed allocation | | `Mem.regionReallocFor(region, p, oldSize, newSize)` | captured-region typed resize | | `Mem.freeFor(p, size)` | release storage selected by a typed allocation route | Containers capture `Mem.currentRegion()` when they are created and route their backing-buffer growth through that captured region. This prevents a container from silently changing allocator lifetime after construction. The `*For` forms select ordinary versus over-aligned storage at compile time. Types whose ABI alignment is at most 16 bytes retain the native fast path with no runtime branch or metadata. Prelude container implementations use these forms so `Ptr`, `Vec`, `Deque`, and `Map` remain valid for over-aligned element layouts. Application code should normally prefer their typed owning APIs instead of calling `Mem.*For` directly. These functions are public so prelude and low-level library types can share the same allocator contract. Application code should not select an arena/heap path manually unless it is implementing an owning abstraction. ## Byte operations | Function | Semantics | | --- | --- | | `Mem.copy(dst, src, n)` | copy `n` bytes; regions must not overlap | | `Mem.move(dst, src, n)` | copy `n` bytes; overlapping regions are supported | | `Mem.set(dst, value, n)` | fill `n` bytes with the low byte of `value` | | `Mem.compare(a, b, n): i32` | bytewise comparison | | `Mem.equals(a, b, n): bool` | equality over `n` bytes | | `Mem.zero(dst, n)` | fill `n` bytes with zero | Prefer `RawBuf` or `Ptr` methods when they better express the offset unit and element type. `Mem` is the shared primitive boundary beneath those wrappers. ## Explicit destruction ```vex let owned = acquireResource() // End this value's lifetime before the surrounding scope exits. Mem.drop(owned) ``` `Mem.drop(value)` consumes the value and runs its ownership-aware destruction path. Use it only for intentional early destruction. Values are otherwise dropped automatically at scope exit; calling `Mem.drop` and then using the moved value is invalid. The raw ownership primitive used to implement `Mem.drop` is compiler-owned and prelude-only. It is not a developer-facing intrinsic. ## Size-metadata compatibility path `Mem.allocCompat(size)`, `Mem.allocZeroedCompat(count, elementSize)`, `Mem.freeCompat(p)`, and `Mem.reallocCompat(p, newSize)` form the canonical path for APIs that cannot carry allocation size metadata to deallocation. They use an inline size header and therefore give up the faster exact-size path. New owning abstractions should preserve a `Layout` and use the exact-size `Mem.alloc/realloc/free` contract. There is no `std/mem` package and no parallel set of free functions. `Mem.*` is the single source of truth across the compiler prelude, VexArch, standard library, and application code. ## Unbounded loops and arena safety `Mem.unboundedLoop()` is a zero-runtime-cost compiler hint for a loop whose exit depends on runtime state and cannot be proven bounded: ```vex while keepRunning { Mem.unboundedLoop() processNextEvent() } ``` The compiler already recognizes `loop {}` and statically true `while` conditions. Use the hint only when a genuinely runtime-gated loop would otherwise look bounded. It prevents scope-root arena allocation from accumulating indefinitely in a loop that may never exit. ## Freestanding boundary `Mem` is a VexArch API, not a promise that Vex source depends on host libc allocation. Its platform implementation may use OS/native system services, a custom allocator, or a freestanding backend. Prelude and standard-library code remain expressed against the same `Mem` contract instead of importing `malloc/free` directly. This separation is essential for freestanding builds: platform-specific memory provision lives below VexArch, while Vex ownership and container code remains portable above it. ## Safety checklist 1. Preserve the exact size and allocator/region that created each block. 2. Do not read uninitialized bytes or access memory after free. 3. Use `Mem.move` when source and destination may overlap. 4. Validate alignment before constructing typed or SIMD views. 5. Prefer RAII owners; expose raw `Mem` operations only inside a small audited implementation. ## Related - [`Ptr`](docs/guide/memory/ptr-t.md) - [`Span`](docs/guide/memory/span-t.md) - [RawBuf](docs/guide/memory/rawbuf.md) - [Ownership](docs/guide/memory/ownership.md) - [Freestanding](docs/guide/freestanding.md) --- Source: https://vex-lang.org/docs/guide/memory/ownership-workflows.md # Ownership Workflows Choose the result's ownership before choosing its container. A parser can return a view into input that remains alive; a report intended to outlive its source needs owned data. The following complete programs show both designs, including error paths and observable results. | Result needed | Useful shape | Who keeps the data alive? | | --- | --- | --- | | Read part of an existing buffer | `Span` | The original owner | | Inspect an existing record | `&T` | The record's owner | | Keep selected data after the source is released | `Vec` containing owned values | The returned Vec | | Remove a value from a collection | `Option` from `pop` or `remove` | The caller, after a successful removal | ## Parse a frame without copying its payload This small wire format has a three-byte header: magic byte `0x56`, a message kind, and a payload length stored as one `u8`. It accepts exactly one complete frame. A short header, an unknown magic byte, and a mismatched payload length produce different errors. `parseFrame` borrows the input through a `Span`. The returned `Packet` contains a view of the payload, so the input Vec remains alive while the packet is used. The parser creates no owned payload copy. The `wire` helper uses a [typed variadic pack](docs/guide/types/variadics.md) to build sample input. ```vex [borrowed-packet.vx] struct Packet { kind: u8, payload: Span } enum FrameError { TruncatedHeader, BadMagic, LengthMismatch } fn parseFrame(bytes: Span): Result { if bytes.len() < 3 { return Err(FrameError.TruncatedHeader); } if bytes[0] != 0x56 { return Err(FrameError.BadMagic); } let length = bytes[2] as usize; if bytes.len() - 3 != length { return Err(FrameError.LengthMismatch); } return Ok(Packet { kind: bytes[1], payload: bytes.slice(3, bytes.len()) }); } fn wire(values: ...u8): Vec { let! output = Vec.new(); for value in values { output.push(*value); } return output; } fn main(): i32 { let input = wire(0x56, 1, 3, 10, 20, 30); let packet = match parseFrame(input.asSpan()) { Ok(value) => value, Err(_) => { return 1; }, }; let! total: u32 = 0; for value in packet.payload { total += *value as u32; } if packet.kind != 1 || packet.payload.len() != 3 || total != 60 { return 2; } $println(f"kind={packet.kind} bytes={packet.payload.len()} total={total}"); let short = wire(0x56, 1); let badMagic = wire(0, 1, 0); let badLength = wire(0x56, 1, 2, 10); match parseFrame(short.asSpan()) { Err(FrameError.TruncatedHeader) => {}, _ => { return 3; }, }; match parseFrame(badMagic.asSpan()) { Err(FrameError.BadMagic) => {}, _ => { return 4; }, }; match parseFrame(badLength.asSpan()) { Err(FrameError.LengthMismatch) => {}, _ => { return 5; }, }; $println("3 invalid frames rejected"); return 0; } ``` Run `vex run borrowed-packet.vx`. Expected stdout: ```text kind=1 bytes=3 total=60 3 invalid frames rejected ``` The program exits 0 after checking the valid result and each error variant. The header-size check occurs before indexing, and subtraction occurs only once at least three bytes exist. Checking the exact length before `slice` is important: `slice` clamps its bounds, which is useful for views but would not itself reject a truncated frame. This format rejects trailing bytes too; a stream parser would additionally return how much input it consumed. Keep `input` alive and avoid changing its storage until the last use of `packet.payload`. Copying a `Span` copies its descriptor and keeps the same lifetime requirement. If the packet must outlive the input, use `packet.payload.toVec()` to clone its bytes into an owned buffer and return that owned buffer instead. See [Span](docs/guide/memory/span-t.md) for exact-size and clamped view operations, and [Error Handling](docs/guide/error-handling.md) for propagating a `Result`. ## Return a report that outlives its source An inventory report often needs only a few fields from larger records. `replenishment` borrows the inventory, selects items below their reorder level, and clones their names into a new Vec. It leaves the inventory unchanged. ```vex [owned-report.vx] struct Item { name: string, stock: i32, reorderAt: i32 } fn replenishment(items: &Vec): Vec { let! names = Vec.new(); for item in items { if item.stock < item.reorderAt { names.push(item.name.clone()); } } return names; } fn main(): i32 { let! items = Vec.new(); items.push(Item { name: "paper", stock: 2, reorderAt: 5 }); items.push(Item { name: "clips", stock: 10, reorderAt: 5 }); items.push(Item { name: "ink", stock: 0, reorderAt: 2 }); let report = replenishment(&items); Mem.drop(items); if report.len() != 2 || report[0] != "paper" || report[1] != "ink" { return 1; } for name in report { $println(name); } $println(f"{report.len()} items need replenishment"); return 0; } ``` Run `vex run owned-report.vx`. Expected stdout: ```text paper ink 2 items need replenishment ``` The result's names remain valid after `Mem.drop(items)` because each explicit `string.clone()` produces an independent string. The returned Vec owns those strings and releases them when it is destroyed. Iteration over `items` borrows each `Item`; it does not remove records from the inventory. Returning `Vec<&string>` instead would retain references into the original records and would require the inventory to remain alive. Returning a shallow copy of an owning string is not a substitute for cloning it. If processing should consume records instead, design an API around `pop` or `remove` and transfer the selected values into the result. See [Vec](docs/guide/types/vec.md) for borrowed access, cloning, and removal. ## Apply the same choice to other APIs For a file reader, a view may borrow a buffer while the reader keeps it alive; a queued message needs owned bytes if processing continues after that buffer is reused. For a configuration query, `&string` is useful while the configuration remains in scope; a cached value can use an explicit clone. For a foreign image handle, a pixel span still depends on the foreign image's lifetime and invalidation rules. In each case, state three things in the API: whether inputs are borrowed or consumed, whether results own their data, and which operation can invalidate a retained view. Errors also need an ownership contract: a failed operation must make clear whether the caller still owns the input. ## Related pages - [Ownership](docs/guide/memory/ownership.md) - [Borrowing](docs/guide/memory/borrowing.md) - [Lifetimes](docs/guide/memory/lifetimes.md) - [Option](docs/guide/types/option-api.md) - [Foreign types and ownership](docs/guide/types/extern-types.md) --- Source: https://vex-lang.org/docs/guide/memory/ownership.md # Ownership Vex uses ownership to make the lifetime and movement of values explicit. An ordinary owning value has an owner; a managed allocation may be kept alive by multiple explicit handles. Passing an owning value to a function or assigning it to another binding can move that ownership; borrowing lets code use the value without taking it over. Container and resource APIs build on these rules: they specify which operations borrow, clone, share, transfer, or destroy a value. Foreign types also retain the foreign library's ownership contract. Complete programs on this page print their computed values and return `0` for successful execution. Printed output and process exit status are separate: returning `42` from `main(): i32` would report a nonzero process status, not print the number. Fragments without `main` belong inside a program. ## Bindings and mutation Bindings are immutable by default: ~~~vex fn main(): i32 { let value = 20; $println(value); return 0; } ~~~ Use let! when the binding must be reassigned: ~~~vex fn main(): i32 { let! total = 20; total += 22; $println(total); return 0; } ~~~ A mutable binding does not make every reference to the value mutable. The reference type must also permit mutation. ## Moves Owning values such as Vec, Box, strings, maps, sets, and most user-defined structs may be moved: ~~~text let data = Vec.new() let moved = data use(moved) use(data) // error: data was moved ~~~ A move is useful when a function or task should become the new owner. If the caller still needs to use the value, pass an immutable or mutable reference instead. ## Copy values Small scalar values such as integers, floating-point values, booleans, and characters are copied in ordinary assignments: ~~~vex fn main(): i32 { let first: i32 = 42; let second = first; $println(first); $println(second); return 0; } ~~~ For an owning or user-defined type, assume that assignment moves unless the type's contract says otherwise. ## Borrowing An immutable borrow uses &T: ~~~text fn inspect(value: &Point): i32 { return value.x + value.y } ~~~ A mutable borrow uses &T!: ~~~text fn update(value: &Point!) { value.x = 10 } ~~~ There may be several immutable borrows, or one exclusive mutable borrow, but the two kinds cannot conflict while they are live. The checker uses non-lexical lifetime reasoning, so an immutable borrow can end at its last use rather than at the end of the surrounding block. ## Partial moves Ownership is tracked at the field level for supported structs. Moving one non-Copy field does not automatically move every independent field: ~~~text struct Pair { public: name: string, age: i32, } let pair = Pair { name: "Alice", age: 30 } let name = pair.name use(pair.age) ~~~ The moved field cannot be read again. Copy fields can remain available when the surrounding type and access path permit it. ## References returned from functions A returned reference must be derived from data that outlives the returned reference: ~~~text fn longest(left: &string, right: &string): &string { if left.len() > right.len() { return left } return right } ~~~ Returning a reference to a local owned value is rejected because the local is destroyed when the function returns. ## Heap-owned values Box is an owning heap value. It is useful when a value needs indirection or a recursive data structure needs a stable allocation: ~~~text let boxed = Box.new(42) use(boxed) ~~~ Box does not bypass ownership. Moving, borrowing, and dropping a boxed value still follow the same rules. ## Low-level views Use the narrowest memory abstraction that expresses the operation: - &T and &T! for ordinary borrows; - `Span` for a non-owning contiguous view; - `Ptr` for typed pointer operations; - RawBuf for explicit raw storage. Keep raw memory and FFI code behind a small, tested boundary. See [FFI](docs/guide/ffi.md), [Pointers](docs/guide/advanced/pointers.md), and [Memory Safety](docs/guide/memory/safety.md). ## Practical rules 1. Borrow when the callee should not become the owner. 2. Move when ownership transfer is intentional. 3. Make mutation visible with let! and mutable references. 4. Use explicit types at FFI and ABI boundaries. 5. Check detached-task captures carefully; a go block cannot safely outlive a borrowed local. ## Next steps - [Ownership workflows](docs/guide/memory/ownership-workflows.md) — complete borrowed-parser and owned-report examples - [Borrowing](docs/guide/memory/borrowing.md) - [Lifetimes](docs/guide/memory/lifetimes.md) - [Memory Safety](docs/guide/memory/safety.md) - [VUMM](docs/guide/memory/vumm.md) --- Source: https://vex-lang.org/docs/guide/memory/pin.md # `Pin` — Move Prevention for Self-References `Pin` is a prelude marker contract used by the compiler to prevent moves that would invalidate self-references. It is not a `Pin` wrapper and it does not use a `$` sigil. ## Why pinning is needed A value becomes address-sensitive when one of its fields can point to the value itself or to storage whose address would change with the owner: ```vex struct Node { value: i32, next: Ptr, } ``` A pointer to the enclosing type can refer to the same allocation as its owner. Moving an object with such a self-address could leave the pointer at the old location. Detection is structural: the compiler conservatively marks this type as pinned; it does not inspect each pointer value to decide whether it currently points back to itself. ## The marker contract The prelude declaration has no methods: ```vex contract Pin {} ``` Pinning is a semantic capability, not an allocation strategy. It does not allocate, reference-count, or make raw pointers safe. ## Compiler detection The compiler analyzes structural patterns including: - a direct reference or pointer to the enclosing type; - tuples, arrays, and declared view/storage shapes containing such an address; - an explicit declaration of the canonical `Pin` contract. Detected types receive `Pin` move restrictions automatically. User code does not need to construct a wrapper or call a pinning function. Recursive ownership alone, such as a `Box` field, is not a self-address and does not imply pinning. Moving a string handle also does not relocate its heap buffer; ordinary borrow rules still decide whether views into it remain valid. ## What is restricted Once the compiler treats a value as pinned, operations that relocate ownership are rejected. Borrowing fields and calling methods in place remain valid. Dropping the value is valid when its ownership/lifetime rules permit it. Do not assume that copying a pointer makes the pointed-to object pinned. The guarantee is attached to the analyzed value/type and enforced by the ownership checker. ## Async frames An async frame can retain owned storage across suspension. A reference into that storage still requires both a live owner and a stable address; pinning supplies the address condition, not a longer lifetime. See the [suspension safety table](docs/guide/concurrency/async-internals.md#suspension-safety) for frame-owned data and escaping references. Use `await` or a documented implicit suspension operation when reasoning about where execution suspends. ## Practical guidance 1. Let compiler detection apply pin semantics. 2. Keep self-referential raw pointers rare and initialization tightly audited. 3. Do not place an already self-referential value into a relocating container. 4. Prefer indices, handles, or owned indirection when they avoid self-reference. 5. Treat a pinning diagnostic as an ownership/layout issue, not a request for a cast. ## Related - [Ownership](docs/guide/memory/ownership.md) - [Borrowing](docs/guide/memory/borrowing.md) - [VUMM](docs/guide/memory/vumm.md) - [Async](docs/guide/concurrency/async.md) - [Memory Safety](docs/guide/memory/safety.md) --- Source: https://vex-lang.org/docs/guide/memory/ptr-t.md # `Ptr` — Typed Raw Pointer `Ptr` is Vex's canonical typed raw-memory handle. It is represented directly as a target pointer—never as a wrapper aggregate—and provides element-based reads, writes, offsets, allocation, and FFI interop. It is a prelude type and needs no import. `Ptr` is not a safe smart pointer: it carries neither a length nor a lifetime. Prefer references, `Box`, or `Span` when they fit the job. Examples on this page are independent fragments. A later fragment that names `values` assumes a live, initialized allocation; it must run before that allocation is freed. ## Allocate and initialize ```vex let! value = Ptr.allocWith(42) unsafe { $println(value.read()) value.free() } ``` Allocation constructors are: | Constructor | Result | | --- | --- | | `Ptr.null()` | const-callable null typed pointer | | `Ptr.nullMut()` | const-callable null pointer with writable-pointee capability | | `Ptr.alloc()` | `Ptr` to one uninitialized `T` | | `Ptr.allocWith(value)` | `Ptr` to one initialized `T` | | `Ptr.allocN(count)` | `Ptr` to `count` uninitialized contiguous elements | An uninitialized allocation must be written before it is read. `Ptr.null` and `Ptr.nullMut` are ordinary Vex `const fn` declarations. They can run at runtime or inside `#const` without allocating; they do not require a special permission reserved for prelude functions. A user-defined const function returning `0 as Ptr` uses the same evaluation rules. A null handle does not authorize a read or write through that pointer. ```vex const fn emptyHandle(): Ptr { return 0 as Ptr; } let handle = #const { emptyHandle() }; // inferred as Ptr let writable = #const { Ptr.nullMut() }; // inferred as Ptr let opaque = #const { Ptr.null() }; // inferred as Ptr ``` Required evaluation preserves the result's pointer type and access mode when embedding it back into runtime code; the local binding needs no extra cast or type annotation. ## Reads and writes ```vex let! values = Ptr.allocN(3) unsafe { values.writeAt(0, 10) values.writeAt(1, 20) values.writeAt(2, 30) let second = values.readAt(1) $println(second) values.freeN(3) } ``` | Method | Unit | | --- | --- | | `read()` / `write(value)` | the pointed-to `T` | | `readAt(index)` / `writeAt(index, value)` | element index | | `refAt(index)` | borrowed element reference | The compiler cannot prove that an index is within the allocation. These operations are unsafe even though their element type is explicit. ## Element-based pointer arithmetic ```vex let third = unsafe { values.add(2) } let previous = unsafe { third.sub(1) } let signed = unsafe { third.offset(-2) } let distance = values.distanceTo(third as Ptr) // 2 elements ``` `add`, `sub`, and `offset` scale by `#Type.sizeOf()`. They never use byte units. Use `RawBuf` when the layout is naturally byte-oriented. ## Views and conversions | Method | Result | | --- | --- | | `asOpaque()` | `Ptr` with erased pointee type | | `addr()` | address as `usize` | | `asSpan(count)` | bounds-aware `Span` view | | `asSlice(count)` | native slice view for low-level/vectorized operations | | `asRef()` / `asMut()` | synthesized Vex reference | | `isNull()` / `isValid()` | null checks | | `isAligned(alignment)` | alignment check | Creating a reference, span, or slice from a raw pointer is unsafe: the caller must prove lifetime, extent, alignment, initialization, and aliasing. The borrow checker retains known subobject paths, so borrowing distinct fields through the same typed pointer does not automatically borrow the whole pointee. This precision does not prove the allocation's lifetime or make raw pointer aliases unique; those remain obligations at the unsafe boundary. A whole-pointee reference and a field reference through the same tracked address participate in the same conflict checks. Direct raw-pointer copies, pointer-to-pointer casts, and proven raw-to-reference call returns retain that address relation. Copying an address does not itself create a safe loan. The local variable holding the address and the pointee have distinct lifetimes: ending the former does not validate or invalidate the allocation, and borrowing the pointer variable itself is still an ordinary local borrow. These checks are not a complete raw-pointer alias analysis; unchecked addresses and opaque memory effects remain the unsafe caller's responsibility. To reinterpret the element type, cross an explicit opaque-pointer boundary: ```vex let bytes = value.asOpaque() as Ptr ``` ## Bulk operations | Method | Behavior | | --- | --- | | `copyFrom(src, count)` | copy `count` elements from `src` into `self` | | `copyTo(dst, count)` | copy `count` elements from `self` into `dst` | | `compare(other, count)` | compare `count` elements bytewise | | `writeBytes(value, count)` | fill `count` bytes | | `swap(other)` | swap the two pointed-to values | The `count` parameter is elements for copy/compare and bytes for `writeBytes`. That distinction should stay visible at call sites. Copy methods require non-overlapping ranges and accept raw pointer values, not references to pointer variables. Bytewise copying an owning value does not create a second valid owner; use typed ownership operations for values that require `Drop`. ## Deallocation - `free()` frees an allocation created for one `T`. It does not null the pointer or its copies; all aliases must be treated as dangling afterward. - `freeN(count)` frees the storage for an allocation created by `allocN(count)` and supplies the correct total byte size. These functions release raw storage; they do not iterate over live elements and invoke their destructors. Move out or destroy owning elements correctly before freeing their storage. Prefer `Vec` or `Box` for automatic cleanup. Call deallocation only on the original allocation pointer, never an offset pointer. Do not use it for foreign memory unless the foreign allocator is explicitly compatible with VexArch's allocator. ## Safety checklist Before every raw access, prove: 1. the pointer is non-null and correctly aligned; 2. the requested range lies within a live allocation; 3. reads observe initialized valid `T` values; 4. mutable access is exclusive for the operation's duration; 5. deallocation uses the original pointer, allocator, and size. ## Related - [`Span`](docs/guide/memory/span-t.md) - [RawBuf](docs/guide/memory/rawbuf.md) - [Memory Prelude](docs/guide/memory/mem-prelude.md) - [Pointers and Low-Level Memory](docs/guide/advanced/pointers.md) - [Unsafe](docs/guide/advanced/unsafe.md) --- Source: https://vex-lang.org/docs/guide/memory/rawbuf.md # RawBuf — Byte-Level Memory View `RawBuf` is VexArch's non-owning view over an opaque `Ptr`. Its offsets are bytes and its generic load/store methods make the value type explicit. It is a prelude API for standard-library internals, allocators, binary protocols, and audited FFI code. RawBuf carries no length, lifetime, or ownership. It centralizes pointer arithmetic but cannot validate an access. Its low-level accessors may not themselves require an `unsafe` block in the inspected prelude; the caller still must prove live allocation, range, initialization, and appropriate write authority. Converting raw storage into a span or reference has additional lifetime and alignment obligations. The snippets below are independent fragments. Navigation and access snippets assume a live allocation of at least 32 bytes, with every read region initialized; place them before deallocation when combining them. ## Basic use ```vex let size = 32 as usize let memory = Mem.alloc(size) let! buffer = RawBuf.of(memory) buffer.zero(size) buffer.store(0, 0x56455821) buffer.store(4, 1) let magic = buffer.load(0) let version = buffer.load(4) Mem.free(memory, size) ``` The inspected source defines a single `Ptr` field and carries no bounds metadata. Do not infer a portable ABI, fixed instruction count, or performance guarantee from this source shape. ## Construction and navigation | Method | Result | | --- | --- | | `RawBuf.of(p)` | view beginning at `p` | | `RawBuf.null()` | null view | | `at(offset)` | raw pointer at a signed or unsigned byte offset | | `advance(offset)` | new RawBuf at a byte offset | | `slice(offset)` | equivalent byte sub-view | | `addr()` | base address as `usize` | | `isNull()` | whether the base is null | ```vex let payload = buffer.advance(8) let fieldPointer = payload.at(4) ``` No navigation method checks allocation extent. ## Typed loads and stores ```vex let count = buffer.load(0) let timestamp = buffer.load(8) buffer.store(0, count + 1) buffer.store(8, timestamp) ``` `load(offset)` and `store(offset, value)` use byte offsets. `loadAt(index)` and `storeAt(index, value)` scale the index by `#Type.sizeOf()`. ```vex let second = buffer.loadAt(1) // byte offset 8 buffer.storeAt(2, 99) // byte offset 16 let reference = unsafe { buffer.refAt(2) } ``` The caller must prove alignment and that the memory contains a valid `T`. `refAt` additionally requires the backing memory to outlive the returned reference and obey reference aliasing rules. ## Bulk byte operations | Method | Behavior | | --- | --- | | `copyFrom(src, len)` | copy bytes from `src` into this buffer | | `copyTo(dst, len)` | copy bytes from this buffer into `dst` | | `copyFromBuf(src, len)` | copy bytes from another RawBuf | | `cmp(other, len)` | three-way byte comparison with a pointer | | `eq(other, len)` | byte equality with another RawBuf | | `fill(value, len)` | fill the base range | | `zero(len)` | zero the base range | | `zeroAt(offset, len)` | zero a range at an offset | The copy methods use non-overlapping copy semantics. Use `Mem.move` when the source and destination may overlap. RawBuf also provides `writeBytes` and `writeBytesAt` overloads for filling from a scalar byte value or copying from `Span` and native arrays. ## Typed views ```vex let words = unsafe { buffer.asSpan(4) } let native = unsafe { buffer.asSlice(4) } ``` Prefer `asSpan` for ordinary bounds-aware access. `asSlice` is the low-level bridge used by native slice/vectorized operations. Both constructors are unsafe because RawBuf cannot prove the count, lifetime, alignment, or element validity. ## RawBuf, Ptr, or Span? | Property | `RawBuf` | `Ptr` | `Span` | | --- | --- | --- | --- | | Offset unit | bytes | elements | elements | | Bounds stored | no | no | yes | | Element type stored | no | yes | yes | | Owns allocation | no | no | no | | Best use | mixed binary layout | homogeneous typed raw memory | bounded borrowed view | Owned collections and `Box` should remain the default for application code. ## Compiler boundary RawBuf is the public prelude layer over compiler-owned memory primitives. Those primitives are deliberately inaccessible to normal source code. Extend RawBuf or another typed prelude abstraction when a reusable low-level operation is missing; do not expose the compiler primitive at each call site. ## Safety checklist 1. Track the allocation base and total byte length outside RawBuf. 2. Check every offset plus access size for overflow and bounds. 3. Respect `T` alignment, initialization, and validity requirements. 4. Do not retain references beyond the backing allocation's lifetime. 5. Pair allocation and deallocation through the same allocator. ## Related - [`Ptr`](docs/guide/memory/ptr-t.md) - [`Span`](docs/guide/memory/span-t.md) - [Memory Prelude](docs/guide/memory/mem-prelude.md) - [Ownership](docs/guide/memory/ownership.md) - [Unsafe](docs/guide/advanced/unsafe.md) --- Source: https://vex-lang.org/docs/guide/memory/safety.md # Memory Safety Layers `Box`, `Span`, and `Ptr` serve different roles: owned storage, a non-owning bounded view, and a raw typed address. Their types alone do not establish all lifetime, exclusivity, FFI, or target-specific requirements. Prefer an owned value or a view tied to a live owner for ordinary code; use raw pointers at a small, explicitly unsafe boundary. | Type | Ownership and access | Essential boundary | | --- | --- | --- | | `Box` | Owning heap-value surface | Follow move and borrowing rules; do not assume a particular internal strategy or zero overhead. | | `Span` | Non-owning pointer and element count | Bounds-checked `get` does not prove the backing storage is still alive or initialized. | | `Ptr` | Read-capable raw address | Reading requires a live, aligned, initialized pointee and an unsafe context. | | `Ptr` | Raw address with writable-pointee capability | Writes additionally require valid writable storage and appropriate exclusive access. A `let!` binding alone does not confer this capability. | ## Raw Allocation Example This complete example allocates three `i32` elements, initializes every element, makes a read-only span while the allocation remains live, then frees the original allocation exactly once. `fill` is itself `unsafe`: the caller must provide a live, aligned, writable range of at least `count` elements with exclusive write access. The raw span conversion must be justified separately. ```vex [raw-span.vx] unsafe fn fill(p: Ptr, count: usize): i32 { let! i: usize = 0; while i < count { p.writeAt(i, (i as i32) + 10); i = i + 1; } return 0; } fn main(): i32 { let p = Ptr.allocN(3); unsafe { fill(p, 3); } let view = unsafe { Span.of(p as Ptr, 3) }; let value = match view.get(1) { Some(item) => *item, None => -1, }; let out_of_bounds = view.get(3).isNone(); unsafe { p.freeN(3); } if value != 11 || !out_of_bounds { return 1; } $println(value); return 0; } ``` The program prints `11` and exits 0. The span is not used after `freeN(3)`. Do not generalize this fixture to foreign allocators: free an allocation only with its matching allocator, original pointer, and correct size. Raw pointer access and deallocation need their required unsafe context even if the pointer is non-null. ## A Rejected Read The following is a **negative** example: on that same local binary, `vex lint` reports `E0133` for `p.read()` outside an unsafe context. ```vex [raw-read-rejected.vx] fn main(): i32 { let p = Ptr.allocWith(42); let value = p.read(); unsafe { p.free(); } return value; } ``` A second **negative** example attempts a write through a read-capability pointer. The same local binary reports `E0308` for the unavailable `write` method, even inside `unsafe`: ```vex [readonly-write-rejected.vx] fn main(): i32 { let p: Ptr = Ptr.allocWith(42); unsafe { p.write(7); } return 0; } ``` `unsafe` permits operations whose preconditions the caller must prove; it does not grant writable-pointee capability. A null check can reject a null address; it cannot prove a non-null pointer is allocated, aligned, initialized, in bounds, live, or unaliased. A dangling non-null pointer remains invalid. Likewise, wrapping an arbitrary address in a normal function does not make the function safe: its API must either establish those facts or expose an unsafe contract to its caller. ## More Reading - [Span](docs/guide/memory/span-t.md) — non-owning views and raw construction obligations - [Typed pointers](docs/guide/memory/ptr-t.md) — operations and deallocation - [Unsafe](docs/guide/advanced/unsafe.md) — unsafe boundaries - [FFI native example](docs/guide/ffi-first-native.md) — `.vxc` boundary and cleanup - [Ownership](docs/guide/memory/ownership.md) --- Source: https://vex-lang.org/docs/guide/memory/span-t.md # Span\ `Span` is a non-owning view of contiguous elements. It carries a pointer and length; it does not allocate or keep its owner alive. The caller must ensure that backing storage stays valid and appropriately borrowed for every use. ## A View of Owned Storage This complete example obtains a view from a live `Vec`, gets a borrowed element, and checks the out-of-bounds case: ```vex [span-owned.vx] fn main(): i32 { let! values = Vec.new(); values.push(10); values.push(20); values.push(30); let view = values.asSpan(); let middle = view.slice(1, 3); let value = match middle.get(0) { Some(item) => *item, None => { return 1; }, }; if value != 20 || middle.len() != 2 || view.get(3).isSome() { return 2; } $println(value); $println(middle.len()); return 0; } ``` Expected stdout is `20` followed by `2`, with exit status 0. Do not mutate, reallocate, or free backing storage while a view or reference requires it. A raw pointer does not carry this lifetime proof; preserve it explicitly when constructing a raw-backed view. ## Creating a View from Raw Storage `Span.of(p, len)`, `Span.ofPtr`, and `Span.ofVec` are `unsafe` constructors in the prelude. The latter name still takes a raw pointer and length; it does not prove that the pointer belongs to a live `Vec`. A raw view requires a correctly aligned, live range of `len` initialized valid elements and compatible aliasing for its entire use. A non-null pointer alone does not prove any of these conditions. See the [raw memory example](docs/guide/memory/safety.md#raw-allocation-example). `Span.empty()` constructs an empty view. Empty ranges do not authorize dereference. ## Access and Mutation - `get(index)` bounds-checks and returns `Option<&T>`; `first`, `last`, and `find` also return borrowed values in the inspected source. - `getUnchecked(index)` has no bounds check. Although its declaration is not marked `unsafe` in that source, calling it out of bounds violates its precondition. Use `get` when the index is not already proven in range. - Indexing checks bounds and panics on an invalid index in the inspected implementation. `slice(start, end)` clamps bounds; `take`, `skip`, and `splitAt` construct views, not owned copies. - `fill`, `copyFromSpan`, `swap`, and `reverse` are unsafe mutations. A mutable binding for a copyable span does not establish exclusive write authority over its backing memory; the caller must prove it. - `asPtr` and `toPtr` expose the address. A raw address does not carry a lifetime. `toVec` copies via the source's `Clone` bound; verify concrete type support. The method contracts follow `lib/runtime/VexArch/src/prelude/span.vxc`. Bounds checks do not validate a dangling or incorrectly constructed view. ## Choosing a view operation | Need | Method and result | | --- | --- | | Optional element | `get(i): Option<&T>` | | First/last element | `first()` / `last(): Option<&T>` | | Up to `n` elements | `take(n): Span` | | Exactly `n` leading/trailing elements | `first(n)` / `last(n): Option>`; `None` when `n > len` | | Remaining suffix | `skip(n): Span`; empty when `n >= len` | | Interval `[start, end)` | `slice(start, end): Span`; both bounds clamp to `len`, reversed bounds give an empty view | | Two views | `splitAt(i): SpanPair` with `.first` and `.second`; the second is empty when `i >= len` | | Independent owned sequence | `toVec()` / `collect(): Vec` where `T: Clone` | The distinction between `take(n)` and `first(n)` is useful for parsers: `take` accepts a short remainder, while `first(n)` can express an exact-length requirement. Neither copies the source elements. `getOr(i, fallback)` returns an owned clone of a present element and requires `T: Clone`; out of bounds, it returns the supplied fallback. This is different from the shallow-copy accessors on `Vec`. ## Iteration, search, and owned transforms `iter().next()` yields `Option<&T>`. `find` accepts `fn(&T): bool` and returns the first borrowed match. The source allocation must remain alive throughout the iterator and every retained item reference. `map(fn(&T): U)` creates a new `Vec`. `filter(fn(&T): bool)` creates a new `Vec` by cloning retained elements and therefore requires `T: Clone`. A callback seeing a borrowed element cannot transfer that element out of the source. Repeated reads do not consume a span's elements. `chunks(size)` yields consecutive non-overlapping subviews, including a final short chunk. `windows(size)` yields overlapping full-size windows. Both reject size zero with a panic. These iterators copy view descriptors, not backing elements; overlapping windows do not provide independent write access. ## Mutating a raw-backed view A mutable `Span` binding permits changes to the descriptor but is not proof of exclusive ownership of the memory it points at. Its mutation methods therefore require an unsafe caller contract. Prefer the owning collection's checked mutable accessor when it can express the operation. - `copyFromSpan` copies the shorter length, requires `T: Copy`, and permits overlap through memmove semantics. - `fill` clones its replacement for each element and drops each old element; it requires `T: Clone` and already initialized destination elements. - `swap` checks both indices and transfers values without cloning them; `reverse`, `sort`, and `sortDesc` likewise require exclusive access to the backing range, with sorting additionally requiring `T: Ord`. Creating additional copies of a span never strengthens these permissions. ## More Reading - [Ownership workflows](docs/guide/memory/ownership-workflows.md) — complete borrowed-parser and owned-report examples - [Memory safety and raw allocation](docs/guide/memory/safety.md) - [Typed pointers](docs/guide/memory/ptr-t.md) - [Ownership](docs/guide/memory/ownership.md) --- Source: https://vex-lang.org/docs/guide/memory/vumm.md # VUMM Memory Model VUMM is Vex's compiler-managed ownership and allocation machinery. Application code expresses values, borrows, moves, and managed sharing; the compiler selects cleanup and storage strategies from their lifetimes and escape paths. The public ownership rules remain the starting point. A representation chosen by an optimizer is not an additional permission to access a value. ## One owning surface, several implementation strategies `Box` is the public heap-value handle. Applications do not select a separate `Rc` or `Arc` wrapper to request local or cross-task ownership bookkeeping. ```vex fn main(): i32 { let answer = Box.new(42); $println(*answer.getRef()); return 0; } ``` Expected stdout is `42`, exit status 0. This simple program does not establish which allocation or reference-count operations survive optimization. The compiler distinguishes unique, locally shared, and concurrently shared ownership. These are internal strategies, not user-defined variants of the `Box` type: | Situation | User-visible ownership contract | Cost to assess | | --- | --- | --- | | One live owning handle | Moves transfer the handle; exclusive access still obeys borrow rules. | Allocation, cleanup, and whether an allocation can be eliminated or placed in an arena. | | Multiple local handles | A box clone shares the payload. Shared handles keep it alive; ordinary mutable payload access is refused while sharing remains. | Retain/release operations and any compiler-proven elimination of them. | | Ownership crossing a task boundary | The compiler arranges the managed ownership needed by supported captures. Referenced external data must also satisfy capture/lifetime rules. | Concurrent ownership bookkeeping, task transport, and application synchronization. | Thread-safe ownership bookkeeping does not make arbitrary mutation of `T` thread-safe. A `go` capture is not a blanket escape from lifetime checking and is not evidence that all nested types or foreign resources can cross tasks. Read the [concurrency guide](docs/guide/concurrency/overview.md) for the capture model. ## Moves, copies, and clones - **Move:** transfers an owning value. The previous binding cannot continue to use a value that has been moved away. - **Copy:** duplicates a value admitted by the type's copy rules. Declaring a marker cannot make an owning payload safely bitwise-copyable. - **Clone:** follows the specific type's API. `Box.clone()` shares its payload; other containers may clone their elements or construct independent storage. - **Drop:** releases ownership and performs the type's cleanup. For a shared box, releasing one handle preserves the payload for the remaining owners. Do not infer that every `clone()` in Vex is a reference-count increment or a deep copy. The receiver type determines the operation. The [Box reference](docs/guide/memory/box.md) describes shared mutation checks, taking a payload, and empty handles. ## Borrowing is separate from ownership bookkeeping A reference or `Span` view does not add an owning handle. Its owner must remain alive, and operations that invalidate its storage are forbidden while the view is live. Allocating an object on the heap does not automatically extend every reference derived from it. For example, growing a vector may relocate its elements even when the vector itself is stored in a box. Keeping the box alive alone is not a proof that an earlier pointer or span into that vector is still valid. Prefer APIs whose borrows express the relationship and keep raw-address operations inside a small unsafe boundary. ## Cleanup and generic containers The compiler specializes cleanup for concrete payload types. A container must release its own allocation and arrange cleanup of the initialized elements it owns; borrowed views must not destroy their source. Moving a field or taking a box payload transfers that cleanup responsibility to the destination. Normal scope cleanup, panic/unwind behavior, and process termination are different execution paths. Use the resource API's explicit close or commit operation when the program needs to observe a cleanup error. Automatic destruction handles owned storage; it is not a transaction or a promise of recovery after process termination. ## Allocation and accelerator boundaries Allocation strategy can depend on escape analysis, payload properties, optimization settings, runtime configuration, and the target. Arena, heap, local-sharing, and concurrent-sharing mechanisms should be understood as implementation choices. There is no general zero-allocation or zero-overhead promise for an owning type. Host/GPU buffer transport has additional alignment, lifetime, synchronization, and backend requirements. Shared physical memory does not remove those requirements or guarantee that every transfer avoids a copy. Use the [SIMD/SIMT contract](docs/guide/simd/simd-simt-contract.md) for that boundary rather than deriving device behavior from `Box`. ## Inspecting an ownership decision The CLI exposes the boxing explanation on the analysis command: ```sh vex lint example.vx --explain-boxing ``` Use this report to understand the compiler's analysis of that input. `lint` does not execute the program or measure allocation cost. For a performance claim, retain the compiler identity, target, build options, generated artifact, and measurements of the actual workload. ## Next steps - [Ownership](docs/guide/memory/ownership.md) - [Borrowing](docs/guide/memory/borrowing.md) - [Box method contracts](docs/guide/memory/box.md) - [Lifetimes](docs/guide/memory/lifetimes.md) - [Verification evidence](docs/guide/verification-evidence.md) --- Source: https://vex-lang.org/docs/guide/modules.md # Modules and Imports Vex uses explicit `import` and `export` forms. Files act as modules, and public API is declared rather than implied. For a complete working example with a project tree, relative import, and test, start with [Your first project](docs/guide/first-project.md). The shorter snippets below demonstrate import/export forms; local module names assume the matching files and declarations exist in your project. ## Import Forms ### Named imports ```vex import { App } from "cli/app"; import { Command } from "cli/command"; ``` This is the most direct form when you only need a few symbols. ### Namespace imports ```vex import * as style from "cli/style"; ``` Namespace imports are useful when the imported module has many entry points and you want calls to stay visibly grouped. ### Relative imports ```vex import { User } from "./user.vx"; ``` Relative paths are common inside package internals and library layout code. ## Export Forms Everything is private unless exported. ### Exporting declarations ```vex export struct Logger { level: i32, } export fn newLogger(level: i32): Logger { return Logger { level }; } ``` ### Exporting methods ```vex export fn (self: &Logger) getLevel(): i32 { return self.level; } ``` ### Re-exporting Re-exports are heavily used to build facade modules: ```vex export { Regex, Match, test } from "./regex.vx"; export { pid, ppid, exit } from "./process.vx"; ``` This pattern is common in package `lib.vx` files that gather several internal modules into one public surface. A private import used inside a module is not a re-export: callers should import from the owning module or from a facade that explicitly exports the symbol. ## File-Based Module Model Each `.vx` file acts as a module. ```text src/ main.vx user.vx service/ auth.vx ``` Typical imports then look like: - package-style: `import { App } from "cli/app";` - relative: `import { User } from "./user.vx";` ## Public API Design Keep implementation details private and export only the surface another module should rely on. Good candidates for export: - stable structs and enums - constructors and factory functions - high-level helper functions - facade re-exports from a package root Less ideal candidates: - internal helpers - temporary glue functions - implementation-specific wiring code ## Common Patterns ### Package facade ```vex export { File } from "./file.vx"; export { readFile, writeFile } from "./convenience.vx"; ``` ### Mixed import style ```vex import { App, Command } from "cli"; import * as style from "cli/style"; ``` ## Guidelines 1. Prefer named imports for a narrow dependency surface. 2. Use namespace imports when the module name adds clarity at each call site. 3. Re-export from one facade file when you want consumers to have a stable entry point. 4. Keep internal file layout flexible by exporting a clean public package surface. ## Next Steps - [Standard Library Overview](docs/guide/stdlib.md) - [FFI](docs/guide/ffi.md) - [Functions](docs/guide/basics/functions.md) --- Source: https://vex-lang.org/docs/guide/platform-support.md # Platform Support Platform support has two separate dimensions: whether the compiler can check a program for a target, and whether the bundled runtime, linker, native I/O, and optional backends can build and run there. Do not treat a target triple or a successful source check as proof of full runtime support. ## Current support matrix | Platform | Current documentation status | Notes | | --- | --- | --- | | macOS ARM64 | Primary development platform | Local fused compile/run and the representative native comptime corpus are characterized; release certification still requires a retained clean-host artifact. | | macOS x86_64 | Outside the current release package matrix | The current compiler release lane targets Apple Silicon; do not use the ARM64 package as an Intel support claim. | | Linux x86_64 / ARM64 | Experimental | Structural target checks and release lanes exist; retain green native artifacts on each exact release host before promoting support. | | FreeBSD | Experimental | Not validated in this documentation pass. | | Windows | Experimental | Toolchain and runtime integration are not validated in this documentation pass. | | WASM | Experimental | Limited compiler and library surface; do not assume native-runtime parity. | | iOS and other Apple targets | Planned or experimental | A target entry alone does not provide a supported runtime port. | ## Building from source The most reliable workflow is to build the compiler from the repository and check a small program first: ~~~bash cargo build --release -p vex-cli --target-dir target target/release/vex --version target/release/vex lint examples/01_basics/hello_world.vx ~~~ The exact native dependencies depend on the compiler checkout and host platform. Follow the repository build instructions and record the toolchain versions when reporting a failure. ## Fusion and native-link boundary `vex lint` validates source semantics but does not execute LLVM object emission, native linking, or the produced program. `vex compile` and `vex run` rehydrate target-selected VexArch sources from the compiler's embedded VRI; they do not rebuild or link a separate runtime artifact. Platform certification must still exercise the requested target's native support pack, linker, system ABI and execution path. ## Reporting platform results Include: - operating-system version and architecture; - compiler version and repository revision; - Rust, LLVM, linker, and C toolchain versions where relevant; - the exact `vex lint`, `vex compile`, or `vex run` command; - whether the failure occurred during source checking, VRI target selection, fused codegen, native linking, or execution. Platform claims should be updated only after the relevant path has been tested on that platform. --- Source: https://vex-lang.org/docs/guide/simd/dynamic-tensors.md # Dynamic Tensors and Masks Use `Tensor` for an owning sequence whose length is known at runtime, and `Tensor` when the length is part of the type. A dynamic `Mask` represents one boolean decision per runtime lane; `Mask` fixes that lane count in the type. Choosing a dynamic tensor does not itself request GPU execution. ## Constructing a Dynamic Tensor The dynamic fill form takes the **element count first**, then the value: ```vex [tensor-fill.vx] fn main(): i32 { let! values = Tensor.fill(4, 7); values[1] = 11; let empty = Tensor.fill(0, 0); if values.len() != 4 || values[0] != 7 || values[1] != 11 { return 1; } if empty.len() != 0 { return 2; } $println(values[1]); $println(empty.len()); return 0; } ``` Save this as `tensor-fill.vx` and run `VEX_NO_GPU=1 vex run tensor-fill.vx`. Expected output is `11` followed by `0`, with exit status 0. An empty tensor has no valid index; constructing it does not authorize reading `empty[0]`. `Tensor.fill(count, value)` is different from the fixed-size `Tensor.fill(value)` form. Do not pass a shape vector where an element count is expected. The old `Tensor.filled(value, count)` recipe is not the constructor taught by this guide. ## Ownership and Copies A dynamic tensor owns its backing allocation. A `Span` is a borrowed view: | Operation | Ownership meaning | | --- | --- | | `tensor.clone()` | Independent dynamic storage; modifying the clone does not modify its source. | | `tensor as Span` | A borrowed view tied to the tensor owner's lifetime. | | `span as Tensor` / `span.toTensor()` | An owned materialization, with allocation/copy cost. | | Fixed tensor to span | Scoped addressable storage; the view must not escape its owner/frame. | Do not infer interchangeability from a similar pointer/length layout. An owning tensor fabricated from borrowed storage would introduce invalid cleanup and lifetime behavior. Keep the conversion explicit in a performance-sensitive path and measure its cost. ## Indexed Reads and Updates `gather(indices)` returns elements in index order. `scatter(indices, updates)` returns an independently owned result with those positions changed; it does **not** mutate the source. Retain the returned value: ```vex [tensor-scatter.vx] fn main(): i32 { let source = Tensor.fill(4, 7); let! indices = Tensor.fill(2, 0); indices[0] = 1; indices[1] = 3; let updates = Tensor.fill(2, 11); let changed = source.scatter(indices, updates); let selected = changed.gather(indices); if source[1] != 7 || source[3] != 7 { return 1; } if changed[0] != 7 || changed[1] != 11 || changed[3] != 11 { return 2; } if selected.len() != 2 || selected[0] != 11 || selected[1] != 11 { return 3; } $println(source[1]); $println(changed[1]); $println(selected.len()); return 0; } ``` Expected output is `7`, `11`, `2`, each on a separate line. Use integer index values within the source extent, and provide one update per selected position. Negative, too-wide and past-end indices are not valid accesses. Repeated indices need a deliberate conflict rule; combining forms such as `scatter_add` are separate operations. Do not infer atomic access to shared application state from the word “scatter”. ## Dynamic Masks A comparison such as `values > 0` produces a boolean decision for each lane. Combine compatible masks with `&`, `|` and `!`; use `any()`, `all()` or `countBits()` when a scalar decision is required. Selection and compaction solve different problems: - `mask.select(whenTrue, whenFalse)` chooses a value per lane and preserves the output extent. - compaction keeps selected values and changes the output extent. Selection is not short-circuit control flow. Do not evaluate a division by zero or an invalid memory read and expect a later mask to undo it. For a guarded calculation, make every evaluated lane valid or use a supported control-flow form with the required semantics. ## Shapes and Reductions A dynamic tensor's flat element count does not by itself describe matrix axes. A reshape or matrix operation must carry compatible shape information through the supported lowering path. `24` elements could represent `4 × 6`, `2 × 3 × 4` or a vector; the choice is part of the algorithm, not a property inferred from the allocation size. For a mean, handle zero length before dividing by the count. Floating-point reductions can have backend-dependent accumulation order. Choose and test a numerical tolerance appropriate to the application. ## GPU Integration Dynamic tensors can participate in supported SIR graphs. They still need a compatible generator, runtime bridge and device. Begin with [Graph Functions](docs/guide/fusion/graph.md), then validate the exact dynamic operation and shape on the chosen target. A CPU-only test of the examples above does not qualify GPU execution. ## Memory Layout The current host compiler uses internal pointer/length aggregates for dynamic tensors and packed storage for dynamic masks. Those are implementation details, not C ABI declarations. See [Tensor and Mask Types](docs/guide/simd/tensor-mask.md) and the [mask representation contract](docs/guide/simd/simd-simt-contract.md#dynamic-mask-representation-in-the-development-implementation). ## Related Pages - [SIMD Operations](docs/guide/simd/simd-operations.md) - [Tensor and Mask Types](docs/guide/simd/tensor-mask.md) - [Span](docs/guide/memory/span-t.md) - [GPU Programming](docs/guide/gpu/index.md) --- Source: https://vex-lang.org/docs/guide/simd/index.md # SIMD and Auto-Vectorization Vex has two related, but different, execution stories: - small fixed-size arrays can be lowered directly to LLVM vector instructions - tensor and graph workloads can flow through SIR, which has its own SIMD backend The important constraint is that vectorization is not a blanket guarantee for every array expression. Some patterns inline cleanly, some lower to vector-loop kernels, and some belong on the `graph fn` and `Tensor` path instead. To keep behavior stable across CPU and GPU, all these routes are expected to follow the same `SIMD/SIMT` contract described in [SIMD/SIMT Unified Execution Contract](docs/guide/simd/simd-simt-contract.md). See also: - [Tensor and Mask Types](docs/guide/simd/tensor-mask.md) - [SIR Optimization Pipeline](docs/guide/simd/sir-pipeline.md) - [SIMD/SIMT Unified Execution Contract](docs/guide/simd/simd-simt-contract.md) ## The practical model Use ordinary arrays when you want straightforward element-wise code: ```vex fn add4(a: [i32; 4], b: [i32; 4]): [i32; 4] { return a + b } fn dot8(a: [f32; 8], b: [f32; 8]): f32 { return <+ (a * b) } ``` For small static arrays, the compiler can lower these operations to direct vector IR. Inline eligibility uses a nonzero power-of-two lane count, at most 64 lanes and at most 64 bytes. A vector IR value may still need multiple physical instructions. When data is dynamic, graph-shaped, or needs tensor-specific routing, use the `graph fn` and `Tensor` path instead: ```vex graph fn squared(x: Tensor): Tensor { return x * x } ``` ## Implemented Paths The source has dedicated lowering paths for: - inline SIMD for small static arrays in compiler codegen - vector comparisons and reductions for qualifying fixed-size arrays - SIR SIMD backends for tensor and graph workloads - mask operations in SIR such as `any`, `all`, `countBits`, `firstSet`, and `select` ## What should be read conservatively Treat these areas as advanced or still moving: - generic tensor arithmetic like `Tensor * Tensor` across arbitrary `T` - broader generic element-converting Tensor casts beyond the exact ownership/view rules documented in the Tensor guide - assuming every dynamic array expression will become a single SIMD instruction - assuming every matrix or signal-processing operator is equally mature on every backend ## Cross-backend contract at a glance The `simd-simt-contract` page is the canonical place for “does this API mean the same thing on CPU SIMD and GPU SIMT” questions. Choose source-level operators and masks first; avoid writing backend-dependent branching in user code. ## Small-array path The fixed-array lowering recognizes these operation families: - element-wise arithmetic such as `+`, `-`, `*`, `/` - comparisons such as `==`, `!=`, `<`, `>` - reductions such as `<+`, `<*`, `?|` Example: ```vex fn energy4(x: [f32; 4]): f32 { return <+ (x * x) } ``` This is the part of the SIMD story backed by `crates/vex-compiler/src/codegen_hir/expr/simd_small`. ## Tensor and graph path When code is naturally tensor-oriented, prefer `graph fn` plus concrete tensor types such as `Tensor`. That path lowers through SIR and then routes to CPU SIMD, GPU, or other backends based on shape and backend support. It is more powerful than the small-array fast path, but it is also where current limitations show up first. ## Choosing the right abstraction Use fixed arrays when: - the shape is small and known at compile time - the code is mostly arithmetic, comparison, or reduction - you want predictable LLVM-level vectorization Use `Tensor` and `graph fn` when: - the data shape is dynamic - the computation is already graph-like - you want SIR routing and backend dispatch ## Verification When SIMD behavior matters, inspect the generated LLVM or backend output instead of assuming fusion happened: ```bash vex compile --emit-llvm file.vx ``` Good signs for the small-array path are direct vector operations and vector reductions. For graph and tensor code, the more relevant check is whether the code lowered into the expected SIR/backend route. Explicit loops remain useful for irregular access or a required accumulation order. A floating-point reduction can reassociate additions; a sequential loop and a parallel reduction need not produce identical low bits. Choose the numerical contract first, then inspect the chosen implementation. ## SIMD Operator Reference | Operator | Description | Example | |----------|-------------|---------| | `<+` | Sum reduction | `<+ [1,2,3]` → `6` | | `<*` | Product reduction | `<* [1,2,3]` → `6` | | `?\|` | Max reduction | `>?\| [3,1,2]` → `3` | | `<&` | AND reduction | `<& [t,t,f]` → `false` | | `<\|>` | OR reduction | `<\|> [t,f,f]` → `true` | | `?` | Element-wise max | `[1,5] >? [3,2]` → `[3,5]` | | `><` | Clamp | `[1,5] >< (2,4)` → `[2,4]` | | `+\|` | Saturating add | `250u8 +\| 10u8` → `255` | | `-\|` | Saturating sub | `5u8 -\| 10u8` → `0` | | `<<<` | Rotate left | `x <<< 1` | | `>>>` | Rotate right | `x >>> 1` | | `<*>` | Matrix multiply | `a <*> b` | | `'` | Transpose | `matrix'` | ## Next Steps - [GPU Programming](docs/guide/gpu/index.md) - Massively parallel compute - [FFI](docs/guide/ffi.md) - Integrating with native libraries - [Memory Management](docs/guide/memory/ownership.md) - Efficient data handling --- Source: https://vex-lang.org/docs/guide/simd/simd-operations.md # SIMD Operations Array and tensor operations express work over multiple elements. LLVM and SIR then choose supported scalar, vector or device paths. Keep three questions separate: what the source expression means, what IR was produced, and which machine instructions execute on the selected target. ## SIMD Model ### Auto-Vectorization Threshold The inline-SIMD eligibility rule requires a nonzero power-of-two lane count, at most 64 lanes and at most 64 bytes in total. Eligible operations can use LLVM vectors; other shapes use different lowering paths. The rule is an implementation threshold, not a language limit or an instruction-count promise. A 64-byte value spans four 128-bit registers on a target using that register width. An expression such as addition on `[f32; 8]` can appear as an LLVM `fadd <8 x float>`. LLVM may split it, scalarize it or use a native vector instruction according to target capabilities. Loading and storing values add work beyond the arithmetic itself. ## Element-Wise Arithmetic and Masks This complete example adds four lanes and counts the lanes above a threshold: ```vex [simd-lanes.vx] fn main(): i32 { let a: [i32; 4] = [1, 2, 3, 4]; let b: [i32; 4] = [4, 3, 2, 1]; let sum = a + b; let selected = a > 2; if sum[0] != 5 || sum[3] != 5 { return 1; } if selected.countBits() != 2 { return 2; } $println(sum[0]); $println(selected.countBits()); return 0; } ``` Save as `simd-lanes.vx` and run `VEX_NO_GPU=1 vex run simd-lanes.vx`. Expected stdout is `5` then `2`, each on its own line, with exit status 0. The test establishes values for these lanes; it does not assert a particular SIMD instruction or GPU route. ## Scalar Broadcast A supported scalar/sequence operation applies the scalar to each lane. Keep the element type explicit when its width or precision matters: ```vex let values: [f32; 4] = [1.0, 2.0, 3.0, 4.0]; let doubled = values * 2.0f32; ``` Broadcasting one scalar is distinct from combining sequences of different lengths. State the required shape relationship in reusable APIs instead of assuming that an arbitrary tensor library's broadcasting rules apply. ## SIMD Comparison and Masks Comparisons produce lane decisions. Combine compatible masks with `&`, `|` and `!`, then use `any()`, `all()` or `countBits()` to obtain a scalar result. `mask.select(left, right)` chooses by lane; it does not make invalid arguments safe by suppressing their earlier evaluation. ### Mask-to-Bitmask Conversion Packed integers are useful at a narrow boundary, but their bit width is finite. A runtime mask can contain more lanes than one integer word. Use the documented windowed operation when necessary and preserve the logical length. See [Tensor and Mask Types](docs/guide/simd/tensor-mask.md) for the distinction between static masks, packed host masks and GPU lane transport. ## Saturating Arithmetic `+|`, `-|` and `*|` express saturating operations for supported integer operands. For example, adding `200` and `100` in `u8` saturates at `255`; normal wrapping arithmetic would instead yield `44`. Pick saturation because clipping is part of the data contract, such as bounded channel intensity. It can hide an error when overflow should instead reject a calculation. ## Min/Max Operations `a ? b` express element-wise minimum and maximum. Integer order and floating-point exceptional-value rules are different concerns. If NaN or signed zero is possible, test the relevant dtype/backend behavior rather than assuming a mathematical total order. ## Fused Multiply-Add (FMA) A mathematical fused multiply-add computes a product and sum with one final rounding. The expression `a * b + c` does not alone prove that the generated program uses that numerical rule or one hardware instruction. SIR has a ternary FMA operation, while source parsing and optimization decide how an expression reaches it. In particular, the two-operand spelling `a *+ b` is not evidence that a following `+ c` is fused. When the rounding distinction matters, inspect the generated operation and compare inputs chosen to distinguish fused from separate evaluation. Measure performance on the actual target; fused operations are not universally faster for every workload or available for every dtype. ## Carry-less Multiply (CLMUL) Carry-less multiplication combines bit-polynomials using XOR rather than integer carry propagation. It is a building block in some CRC and finite-field algorithms. A product alone is **not** a CRC: a CRC definition also specifies the reduction polynomial, bit order, initial state and final transformation. Use a maintained checksum or cryptographic API when that complete operation is required. The [crypto guide](docs/guide/crypto.md) describes those higher-level boundaries. ## Bit Rotation Rotation moves bits cyclically within the operand width: ```vex let x: u8 = 0b1000_0001; let left = x <<< 1; // 0b0000_0011 let right = x >>> 1; // 0b1100_0000 ``` State the width explicitly in bit-level protocols. A rotation of `u8` and one of `u32` operate on different rings of bits even for the same numeric input. ## Horizontal Reductions Reductions combine lanes into a scalar. For example, the source spelling `<+ values` sums a fixed array in the inline path: ```vex fn sum4(values: [i32; 4]): i32 { return <+ values; } ``` A floating-point reduction is sensitive to accumulation order. Define empty input behavior and, for averages, reject or separately handle zero length before dividing by the count. Use a reference implementation to establish correctness before comparing CPU and GPU timing. ## Matrix Operations Matrix multiplication needs an explicit relationship between dimensions: `M × K` multiplied by `K × N` produces `M × N`. A flat array of four elements does not by itself establish that it represents a `2 × 2` matrix. The compiler has shape-aware paths for supported fixed rank-two operations and SIR matrix nodes, but element type and backend support vary. Do not infer that recognizing `<*>`, `<^>` or `<\>` means every matrix product, power or solve can execute on every backend. A linear solve also needs a policy for singular or ill-conditioned input. For a complete algorithm reference with rectangular dimensions and tail handling, see [Graph Functions and GPU Execution](docs/guide/gpu/graph-functions.md). That sequential reference is useful for checking a device implementation; it is not a manually launched Vex kernel. ## SIMD Math Intrinsics The `Math` namespace provides math operations with supported lifted forms. Math intrinsics are IR-level operations, not cycle-count guarantees. A transcendental operation can become a library call or a sequence of instructions. Decimal approximations to π also do not yield exact zeros from trigonometric functions. Specify a tolerance when checking results. ## Gather and Scatter `gather(indices)` produces a sequence in the requested index order. `scatter(indices, updates)` returns a new result and leaves its source unchanged. Ignoring that result does not update the source tensor. The complete [indexed tensor example](docs/guide/simd/dynamic-tensors.md#indexed-reads-and-updates) checks both the result and the unchanged source. Use integer indices within bounds and matching update extents. The combining operations are spelled `scatter_add`, `scatter_mul`, `scatter_min` and `scatter_max`; duplicate-index and floating-point ordering behavior need operation-specific validation. These operations do not authorize unsynchronized application-level sharing. ## SIMD Backend Configuration SIMD width and target-feature selection belong to compiler/backend configuration. An internal `SimdBackend` struct is not a Vex source-level configuration object. Wider vectors can increase register pressure and do not automatically improve throughput. Use the CLI options documented by the selected compiler and inspect the result for the deployment target. ## Practical Workflow 1. Define element type, shape, empty input and error behavior. 2. Keep an independently understandable scalar reference. 3. Check exact integer results and meaningful floating-point edge cases. 4. Inspect IR or machine code only when a specific lowering matters. 5. Measure the complete workload, including allocation and data movement. ## Related Pages - [SIMD Overview](docs/guide/simd/index.md) - [Tensor and Mask Types](docs/guide/simd/tensor-mask.md) - [Dynamic Tensors](docs/guide/simd/dynamic-tensors.md) - [SIR Pipeline](docs/guide/simd/sir-pipeline.md) - [Operators Reference](docs/guide/advanced/operators-reference.md) --- Source: https://vex-lang.org/docs/guide/simd/simd-simt-contract.md # SIMD / SIMT Unified Execution Contract Vex uses one user-visible compute model for both CPU vectorization and GPU execution. The goal is simple: - write normal Vex code (`array` / `Tensor` / `Tensor` / `Span`) - keep semantics in one place - let runtime pick CPU SIMD, SIMD-like CPU kernels, or GPU SIMT backend There is **no separate “SIMT API”** in user code; kernel concepts come from the same algebraic operations and the same `Tensor`/`Mask` abstractions. This page states intended semantics and implementation boundaries, not a blanket parity certification. In particular, current Metal and WGSL type lowering can narrow `f64`; see the precision qualification below before relying on equivalent numerical results. ## 1) Core cross-backend contract The intended source-level meaning of these operation categories does not depend on backend: - `Map` (unary/binary element-wise ops): `f(a)` / `f(a,b)` - `Reduce`: `sum`, `prod`, `min`, `max`, `all`, `any`, etc. - `Compare`: `==`, `<`, `>`, `<=`, `>=` - `Mask` creation + mask algebra: `&`, `|`, `^`, `~` - `Select`: `cond ? a : b` / `mask.select(a,b)` - `Index`: `gather`, `scatter`, `scatter_add`, `scatter_max`... - `Prefix/scan` style kernels used in higher-level algorithms The compiler emits the same semantic node for both backends where possible; execution engine choice is done only by dispatch policy and capability. ## 2) Ownership and shape contract - `Mask` and `Tensor` represent **fixed-shape** values and are suitable for register-level codegen when width/shape allow it. - `DynMask` / `Tensor` represent **runtime-shape** values. `DynMask` stores packed bits and an owner field; it is not a `{ptr,len}` byte slice. - Scalar forms always stay scalar. Vectorized backends must not change user-visible scalar behavior. - `Span` is a borrowed view; moving into owned tensor values follows the ownership rules documented in memory sections. ### Dynamic mask representation in the development implementation The public `Mask` is an abstract value; its internal fields are not a public struct or a stable C ABI. The following describes the development source, not a layout guarantee for every release or target: | Boundary | Representation and ownership | | --- | --- | | Source | Runtime-sized `Mask` with logical boolean lanes; its internal storage is not accessible as source fields. | | Host LLVM / drop glue | The compiler's `%VexDynMask` uses `{ ptr, i64, ptr }`: packed-bit data, logical lane count, and owner pointer. A null owner denotes a borrowed/static or empty mask; otherwise it owns the backing allocation. Pointer width, alignment and aggregate size depend on the target. | | SIR execution descriptor | Non-owning input/output descriptors carry a logical encoding and lane count separately from buffers and dispatch geometry; they are not the host `%VexDynMask` aggregate. | | GPU storage boundary | For the descriptor mask-lane path, host packed bits or logical bytes are expanded to one `u32` per GPU lane. Returned device lanes are normalized to logical bytes. This is transport encoding, not the source type's public layout. | The host packed-mask ABI specifies word-rounded readable storage and zeroed tail padding for its consumers. The `vex-abi` field-index test and compiler layout tests describe the source contract; the SIR mask I/O tests exercise the conversion logic. These are not a substitute for running the relevant tests against a pinned release, target and GPU device. Do not serialize or pass this internal aggregate to foreign code as a stable ABI. For a local host probe, save this program as `mask-probe.vx`: ```vex [mask-probe.vx] fn make(): Mask { let values: [u8; 8] = [1, 0, 1, 0, 1, 0, 1, 0]; let mask: Mask<8> = values == (1 as u8); return mask; } fn main(): i32 { let mask = make(); $println(mask.len()); $println(mask.toBitmask()); return 0; } ``` Run `vex run mask-probe.vx`; expected output is `8` and `85` on separate lines. The set bits are lanes 0, 2, 4, and 6: `1 + 4 + 16 + 64 = 85`. Use `vex compile mask-probe.vx --emit-llvm -O0 -o mask-probe` to inspect the host representation. Host storage and device transport are separate boundaries; keep their layouts out of a public C ABI. ## 3) CPU SIMD vs GPU SIMT behavior - **SIMD backend** = register/vector execution (`+simd` style codegen, loop-vectorized kernels, and fixed-width tensor lowering). - **SIMT backend** = one lane/thread lane mapping (GPU warp/wavefront model). They differ in scheduling: - register width / lane count - memory model (`cache` vs `threadgroup`/`global`) - launch granularity (`for`-body vs kernel/thread semantics) They **must not** differ in: - operator identities - mask semantics - comparison truth tables - overflow and clamp policies - ownership transitions (when a result is borrowed vs owned) ## 4) What "same interface" looks like in practice The same source stays identical: ```vex // same user code for both fallback SIMD and GPU path fn relu(x: Tensor): Tensor { return x.max(0.0) } fn keep_positive(x: Tensor): Tensor { let m = x > 0.0 return m.select(x, 0.0) } ``` If a backend cannot support the exact fast path, it must preserve correctness and fall back to a valid implementation of the same contract instead of changing semantics. ## 5) Per-operation contract These are semantic requirements for a supporting route, not an all-backends support matrix. Dtype, shape, executor and compiler-bridge limits still apply. | API family | Contract to preserve | | --- | --- | | Element-wise arithmetic | Numeric type, signedness and exceptional-value rules | | Comparisons and mask algebra | Logical lane order and boolean meaning | | Reduction | Scalar result, accumulation policy and empty-input behavior | | Selection | Result for each lane; both value arguments are already evaluated | | Gather/scatter | Index validation, result ownership and duplicate-index policy | | Fixed-mask compaction | Stable selected prefix, exact count and zero tail | Check the [backend implementation map](docs/architecture/sir-backends-reference.md) and validate the actual operation. A successful fixed-mask kernel does not qualify unrelated tensor reductions or all element types on that backend. ## 6) Lane width and compaction `#Target.simdLanes()` reports the logical lane count selected for `T` at compile time. The meaning is shared, while the physical executor differs: - on CPU it is the number of `T` elements in the selected native vector width, - on CUDA and Metal it is the native 32-lane warp/simdgroup width, - on ROCm it follows the selected device's wave32/wave64 profile, - on portable SPIR-V/WGSL it is unavailable until a concrete device profile guarantees subgroup capabilities and width. The last case is deliberately fail-closed. A `#` intrinsic cannot truthfully return a subgroup size that is known only after runtime adapter selection. For dynamically routed `graph fn` code, lane-dependent graph specialization must therefore happen after the backend/device profile is selected. A lane constant produced for the CPU variant must not be reused by a GPU variant. HIR lowers the exact intrinsic identity to a symbolic SIR `ExecutionLanes` node. The selected backend then clones the graph and replaces that node with a constant: element-width-aware on CPU, 32 on CUDA/Metal, wave32/wave64 on ROCm, or the exact adapter subgroup width for SPIR-V/WGSL. The source graph is never mutated, so independently compiled CPU and GPU variants cannot leak constants into each other. Inside `graph fn`, use the value as an ordinary expression. It is not legal in `#if` or `#const`, because backend/device routing happens after graph creation. The backend-specialized value is still emitted as a constant and has no runtime query cost. For a fixed `Mask` and `[T; N]`, `mask.compress(values)` has one definition on every backend: ```vex let (packed, count) = mask.compress(values) ``` - selected values occupy `packed[0..count]` in their original order, - `packed[count..N]` is deterministically zero, - `count` is `usize`, - inactive physical GPU lanes do not participate, - and a mask wider than one native subgroup uses a bounded whole-mask legalization; a backend never presents independent subgroup compactions as one result. Current SIR lowering covers CPU scalar/SIMD, Metal, CUDA, ROCm, and SPIR-V/WGSL. Profiled SPIR-V/WGSL compaction uses subgroup arithmetic for an exact stable rank plus a subgroup barrier; it does not pay for a ballot unless an actual bitmask is requested. The WebGPU runtime requests `SUBGROUP` and `SUBGROUP_BARRIER` and reads the selected adapter's subgroup range. An exact range (`min == max`) can specialize `simdLanes`; a variable range cannot. It can still run the native `compress` path when `N <= min`. Without that proof—or when the fixed mask is wider—the backend emits a bounded portable whole-mask kernel. This does not manufacture a `simdLanes` constant and therefore keeps the compile-time query honest while preserving operation semantics. The standalone-kernel boundary validates this structurally before any backend sees the graph: `Mask` is fixed to `1..=64`, operands and results must have matching lane counts and dtypes, and unrelated SIR nodes or extra buffers are rejected instead of being silently discarded. `toBitmask` uses one `i64/u64` transport scalar. Packed `Int4`/`Fp4` compaction uses two nibbles per logical host byte and eight nibbles per canonical GPU `u32` word. Conversion is owned by the descriptor boundary, so no backend can reinterpret packed values as byte lanes. `Mask` also has one transport contract. Its source and host representation remains abstract (fixed masks may be packed), while GPU storage buffers use one `u32` per lane because WGSL/SPIR-V do not permit boolean storage-buffer lanes. The shared SIR runtime expands packed or byte-per-lane inputs at the GPU boundary and restores mask outputs to logical one-byte values. This is an internal ABI detail: CUDA, ROCm and Metal source code does not acquire a different `Mask` API. The versioned execution descriptor carries the exact kernel representation, entry point, ordered inputs and outputs, per-buffer logical encoding, and grid/workgroup geometry. Metal, WebGPU and CUDA consume this same contract; backend-specific positional FFI conventions are not part of `Mask` or `Tensor` semantics. Kernel representation is selected by the concrete executor, not by the host OS: a Metal executor requests MSL, while a WebGPU executor requests SPIR-V even when WebGPU is the fallback on macOS. This keeps device routing and subgroup specialization attached to the same capability source. Metal, CUDA and ROCm lower the canonical `(packed, count)` result as one real standalone kernel with inputs followed by outputs in the runtime binding order. Each selected lane computes a stable rank, the lane group clears the tail, synchronizes once, and writes the selected prefix. Metal output is compiled by Apple's shader compiler in the regression suite; CUDA PTX and ROCm HIP receive structural codegen tests and require their native toolchains/hardware in the platform CI matrix. Codegen parity and runtime-routing parity are deliberately separate. Metal, WebGPU and feature-gated CUDA PTX implement the common descriptor-based SIR graph executor. CUDA honors the descriptor's exact entry point, ordered buffers and grid/block geometry. ROCm can execute a descriptor containing precompiled HSACO; HIP source and compiled HSACO are different kernel representations, so HIP source fails closed until hipRTC or an AOT compilation step produces a real code object. Vulkan SPIR-V codegen is also not confused with a native Vulkan dispatcher. This preserves one public SIMD/SIMT interface without pretending that every deployment bridge is already complete. The AOT compiler bridge is gated independently from the runtime executor. Metal currently has a compatible compiler call bridge. WebGPU remains fully usable through the SIR runtime executor, but compiler-generated calls fall back until the legacy N-input/single-output FFI is replaced with the same descriptor contract. This prevents an ABI mismatch while preserving WebGPU's real runtime capability. Preserving value semantics across backend selection is a design requirement, not a qualification result for every operation. Metal codegen rejects `Mask.compress` over `f64`; the selected execution path must handle that failure or route it elsewhere. Other Metal codegen paths currently map `f64` to `float` and emit a warning, and WGSL type mapping also contains narrowing. Those paths can change results and must not be treated as transparent fallbacks. Per-operation routing, special values, rounding and device tests remain qualification work. Native standalone Mask kernels use one warp/wave/simdgroup when possible. Wider fixed masks use the bounded whole-mask path rather than changing the result or requiring source-level backend branching. The descriptor-based SIR runtime carries both outputs and performs the mask transport conversion. The older compiler GPU FFI bridge still accepts only one ordinary output buffer; it now rejects fixed/DynMask transport and multi-output graphs so dispatch falls back to CPU instead of risking a buffer overrun. It will be enabled for this path only after the same descriptor ABI is wired into that bridge. All cross-lane operations (`toBitmask`, `any`, `all`, `countBits`, `firstSet`, and `compress`) use a proven native execution-lane group when possible and a bounded whole-mask legalization otherwise. No backend may independently reduce or compact each warp/wave and present that as a whole-mask result. ## 7) How we keep backend parity safe - Keep the language surface in `Tensor`/`Mask` operations and do not branch on backend in user code. - Treat SIMD width and GPU workgroup size as hints chosen by compiler/runtimes. - Use the documented semantic contract together with owning-source tests and target validation. - Validate important kernels both on CPU SIMD and GPU paths when changing contracts (especially reductions). ## 8) Why this matters When this contract is respected: - compiler codegen can optimize one operation into many backends - `graph fn` can stay backend-agnostic - benchmark deltas come from schedule/capability, not API drift If you want raw backend-specific tuning, do it behind a feature-gated call boundary without replacing this base contract. ## Related docs - [SIMD Overview](docs/guide/simd/index.md) - [SIR Pipeline](docs/guide/simd/sir-pipeline.md) - [Tensor and Mask Types](docs/guide/simd/tensor-mask.md) - [GPU Programming](docs/guide/gpu/index.md) --- Source: https://vex-lang.org/docs/guide/simd/sir-pipeline.md # SIR Optimization Pipeline This page describes the current pipeline conservatively: what is clearly implemented, what route a workload tends to take, and where the sharp edges still are. ## High-level picture There are two different optimization routes that often get conflated: - compiler-side inline SIMD for qualifying small static arrays - SIR lowering and backend dispatch for tensor or graph workloads Conceptually: ```text source code -> HIR -> either small-array inline SIMD -> or SIR graph lowering -> backend selection -> LLVM IR / target code ``` Both routes are expected to follow the same SIMD/SIMT execution contract. The canonical contract definition is: - [SIMD/SIMT Unified Execution Contract](docs/guide/simd/simd-simt-contract.md) ## Route 1: inline SIMD for small arrays The compiler has a dedicated `simd_small` path for qualifying fixed-size arrays. The current backend threshold is explicit: - maximum 64 bytes total - maximum 64 elements - element count must be a power of two That threshold is implemented in `crates/vex-sir/src/codegen/backends/simd/inline.rs` and mirrored by the small-array codegen helpers in `crates/vex-compiler/src/codegen_hir/expr/simd_small`. Typical examples on this path are: - element-wise arithmetic on `[T; N]` - vector comparisons on `[T; N]` - reductions such as `<+` and `>?|` on small arrays Example: ```vex fn sum8(x: [i32; 8]): i32 { return <+ x } ``` On this path, the likely evidence in emitted LLVM is: - `` vector values - `insertelement` chains for tiny literals - `llvm.vector.reduce.*` intrinsics for reductions The same operation family can be routed to SIMT kernels via SIR when shapes are dynamic or graph-oriented. ## Route 2: SIR for tensor and graph code When code is written around `graph fn`, `Tensor`, or other graph-shaped tensor operations, the compiler lowers into SIR first and then chooses a backend based on shapes and supported node families. This route is the right mental model for: - dynamic tensors - graph compute - gather and scatter families - backend dispatch between CPU SIMD and GPU-style paths Backend choice is implementation detail. Correctness is checked at the SIR contract level. ## Static and dynamic shape routing The internal contract distinguishes between static and dynamic shapes: - static tensors like `Tensor` carry fixed shape information - dynamic tensors like `Tensor` lower to `%VexDynTensor { ptr, i64 }` - `Span` lowers as a non-owning `%VexSlice { ptr, i64 }` These are compiler-internal host layouts, not public foreign ABI declarations. Target width/alignment and ownership still apply. That distinction matters: A dynamic tensor owns storage and participates in drop behavior, while a span is a borrowed view. ## Important coercion boundary One of the easy mistakes is assuming every tensor-like value is interchangeable because the layouts look similar. They are not. The compiler has an explicit safety guard to avoid silently fabricating an owning dynamic tensor from a stack-aliased vector value. Conversions into `Tensor` must go through the proper owned path. In practical terms: - `Span -> Tensor` is an owned materialization - `Tensor -> Span` is an owner-bound borrowed view - `Tensor -> Span` uses scoped addressable storage and cannot escape - `Tensor` and `Span` are not just two names for the same thing - bugs at generic call boundaries have historically shown up exactly here ## Unified Silicon IR (SIR) Operator Reference The following catalog describes internal SIR operation families. It is not a complete source-syntax or backend-support guarantee: source lowering, dtype/shape validation, generation and runtime execution are separate boundaries. Scalar and floating-point mappings also differ. ### Arithmetic and Shape Nodes SIR distinguishes element-wise maps from reductions, reshapes/permutations, gathers/scatters and matrix operations. Element-wise arithmetic has lane-local data dependencies; a reduction combines many lanes; matrix multiplication requires compatible ranks and a matching inner dimension. These differences affect fusion and scheduling even when source expressions look similarly short. For executable source spellings, use the [SIMD operator guide](docs/guide/simd/simd-operations.md) and [operator reference](docs/guide/advanced/operators-reference.md). Internal enum variants such as `Fma`, `Atan2` or `Transpose` do not establish a public bare function, Unicode operator, or method with the same name. ### Numeric Lowering A backend selects operations according to signedness and element type. Integer division is not always `sdiv`; unsigned operands need unsigned semantics. A floating-point min/max lowering must define NaN and signed-zero behavior. Rotations and carry-less multiplication may use intrinsics or expanded instruction sequences depending on target capabilities. An SIR `Fma` is a three-input operation. A two-operand source token does not supply an implicit third operand. Similarly, a vector `Select` chooses between computed lane values; it does not provide scalar branch short-circuiting for unsafe reads or division by zero in the unused lane expression. ### Reduction and Mask Nodes Canonical source reductions use `<+`, `<*`, `?|`, `<&` and `<|>`. The emitter determines the legal accumulation strategy for the selected dtype and backend. A reduction intrinsic in LLVM is not proof of one hardware instruction or bitwise parity with another accumulation order. Masks have scalar queries (`any`, `all`, `countBits`, `firstSet`, `toBitmask`) and mask-valued operations such as boolean algebra. `fromBitmask` constructs a mask; it does not return a scalar. Fixed masks and runtime masks can have different internal representations, while the documented logical lane order must remain consistent. See [Tensor and Mask](docs/guide/simd/tensor-mask.md) for ownership and [SIMD/SIMT](docs/guide/simd/simd-simt-contract.md) for transport details. ## Backend Operator Support Matrix Support is checked per operation, dtype, shape and capability. A table marking all element-wise math, reductions or matrix operations “Full” across every backend would hide those boundaries. Use the [backend implementation map](docs/architecture/sir-backends-reference.md) and [SIMD/SIMT contract](docs/guide/simd/simd-simt-contract.md) to identify the selected route, then validate the concrete workload. Shader generation, driver acceptance and correct execution are separate results. ## Performance Routing & FLOP Weights Dispatch policy estimates work and transfer cost using operation weights, shape information and runtime capabilities. These weights are relative model inputs, not measured cycles or floating-point throughput. Exceeding a threshold does not bypass graph-support or executor checks and does not guarantee GPU execution. Constants differ across implementation paths and can change between compiler builds. See [GPU dispatch](docs/guide/gpu/index.md#runtime-deferred-dispatch) for how to validate the actual route. --- ## See also - [SIMD and Auto-Vectorization](docs/guide/simd/index.md) - [Tensor and Mask Types](docs/guide/simd/tensor-mask.md) - [GPU Programming](docs/guide/gpu/index.md) --- Source: https://vex-lang.org/docs/guide/simd/tensor-mask.md # Tensor and Mask Types `Tensor` and `Mask` are the types that connect user-facing graph code to the SIR and SIMD backends. The important distinction is this: - small static tensors line up closely with array and vector lowering - dynamic tensors are owning fat-pointer values with their own ABI and drop behavior - masks are the boolean side of that model and have both static and dynamic forms ## Layout overview Current compiler and SIR shape contracts are centered around these mappings: ```text Tensor -> Ty::Array(f32, 4) -> <4 x float> Tensor -> Ty::Array(f32, 32) -> [32 x float] Tensor -> Ty::DynTensor(f32) -> internal pointer/length aggregate Mask<4> -> Ty::Mask(4) -> <4 x i1> Mask -> Ty::DynMask -> internal packed-mask aggregate ``` That split matters because static and dynamic tensors do not behave like a single interchangeable runtime object. See the [dynamic mask representation table](docs/guide/simd/simd-simt-contract.md#dynamic-mask-representation-in-the-development-implementation) for the current host and GPU boundaries; it is not a stable public ABI. ## Static `Tensor` Static tensors are compile-time sized. In practice, the compiler lowers them through array machinery first: - The inline SIMD eligibility rule requires a nonzero power-of-two lane count, at most 64 lanes and at most 64 bytes. Eligible operations can use LLVM vector values. - Larger or ineligible values use other lowering paths, including memory arrays and loops. An LLVM vector can require several machine instructions; the threshold does not promise a single hardware register or instruction. So `Tensor` and `Tensor` are good mental models for inline SIMD, while larger static tensors should be thought of as shaped arrays. Example: ```vex let a: Tensor = [1.0, 2.0, 3.0, 4.0] let b: Tensor = [4.0, 3.0, 2.0, 1.0] let c = a + b ``` --- ## Dynamic `Tensor` Dynamic tensors lower to an owning `%VexDynTensor { ptr, i64 }` layout. The data buffer is heap-managed via the VUMI/VUMM allocator and participates in drop logic. Conversions into `Tensor` from `Span` involve an owned copy. The reverse explicit cast has view semantics: - `dynamicTensor as Span` is zero-copy and the borrow checker ties the span to the Tensor owner. - `staticTensor as Span` materializes scoped addressable storage for the SIMD value. LLVM can eliminate that storage when the view stays local, but the view cannot escape the frame. - `Span.toTensor()` and `span as Tensor` always produce independently owned dynamic storage; they never forge a Tensor owner over borrowed memory. Example: ```vex graph fn relu(x: Tensor): Tensor { return (x > 0.0f32).select(x, 0.0f32) } ``` --- ## Tensor and Dynamic Tensor Operations Start with the complete [dynamic tensor examples](docs/guide/simd/dynamic-tensors.md). The following forms describe distinct operations; an operation may have a narrower dtype or backend domain than the tensor type itself. | Form | Meaning and important constraint | | --- | --- | | `Tensor.fill(count, value)` | Allocate a dynamic tensor with `count` initialized elements. Count comes before value. | | `Tensor.fill(value)` | Construct a fixed-size tensor; `N` is a compile-time dimension. | | `tensor.len()` | Logical element count; zero length does not permit any index. | | `tensor[index]` | Access an element within the logical extent. | | `tensor.clone()` | Independent owned dynamic storage. | | `tensor as Span` | A borrowed view; keep the owner alive and obey its borrowing rules. | | `tensor.gather(indices)` | A result in the order specified by integer indices. | | `tensor.scatter(indices, updates)` | A new owned result; the source remains unchanged. | | `scatter_add`, `scatter_mul`, `scatter_min`, `scatter_max` | Combining updates with operation-specific conflict and numerical rules. | The compiler also contains builder and transformation operations such as `arange`, `linspace`, sorting and prefix scans. Their argument and shape rules must be checked for the selected path; the existence of an internal SIR node is not a universal method signature. In particular, this guide does not teach `fill(value, Vec shape)` or Rust's `*const ()` as Vex API syntax. A raw address obtained through a supported pointer interface remains non-owning and carries no lifetime. Use the canonical `Ptr` forms at a narrow boundary; never reinterpret a tensor aggregate as a foreign pointer or transfer its allocation to another allocator. --- ## `Mask` and `Mask` Masks represent boolean results from comparisons and masking operations. `Mask` has a fixed logical width; its lowering and register use depend on the target. Dynamic `Mask` has runtime length and separate packed host storage; its GPU transport is described in the [representation table](docs/guide/simd/simd-simt-contract.md#dynamic-mask-representation-in-the-development-implementation). ### Mask Operations | Operation | Meaning | | --- | --- | | `select(whenTrue, whenFalse)` | Lane-wise choice preserving the output extent; it does not suppress earlier evaluation of its arguments. | | `any()` / `all()` | Scalar tests for whether any/all logical lanes are true. | | `countBits()` | Number of true logical lanes. | | `firstSet()` | First true lane, with the empty-result convention of the selected mask API. | | `toBitmask()` / `toBitmaskAt(offset)` | Pack logical lanes into an integer window; a dynamic mask may exceed one word. | Static and dynamic mask representation and integer-result widths need not be identical. Do not use a whole-mask packing operation as if it could retain an arbitrary number of lanes in a fixed-width integer. See the canonical [mask contract](docs/guide/simd/simd-simt-contract.md) before exchanging masks with native or GPU code. Example: ```vex let mask = data > 0.0 if mask.any() { let first = mask.firstSet() $println("First positive value index: {}", first) } ``` --- ## Hardware Lowering Summary The compiler routes target workloads based on shapes and constraints: - Eligible small static operations can use LLVM vectors; target legalization chooses registers and instructions. - Dynamic operations can use loops, runtime support or compatible accelerator paths. Shape and capability checks determine the actual route. ## See also - [SIMD and Auto-Vectorization](docs/guide/simd/index.md) - [SIR Optimization Pipeline](docs/guide/simd/sir-pipeline.md) - [GPU Programming](docs/guide/gpu/index.md) - [SIMD/SIMT Unified Execution Contract](docs/guide/simd/simd-simt-contract.md) --- Source: https://vex-lang.org/docs/guide/stdlib-start.md # Your first standard-library workflow You do not need to read the entire library before writing a useful program. Start with one input, one transformation and an observable result. This path assumes you have completed [your first Vex project](docs/guide/first-project.md). ## Build confidence in three steps | Step | Do this | You are ready to continue when | | --- | --- | --- | | Parse a value | Run the complete [checked JSON example](docs/std/serde/json.md) and print the result | You can change a field and explain how parse failure reaches the caller | | Transform it | Use [checked string conversion](docs/std/strconv.md) and [string construction](docs/std/strings.md) for the value you need | You can handle a missing or invalid field without inventing a default | | Keep it working | Put the expected result and a rejected input into a [test](docs/std/testing.md) | The test detects a deliberate change to the expected behavior | Run each complete example before combining packages. Retain its imports and expected output. When the guide marks a snippet as a fragment, read the surrounding setup rather than pasting it as an independent program. ## Choose the next package by the job | I want to… | Start here | Decide before connecting it | | --- | --- | --- | | Read arguments and print a result | [CLI](docs/std/cli.md), [logging](docs/std/log.md) | Required versus optional input; output intended for people or machines | | Read a configuration file | [Files](docs/std/fs/index.md), [serde](docs/std/serde/index.md) | Who owns the bytes, size limits, and required fields | | Order or search records | [Sort](docs/std/sort.md), [collections](docs/std/collections.md) | Key type, ordering and whether stable order matters | | Call an HTTP endpoint | [HTTP](docs/std/http/index.md), [context](docs/std/context.md) | Response ownership, deadline and failure handling | | Store local records | [Database](docs/std/db/index.md) | Connection lifetime, statement errors and the native provider | | Parse a URL or encoded text | [URL](docs/std/url.md), [encoding](docs/std/encoding.md) | Accepted syntax and whether the returned data owns its storage | | Measure elapsed work | [Time](docs/std/time/index.md) | Monotonic elapsed time versus a wall-clock timestamp | Use the [complete package map](docs/std/index.md) for media, numerical work, cryptography and language tooling. Read the particular package's provider and integration requirements before extending a small example to a full service. ## Keep three boundaries visible **Imports.** `Vec`, `Map`, `Option` and `Result` belong to the prelude. Import packages using their documented paths, such as `"fs"` or `"serde/json"`. The [prelude and package guide](docs/guide/stdlib.md) explains which names need imports. **Ownership.** An owning result can outlive its input; a view needs its owner. Check the receiver and return type before storing or returning a value. Use [ownership workflows](docs/guide/memory/ownership-workflows.md) when connecting two APIs across a function, collection or async boundary. **Validation.** Successful parsing establishes the format contract. Your application still checks required fields, value types and ranges. For a binary format, follow the safe dynamic path described by [CBOR](docs/std/serde/cbor.md) or [MessagePack](docs/std/serde/msgpack.md) before constructing domain values. ## A small exercise Adapt the JSON example to accept a configuration with an `enabled` boolean. Keep one accepted input and reject both a missing field and a string in place of the boolean. Print a result only after validation. Then move the validation into a function and test it. Your completion check is the same behavior before and after that refactor, including the two rejected inputs. For a larger next step, choose one [worked application example](docs/guide/examples.md). Keep the compiler identity and commands with your result using [verification evidence](docs/guide/verification-evidence.md). --- Source: https://vex-lang.org/docs/guide/stdlib.md # Standard Library > **Vex's standard library.** Prelude (auto-imported) plus explicitly imported packages. For a practical learning sequence, start with [your first standard-library workflow](docs/guide/stdlib-start.md), then return here to distinguish prelude names from package imports. ## Prelude (Auto-Imported) These are available everywhere without `import`: ### Collections | Type | Description | |-----|----------| | `Vec` | Dynamic array bound to its construction-time allocator region | | `Map` | Hash map (SwissTable) | | `Set` | Hash set | | `string` | Owning string with inline storage for small values | | `str` | Borrowed string view | ### Smart Pointers | Type | Description | |-----|----------| | `Box` | Compiler-managed heap ownership; sharing and thread safety are inferred automatically | | `Ptr` | Typed pointer | | `Span` | Non-owning pointer-and-length view; checked access does not validate its lifetime | | `RawBuf` | Raw byte buffer | | `Layout` | Checked allocation size and alignment | | `Mem` | Canonical low-level allocation and byte-operation namespace | | `Limits` | Target-aware compile-time integer minimum and maximum values | ### Error & Optionality | Type | Description | |-----|----------| | `Result` | Operations that can fail | | `Option` | Values that may not exist | | `Range` | Range expressions | | `Complex` | Complex numbers | ## Packages (Import Required) Memory primitives are deliberately absent from this list: there is no `std/mem` package. Low-level code uses the prelude `Mem.*` boundary; most code uses owning types such as `Box`, `Vec`, or `string`. Use each package's documented path, for example `import { File } from "fs";`. A heading such as “standard library” is not an instruction to prepend `std/` to every import. `Math`, `Bit`, and `Crypto` are builtin namespaces; they do not require imports. The `crypto` package is distinct from the `Crypto` builtin namespace. Choose a package by the task and data ownership you need. Each linked guide shows its imports, examples and specific input/output contracts. | Area | Guide | | --- | --- | | Command-line programs | [CLI](docs/std/cli.md), [system](docs/std/sys.md), [logging](docs/std/log.md) | | Data structures and ordering | [Collections](docs/std/collections.md), [sort](docs/std/sort.md), [filter](docs/std/filter.md) | | Errors and cancellation | [Errors](docs/std/errors.md), [context](docs/std/context.md) | | Files and paths | [File system](docs/std/fs/index.md) | | Byte streams and compression | [I/O](docs/std/io.md), [compression](docs/std/compress/index.md) | | Structured data | [Serde](docs/std/serde/index.md): JSON, TOML, YAML, CSV, CBOR and MessagePack | | Text and parsing | [Strings](docs/std/strings.md), [strconv](docs/std/strconv.md), [Unicode](docs/std/unicode.md), [encoding](docs/std/encoding.md) | | TCP and UDP | [Networking](docs/std/net.md) | | Web protocols | [HTTP](docs/std/http/index.md), [URL](docs/std/url.md), [TLS](docs/std/tls.md), [WebRTC](docs/std/webrtc.md) | | Regular expressions | [Regex](docs/std/regex/index.md) | | Hashes, secrets and random values | [Hash](docs/std/hash.md), [crypto](docs/std/crypto/index.md), [randomness](docs/std/rand.md) | | Database access | [Database](docs/std/db/index.md) | | Time | [Time](docs/std/time/index.md) | | Locations and routes | [Geo](docs/std/geo.md) | | Images, video and audio | [Vips](docs/std/vips.md), [media](docs/std/media.md) | | Numeric/model computation | [ML](docs/std/ml.md), [inference](docs/std/inference.md) | | Version requirements | [Semver](docs/std/semver.md) | | Reusable protocols and tests | [Contracts](docs/std/contracts.md), [testing](docs/std/testing.md) | | Build language tools | [IDE packages](docs/guide/tooling/language-tools.md) | The [standard library index](docs/std/index.md) lists the package families. Import paths come from the individual module guides, including focused submodule imports when a program needs only a parser, codec or transform. ## Compose packages around ownership A file-processing command can parse arguments with `cli`, read bounded input with `fs`, decode structured data with `serde`, sort records with `sort` and write its result through `io`. Keep parse and I/O errors typed until the CLI boundary. Use `context` when cancellation/deadline state must follow an operation. For media work, `vips` operates on image pixels, `media` on explicit frame/audio layouts, and `webrtc` on encoded packets and presentation timing. Conversion between packages may copy into a new owner; it is not automatically a pointer transfer. The image/media guides show that boundary directly. ## Next Steps - [VUMM Memory Model](docs/guide/memory/vumm.md) - [Error Handling](docs/guide/error-handling.md) - [FFI](docs/guide/ffi.md) --- Source: https://vex-lang.org/docs/guide/tooling/compilation-modes.md # Compilation Modes and Optimization `vex run` compiles and executes a program; `vex compile` produces a persistent artifact when code generation and linking succeed. The options below describe the CLI inspected for the 0.4.0 documentation. Check `vex --version`, `vex compile --help` and `vex run --help` when using an older release or a different candidate; their option sets can differ. ## Compilation Modes ```bash vex run main.vx vex compile main.vx ``` `run` executes a temporary native executable as a subprocess. `compile` emits a native artifact; `-o ` selects its output location. A successful `lint` check alone does not exercise native code generation, linking or execution. ## Optimization Levels Both commands accept numeric levels `0` through `3` with `-O` or `--opt-level`. In the current CLI, **compile defaults to O2 and run defaults to O1**. `--fast` is a compile option for a no-optimization, no-LTO fast path; it is not a universal performance guarantee. ```bash vex compile -O 0 main.vx vex compile -O 3 main.vx vex run -O 2 main.vx ``` Higher levels can increase compilation time and change optimization choices; measure the actual workload and target. Do not assume a particular LLVM pass, instruction, speedup or binary size from a level alone. The current numeric CLI schema does not define `-Oz` or `-Os` as optimization levels. ## Emit Flags ```bash vex compile --emit-llvm main.vx vex compile --emit-asm main.vx ``` These modes emit `.ll` and `.s` respectively and return without linking a native executable. They are mutually exclusive. `vex run --emit-llvm main.vx` is a separate run-time debugging option. The current compile CLI does not provide `--emit-obj`, `--emit-llvm-ir` or `--emit-all` options; consult its help for the available surface. ## LTO (Link-Time Optimization) The development compile CLI exposes `--lto` and `--thin-lto`. The compiler's link path checks LLVM/Clang compatibility before using bitcode. On the checked path, ThinLTO emission can also be selected at O2 or higher when the compatible Clang is not Apple Clang. Availability and final behavior depend on the linker, compiler, target and other flags; requesting a flag does not by itself prove that a given artifact used LTO. Inspect diagnostics and validate the artifact on the intended environment. ```bash vex compile --lto main.vx vex compile --thin-lto main.vx ``` The current CLI exposes these as switches; `--lto=off` is not its documented off switch. Benchmark different modes for your application rather than assuming a fixed relative speed or optimization quality. ## Build Profiles The development `vex compile` command does not currently expose the `--profile` or `--release` options shown in some older examples. Set an explicit numeric optimization level and other supported options instead. TOML profile blocks are not a demonstrated configuration for this CLI. Check the [package-manager reference](docs/references/vex-pm-reference.md) for the manifest and commands supported by the selected version. ## Incremental and Parallel Compilation Caching and parallel work exist in parts of the compiler and toolchain, but this page does not promise a general incremental or parallel-build contract. The available modes and their invalidation or resource behavior require separate qualification for the compiler revision and workload. ## Cross-Compilation `vex compile --target main.vx` selects a target triple. Parsing a triple or emitting code is not proof that the corresponding runtime support, linker, system libraries and native execution are available. Consult the [platform support matrix](docs/guide/platform-support.md), then build and run a representative artifact on the exact target before relying on it. ## Debug Symbols (DWARF) The CLI accepts `-g` / `--debug-info` for additional debug information. The current native linking path also preserves line-table information for crash symbolication, but debugger features and available symbols must be checked on the actual target and build. ## Sanitizer Integration The compile CLI accepts `--sanitize` values including `address`, `memory`, `thread` and `undefined`; the linker path passes the corresponding sanitizer flag through a Clang driver. Toolchain and target support differ, and passing a linker flag alone does not establish complete instrumentation or detection coverage. Qualify each sanitizer with a known failing test on the intended compiler and target before using it as a CI safety gate. ## Best Practices 1. Start with `vex lint`, then run or compile the example on the intended host. 2. Record the compiler revision, optimization level, target and toolchain. 3. Use `--help` from that binary for its supported flags; avoid copying release-profile, sanitizer or cross-target recipes from a different revision. 4. Measure performance and validate debugging and sanitizer behavior separately. --- Source: https://vex-lang.org/docs/guide/tooling/full-toolchain.md # Toolchain -- Complete Reference The `vex` CLI provides compilation, analysis, testing, project, and inspection commands. This page describes the 0.4.0 command surface and the workflows for building, checking, inspecting and maintaining a Vex project. ## `vex` CLI ```bash vex [options] [args] ``` ### All Subcommands | Command | Description | |---------|-------------| | `vex run ` | Compile and execute a Vex program | | `vex compile ` | AOT compile to native binary | | `vex build` | Build a package selected by `vex.json` | | `vex lint [target]` | Correctness analysis, semantic lints and verified fixes without codegen | | `vex ir ` | Emit LLVM IR (shorthand for `compile --emit-llvm`) | | `vex test` | Run tests or benchmarks | | `vex format ` | Format source code (`-i` for in-place) | | `vex doc` | Generate documentation from source | | `vex new ` | Create a new Vex project | | `vex init` | Initialize `vex.json` in existing directory | | `vex add ` | Add a dependency | | `vex remove ` | Remove a dependency | | `vex update` | Update all dependencies | | `vex list` | List all dependencies | | `vex watch ` | Watch and recompile on changes | | `vex workspace` | Workspace management for monorepos | | `vex tool ` | Invoke bundled LLVM tools | | `vex env` | Show environment configuration | | `vex setup` | Setup `VEX_HOME` with standard library | | `vex clean` | Clean cache and build artifacts | | `vex repl` | Inspect interactive input with retained parsing context | | `vex view ` | Inspect AST, CFG, DFG, layout or escape information | | `vex prof ` | Profile microarchitectural pipeline performance using LLVM-MCA | | `vex mod` | Dependency graph, verification, and module maintenance commands | | `vex vxm` | Inspect and verify portable VXM package images | | `vex daemon` | Manage the compiler daemon | ## `vex compile` -- AOT Compilation ```bash # Basic compilation vex compile main.vx # With optimization vex compile -O 3 main.vx vex compile --opt-level 3 main.vx # Emit artifacts vex compile --emit-llvm main.vx # LLVM IR (.ll) vex compile --emit-asm main.vx # Assembly (.s) vex compile --emit-spirv main.vx # SPIR-V (for GPU functions) # Enable features vex compile --gpu main.vx # GPU support # Debug build vex compile -g main.vx # DWARF debug info # Output file vex compile -o mybinary main.vx # Compile as a dynamic/shared library (.dylib, .so, or .dll) vex compile --shared lib.vx # Structured semantic diagnostics vex lint --format json main.vx ``` Data-parallel lowering follows the program, target and optimization pipeline described in the [SIMD guide](docs/guide/simd/index.md). Use `vex lint --format json main.vx` for structured semantic diagnostics and retain the command's exit status. ## `vex run` -- Compile and Execute ```bash vex run main.vx # compile and run vex run -O 3 main.vx # with optimization ``` Check the help for the command you use rather than transferring options between commands. For program arguments, use `vex run main.vx -- arg1 arg2`. The [GPU guide](docs/guide/gpu/index.md) explains graph execution and target selection. Ordinary user `vex compile` and `vex run` refresh V1 symbol sidecars from current source and HIR without publishing a complete portable V2 package. Existing V2 images stay unchanged, and fresh V1 metadata does not make a stale V2 image valid. Generated declaration namespaces currently fall back to complete publication. `vex build`, compiler-runtime compilation and explicit `vex lint --publish-vxm` retain complete publication. Keep source available unless a complete portable image has been successfully published. ## `vex lint` -- Semantic Validation and Cleanup ```bash vex lint main.vx # check and lint one file vex lint . # check and lint a package vex lint --deny-warnings . # CI quality gate vex lint --diff . # preview verified fixes vex lint --fix . # apply verified fixes ``` `vex lint` runs parser, resolution, type, borrow and validation queries without LLVM codegen. Fixes are revision-bound structured edits and are committed only after semantic re-analysis. The former `vex check`, `vex analyze` and `vex fix` compatibility commands are removed; use the corresponding `vex lint` mode. See [Linting and Verified Fixes](docs/guide/tooling/lint.md) for the complete rule catalog, configuration, suppressions, pointer migration, and transactional fix guarantees. ## `vex ir` -- LLVM IR Quick View ```bash vex ir main.vx # write vex-builds/main.ll vex ir main.vx -o inspected # write inspected.ll ``` IR is written to a file: the compiler replaces the selected output extension with `.ll`. The informational terminal message is not the IR payload. ## `vex format` -- Code Formatter ```bash vex format main.vx # output formatted to stdout vex format -i main.vx # format in-place # Check formatting in CI: vex format main.vx | diff main.vx - ``` ## `vex test` -- Test Runner ```bash # Run all tests vex test # Select a test directory and filter function names with a regular expression vex test --run '^test_addition$' tests/ # Run benchmarks vex test --bench # Benchmark with a custom target duration (capped at 1 second) vex test --bench --benchtime 500ms # Show memory stats during benchmark vex test --bench --benchmem # Fail fast vex test --failfast # Filter tests by regex vex test --run "parser_.*" # JSON output vex test --json # Short mode (skip slow tests) vex test --short ``` ### Writing Tests Directory discovery includes files named `*.test.vx`, `*_test.vx` and `*_bench.vx`. A positional argument selects a path or glob; `--run` filters function names. An empty selection does not prove a test passed. See the [test reference](docs/references/vex-test-reference.md) for discovery and exit behavior. ```vex // tests/arithmetic.test.vx fn test_addition() { let result = 1 + 1 $assert(result == 2, "1 + 1 must equal 2") } fn test_option_default() { let opt = Some(42) $assert(opt.or(0) == 42, "Some(42).or(0) == 42") } ``` ## `vex new` / `vex init` -- Project Scaffolding ```bash vex new my-project # create new project directory vex init # initialize in current directory ``` Creates: ``` my-project/ ├── vex.json # package manifest ├── src/ │ └── lib.vx # starter source and entry point └── tests/ # test directory ``` ## `vex add` / `vex remove` -- Dependency Management ```bash vex add github.com/your-org/your-package@v1.2.0 vex remove github.com/your-org/your-package vex update # resolve dependency updates vex list # list all dependencies ``` Replace the example repository and tag with a real package you can access. These commands operate on `vex.json` and `vex.lock` in the project directory. Standard-library imports such as `http` are not instructions to install a registry package with that bare name. Review manifest and lockfile changes after updating, and rerun the application's tests before adopting them. ## `vex watch` -- Watch Mode ```bash vex watch main.vx # recompile on file changes ``` The current implementation recompiles through its compiler driver when the entry file changes. It does not provide a complete dependency watcher or automatically execute a newly linked application. Use `vex run` explicitly when you need to exercise runtime behavior. ## `vex workspace` -- Monorepo Management ```bash vex workspace list # list workspace members vex workspace add ./new-crate # add member ``` ## `vex tool` -- Bundled LLVM Tools ```bash vex tool objdump -d mybinary # disassemble vex tool nm mybinary # list symbols vex tool ar crs libfoo.a foo.o # create static library vex tool strip mybinary # strip debug symbols vex tool lld -- # invoke lld linker vex tool info # show toolchain info ``` ## `vex repl` -- Interactive REPL `vex repl` accepts interactive input and keeps selected declarations as parsing context. For the complete edit/check/run workflow, save a program to a file, check it with `vex lint example.vx`, then execute it with `vex run example.vx`. ## `vex clean` -- Clean Artifacts ```bash vex clean # clean build cache ``` ## `vex env` / `vex setup` -- Environment ```bash vex env # show VEX_HOME, toolchain paths vex setup # setup ~/.vex with stdlib ``` ## Best Practices 1. Use `vex lint` for fast semantic validation during development. 2. Use `vex format -i` before committing code. 3. Run `vex test --bench` before and after optimization changes. 4. Test parsers with valid, malformed, truncated and boundary inputs. Compiler developers can also use the [compiler testing tools](docs/references/compiler-testing-tools.md). 5. Use `vex watch` for its supported entry-file recompilation, and run the application explicitly when checking behavior. ## Build your own language tools The [language-tooling libraries](docs/guide/tooling/language-tools.md) cover lexing, grammar rules, syntax trees, incremental query metadata, diagnostics, document layout, protocol messages and a Vex-written IR toolkit. They are useful for formatters, source browsers, small languages and editor integrations written in Vex. ## Editor integration with `vex-lsp` `vex-lsp` serves the Language Server Protocol over standard input/output. Configure your editor's LSP client with the absolute path to the server executable, the Vex file type and the project workspace root. Open the package root containing `vex.json` so imports and project configuration have the same context as the command-line tools. For a source build, from the compiler checkout root: ```bash cargo build --release -p vex-lsp --target-dir target ``` The server is `target/release/vex-lsp` (`.exe` on Windows). The editor launches it as a protocol process; stdout belongs to that protocol. Server logs go to the temporary-directory `vex-lsp.log` stream. Keep the compiler, standard library and server revisions aligned when checking an editor diagnostic. The server exposes completion and signature help, hover and navigation, references and rename, symbols and hierarchies, semantic tokens and inlay hints, formatting and code actions. Lint code actions use the same rule identities and verified edit model as [command-line linting](docs/guide/tooling/lint.md). Editor diagnostics help during editing; run the program and tests for execution checks. A useful editor acceptance flow is to open two importing files, navigate to an export, change a referenced type, inspect the resulting diagnostic, apply a verified fix and rerun the package tests. This exercises the relationship between document state, project imports and compiler semantics. ## Formatting configuration `vex format` uses the formatter library and discovers `vexfmt.toml` or `vexfmt.json` from the input file's directory and its ancestors. For example, save this valid configuration as `vexfmt.json` at the project root: ```json [vexfmt.json] { "max_width": 100, "indent_size": 4, "brace_style": "same_line", "trailing_comma": "multiline", "quote_style": "double" } ``` Preview a file in the terminal, then write the formatted result when ready: ```bash vex format src/main.vx vex format -i src/main.vx ``` Keep formatting separate from semantic cleanup: use `vex lint --diff` to inspect a proposed fix and `vex lint --fix` to apply verified changes. Re-run the relevant tests after changes that alter program behavior. 6. Use `vex lint --format json` for structured analysis diagnostics and the language server for editor integration. Check command-specific output contracts before parsing other CLI modes as JSON. --- Source: https://vex-lang.org/docs/guide/tooling/language-tools.md # Build language tools in Vex Vex's `std/ide` packages provide building blocks for language tools written in Vex: tokenization, grammar descriptions, syntax trees, query metadata, formatted diagnostics, document layout and protocol messages. Use them to build a small configuration language, a source browser, a formatter or an editor integration. Choose the library layer that owns your problem. These packages are distinct from the compiler's Rust implementation and from the `vex-lsp` executable used to edit Vex programs. ## Choose a component | Import | Use it for | Main entry points | | --- | --- | --- | | `ide/logos` | Tokens and source positions for Vex-like input | `newLexer`, `nextToken`, `slice` | | `ide/ungram` | Named grammar rules, references and validation | `newUngrammar`, `addNode`, `parseUngramText`, `validateGrammar` | | `ide/rowan` | A syntax tree that can reconstruct retained source text | `newSyntaxTreeBuilder`, `createGreenToken`, `createGreenNode`, `toRedNode` | | `ide/salsa` | Revision and dependency metadata for incremental queries | `newDatabase`, `queryOrCompute`, `advanceRevision`, `invalidateKey` | | `ide/ariadne` | Source labels, diagnostic layout and terminal output | `newReport`, `withLabel`, `renderReportToString`; source caches and terminal-policy helpers | | `ide/pretty` | Width-sensitive layout for generated text | `newPrettyBuilder`, `docText`, `docBreak`, `docGroup`, `formatDocWithWidth` | | `ide/doc` | Structured documentation with HTML or terminal output | `newDocumentationModule`, `addHeader`, `addParagraph`, `addCodeBlock`, `extractDocComments` | | `ide/lsp` | LSP-shaped positions, diagnostics, requests and responses | `newLspServer`, `parseLspMessage`, `formatLspResponse`, `formatDiagnosticNotification` | | `ide/dap` | Debug adapter messages and supplied debugger state | `newDapServer`, `setActiveFrame`, `addVariable`, `parseDapMessage`, `formatDapResponse` | | `ide/vxir` | A Vex-written IR toolkit: graphs, analysis, passes and emitters | Graph and type tables, verifier, pass manager, dialect and target modules | Import only the components you use. For installed toolchains, select a standard library tree containing those packages. In a compiler source checkout their public entry points are `lib/std/ide//src/lib.vx`. ## Tokenize a small declaration Save this complete program as `tokens.vx`. It consumes tokens until the explicit end-of-file kind, returns a nonzero exit code for an error token and prints each token's source text. ```vex [tokens.vx] import { newLexer, nextToken, slice } from "ide/logos"; fn main(): i32 { let! lexer = newLexer("let count = 12;"); while true { let token = nextToken(&lexer!); if token.kind == 99 { return 0; } if token.kind == 0 { return 1; } $println(slice(&lexer, token)); } return 0; } ``` ```sh vex run tokens.vx ``` Expected stdout, with exit status 0: ```text let count = 12 ; ``` `TokenSpan.start` and `end` identify a half-open source range; line and column values accompany it. The lexer owns its source string and advances through a mutable borrow. Token kind 0 is an error and 99 is end of input in this package's token model. Keep these values behind named constants in a larger application. The lexer skips whitespace. A formatter or exact source reconstruction tool must retain the gaps between token spans as well as comments. A sequence of token texts alone cannot reproduce spaces that were skipped. ## Format the same document at two widths A pretty printer separates the content from its layout. `docBreak` is a potential line break; `docGroup` allows the layout engine to flatten that break to a space when the group fits. `docNest` adds indentation to a nested document. Save this complete program as `layout.vx`: ```vex [layout.vx] import { newPrettyBuilder, docText, docBreak, docConcat, docGroup, formatDocWithWidth } from "ide/pretty"; fn main(): i32 { let! builder = newPrettyBuilder(); let first = docText(&builder!, "alpha,"); let split = docBreak(&builder!); let second = docText(&builder!, "beta"); let tail = docConcat(&builder!, split, second); let body = docConcat(&builder!, first, tail); let group = docGroup(&builder!, body); let wide = formatDocWithWidth(&builder, group, 0, 80); let narrow = formatDocWithWidth(&builder, group, 0, 5); $println(wide); $println(narrow); if wide != "alpha, beta" { return 1; } if narrow != "alpha,\nbeta" { return 2; } return 0; } ``` ```sh vex run layout.vx ``` Expected stdout, with exit status 0: ```text alpha, beta alpha, beta ``` The width is a layout budget, not permission to split an indivisible text node: `alpha,` remains six characters even when the requested width is five. Keep document IDs with the builder that created them. ## Assemble a lossless syntax tree Rowan separates stored syntax from its position in a tree. Green nodes retain token text and child structure; red nodes add offsets and parent/depth context. The following function is a library fragment, not a complete program: ```vex import { GreenNode, newSyntaxTreeBuilder, createGreenToken, createGreenNode, reconstructSourceText } from "ide/rowan"; fn reconstructedDeclaration(): string { let! builder = newSyntaxTreeBuilder(); let keyword = createGreenToken(&builder!, 1, "let "); let name = createGreenToken(&builder!, 2, "count"); let value = createGreenToken(&builder!, 3, " = 12;\n"); let! children = Vec.new(); children.push(keyword); children.push(name); children.push(value); let root = createGreenNode(&builder!, 10, children); return reconstructSourceText(&root); } ``` The expected string is `"let count = 12;\n"`. The kind numbers here belong to this example's grammar, not a universal token enumeration. Keep trivia in the tree when preserving source spelling; use a separate formatted document when you intentionally want to change layout. A parser built on these components still owns precedence, recovery and the mapping from tokens to grammar rules. ## Organize incremental work Salsa's `Database` records revisions and memo entries. A useful editor workflow is: 1. Give each logical input/query a unique `queryId` and retain its key hash. 2. Compute the result and pass its hash to `queryOrCompute` with dependency IDs. 3. After an edit, advance the revision and update affected inputs, then recompute affected intermediate queries from dependencies toward consumers. 4. Reuse a parent result only after its direct dependencies have current metadata; freshness checks read those entries rather than recursively evaluating their dependencies. The package receives `computedHash`; it does not execute a user callback to compute the result. Store the actual result in your application and keep that storage consistent with the recorded hashes. The entry representation has two dependency slots. Design query nodes around that representation or aggregate larger dependency sets through intermediate nodes. ## Turn source locations into useful diagnostics Ariadne combines a report with labelled source ranges, messages and optional notes. Keep the source snapshot alive for the report, choose the byte-span or character-span API deliberately, and use the matching source-cache/indexed adapter. A Unicode character index, UTF-8 byte offset and editor protocol position are different coordinates; convert at a defined boundary. Use the terminal-policy helpers when selecting ANSI color and output style. Keep the diagnostic message meaningful without color. Documentation output can use `ide/doc` to compose headers, paragraphs and code blocks, then render to HTML or ANSI terminal text. ## Connect an editor or debugger An integration owns three layers: | Layer | Responsibility | | --- | --- | | Transport | Read/write messages, handle framing, enforce size limits and close cleanly | | Protocol | Decode requests, preserve request IDs, encode responses and notifications | | Language/debugger state | Resolve the requested document revision or stopped process and produce the actual result | The LSP/DAP packages expose message types and response-building helpers. Connect them to your own source database or debugger adapter; completion contents, hover text, frames and variables must come from that state. Advertise only the methods your integration serves. For editing Vex itself, use the compiler's `vex-lsp` tool described in the [toolchain guide](docs/guide/tooling/full-toolchain.md). ## Build an IR-based tool VXIR is a separate Vex-written toolkit for building compiler-like programs. Its public entry module groups type/data-layout tables, graph construction, verification, control-flow and dominance analysis, transformation passes, register allocation, object writers and target encoders. Choose the smallest layer your tool needs and verify its IR before and after a transformation. For example, a teaching compiler can start with parsing, a typed graph and a scalar interpreter/reference result before selecting a native emitter. Keep target data layout, calling convention, relocations and object format in the target layer. VXIR is distinct from the main Vex compiler's [Silicon IR](docs/architecture/sir-and-backends.md); their APIs and pass identities must not be interchanged. ## Continue building - [Modules and public interfaces](docs/guide/modules.md) - [Ownership](docs/guide/memory/ownership.md) and [strings](docs/guide/types/strings.md) - [Testing](docs/guide/tooling/testing.md) for positive, malformed and boundary inputs - [Documentation generator](docs/references/vex-doc-reference.md) for the compiler's CLI tool - [Native integration](docs/guide/ffi-first-native.md) for an external parsing or debugger library --- Source: https://vex-lang.org/docs/guide/tooling/lint.md # Linting and Verified Fixes `vex lint` is Vex's canonical source-analysis command. It runs parser, resolution, type, control-flow, borrow, ABI, and validation checks together with the configurable lint registry, without invoking LLVM code generation. Use it for ordinary diagnostics, CI quality gates, safe cleanup, and source migrations: ```bash vex lint src/main.vx vex lint . vex lint --fix . vex lint --diff --only pointer_migration . vex lint --format json --deny-warnings . vex lint --format sarif . vex lint --format json --timings . vex lint --analyze-comptime . vex lint --explain-boxing src/main.vx vex lint --explain-arena src/main.vx ``` The former `vex check`, `vex analyze`, and `vex fix` compatibility commands have been removed. Use `vex lint`, `vex lint --fix`, or `vex lint --diff`. `--explain-boxing` exposes VUMM ownership/boxing decisions and `--explain-arena` exposes AutoArena allocation decisions. They are diagnostic views over the same semantic session, not separate analysis commands. `--analyze-comptime` runs the shared typed staging probe after successful semantic analysis and writes an aggregate known/residual/error summary to stderr. Lint findings in text, JSON, and SARIF remain unchanged. The option is default-off and never applies staged replacements. ## Analysis targets `TARGET` may be: - one `.vx` or `.vxc` file; - a package directory; - omitted, in which case Vex discovers the nearest enclosing `vex.json`. A directory must belong to a package. Vex rejects an unscoped repository root instead of merging all nested packages into one enormous analysis session, and package inventory stops at nested `vex.json` boundaries. Directory analysis selects the source variants matching the active target OS and architecture. Cross-target analysis uses the same routing as compilation: ```bash vex lint --target x86_64-pc-windows-msvc . ``` `.git`, `.vex`, `.vxm`, `target`, `build`, `vendor`, and `generated` directories are skipped by default. Package-specific exclusions can be added in `vex.json`. Compiler-generated `vex_test_runner_*`, `.vex_test_runner_*`, and `.vex_bench_*` files are execution artefacts rather than package members, so lint excludes them even if an interrupted test or benchmark process left them beside the original source. ## Diagnostics versus lints `vex lint` reports two kinds of findings: 1. **Correctness diagnostics** are compiler errors such as invalid syntax, unresolved names, type mismatches, borrow violations, illegal pointer capability escalation, and invalid FFI declarations. They cannot be disabled. 2. **Lint diagnostics** are configurable findings with stable symbolic IDs. Their levels are `allow`, `warn`, or `deny`. This separation matters in fix mode: an unrelated existing compiler error may coexist with an exact syntax migration, but a semantic cleanup never runs without the phase that proves it safe. ## Current rules | Rule | Group | What it detects | Automatic fix | | --- | --- | --- | --- | | `unused_import` | `unused` | resolved imports with no semantic use | yes | | `unused_local` | `unused` | local bindings with no semantic reads | suggestion; deletion only when proven effect-free | | `unused_mutability` | `unused` | binding mutability never required | yes | | `unused_assignment` | `unused` | value overwritten before any read | yes when the RHS is effect-free | | `ignored_result` | `unused` | discarded value resolving to the canonical `Result` lang item | no | | `unawaited_future` | `unused` | discarded value whose resolved type is `Future` | no | | `redundant_identity_cast` | `redundancy` | exact non-pointer identity casts | yes | | `redundant_literal_cast` | `redundancy` | a literal suffix already fixes the destination type | yes | | `redundant_pointer_cast` | `pointer_migration` | exact pointer identity casts | yes, only with semantic identity proof | | `redundant_clone` | `redundancy` | cloning an exact `Copy` value | yes | | `no_effect_statement` | `redundancy` | discarded expression proven effect-free | yes | | `self_assignment` | `suspicious` | both sides resolve to the same semantic place | yes | | `unreachable_code` | `suspicious` | local code after unconditional control flow | suggestion | | `suspicious_shadowing` | `pedantic` | a nested same-named binding ends and the exact outer binding resumes | no; opt-in | | `unreachable_match_alternative` | `pedantic` | earlier unguarded alternatives fully cover an exact bool/enum pattern | no; opt-in | | `borrowed_value_escapes` | `pedantic` | a borrowed/view value crosses an exact container-store or channel boundary | no; opt-in | | `constant_comparison` | `suspicious` | comparison result proven by typed operand ranges | no | | `empty_range` | `suspicious` | range proven empty by typed bounds | no | | `empty_block` | `suspicious` | empty block without an explanatory comment | suggestion | | `deprecated_syntax` | `migration` | supported legacy grammar with an exact replacement | yes | | `legacy_pointer_syntax` | `pointer_migration` | `ptr`, `*T`, legacy null casts | yes | | `legacy_void_type` | `pointer_migration` | legacy Vex `void` type positions | yes | | `discarded_allocation` | `performance` | exactly proven allocation result immediately discarded | no; opt-in | | `last_use_owned_clone` | `performance` | a non-Copy owned local is cloned at its proven final non-repeating use | no; opt-in | | `exported_allocation` | `api` | exported function with allocation in its transitive effect summary | no; opt-in | | `exported_raw_pointer_abi` | `api` | exported Vex signature exposing a raw pointer capability | no; opt-in | | `exported_borrowed_return` | `api` | exported return is a borrow/view derived from an exact input binding | no; opt-in | | `exported_ownership_transfer` | `api` | exported return transfers ownership out of an exact input/receiver chain | no; opt-in | | `redundant_contract_bound` | `pedantic` | a resolved bound is implied by another exact contract inheritance edge | no; opt-in | | `out_of_range_numeric_cast` | `pedantic` | integer value range proven outside the target type | no; opt-in | | `potentially_lossy_numeric_cast` | `pedantic` | numeric type domains cannot preserve every source value | no; opt-in | The default profile warns for correctness-adjacent, unused, redundancy, suspicious, and migration rules. Evidence-backed performance, API, and pedantic rules remain `allow` until selected. Unknown selectors are configuration errors instead of silently doing nothing. Available profiles are: | Profile | Additional opt-in groups | | --- | --- | | `default` | none | | `performance` | `performance` | | `pedantic` | `pedantic` | | `library` | `api` | | `strict` | `performance`, `pedantic`, `api` | An explicit rule/group level overrides profile promotion. `--only` also promotes the selected opt-in rule or group to `warn`, unless it was explicitly set to `allow`. ## Pointer migration The canonical raw-pointer surface is: ```vex Ptr // readable pointee capability Ptr // writable pointee capability Ptr // opaque C-compatible object pointer ``` The focused migration group performs syntax-aware conversions: ```text ptr -> Ptr *T -> Ptr *T! -> Ptr 0 as *T -> Ptr.null() fn callback(): void -> fn callback(): () Result -> Result ``` Run it independently from unrelated cleanup rules: ```bash vex lint --only pointer_migration legacy-package vex lint --diff --only pointer_migration legacy-package vex lint --fix --only pointer_migration legacy-package ``` Direct function and callback results use `()`. Nested or value-position unit types use the `unit` keyword because it is unambiguous inside generic grammar. C source embedded as a compiler fixture remains C and is not interpreted as Vex pointer syntax. ## Why `--fix` is conservative `vex lint --fix` does not apply a bag of textual replacements. Every edit is: - attached to the exact source revision and expected original text; - planned with overlap and conflict detection; - applied first to an in-memory workspace; - reparsed and semantically reanalyzed; - iterated to a fixed point, with a maximum of four passes; - written atomically only after verification succeeds. Verification fingerprints function identity, inferred signatures and bindings, callable and overload selection, generic arguments, call operand/result types, and correctness diagnostics. If a fix changes a semantic decision or introduces a new compiler error, no files are committed. Use `--diff` to run the same verified pipeline without writing: ```bash vex lint --diff . ``` ## Rule selection and levels ```bash vex lint --only unused . vex lint --allow empty_block . vex lint --warn performance . vex lint --deny unused_import . vex lint --deny-warnings . ``` `--only` selects one rule or group while correctness analysis still runs. Repeated `--allow`, `--warn`, and `--deny` flags may target either a symbolic rule ID or a group. CLI settings override manifest settings. Package configuration lives in `vex.json`: ```json { "lint": { "profile": "default", "levels": { "unused": "warn", "unused_import": "deny", "pedantic": "allow" }, "exclude": ["generated/**", "vendor/**"], "baseline": ".vex/lint-baseline.json" } } ``` ## Staged CI baselines A baseline lets an existing package adopt strict lint gates without hiding its current debt: ```bash vex lint --deny-warnings --write-baseline .vex/lint-baseline.json . vex lint --deny-warnings --baseline .vex/lint-baseline.json . ``` Baseline findings remain present in terminal, JSON, SARIF, and editor output; they are tagged as baselined and do not fail the lint gate. New findings do. Compiler correctness errors are never baselined. Reports include `matched`, `new`, and `stale` counts, making obsolete entries visible instead of silently accumulating them. The file is strict, versioned JSON and is written atomically. Entries use package-relative paths and source-aware anchors rather than absolute line numbers, so inserting unrelated lines does not churn the baseline. Configure it once in `vex.json` with `lint.baseline`; an explicit `--baseline` path overrides the manifest. ## Local suppression Suppressions use stable rule or group IDs: ```vex // vex-lint: allow-file unused_import, deprecated_syntax fn example() { // vex-lint: allow-next unused_mutability let! intentionallyMutable = 1 } ``` `allow-file` is valid only before the first item. `allow-next` applies to the next syntax item or statement. Suppressed diagnostics remain visible in JSON metadata so editors and audit tools can explain the decision. Correctness errors cannot be suppressed this way. ## Machine-readable output and editors ```bash vex lint --format json . vex lint --format sarif . vex lint --format json --timings . ``` JSON reports stable rule IDs, groups, levels, byte ranges, notes, structured fixes, applicability, source revisions, and suppression metadata. Diagnostic ordering is deterministic by file, source offset, severity, and rule ID. The top-level `semantic_fact_schema_version` lets consumers version semantic facts independently from diagnostic wording. Schema v5 models pattern-binding origins and treats clone, transfer, and exact owning coercions such as `str -> string` as ownership provenance barriers. It consumes the compiler-owned `Copy` contract identity and distinguishes immutable program-storage literals from ordinary borrows. Trusted container and channel facts also identify the exact parameter slots that escape; indices and other non-stored arguments are never inferred to escape. SARIF 2.1.0 carries compiler correctness and lint results for external code scanners without changing the canonical JSON schema. `--timings` adds sorted per-rule invocation, finding, and elapsed-nanosecond telemetry to JSON/SARIF. Ordinary lint runs avoid clock reads entirely. Machine formats always emit exactly one parseable document. `--diff` and `--explain-boxing`/`--explain-arena` therefore require text output; fix status messages are suppressed for JSON/SARIF. The Vex language server consumes the same `LintReport` and source revisions as the CLI. Quick fixes and `source.fixAll.vex` use the shared conflict planner; the editor does not rediscover warnings or reconstruct edits from message text. ## Exit status | Code | Meaning | | ---: | --- | | `0` | no correctness errors or denied lints; ordinary warnings are allowed | | `1` | correctness errors, denied lints, or warnings denied by `--deny-warnings` | | `2` | invalid target, option, output format, or lint configuration | | `3` | fix planning or verification failed; no partial write was committed | | `101` | internal compiler or linter failure | ## Stability boundary The source tree contains tests for the registry, configuration, suppressions, reporting, LSP integration, revision-bound fixes, transactional writes, four-pass cycle guard, target-aware source routing, and pointer migration. These test definitions explain intended behavior; release qualification needs their results for the selected compiler and target. Do not infer Linux or Windows execution from a macOS run, or native program correctness from a successful lint check. The V2 corpus calibration covers VexArch and every standard-library package. Opt-in ownership/API findings remain visible for explicit review rather than being hidden to claim a clean corpus. Corpus review moved provably out-of-range casts to `pedantic`, because explicit signed-to-unsigned sentinel encodings are a valid low-level pattern; genuine discarded `Result` findings are fixed instead of suppressed. Automatic fixes intentionally cover less than diagnostics. Vex does not automatically rewrite pointer provenance, pointer/integer conversions, address-space changes, numeric narrowing, general arithmetic, alias-sensitive global stores, or speculative performance transformations. ## V2 semantic foundation V2 extends the same engine rather than introducing another linter. A lazy, revision-bound schema-v5 fact graph now owns exact call edges, transitive effect and allocation summaries, value provenance, compact ownership-transition and parameter-origin chains, exact unreachable match alternatives, and target-aware integer/conversion ranges. Reverse call edges use a monotone worklist, so only callers affected by a growing callee summary are revisited; recursive cycles converge without per-rule HIR recursion. All selected body rules share the same lowered body, inference result, binding facts, and V2 facts. Must-use ownership also prevents generic `no_effect_statement` from duplicating `Result`/`Future` diagnostics or offering an unsafe deletion fix. Ordinary lint analysis uses a semantic diagnostics snapshot and never flattens the import graph into a codegen module. The more expensive VUMM/codegen-ready snapshot is requested only by `--explain-boxing` or `--explain-arena`. Likewise, the full overload/signature/binding fingerprint is built only for `--fix` and `--diff`, where it proves that a proposed edit preserved semantics. This keeps normal diagnostics free of codegen-only module merging without weakening fix verification. For one-document editor runs, only the active file's reachable loaded imports join the fact graph as non-reporting support modules. Their effects reach the active file, while their diagnostics remain owned by their own publication and unrelated open files do not inflate the analysis. The first correctness, performance, and API rules listed above are implemented. Long-lived LSP sessions now retain a bounded semantic-fact cache across source revisions. Reuse requires exact Salsa body, signature, inference, and lang-item identity plus matching target and callee summaries; a dependency change cannot reuse stale caller effects. Rule work is also bounded-parallel: small jobs stay serial, larger jobs use at most four owned Salsa database forks and always merge in semantic source order. Exact borrowed escape, public ownership, last-use clone, resumed shadowing, unreachable-alternative, and redundant-bound rules consume these facts. Dead-private-item analysis remains gated on explicit entry/test/reflection root identities; it will not guess roots from names. Machine-readable staged-CI baselines are implemented. No V2 rule may infer meaning from a function or type name. Default-profile admission requires corpus false-positive review, and automatic fixes retain V1's atomicity, idempotence and semantic-fingerprint verification. Performance rules cannot assume that LLVM will make a transformation safe or profitable. ## Related - [`Ptr`](docs/guide/memory/ptr-t.md) - [Canonical raw pointers](docs/guide/types/raw-pointers.md) - [Pointers and low-level memory](docs/guide/advanced/pointers.md) - [CLI reference](docs/references/vex-cli-reference.md) - [Testing](docs/guide/tooling/testing.md) --- Source: https://vex-lang.org/docs/guide/tooling/testing.md # Testing and benchmarking Vex compiles each discovered test file with a generated runner. This gives tests the same ownership, contracts, SIMD, async and target semantics as normal programs while retaining process isolation and bounded execution. ## A complete test file Save the following as `tests/credit.test.vx`. The function applies a credit to an invoice total in integer minor units. It rejects negative inputs and a credit larger than the total before subtracting; valid inputs therefore produce a nonnegative result within the `i32` range. ```vex [tests/credit.test.vx] fn apply_credit(total: i32, credit: i32): Result { if total < 0 || credit < 0 { return Err(1); } if credit > total { return Err(2); } return Ok(total - credit); } fn test_credit_amounts(): bool { let partial = match apply_credit(1000, 250) { Ok(value) => value == 750, Err(_) => false, }; let full = match apply_credit(1000, 1000) { Ok(value) => value == 0, Err(_) => false, }; let zero = match apply_credit(0, 0) { Ok(value) => value == 0, Err(_) => false, }; return partial && full && zero; } fn test_credit_errors(): bool { let negative_total = match apply_credit(-1, 0) { Err(code) => code == 1, Ok(_) => false, }; let negative_credit = match apply_credit(1000, -1) { Err(code) => code == 1, Ok(_) => false, }; let excessive = match apply_credit(1000, 1001) { Err(code) => code == 2, Ok(_) => false, }; return negative_total && negative_credit && excessive; } ``` Run `vex test tests/credit.test.vx` from the project root. The intended result is two passing tests and process exit status 0. The file has no `main`: the runner supplies the entry point. Each test returns a boolean derived from the actual result, so an incorrect value or error code fails the test. This small example tests the function's contract, including zero, full-credit, and invalid-input boundaries. A real billing system would additionally define currency, rounding, persistence, and concurrency behavior; those concerns are outside this integer calculation. ## Tests The following **context-test fragment** shows subtest reporting. `decode` is an application-provided parser returning a result; define or import it before running this fragment. ```vex import { TestCtx } from "testing"; fn test_decode(t: &TestCtx!) { t.run("valid", |child: &TestCtx!| { child.assertTrue(decode("42").isOk()); }); t.run("invalid", |child: &TestCtx!| { child.assertTrue(decode("?").isErr()); }); } ``` Context tests return unit and report through `TestCtx`. Zero-argument tests may return `bool` (`true` passes) or an integer status (`0` passes). A zero-argument unit test can fail only by panic/abort, so use `TestCtx` for assertions. Discovery reads parsed function declarations rather than source lines. Test and benchmark names, `async`, context parameters and return types therefore retain the same meaning when a legal signature spans multiple lines. Receiver methods are not free test entrypoints. Select an existing directory, an exact `.vx` file, or a quoted glob. Directory discovery includes `*.test.vx`, `*_test.vx` and `*_bench.vx`; file globs can select other `.vx` filenames explicitly. Missing paths and globs selecting no source files fail with a nonzero exit status. An existing empty directory or a name filter matching no functions is an empty selection, not a passing test suite. Automatic traversal excludes generated runners and build/cache directories, does not follow directory symlinks, and deduplicates source-file aliases. An explicit directory-symlink root is supported. See the [`vex test` reference](docs/references/vex-test-reference.md) for the full selection rules. Skipped contexts are reported as SKIP, not PASS. Test state is private and cannot be overwritten by the test body. A test file containing discovered test functions must not define `main`. ## Benchmarks This **benchmark fragment** assumes an application-provided `table.lookup` operation. Use a real table and representative keys when measuring it. ```vex import { BenchCtx } from "testing"; fn bench_lookup(b: &BenchCtx!) { b.setBytes(4096); b.iter(17 as i64, |key: i64| table.lookup(key)); } ``` The duration-based `iter` family is preferred. Inputs and results cross a compiler barrier, clock checks are adaptively batched, and temporary arena allocations live in an isolated child region reclaimed every 128 operations. The runner restores the caller's previous region and arena mode before returning. For explicit setup, this fragment assumes application-provided `prepare` and `run` functions and an imported `blackBox` from `testing`: ```vex fn bench_manual(b: &BenchCtx!) { let data = prepare(); b.resetTimer(); for let i in 0..b.n { blackBox(run(data, i)); } b.stopTimer(); } ``` Run performance measurements with optimization enabled: ```bash vex test --bench -O3 --benchtime 1s --count 5 --benchmem path/to/tests ``` Benchmark files compile concurrently within a bounded worker pool, but run serially for isolation. `--count` repeats execution of the same compiled artifacts; it does not rebuild and relink every round. Report the compiler revision, target, input distribution, optimization level, iteration count and sample spread. Do not compare fastest outliers across different workloads. ## Useful commands ```bash vex test path/to/tests vex test "lib/std/net/tests/*.test.vx" vex test --run expression path/to/tests vex test --no-parallel --timeout 60 path/to/tests vex test --failfast path/to/tests vex test --json path/to/tests vex test --analyze-comptime path/to/tests ``` `--analyze-comptime` is observation-only; it does not change semantics or enable speculative rewrites. For tests, `--timeout` limits execution of each generated file runner, starting at entry to `main`. It is not multiplied by the number of test functions. Compilation and process startup use separate watchdogs; a slow compile does not consume the runtime allowance. A later timeout preserves completed test outcomes and partial diagnostics. Failure during process finalization is reported separately from individual tests, including when every test has already passed. JSON consumers should check the process exit status and `file_errors` as well as test counts; see the [`vex test` reference](docs/references/vex-test-reference.md). --- Source: https://vex-lang.org/docs/guide/tooling/vape.md # VAPE: Analysis, Fixes and Performance Tooling VAPE groups three complementary tools: `vex lint` for semantic source analysis, `vex view` for compiler representations, and `vex prof` for native microarchitectural inspection. ## `vex lint` `vex lint` is the canonical correctness and lint command. It analyzes one `.vx`/`.vxc` file, a package directory, or the nearest package when the target is omitted. It runs the parser and semantic pipeline without LLVM codegen. ```bash vex lint main.vx vex lint --format json main.vx vex lint --format sarif . vex lint --format json --timings . vex lint --deny-warnings . ``` Correctness errors are non-configurable. Lint findings use stable symbolic IDs in the `unused`, `redundancy`, `suspicious`, `migration`, `pointer_migration`, `performance`, `api` and `pedantic` groups. The default rules cover unused imports/locals/assignments/mutability, proven redundant casts and clones, pure discarded statements, self-assignment, unreachable code, empty blocks and exact syntax migrations. Semantic rules use resolved declaration and callable identities plus a shared, revision-bound graph of transitive effects, provenance, and target-aware numeric ranges. They do not decide whether code is unused, Copy, unsafe, allocating, or redundant from a source name. The `performance`, `library`, `pedantic`, and `strict` profiles promote evidence-backed opt-in groups. SARIF 2.1.0 integrates external code scanners without replacing canonical JSON. `--timings` adds sorted rule invocation/finding/latency counters only when requested; ordinary runs avoid clock reads. ### Configuration ```json { "lint": { "profile": "default", "levels": { "unused": "warn", "unused_import": "deny", "pedantic": "allow" }, "exclude": ["generated/**"] } } ``` CLI overrides take precedence: ```bash vex lint --only unused . vex lint --allow unused_mutability . vex lint --deny unused_import . ``` Local suppressions are structural: ```vex // vex-lint: allow-file unused_import fn example() { // vex-lint: allow-next unused_mutability let! value = 1 } ``` `allow-file` must appear before the first item. `allow-next` applies once to the next item or statement. JSON output retains suppressed findings and the directive that matched them. ## Verified automatic fixes ```bash vex lint --diff . vex lint --fix . vex lint --fix --only pointer_migration . ``` Fixes are revision-bound structured edits, not regular-expression rewrites. The engine rejects stale or conflicting edits, applies changes in memory, reruns semantic analysis for at most four fixed-point passes, and verifies that function signatures, binding types, exact overload/callable selection, generic arguments and correctness diagnostics do not regress. Files are atomically replaced only after verification succeeds; `--diff` performs the same proof without writing. The former `vex analyze`, `vex fix` and `vex check` compatibility commands have been removed. Commands, scripts and examples must use `vex lint`. ## LSP parity The Vex language server consumes the same report and fix structures. It uses the same rule IDs and conflict planner, marks unused/redundant diagnostics as unnecessary, rejects stale revisions, and exposes `source.fixAll.vex`. It does not independently scan names for unused imports or rebuild lint edits from diagnostic text. ## `vex view` ```bash vex view ast main.vx --format json vex view cfg main.vx --output cfg.dot vex view dfg main.vx --output dfg.dot vex view layout main.vx --struct-name Packet vex view escape main.vx --output escape.dot ``` These commands expose syntax, control/data flow, layout and ownership/escape information without applying source changes. ## `vex prof` ```bash vex prof main.vx vex prof main.vx --cpu apple-m2 ``` `vex prof` uses LLVM-MCA to report instruction throughput, latency and target execution-resource pressure. Profiling is deliberately separate from lint: source diagnostics and fixes never rely on an LLVM optimization result. --- Source: https://vex-lang.org/docs/guide/types/advanced-patterns.md # Pattern Matching -- Advanced Patterns Examples without `fn main` are independent fragments; application-specific functions such as `compute` and `process` stand for your own code. This page covers pattern matching features beyond the basics: `if let`, `while let`, match guards, or-patterns, rest patterns, and destructuring in `let` bindings. ## `if let` -- Conditional Single-Pattern Match `if let` tests a value against a single pattern and executes the block only if it matches. It is syntactic sugar for a `match` with one arm and a wildcard. ```vex let opt: Option = Some(42) // if let: concise single-pattern match if let Some(value) = opt { $println(f"Got value: {value}") } // Equivalent match (more verbose) match opt { Some(value) => $println(f"Got value: {value}"), None => {}, } ``` ### `if let` with Multiple Conditions Test an additional condition inside the successful pattern branch: ```vex let data: Result = fetchData() if let Ok(value) = data { if value > 0 { $println(f"Positive result: {value}") } } ``` ### `if let` with Struct Patterns ```vex struct Point { public: x: f64, y: f64, } let maybe_point: Option = Some(Point { x: 3.0, y: 4.0 }) if let Some(Point { x, y }) = maybe_point { $println(f"Point at ({x}, {y})") } ``` ### `if let` with `else` ```vex let result = compute() if let Ok(data) = result { process(data) } else { $println("Computation failed") } ``` ## `while let` -- Loop While Pattern Matches `while let` repeatedly tests a value against a pattern, continuing as long as it matches: ```vex let! stack = Vec.new() stack.push(1) stack.push(2) stack.push(3) // pop removes the final element: this is a stack. while let Some(item) = stack.pop() { $println(f"Processing: {item}") } // Output: Processing: 3, Processing: 2, Processing: 1 ``` ### Iterator Pattern with `while let` ```vex let! iter = someCollection.iter() while let Some(element) = iter.next() { process(element) } ``` ### Draining Available Channel Messages ```vex while let Some(msg) = channel.tryRecv() { handleMessage(msg) } ``` `tryRecv` is nonblocking. This loop stops when no message is immediately available; it does not wait for future messages or prove that producers have finished. See [Channels](docs/guide/concurrency/channels.md) for blocking receive and closure behavior. ## Match Guards -- Conditional Patterns Match guards add a boolean condition after a pattern using `if`: ```vex let number = 15 let description = match number { n if n < 0 => "negative", n if n == 0 => "zero", n if n < 10 => "single digit", n if n % 2 == 0 => "even", n => "odd", } // description = "odd" ``` ### Guards with Enum Patterns ```vex fn processResult(res: Result): string { return match res { Ok(v) if v > 100 => "large success", Ok(v) if v > 0 => "small success", Ok(v) => "zero or negative", Err(e) if e.startsWith("NET_") => f"Network error: {e}", Err(e) => f"Other error: {e}", } } ``` ### Guards with Destructured Patterns ```vex struct Person { public: name: string, age: i32, } fn canDrink(person: Person): bool { return match person { Person { age, .. } if age >= 21 => true, _ => false, } } ``` ### Bindings in guarded alternatives Every alternative must provide the bindings the arm uses. For example, `Some(n) | None if n > 0` is invalid because `None` does not bind `n`. Use separate arms for these different shapes: ```vex fn positive(value: Option): bool { return match value { Some(n) if n > 0 => true, Some(_) => false, None => false, }; } ``` ## Or-Patterns -- Multiple Patterns, One Arm Use `|` to match multiple patterns with the same handler: ```vex let x = 2 let kind = match x { 1 | 2 | 3 => "small", 4 | 5 | 6 => "medium", _ => "large", } ``` ### Or-Patterns with Enums ```vex fn isClientError(res: Result): bool { return match res { Err(BadRequest) | Err(Unauthorized) | Err(Forbidden) | Err(NotFound) => true, _ => false, } } ``` ### Matching Different Shapes ```vex [areas.vx] enum Shape { Circle(f64), Rectangle(f64, f64), Triangle(f64, f64, f64), } fn area(shape: Shape): f64 { return match shape { Shape.Circle(r) => 3.14159 * r * r, Shape.Rectangle(w, h) => w * h, Shape.Triangle(a, b, c) => { let s = (a + b + c) / 2.0; Math.sqrt(s * (s - a) * (s - b) * (s - c)) }, }; } fn main(): i32 { let circle = area(Shape.Circle(2.0)); let square = area(Shape.Rectangle(2.0, 2.0)); let rectangle = area(Shape.Rectangle(2.0, 3.0)); let triangle = area(Shape.Triangle(3.0, 4.0, 5.0)); if circle < 12.56635 || circle > 12.56637 { return 1; } if square != 4.0 || rectangle != 6.0 || triangle != 6.0 { return 1; } $println("areas ok"); return 0; } ``` This fixture assumes non-negative circle and rectangle dimensions and valid triangle sides; it does not validate inputs. The circle uses an approximation of π, so its check uses a tolerance. The expected output is `areas ok`, with exit status 0. ## Rest Patterns -- Ignoring Remaining Fields The `..` pattern ignores remaining fields or elements: ### In Struct Patterns ```vex struct Config { public: host: string, port: i32, timeout: i32, retries: i32, verbose: bool, } let cfg = Config { host: "localhost", port: 8080, timeout: 5000, retries: 3, verbose: true } // Only extract what you need let Config { host, port, .. } = cfg // host = "localhost", port = 8080, rest is ignored ``` ### In Tuple Patterns Spell the tuple shape explicitly and use `_` for each ignored position: ```vex let triple = (1, 2, 3) let (first, _, last) = triple // first = 1, last = 3 ``` ### In Array Patterns Array rest patterns are terminal. `..` ignores the remaining elements; `...rest` binds them. A suffix after the rest, such as `[first, .., last]`, is not accepted. ```vex let numbers = [10, 20, 30, 40, 50] let [head, ..] = numbers let [first, second, ...rest] = numbers // head = first = 10; second = 20; rest contains 30, 40, 50. ``` Use a pattern whose fixed prefix fits the array. Matching a fixed-size array against an empty-array pattern does not make it a variable-length collection. ## Destructuring in `let` Bindings Beyond `match`, patterns work directly in `let` statements: ### Struct Destructuring ```vex struct Point { public: x: f64, y: f64, } let p = Point { x: 3.0, y: 4.0 } // Destructure into individual variables let Point { x, y } = p // x = 3.0, y = 4.0 // Rename fields during destructuring let Point { x: px, y: py } = p // px = 3.0, py = 4.0 ``` ### Tuple Destructuring ```vex let pair = (42, "hello") let (num, text) = pair // num = 42, text = "hello" ``` ### Array Destructuring ```vex let rgb = [255u8, 128u8, 64u8] let [r, g, b] = rgb // r = 255, g = 128, b = 64 ``` ### Enum variants and early return A variant can fail to match, so handle that branch explicitly with `match` or `if let`. The documented `let` destructuring forms are tuples, structs, and arrays; use the following early-return pattern for an `Option`: ```vex fn incrementPresent(value: Option): Option { let inner = match value { Some(inner) => inner, None => return None, }; return Some(inner + 1); } ``` This keeps `inner` available after the match and makes the unsuccessful path visible. It does not require `let Some(...) = ... else` syntax. ## Pattern Matching on References When matching through references, Vex automatically dereferences: ```vex fn describe(opt: &Option): string { return match opt { Some(v) => f"Value: {v}", // v is &i32, auto-derefed None => "Nothing", } } ``` ## Best Practices 1. Use `if let` when you only care about one pattern and want to ignore all others. 2. Use `while let` for consuming iterators or processing queues until exhaustion. 3. Use guards (`if` in match arm) instead of complex nested matches. 4. Use `|` (or-patterns) to avoid code duplication when multiple patterns share the same handler. 5. Use `..` (rest pattern) to extract only the fields you need from large structs; use terminal array rest patterns for arrays. 6. Prefer `let` destructuring for fixed-shape data (tuples, known struct fields). 7. Use `match` when you need exhaustiveness checking -- the compiler ensures all cases are covered. 8. Use explicit `match` and early `return` when a variant mismatch must stop the function. ## Related Pages - [Pattern Matching](docs/guide/types/pattern-matching.md) -- basic patterns - [Enums](docs/guide/types/enums.md) -- enum variant patterns - [Structs](docs/guide/types/structs.md) -- struct destructuring --- Source: https://vex-lang.org/docs/guide/types/aliases.md # Type Aliases A type alias gives an existing type another name. It improves readability but does not create a distinct type or enforce a domain invariant by itself. ## Basic Aliases This complete example uses a transparent alias, a generic tuple alias, and two distinct wrapper structs: ```vex [aliases.vx] type UserId = u64; type Pair = (T, T); struct OrderId { value: u64, } struct AccountId { value: u64, } fn show(id: UserId): u64 { return id; } fn main(): i32 { let raw: u64 = 42; let id: UserId = raw; let pair: Pair = (3, 4); let account = AccountId { value: id }; let order = OrderId { value: 7 }; $println(show(raw)); $println(pair.0 + pair.1); $println(account.value + order.value); return 0; } ``` `vex run aliases.vx` prints `42`, `7`, and `49` on separate lines. Passing the `u64` variable `raw` to `show`, whose parameter is `UserId`, illustrates that the alias is transparent. The generic `Pair` is a tuple of two `i32` values. ## Generic Aliases A generic alias can name a repeated type expression such as `Pair = (T, T)` above. It does not add new behavior to the aliased type. For associated types on a contract, use the [contract example](docs/guide/types/contracts.md#associated-types); an associated type is part of a contract implementation, not a generic alias declaration. ## When to Use Use aliases for readable names or repeated type expressions. When two values must remain distinct, use separate named structs with named fields, as `AccountId` and `OrderId` above do. Assigning `account` directly to an `OrderId` is a type error: the two named structs have distinct identities. A wrapper alone does not validate the numeric value; enforce invariants at construction boundaries. ## Associated Types in Contracts Associated types are selected by a contract implementation and may be used through a generic bound. See the [complete `NextInt` example](docs/guide/types/contracts.md#associated-types). ## Choosing a type abstraction Use a generic alias to give the same type expression a reusable name. Use a contract with an associated type when each implementation chooses a related type, such as an iterator's `Item`. Use a named wrapper when values with the same representation must have different identities. These choices express different constraints; an alias does not convert or validate a value. ## Best Practices - Choose a name that explains the role of the value; an alias does not guarantee uniqueness or validity. - Use a named struct when distinct types matter, and validate any stronger invariants explicitly. - Keep aliases close to the domain they describe; use an associated type when the choice belongs to a contract implementation. ## Next Steps - [Generics](docs/guide/types/generics.md) - [Contracts](docs/guide/types/contracts.md) - [Comptime](docs/guide/advanced/comptime.md) --- Source: https://vex-lang.org/docs/guide/types/arrays.md # Arrays An array `[T; N]` stores a fixed number of elements of one type. The count is part of the type, so `[i32; 3]` and `[i32; 4]` are different types. Use an array when a shape is fixed; use `Vec` when the sequence must grow or shrink. ## Declaration and initialization ```vex let samples: [i32; 4] = [10, 20, 30, 40]; let zeros: [i32; 4] = [0; 4]; let weights: [f32; 3] = [1.0, 2.0, 3.0]; ``` A repeated initializer is useful for Copy values such as numbers. It does not mean that an arbitrary owning value can be duplicated by copying its bytes. ## A complete computation ```vex [array-sum.vx] fn sum4(values: [i32; 4]): i32 { let! total = 0; for value in values { total += value; } return total; } fn main(): i32 { let samples: [i32; 4] = [10, 20, 30, 40]; let total = sum4(samples); $println(total); if total != 100 { return 1; } return 0; } ``` Save it as `array-sum.vx` and run `vex run array-sum.vx`. Expected stdout is `100` and exit status is 0. Passing a different length to `sum4` is a type mismatch; length is not merely a runtime convention. ## Element access Indices are zero-based. For an array of length `N`, valid element indices are `0` through `N-1`; an empty array has no valid element index. ```vex let! samples: [i32; 3] = [10, 20, 30]; samples[1] = 99; $println(samples[1]); // 99 ``` A mutable binding permits assignment to its elements when no conflicting borrow is live. Use a checked container accessor or validate an external index before indexing; do not rely on an out-of-bounds read yielding a sentinel. ## Iteration and transformation For ordinary integer processing, an explicit loop makes the output shape and ownership visible: ```vex [array-transform.vx] fn main(): i32 { let input: [i32; 3] = [1, 2, 3]; let! doubled: [i32; 3] = [0; 3]; for index in 0..3 { doubled[index] = input[index] * 2; } $println(doubled[0]); $println(doubled[1]); $println(doubled[2]); return 0; } ``` Expected stdout is `2`, `4`, and `6`, exit status 0. A transformation that can change the number of elements should generally return a `Vec` or an explicit count, rather than pretending a fixed-size array has shrunk. ## Arithmetic and masks The tensor/SIMD surface supports element-wise operations on compatible fixed numeric arrays, scalar broadcast, and masks. The array lengths and element types must fit the operation's requirements: ```vex let left: [f32; 4] = [1.0, 2.0, 3.0, 4.0]; let right: [f32; 4] = [5.0, 6.0, 7.0, 8.0]; let sum = left + right; // element-wise: 6, 8, 10, 12 let shifted = left + 10.0; ``` These are numeric-operation fragments, not guarantees of a particular instruction count. A source-level vector operation may become several machine instructions, a loop, or scalar code depending on its shape, target features, operation, and optimization settings. A compiler lowering threshold such as 64 bytes is not a promise that every CPU has a register of that width. See [SIMD](docs/guide/simd/index.md) for operation and backend boundaries. ## Views and slices A view borrows storage; it does not own the array or extend its lifetime. When an API needs a `Span`, use the supported view construction for that source type and keep the owner alive for the entire use. Do not assume that all array, vector, pack, and raw-pointer conversions have the same coercion rule. The [Span guide](docs/guide/memory/span-t.md) provides a complete example using the explicit `Vec.asSpan()` interface and explains raw construction separately. ## Multidimensional arrays Nested arrays encode each dimension: ```vex let matrix: [[i32; 3]; 2] = [ [1, 2, 3], [4, 5, 6], ]; let last = matrix[1][2]; // 6 ``` The outer count is the number of rows; the inner count is the number of elements in a row. Validate each index against its own dimension. ## Destructuring A fixed array can be destructured in a `let` or `match` pattern: ```vex let [red, green, blue] = [255 as u8, 128 as u8, 64 as u8]; let values = [10, 20, 30]; let total = match values { [a, b, c] => a + b + c, _ => 0 }; ``` A trailing `..` ignores remaining elements. A trailing `...rest` binds them. The rest must be the final array-pattern element: `[first, .., last]` is not accepted. Do not assume that a rest binding is an independently owning copy; its access and lifetime depend on the matched value and pattern context. See [Advanced patterns](docs/guide/types/advanced-patterns.md). ## Copy and move semantics An array is Copy when its elements satisfy the structural Copy rules. An array of integers can therefore be assigned while the original remains usable. An array containing owning boxes is not made Copy merely because its fixed length is known. Assignment and destructuring must preserve element ownership; use borrows when the original values need to remain in place. ## Choosing a collection | Need | Usual choice | | --- | --- | | Fixed shape encoded in the type | `[T; N]` | | Owned sequence with changing length | `Vec` | | Borrowed contiguous view | `Span` | | Heterogeneous group of values | A tuple or named struct | ## Related pages - [Tuples](docs/guide/types/tuples.md) - [Vectors](docs/guide/types/vec.md) - [SIMD operations](docs/guide/simd/simd-operations.md) - [Pattern matching](docs/guide/types/pattern-matching.md) --- Source: https://vex-lang.org/docs/guide/types/closures.md # Closures Closures (also called lambdas or anonymous functions) are functions that can capture variables from their enclosing scope. They are a core building block for functional-style programming, callbacks, and iterator chains in Vex. ## Syntax Vex closure syntax uses pipe-delimited parameters directly followed by the body expression or block. No `=>` is needed: ```vex // Basic closure: |params| expression let double = |x: i32| x * 2 // Multi-parameter let add = |a: i32, b: i32| a + b // No parameters let greet = || $println("Hello") // Multi-statement body with braces let compute = |x: i32, y: i32| { let temp = x * y let result = temp + 10 return result } ``` ## Calling a Closure Call closures with the same `()` syntax as regular functions: ```vex let triple = |n: i32| n * 3 let six = triple(2) // 6 let nine = triple(3) // 9 ``` ## Type Inference Closure parameter types can often be inferred from context: ```vex // Named function reference: fn timesTwo(x: i32): i32 { return x * 2 } let number: Option = Some(5) let doubled: Option = number.map(timesTwo) // An explicitly typed closure is another way to provide the callback: let doubledAgain: Option = number.map(|x: i32| x * 2) ``` An expected callable type supplies context for a closure. Explicit parameter types also document the callback contract and distinguish a borrowed `&T` from an owned `T`. This matters for generic collection transforms and for callbacks whose input and output types differ. See the [Option](docs/guide/types/option-api.md) and [Result](docs/guide/types/result-api.md) examples. ## Capture Modes Closures may capture variables from their enclosing scope. The compiler analyzes how each capture is used and checks its ownership and lifetime. Do not infer the physical representation solely from the source syntax: the compiler can copy a read-only scalar into the environment, borrow storage, or transfer ownership depending on the value and use. ### Shared (Immutable) Capture When a closure only reads captured variables: ```vex let multiplier = 10 // Reads multiplier. A Copy scalar can be copied into the environment. let scale = |x: i32| x * multiplier let result = scale(5) // 50 // multiplier is still usable here ``` ### Mutable Capture When a closure modifies captured variables: ```vex let! counter = 0 // Captures counter by mutable reference let increment = || { counter += 1 } increment() increment() // counter is now 2 ``` ### Move Capture Some uses transfer ownership into a closure environment. The exact outcome depends on the captured type and how the closure is used. Do not assume that a move-only value remains usable after ownership transfers. If a callback needs repeatable access, borrow for a bounded call or give it an explicitly owned handle with the appropriate sharing policy. A closure returning or retaining a reference cannot extend the lifetime of its referent. ### A runnable capture example This example exercises a read-only scalar, a mutable capture, an ordinary callback and a returned closure. Save it as `capture-example.vx`: ```vex [capture-example.vx] fn applyTwice(f: fn(i32): i32, x: i32): i32 { return f(f(x)); } fn makeMultiplier(factor: i32): fn(i32): i32 { return |x: i32| x * factor; } fn addOne(x: i32): i32 { return x + 1; } fn main(): i32 { let multiplier = 10; let scale = |x: i32| x * multiplier; $println(scale(5)); $println(multiplier); let! counter = 0; let increment = || { counter += 1; }; increment(); increment(); $println(counter); let addThree = |n: i32| n + 3; $println(applyTwice(addThree, 10)); let timesFive = makeMultiplier(5); $println(timesFive(10)); let named: fn(i32): i32 = addOne; $println(named(41)); return 0; } ``` `vex run capture-example.vx` prints: ```text 50 10 2 16 50 42 ``` ## Closure Types Use a function-value signature to describe the callback interface independently of its captures: ```vex // Function that accepts any callable returning i32 fn applyTwice(f: fn(i32): i32, x: i32): i32 { return f(f(x)) } let addThree = |n: i32| n + 3 let result = applyTwice(addThree, 10) // (10+3)+3 = 16 ``` ## Closures as Callbacks Closures are the standard way to pass behavior into higher-order functions: ```vex fn sumWhere(values: &Vec, predicate: fn(i32): bool): i32 { let! total = 0; for value in values { if predicate(*value) { total += *value; } } return total; } ``` The vector remains borrowed for the call, and the callback receives an integer copy. With `[1, 2, 3, 4, 5, 6]` stored in a `Vec`, `sumWhere(&numbers, |n: i32| n % 2 == 0)` returns `12`. For library adapters, use the receiver and callback signatures on the [Vec](docs/guide/types/vec.md), [Option](docs/guide/types/option-api.md), and [Result](docs/guide/types/result-api.md) pages. An array does not gain those methods merely because it contains the same element type. ## Closures with `go` Blocks `go` blocks capture the values they use. Ownership, borrowing and lifetime checks still apply; inspect the diagnostics for the captured types rather than assuming that every capture has the same representation: ```vex let! messages = Channel.new(10) let prefix = "Msg: " // The block uses both prefix and messages. go { let text = prefix + "hello from goroutine" messages.send(text) } let received = <-messages ``` ## Closures vs Function Pointers | Feature | Closure | Named Vex function as a value | | --- | --- | --- | | Captures | May use an environment | Does not capture local variables | | Native callable | Entry point plus environment/context | Uses the Vex callable representation as well | | Cost | Depends on capture, lifetime, lowering and optimization | Depends on lowering and optimization | | Foreign callback | Requires an explicitly supported foreign adapter and lifetime contract | Also requires the exact foreign ABI and a supported adapter | The native implementation represents a Vex function value with a code pointer and an environment/context pointer. Environment storage depends on the captures and may outlive the defining scope when supported. This is an internal implementation detail, not a stable public or C ABI. Do not assume a native `fn(...)` value is one pointer or that either kind of callable is directly interchangeable with a C callback. See [Function Types](docs/guide/types/function-types.md) and [FFI callbacks](docs/guide/ffi-deep-dive.md#callbacks). ```vex // Named function as a native Vex callable; no local capture. let fp: fn(i32): i32 = someTopLevelFn // Closure: can capture, used for local callbacks let closure = |x| x + capturedValue ``` ## Returning Closures An escaping closure must retain valid captures for its lifetime. Allocation and capture strategy are implementation details and may vary with the compiler: ```vex fn makeMultiplier(factor: i32): fn(i32): i32 { // This closure escapes the function and retains the scalar factor. return |x: i32| x * factor } let timesFive = makeMultiplier(5) let result = timesFive(10) // 50 ``` ## Best Practices 1. Use the shortest closure form (`|x| x * 2`) when the body is a single expression. 2. Use brace-delimited bodies for multi-statement closures. 3. Let type inference work -- annotate parameter types only when the compiler asks for it. 4. Be aware of capture and ownership: reads may copy or borrow, mutation requires appropriate access, and some uses transfer ownership. 5. For `go` blocks, be explicit about which variables are used inside to avoid accidental captures. 6. For FFI callbacks, verify the foreign ABI, adapter, context lifetime and thread rules; a native `fn(T): R` alone is not sufficient. ## Related Pages - [Function Types](docs/guide/types/function-types.md) -- `fn(T): R` pointers - [Loops & Labels](docs/guide/basics/loops.md) -- closures in iteration - [Async](docs/guide/concurrency/async.md) -- closures in async context --- Source: https://vex-lang.org/docs/guide/types/complex.md # Complex Numbers `Complex` groups real and imaginary components. The prelude representation uses the public fields `real` and `imag`; choose an explicit numeric component type such as `f64` for numerical work. ## Construction and components Construct the value with a struct literal: ```vex let point = Complex { real: 3.0, imag: 4.0 }; let real_part = point.real; let imaginary_part = point.imag; ``` Zero and purely real or imaginary values use the same form. Do not assume constructors such as `Complex.new`, `fromPolar`, or `fromImaginary` are present merely because another complex-number library offers them. ## Addition, subtraction, and multiplication The prelude defines component-wise addition and subtraction and the usual complex product `(a + bi)(c + di) = (ac - bd) + (ad + bc)i`: ```vex [complex-product.vx] fn main(): i32 { let left = Complex { real: 1.0, imag: 2.0 }; let right = Complex { real: 3.0, imag: 4.0 }; let sum = left + right; let product = left * right; if sum.real != 4.0 || sum.imag != 6.0 { return 1; } if product.real != -5.0 || product.imag != 10.0 { return 2; } $println("complex arithmetic ok"); return 0; } ``` Expected stdout is `complex arithmetic ok`, exit status 0. These particular values have exactly representable results; general floating-point calculations need a tolerance and an explicit numerical error policy. Scalar addition/subtraction updates the real component while preserving the imaginary component. The prelude also defines scalar-left multiplication for its floating component types. Keep the scalar type compatible with the component type: ```vex let value = Complex { real: 3.0, imag: 4.0 }; let shifted = value + 10.0; // 13 + 4i let scaled = 2.0 * value; // 6 + 8i ``` ## Derived operations A small helper can express an operation whose method is not part of the prelude surface. For moderate finite values, the squared magnitude is: ```vex fn normSquared(value: &Complex): f64 { return value.real * value.real + value.imag * value.imag; } fn conjugate(value: &Complex): Complex { return Complex { real: value.real, imag: -value.imag }; } ``` The first formula can overflow or underflow for extreme components. Use a numerically scaled algorithm when that range matters. A formula illustrating complex arithmetic is not a substitute for a numerical library's error and exception contracts. Division, reciprocal, transcendental functions, polar conversion, and precision-conversion convenience methods are not provided by the inspected prelude declaration. This page therefore does not present `exp`, `ln`, `pow`, `sin`, `cos`, `tan`, `as_f32`, or `as_f16` as methods you can copy into a program. Build the required operation from validated component arithmetic or use a library that defines it explicitly. ## Example: bounded Mandelbrot iteration This helper uses only the component fields and the multiplication/addition operations above: ```vex [mandelbrot.vx] fn mandelbrotIterations(c: Complex, maxIterations: i32): i32 { let! z = Complex { real: 0.0, imag: 0.0 }; for iteration in 0..maxIterations { let squared = z.real * z.real + z.imag * z.imag; if squared > 4.0 { return iteration; } z = z * z + c; } return maxIterations; } fn main(): i32 { let inside = Complex { real: 0.0, imag: 0.0 }; let outside = Complex { real: 2.0, imag: 2.0 }; if mandelbrotIterations(inside, 10) != 10 { return 1; } if mandelbrotIterations(outside, 10) != 1 { return 2; } $println("bounded iteration ok"); return 0; } ``` Expected stdout is `bounded iteration ok`, exit status 0. The helper assumes finite components and a nonnegative iteration limit. Reaching the limit means that escape was not observed within that many iterations; it is not a proof of membership for every input. ## Ownership and arrays `Complex` follows the structural ownership of its two components. Numeric components can copy; an owning component does not become Copy merely because the declaration carries the Copy marker. An array of complex values is a fixed-shape collection. Do not infer support for every tensor operator, GPU backend, or vectorized transcendental function from that fact. Start with scalar correctness and verify the exact operation and target before relying on accelerated execution. ## Memory layout and FFI `Complex`, `[f64; 2]`, and C `_Complex double` are not interchangeable foreign-call contracts. In-memory fields and aggregate argument/return conventions are separate. A matching byte size does not establish ABI compatibility; use a target-specific C shim and validate both sides. ## Related pages - [Primitive types](docs/guide/types/primitives.md) - [Arrays](docs/guide/types/arrays.md) - [Operator methods](docs/guide/advanced/operators.md) - [FFI](docs/guide/ffi.md) --- Source: https://vex-lang.org/docs/guide/types/contracts-reference.md # Contracts Reference This page describes the main prelude and standard-library contracts. Contracts define shared behavior across types, similar to traits in Rust or interfaces in Go. ## Contract Categories Contracts are organized into three layers: | Layer | Location | Description | | ---------------------- | ------------------------------ | ------------------------------------------------------- | | **Operator Contracts** | `prelude/ops.vx` | Arithmetic, bitwise, comparison, indexing operators | | **Builtin Contracts** | `prelude/builtin_contracts.vx` | Core language capabilities (Display, Clone, Drop, etc.) | | **Standard Contracts** | `lib/std/contracts/src/` | Explicit conversion, collection and packed-data protocols | --- ## Operator Contracts (`prelude/ops.vx`) ### Arithmetic Operators #### `Add` -- Addition (`a + b`) ```vex contract Add { op+(rhs: Self): Self } ``` ```vex struct Vector2: Add { public: x: f64, y: f64, } fn (self: &Vector2) op+(rhs: Vector2): Vector2 { return Vector2 { x: self.x + rhs.x, y: self.y + rhs.y } } ``` #### `Sub` -- Subtraction (`a - b`) ```vex contract Sub { op-(rhs: Self): Self } ``` #### `Mul` -- Multiplication (`a * b`) ```vex contract Mul { op*(rhs: Self): Self } ``` #### `Div` -- Division (`a / b`) ```vex contract Div { op/(rhs: Self): Self } ``` #### `Mod` -- Modulo (`a % b`) ```vex contract Mod { op%(rhs: Self): Self } ``` #### `Neg` -- Unary Negation (`-a`) ```vex contract Neg { op-(): Self } ``` ```vex fn (self: &Vector2) op-(): Vector2 { return Vector2 { x: -self.x, y: -self.y } } ``` ### Bitwise Operators #### `BitAnd` -- Bitwise AND (`a & b`) ```vex contract BitAnd { op&(rhs: Self): Self } ``` #### `BitOr` -- Bitwise OR (`a | b`) ```vex contract BitOr { op|(rhs: Self): Self } ``` #### `BitXor` -- Bitwise XOR (`a ^ b`) ```vex contract BitXor { op^(rhs: Self): Self } ``` #### `BitNot` -- Bitwise NOT (`~a`) ```vex contract BitNot { op~(): Self } ``` #### `Shl` -- Left Shift (`a << b`) ```vex contract Shl { op<<(rhs: i32): Self } ``` #### `Shr` -- Right Shift (`a >> b`) ```vex contract Shr { op>>(rhs: i32): Self } ``` ### Comparison Operators #### `Eq` -- Equality (`a == b`, `a != b`) ```vex contract Eq { op==(rhs: &Self): bool op!=(rhs: &Self): bool // auto-implemented as !(a == b) } ``` ```vex struct Point: Eq { public: x: i32, y: i32, } fn (self: &Point) op==(rhs: &Point): bool { return self.x == rhs.x && self.y == rhs.y } fn (self: &Point) op!=(rhs: &Point): bool { return self.x != rhs.x || self.y != rhs.y } ``` #### `Ord` -- Ordering (`a < b`, `a > b`, `a <= b`, `a >= b`) ```vex contract Ord { op<(rhs: &Self): bool op>(rhs: &Self): bool op<=(rhs: &Self): bool op>=(rhs: &Self): bool } ``` #### `Not` -- Logical NOT (`!a`) ```vex contract Not { op!(): bool } ``` ### Other Operator Contracts #### `Index` and `IndexMut` -- Indexed Access ```vex contract Index { type Output; op[](index: Idx): Output; } contract IndexMut { op[](index: Idx): &Val!; op[]=(index: Idx, value: Val); } ``` The immutable output may itself be a reference. A collection must document its out-of-bounds policy and the lifetime of that reference; the contract alone does not choose panic, optional lookup, or unchecked access. See [Vec](docs/guide/types/vec.md) for the difference between `get`, `getMut`, and indexing. #### `Iterator` and `IntoIterator` ```vex contract Iterator { type Item; fn next(): Option; } contract IntoIterator { type Item; type IntoIter; fn iter(): IntoIter; } ``` These are the prelude declarations. The actual receiver implementation defines how cursor state advances. `Item` determines whether iteration yields an owned value or a reference; for example, `Vec.iter()` yields `&T`. A `for` loop does not imply that the collection's elements are moved out. --- ## Builtin Contracts (`prelude/builtin_contracts.vx`) ### `Display` -- Human-Readable String Used by `$println("{}", value)` and `toString()`. ```vex contract Display { fn toString(): string } ``` ```vex struct User: Display { public: name: string, age: i32, } fn (self: &User) toString(): string { return f"User({self.name}, {self.age})" } ``` ### `Debug` -- Debug String Representation Used by `$println("{:?}", value)`. ```vex contract Debug { fn debug(): string } ``` ### `Clone` -- Explicit Duplication Creates another value according to the implementing type's policy. It is not a universal deep-copy guarantee: `Box.clone()` shares the allocation, while a container may duplicate its storage and clone its elements. ```vex contract Clone { fn clone(): Self } ``` ```vex struct Node: Clone { public: value: i32, children: Vec, } fn (self: &Node) clone(): Node { return Node { value: self.value, children: self.children.clone() } } ``` ### `Drop` -- RAII Cleanup Called automatically when a value goes out of scope. Used for releasing resources. ```vex contract Drop { fn drop() } ``` The following fragment assumes a matching foreign `close` declaration and that this value uniquely owns a valid handle: ```vex struct File: Drop { public: handle: i32, } fn (self: &File!) drop() { unsafe { close(self.handle) } $println("File closed") } ``` ### `Hash`, `Hasher`, and `BuildHasher` -- Collection Hashing `Hash` values feed equality-relevant data into the state selected by a `Map` or `Set`. The value does not finalize its own hash. This lets each hosted container use an independent random key while deterministic tools select an explicit reproducible builder. **Rule:** `a == b` implies identical feeds, in identical order, for every `Hasher` implementation. ```vex contract Hasher { fn writeBytes(bytes: Span)! fn writeU32(value: u32)! fn writeU64(value: u64)! fn finish(): u64 } contract Hash { fn hashInto(state: &H!) } contract BuildHasher { type State: Hasher fn build(): Self.State } struct UserId: Eq, Hash { public: value: u64, } fn (self: &UserId) op==(other: &UserId): bool { return self.value == other.value; } fn (self: &UserId) op!=(other: &UserId): bool { return self.value != other.value; } fn (self: &UserId) hashInto(state: &H!) { self.value.hashInto(state) } ``` The default table policy is a keyed implementation detail, not a stable file format. Use the named `hash` package algorithms when output bytes must remain stable. Floating-point values do not implement `Hash` until their equality and NaN policy is defined consistently. ### `Bytes` -- Binary Serialization A byte-conversion protocol, whose implementation must define the encoding: ```vex contract Bytes { fn asBytes(): &[u8]; fn fromBytes(bytes: &[u8]): Result; } ``` The borrowed bytes must remain valid for their documented borrow lifetime. This contract does not establish that arbitrary struct memory is a wire format. Padding, endianness, alignment, and validation belong to the encoding implementation. Do not return a slice into a local temporary buffer or expose uninitialized padding as serialized data. ### Capability Marker Contracts These are **marker contracts** -- they have no methods and are used by the compiler for static analysis. #### `Copy` -- Bitwise Copyable Types that can be duplicated by copying their bits. Scalar primitives are `Copy`. Aggregate declarations opt in explicitly, and the compiler then proves the exact instantiated shape before granting the capability: ```vex // Marker -- no methods contract Copy { } struct Pair: Copy { left: T, right: T, } // Pair is Copy; Pair is not. ``` The spelling of a type is irrelevant. Prelude types such as `Option`, `Result`, `Range`, `Span`, and `Ptr` receive Copy behavior from their Vex declarations, not from a Rust-side type-name list. #### `Pin` -- Self-Referential Prevention Prevents moving self-referential types. Auto-applied by the compiler when self-referential fields are detected. ```vex contract Pin { } // marker ``` #### `Owner` -- Owning Capability The value is responsible for eventual destruction. VexArch owning types such as `Box`, `Vec`, `Map`, `Channel`, and `string` declare this capability in their source definitions. ```vex contract Owner { } // marker ``` #### `BorrowedView` -- Non-Owning View Non-owning reference into proven-live storage of `T`. `Span` and `str` declare this relationship in VexArch; ordinary `&T` and slices have equivalent intrinsic borrow semantics. ```vex contract BorrowedView { } // marker ``` #### `IndirectStorage` -- Out-of-Line Storage States that values of `T` live behind a container-owned backing allocation. The borrow checker follows this semantic edge when storage moves or grows; it does not recognize `Vec`, `Map`, or any other container name. ```vex contract IndirectStorage { } // marker ``` The same declaration also informs generic variance. Because the public abstraction owns values of `T` independently of its private raw backing pointer, `T` can remain covariant without a compiler-side `Vec`/`Map` table. #### `RelocationStableStorage` -- Storage Stable Across Owner Moves The owner's initialized `T` storage keeps its address when the owner handle moves. This sealed contract permits analysis of an aggregate that owns storage and holds a view into that same storage. It does not freeze the contents: growth, insertion, removal, and replacement can still invalidate views and remain subject to ordinary borrowing rules. ```vex contract RelocationStableStorage { } // sealed marker ``` #### `BulkReclaimSafe` -- Region Drop Elision Marks an audited VexArch value whose destructor has no observable effect beyond releasing storage owned by a compiler-selected region. If the exact allocation is routed into that region, Vex may omit the individual destructor and reclaim the storage in one bulk operation. ```vex contract BulkReclaimSafe { } // sealed marker ``` This is not a general-purpose user contract. It is sealed because an incorrect implementation could erase file, socket, synchronization, foreign-resource, or other observable cleanup. Types that do not need `Drop` are already eligible structurally; types that do need `Drop` receive this optimization only from the exact compiler-installed contract declaration. A same-named user contract has no effect. `string` currently opts in through its VexArch declaration; ordinary containers and custom destructors retain full drop behavior unless separately audited. #### `Invariant` -- Invariant Generic Parameter Declares that an abstraction both consumes and produces `T`, or otherwise requires exact type/lifetime identity. `Channel` and `Ptr` use this user-available conservative source marker. It overrides representation-only variance inference but can only reject conversions; it cannot grant ownership or lifetime authority. ```vex contract Invariant { } // marker ``` #### `ManagedSharing` -- Compiler-Managed Shared Handle Marks a trusted owning handle whose representation supports compiler-managed sharing. Developers still use the normal value type; public `Rc`/`Arc` and manual retain/release bookkeeping are not part of the Vex model. ```vex contract ManagedSharing { } // marker ``` #### `RawPointer` -- Raw Memory Handle Types carrying raw, unmanaged pointers. Used for FFI and low-level code. ```vex contract RawPointer { } // marker ``` #### `SuspendSafe` -- Await-Safe Marks trusted storage/lifetime behavior across `await` suspension boundaries. It does not permit a reference to outlive its owner. ```vex contract SuspendSafe { } // marker ``` #### `ConcurrentSafe` -- Thread-Safe Marks trusted behavior at concurrency boundaries. Sharing an allocation does not itself synchronize payload mutation; follow the container's public access and synchronization contract. ```vex contract ConcurrentSafe { } // marker ``` #### `ForeignManaged` -- Externally Owned Describes a trusted foreign-lifetime relationship. It does not, by itself, specify which foreign function releases a resource or make arbitrary foreign access safe. Application wrappers must state whether they borrow or own the foreign resource and follow the supported boundary for that representation. See [Extern Types](docs/guide/types/extern-types.md) for the supported surface and its limits. ```vex contract ForeignManaged { } // marker ``` #### `Dealloc` -- Manual Deallocation Types that support explicit, manual deallocation (typically unsafe). ```vex contract Dealloc { fn free() } ``` --- ## Standard Contracts (`lib/std/contracts/src/`) ### Conversion Contracts #### `From` -- Infallible Conversion ```vex contract From { static fn fromValue(value: T): Self; } ``` ```vex struct Celsius: From { public: value: f64, } fn Celsius.fromValue(value: f64): Celsius { return Celsius { value }; } let temp = Celsius.fromValue(100.0); ``` `From` is an explicit protocol. Constructor-driven implicit coercion is a separate compiler feature. #### `Into` -- Reverse of From ```vex contract Into { static fn intoValue(value: Self): T; } ``` The explicit `Self` parameter consumes the owner. Vex does not synthesize a blanket `Into` implementation from `From`. #### `TryFrom` -- Fallible Conversion ```vex contract TryFrom { type Error; static fn tryFromValue(value: T): Result; } ``` ```vex struct PositiveInt: TryFrom { public: value: i32, type Error = str; } fn PositiveInt.tryFromValue(value: i32): Result { if value <= 0 { return Err("value must be positive"); } return Ok(PositiveInt { value }); } ``` #### `TryInto` -- Fallible Reverse Conversion ```vex contract TryInto { type Error; static fn tryIntoValue(value: Self): Result; } ``` #### `Default` -- Default Value ```vex contract Default { static fn defaultValue(): Self; } ``` ```vex struct Config: Default { public: host: string, port: i32, } fn Config.defaultValue(): Config { return Config { host: "localhost", port: 8080 }; } let defaultConfig = Config.defaultValue(); ``` ### Comparison Contracts `std/contracts` exports only the `Ordering` value enum (`Less`, `Equal`, and `Greater`) in this category. `Eq`, `Ord`, operator behavior and hashing contracts are canonical prelude identities; the package does not create parallel aliases for them. ### Collection Contracts #### `Collection` Base contract for all collection types. ```vex contract Collection { len(): usize; isEmpty(): bool; clear()!; } ``` #### `Stack` -- LIFO ```vex contract Stack: Collection + Growable { push(value: T)!; pop()!: Option; peek(): Option<&T>; peekMut()!: Option<&T!>; } ``` #### `Queue` -- FIFO ```vex contract Queue: Collection + Growable { enqueue(value: T)!; dequeue()!: Option; front(): Option<&T>; frontMut()!: Option<&T!>; } ``` #### `Indexable` -- Indexed Access ```vex contract Indexable: Collection { get(index: Idx): Option<&T>; getMut(index: Idx)!: Option<&T!>; set(index: Idx, value: T)!; } ``` Iteration uses the canonical prelude `Iterator` and `IntoIterator` contracts; `std/contracts` does not define an `Iterable` alias. #### `Growable` -- Capacity Management ```vex contract Growable { capacity(): usize; reserve(minimumCapacity: usize)!; shrinkToFit()!; } ``` ### Ownership and memory contracts Ownership contracts such as `Drop` and `Owner` are canonical language contracts from the prelude; `std/contracts` does not define parallel versions. Heap ownership uses `Box`. The compiler and VUMM manage unique and shared handle modes internally—there are no public `Rc`, `Arc`, reference-count, retain, or release APIs for application code. The compiler resolves these contracts by declaration identity. It never grants ownership, view, indirect-storage, or sharing semantics because a type happens to be named `Vec`, `Span`, `Ptr`, `Box`, or `Channel`. Ordinary user aggregates receive the same structural Copy/Drop/borrow analysis as prelude aggregates. Memory-authority markers are sealed: only audited VexArch/standard-library definitions may assert a raw or hidden-storage invariant that structure alone cannot prove. `Invariant` is deliberately open because it is purely restrictive and grants no memory capability. #### `Owner` -- Ownership Marker ```vex contract Owner { } ``` #### `BorrowedView` -- Borrow Marker ```vex contract BorrowedView { } ``` #### `IndirectStorage` -- Backing-Allocation Marker ```vex contract IndirectStorage { } ``` #### `Invariant` -- Exact Generic-Identity Marker ```vex contract Invariant { } ``` #### `ManagedSharing` -- Managed Handle Marker ```vex contract ManagedSharing { } ``` #### `RawPointer` -- Raw Handle Marker ```vex contract RawPointer { } ``` #### `SuspendSafe` -- Async Safety Marker ```vex contract SuspendSafe { } ``` #### `ConcurrentSafe` -- Thread Safety Marker ```vex contract ConcurrentSafe { } ``` ### `PackedType` Contract Describes a custom block-encoded representation that can be decoded to and encoded from a logical element type. It is used by quantized ML formats and other packed-domain formats; it does not change a struct's native layout. ```vex contract PackedType { name(): str blockSize(): usize blockBytes(): usize bitsPerElement(): u8 decodeBlock(raw: Span): Tensor encodeBlock(input: &Span): Tensor } ``` The following is an incomplete implementation sketch: a conforming type must also implement both transforms. It is not a runnable encoder. ```text struct Q4: PackedType {} fn (self: Q4) name(): str { "Q4" } fn (self: Q4) blockSize(): usize { 32 } fn (self: Q4) blockBytes(): usize { 16 } fn (self: Q4) bitsPerElement(): u8 { 4 } // decodeBlock / encodeBlock define the representation transform. ``` For wire structs or C ABI layout, verify `#Type.sizeOf`, `#Type.alignOf`, and `#Type.offsetOf` explicitly. `PackedType` is a behavior contract, not a `packed` layout attribute. --- ## Contract Inheritance Contracts can inherit from other contracts: ```vex contract Named { name(): str; } contract Described: Named { description(): string; } ``` An implementing type must provide both requirements. These are domain contracts; they do not redefine the canonical prelude `Ord` or `Iterator`. ## Associated Types See the [complete associated-type example](docs/guide/types/contracts.md#associated-types) for a declared contract, mutable receiver, implementation, and bound-based call. It demonstrates the associated result type and the required receiver. ## Best Practices 1. Use operator contracts (`Add`, `Eq`, etc.) to make your types work with standard operators. 2. Implement `Display` for user-facing string representations; `Debug` for developer-facing ones. 3. Implement `Drop` when your type owns resources (files, sockets, allocations) that need cleanup. 4. Treat sealed memory-authority markers as compiler/library contracts; ordinary user declarations cannot grant themselves those capabilities. 5. Prefer `From`/`Into` for infallible conversions and `TryFrom`/`TryInto` for fallible ones. 6. Prelude contracts use their plain names; `$` prefixes runtime intrinsics such as `$println`, not contract names. 7. Standard-library contracts require an explicit package import, for example `import { From } from "contracts";`. ## Related Pages - [Contracts](docs/guide/types/contracts.md) -- contracts overview - [Operators Reference](docs/guide/advanced/operators-reference.md) -- operator contracts - [Policies](docs/guide/types/policies.md) -- field metadata policies --- Source: https://vex-lang.org/docs/guide/types/contracts.md # Contracts Contracts define shared behavior in Vex. They are the language mechanism behind reusable capabilities such as display, cloning, dropping, iterators, and operator overloading. ## Core syntax Vex uses `contract`, not `trait` or `interface`. ```vex contract Describe { describe(): string; } contract Cursor { type Item; next()!: Option; } ``` Current repo examples most commonly use this signature style inside contracts: method declarations without a receiver body. ## Implementing a contract Attach the contract to the type with colon syntax and then define normal receiver methods. ```vex contract Describe { describe(): string; } struct Point: Describe { public: x: i32, y: i32, } fn (self: &Point) describe(): string { return "Point(" + self.x.toString() + "," + self.y.toString() + ")"; } ``` Rust-style `impl Contract for Type` is not Vex syntax. ## Implicit Receivers and Mutability An instance requirement has an implicit receiver; do not add `self: &Self` as an ordinary parameter. A `static fn` requirement has no receiver, as shown below. * `convert(val: T): U;` defines a method taking an **Immutable Reference** (`self: &Self`). * `convert(val: T)!: U;` defines a method taking a **Mutable Reference** (`self: &Self!`). The `!` indicates state mutation. ```vex contract Incrementable { // Immutable read method count(): i32; // Mutable write method (note the '!' after parameters) increment()!; } ``` If you accidentally write `self: &Self` inside a contract (e.g. `convert(self: &Self)`), the compiler will emit a warning correcting this habit. ## Generic contracts and defaults Contracts can take type parameters, including defaults such as `Self`. ```vex contract Combine { combine(other: Rhs): Self; } ``` The default makes `Combine` mean `Combine`. This custom contract is separate from the prelude arithmetic contracts. ## Static requirements and generic type designators Use `static fn` when the operation belongs to the implementing type rather than a borrowed instance. A generic bound may invoke the requirement through its type parameter; the compiler resolves the exact binder and contract member at compile time. ```vex contract From { static fn fromValue(value: T): Self; } fn convert>(value: T): U { return U.fromValue(value); } ``` This dispatch is monomorphized. It does not create a runtime contract object or perform method-name lookup. A static requirement may also provide a default body. The body is compiled once per exact implementing type and contract specialization. `Self` denotes that type, but no instance receiver or vtable is introduced. ## Associated types Contracts can expose associated types. This complete example declares conformance on `Counter`, provides a mutable receiver implementation, and calls it through the generic bound `T: NextInt`: ```vex [contract-counter.vx] contract NextInt { type Item; next()!: Option; } struct Counter: NextInt { type Item = i32; value: i32, } fn (self: &Counter!) next(): Option { self.value = self.value + 1; return Some(self.value); } fn advance(item: &T!): Option { return item.next(); } fn main(): i32 { let! counter = Counter { value: 0 }; $println(advance(&counter) ?? -1); $println(advance(&counter) ?? -1); return 0; } ``` `vex run contract-counter.vx` prints `1` and `2` on separate lines. The associated type `T.Item` is resolved through the bound. Each implementation must provide the required methods with matching parameter and result types. Declare receiver mutability consistently in the requirement and implementation: this counter advances its state, so `next!()` requires mutable access. A domain contract describes behavior; a compiler-recognized marker such as `Copy` can carry additional language semantics; [policies](docs/guide/types/policies.md) describe field metadata and are a separate mechanism. A user-defined same-named contract does not automatically gain a built-in marker's compiler role. ## Builtin contracts Many important contracts live in the prelude and are available without an import. `$` prefixes runtime intrinsics such as `$println`; it is not part of a contract name. ### `Copy` `Copy` values copy on assignment instead of moving. ```vex let x = 42; let y = x; $println(x); ``` Typical `Copy` values include primitive numbers, `bool`, `char`, `str`, and raw pointer-like values. ### `Clone` `Clone` provides explicit duplication. ```vex struct Config: Clone { public: name: string, value: i32, } fn (self: &Config) clone(): Config { return Config { name: self.name.clone(), value: self.value }; } ``` ### `Drop` `Drop` runs cleanup when a value leaves scope. ```vex struct Trace: Drop { public: label: string, } fn (self: &Trace!) drop() { $println("leaving " + self.label); } ``` This example logs destruction. A real resource owner must also release its resource using the owning API; printing a message does not close a file. ### `Display` and `Debug` These support human-readable and debug-oriented text conversion. ```vex struct Color: Display, Debug { public: r: u8, g: u8, b: u8, } fn (self: &Color) toString(): string { return "rgb(" + self.r.toString() + "," + self.g.toString() + "," + self.b.toString() + ")"; } fn (self: &Color) debug(): string { return "Color{r:" + self.r.toString() + ",g:" + self.g.toString() + ",b:" + self.b.toString() + "}"; } ``` These contracts integrate directly with formatting: ```vex let color = Color { r: 32, g: 64, b: 255 }; $println("color={} details={:?}", color, color); let label = $format("selected: {}", color); ``` `{}` selects the exact `Display.toString` implementation. `{:?}` and `{:#?}` select the exact `Debug.debug` implementation. Resolution is based on the trusted contract/member identity, not a type or method name, so an unrelated same-spelled contract cannot intercept formatting. Both methods are borrowed receiver calls and must return `string`; their temporary result is released after formatting consumes it. ## Operator contracts Operator behavior is expressed with contracts and `op...` methods. ```vex contract Add { op+(other: Self): Self; } struct Vec2: Add { public: x: i32, y: i32, } fn (self: &Vec2) op+(other: Vec2): Vec2 { return Vec2 { x: self.x + other.x, y: self.y + other.y }; } ``` The prelude arithmetic `Add` contract takes `Self` as its right operand. Indexing uses `Index` with an associated `Output` type, while mutable indexing has its own `IndexMut` contract. Consult the [contract reference](docs/guide/types/contracts-reference.md) for the exact signatures. ## Guidance - Use plain contracts for domain behavior. - Use `Drop`, `Clone`, and `Display` when you want standard language integration. - Prefer simple method contracts first; add associated types or generic defaults when the API really needs them. - Keep examples aligned with real syntax from the repo: `struct Type: Contract {}` plus receiver methods. ## See also - [Generics](docs/guide/types/generics.md) - [Ownership](docs/guide/memory/ownership.md) - [Pattern Matching](docs/guide/types/pattern-matching.md) --- Source: https://vex-lang.org/docs/guide/types/enums.md # Enums Enums model a value chosen from a finite set of variants. A variant may be a tag on its own or carry one or more values. Enums are useful for state machines, parser results, and explicit success or failure. ## Simple enums ~~~vex enum Color { Red, Green, Blue, } fn main(): i32 { let color = Color.Green; let code = match color { Color.Red => 1, Color.Green => 2, Color.Blue => 3, }; $println(code); return 0; } ~~~ A match expression must account for the variants that the compiler can see. Use a wildcard only when the fallback is intentional. ## Payload variants A variant can carry typed data: ~~~vex enum Message { Quit, Move(i32, i32), Write(string), } fn describe(message: Message): i32 { return match message { Message.Quit => 0, Message.Move(x, y) => x + y, Message.Write(text) => 1, }; } fn main(): i32 { $println(describe(Message.Move(3, 4))); return 0; } ~~~ The payload pattern introduces local bindings for the values stored in the variant. Those bindings follow the same ownership rules as other local values. ## Generic enums Enums can be generic: ~~~vex enum Outcome { Ok(T), Err(E), } fn divide(left: i32, right: i32): Outcome { if right == 0 { return Outcome.Err(1); } return Outcome.Ok(left / right); } fn main(): i32 { match divide(20, 4) { Outcome.Ok(value) => { $println(value); }, Outcome.Err(code) => { $println(code); return 1; }, }; return 0; } ~~~ The payload types are selected independently: `Outcome` uses an integer for both branches, while other instantiations can carry an owned value and a domain error enum. This toy `divide` demonstrates enum construction; see [Error Handling](docs/guide/error-handling.md) for checked integer division. ## Matching patterns Vex supports literal patterns, constructor patterns, wildcard patterns, and or-patterns: ~~~vex fn classify(value: i32): i32 { return match value { 0 => 0, 1 | 2 | 3 => 1, _ => 2, }; } fn main(): i32 { $println(classify(2)); return 0; } ~~~ Pattern matching is an expression when all arms produce compatible values. Use a block arm when an arm needs several statements: ~~~text match value { 0 => { $println("zero"); return 0; } _ => { $println("other"); return 1; } } ~~~ ## Option and Result Option and Result are standard enum-shaped values used by the language and library: - `Option` represents a value that may be absent, with `Some(value)` and `None` variants. - `Result` represents success or failure, with `Ok(value)` and `Err(error)` variants. A complete Option example: ~~~vex fn value_or_zero(value: Option): i32 { return match value { Some(number) => number, None => 0, }; } fn main(): i32 { let value: Option = Some(42); $println(value_or_zero(value)); return 0; } ~~~ This example uses the prelude `Option`; no import or redeclaration is needed. It prints `42` and exits 0. The convenience methods on Option and Result are documented in the [Option API](docs/guide/types/option-api.md) and [Result API](docs/guide/types/result-api.md). Those APIs are evolving more quickly than the core enum syntax. ## Constructors and qualification Constructors can be written with the enum name when qualification is useful: ~~~text Outcome.Ok(42) Outcome.Err(1) ~~~ For a known expected enum type, the shorter constructor form may also be accepted: ~~~text Ok(42) Err(1) ~~~ Prefer the qualified form in public examples when several enum types have similarly named variants. ## Guidance Use an enum when the set of valid states is part of the type. Prefer Option over a sentinel value for absence and Result over an integer error code for recoverable failure. Keep payloads small and meaningful; if a variant contains many unrelated fields, a struct is usually clearer. ## Next steps - [Pattern Matching](docs/guide/types/pattern-matching.md) - [Error Handling](docs/guide/error-handling.md) - [Option API](docs/guide/types/option-api.md) - [Result API](docs/guide/types/result-api.md) --- Source: https://vex-lang.org/docs/guide/types/extern-types.md # Foreign types and ownership Foreign handles and pointers have contracts defined by the foreign library, not just by a Vex type. A binding must specify nullability, valid lifetime, who closes the handle, the matching allocator/destructor, thread and reentrancy rules, and the error paths. Do not infer those facts from a raw pointer alone. ## Choose one owner and one cleanup path - **Caller-owned handle:** after successful creation, arrange for the matching foreign destructor to run exactly once. On creation failure, do not destroy a null or uninitialized handle unless the foreign API explicitly permits it. - **Foreign-owned handle:** the application borrows it only while the foreign owner guarantees validity. The application must not free it. Synchronize invalidation and callbacks according to the foreign library's rules. - **Transferred handle:** agree on the precise transfer point and what happens when the operation fails. A pointer crossing a boundary does not by itself establish a transfer. Do not combine explicit cleanup with automatic drop unless the documented ownership contract proves that only one path can perform destruction. A `defer` and automatic destruction can otherwise release the same handle twice. See [First native bridge](docs/guide/ffi-first-native.md) for a tested `.vxc`/`.vx` example with explicit cleanup and counters on success and error paths. ## Design the boundary around ownership User-package foreign declarations belong in a `.vxc` boundary. Keep the raw handle and the matching foreign operations together, then give the public Vex wrapper an explicit ownership contract: | Foreign operation | Contract to expose in the wrapper | | --- | --- | | Create or open | Success produces one owned handle; failure produces no usable handle | | Read or inspect | Borrows the handle; any returned pointer states which owner keeps it alive | | Register a callback | States who retains the callback and when registration is released | | Transfer or adopt | Consumes ownership at a defined success point; defines ownership on failure | | Close or destroy | Releases an owned live handle once using the matching foreign function | For example, an image wrapper may own the image handle while a pixel view borrows its storage. Destroying or resizing the image invalidates that view. Returning copied pixel data creates an independent owner; returning the raw address does not. An error result from an operation must also state whether the original handle remains usable. Use `defer` for an explicit cleanup path when the handle remains in one scope. If a wrapper provides automatic destruction, transfer that responsibility along with the wrapper and avoid a second explicit destroy. See [First native bridge](docs/guide/ffi-first-native.md) for complete `.vxc` and `.vx` code, [FFI](docs/guide/ffi.md) for declarations, and [Unsafe](docs/guide/advanced/unsafe.md) for raw access obligations. ## Related - [First native bridge](docs/guide/ffi-first-native.md) - [FFI deep dive](docs/guide/ffi-deep-dive.md) - [Memory model](docs/guide/memory/vumm.md) --- Source: https://vex-lang.org/docs/guide/types/function-types.md # Function Types and Pointers Vex supports first-class function types, allowing functions to be passed as arguments, returned from other functions, and stored in data structures. ## Function Type Syntax A function type is written as `fn(ParamTypes): ReturnType`: ```text // Function taking i32, returning bool let predicate: fn(i32): bool // Function taking two f64, returning f64 let binaryOp: fn(f64, f64): f64 // Function with no parameters returning i32 let supplier: fn(): i32 // Function taking nothing, returning nothing let action: fn(): () ``` An async function type is written with the same source marker as an async declaration. It means that invoking the value produces a compiler-owned `Future`; users do not spell or construct that scheduler handle manually. ```vex type Fetch = async fn(url: str): string async fn fetchText(url: str): string { return "ok" } async fn fetchAndMeasure(fetch: Fetch): usize { return (await fetch("https://example.test")).len() } ``` `async fn(Args): T` is distinct from `fn(Args): T`. It is not an FFI callback type and cannot be substituted for a synchronous callback: its pointer ABI returns Vex's task handle and its call must be awaited in an async context. ## Function Pointers vs Closures Named functions and closures can both produce callable values: **Named functions** do not capture local variables. A native Vex `fn(T): R` value nevertheless uses Vex's callable representation: a code pointer and an environment/context pointer. Do not assume that it is pointer-sized or has a C callback ABI. This describes the current implementation, not a stable public binary layout across compiler versions. **Closures** may capture variables. Their environment stores the captures; the native callable value carries the entry point and its environment pointer. The function type describes the parameters and result, not the capture size. ```vex // Top-level function fn addOne(x: i32): i32 { return x + 1 } // Function pointer to addOne let ptr: fn(i32): i32 = addOne let result = ptr(41) // 42 // Explicitly typed non-capturing closure let closure: fn(i32): i32 = |x: i32| x + 1 ``` ## Passing Functions as Arguments ```vex fn applyTwice(f: fn(i32): i32, x: i32): i32 { return f(f(x)) } fn square(n: i32): i32 { return n * n } let result = applyTwice(square, 3) // square(square(3)) = 81 ``` ## Returning Functions ```vex fn chooseOp(kind: i32): fn(i32, i32): i32 { if kind == 0 { return add // returns function pointer } else { return mul } } fn add(a: i32, b: i32): i32 { return a + b } fn mul(a: i32, b: i32): i32 { return a * b } let op = chooseOp(0) let result = op(3, 4) // 7 ``` ## Storing Functions in Data Structures ```vex struct Handler { callback: fn(i32): (), name: string, } fn onData(code: i32) { $println(f"Got code: {code}") } let handler = Handler { callback: onData, name: "data_handler" } handler.callback(200) ``` ## Functions in Collections ```vex // Array of function pointers let operations: [fn(i32, i32): i32; 3] = [add, mul, sub] for operation in operations { $println(operation(10, 5)); } // Prints 15, 50, 5; add, mul and sub have signature fn(i32, i32): i32. ``` ## Generic Function Types Function types work with generics: ```vex fn mapValues(values: &Vec, transform: fn(&T): U): Vec { let! result = Vec.new() for v in values { result.push(transform(v)) } return result } let! numbers = Vec.new() numbers.push(1) numbers.push(2) numbers.push(3) let strings = mapValues(&numbers, |n: &i32| (*n).toString()) ``` ## FFI and Function Pointers Native Vex callables and raw foreign callback pointers are different ABI contracts. A foreign callback requires the exact foreign entry signature and a supported adapter/declaration boundary, including any context and lifetime requirements. Merely writing `fn(...)` inside an extern declaration does not prove that an ordinary Vex function value can be passed as one raw pointer. Do not cast a native callable to `Ptr` to manufacture a foreign callback. See the [FFI guide](docs/guide/ffi.md) for foreign declaration contracts. ## Unit-Returning Function Types A function that takes no parameters and returns nothing has type `fn(): ()`. The `()` is the unit type: ```vex let noop: fn(): () = || {} // closure returning unit let alsoNoop: fn(): () = myNoopFn ``` The unit result does not make the callable value itself zero-sized. ## Limitations - Named functions do not capture local variables; use closures for that. - A native callable is not automatically a foreign callback, even when it has no captures. Use the exact declared foreign entry contract. - `async fn(Args): T` values are Vex-runtime callbacks, not C callbacks. Keep FFI callback signatures synchronous. - Variadic C functions require the `...` syntax (see Variadic Functions documentation). ## Best Practices 1. Use `fn(T): R` as a native callable parameter type, and validate the capture and lifetime requirements of the particular call. 2. Be explicit about function pointer types at API boundaries for clarity. 3. Prefer closures for local callbacks when useful; optimization may remove unnecessary environment work, but it does not change the source ABI contract. 4. For FFI callbacks, verify the foreign signature and conversion explicitly; a top-level Vex declaration alone is not an ABI proof. ## Related Pages - [Closures](docs/guide/types/closures.md) -- anonymous capturing functions - [FFI](docs/guide/ffi.md) -- function pointers for C interop - [Methods](docs/guide/advanced/methods.md) -- method syntax and receivers --- Source: https://vex-lang.org/docs/guide/types/generics.md # Generics Generics let one function, struct, or contract work across many concrete types. In Vex, generic code is monomorphized, so the generated code is specialized per concrete use. ## Generic functions The most common pattern is a reusable function with one or more type parameters: ```vex fn identity(x: T): T { return x; } fn pair_first(a: A, b: B): A { return a; } ``` You can call generic functions with inference: ```vex let a = identity(42); let b = identity("hello"); ``` Or with explicit type arguments when clarity matters: ```vex let first = pair_first(10, 20); ``` ## Generic structs ```vex struct Container { public: value: T, } struct Pair { public: left: T, right: U, } ``` This is the standard way to build reusable collections, wrappers, and data-model helpers. ### Struct literal inference A literal can infer its owner arguments through a field's structure, not only when the field is directly `T`. References, typed pointers, tuples, arrays, function signatures and nested nominal generic types contribute constraints. ```vex struct Record { public: value: i32 } struct Slot { public: source: &T } let record = Record { value: 997 }; let slot = Slot { source: &record }; // Slot ``` All occurrences of one parameter must agree, or admit the ordinary value coercions required by the selected field type. Numeric widening does not permit reinterpreting reference pointees or incompatible function-pointer signatures. A missing constraint requires an explicit type/context or a declared default; contradictory constraints are an error, not a reason to use a default. Fixed array extents can also infer a const parameter. Mixed type/const arguments retain declaration order, including inside a nested generic owner: ```vex struct Samples { public: values: [T; N], extra: &U, } let samples = Samples { values: [10, 11, 12], extra: &record }; // Samples ``` Two fields constraining the same `N` to different lengths are rejected. This does not introduce general symbolic equation solving for const expressions. Nested types and contract bounds belong to the selected declaration's module; an import alias or a same-spelled local type does not replace that identity. ## Generic methods Generic types use normal receiver syntax for methods: ```vex struct Wrapper { public: value: T, } fn (self: &Wrapper) get(): &T { return &self.value; } fn (self: &Wrapper!) set(new_value: T) { self.value = new_value; } ``` ## Contract bounds Bounds let you say what operations a type parameter must support. ```vex contract Stringify { toString(): string; } fn print_item(item: T) { let s = item.toString(); $println(s); } ``` Use bounds when a function depends on behavior, not on one exact type. ## Default type parameters Struct parameters can have defaults, including a preceding type parameter: ```vex struct Defaulted { public: value: T } struct Tagged { public: value: T } let inferred = Defaulted { value: 42 as i32 }; // Defaulted let explicit: Defaulted = Defaulted { value: 42 as i32 }; let tagged = Tagged { value: 42 as i32 }; // Tagged ``` An explicit owner or matching expected owner supplies the field context. Otherwise, field inference runs first and defaults fill only unconstrained slots. A default never masks conflicting field types. Contracts can provide defaults for type parameters. A common pattern is `Self`: ```vex contract Combine { combine(other: Rhs): Self; } ``` That lets a custom contract accept either its own type or a specified input type. It does not redefine the prelude `Add` contract. ## Associated types An associated type names an output selected by an implementation of a contract. The [complete `NextInt` example](docs/guide/types/contracts.md#associated-types) declares `type Item`, implements the mutable `next()!` requirement for `Counter`, and calls it through a generic contract bound. ## Const generics Use const generics when part of the type is a compile-time value: ```vex struct Matrix { public: rows: [[T; M]; N], } fn elementCount(): usize { return N * M; } ``` This is useful for fixed-size math structures, static buffers, and shape-encoded APIs. ## Practical guidance - Keep type parameter lists short and purposeful. - Add bounds only where operations actually require them. - Prefer inference for callers, explicit type arguments for docs and tricky code. - Use const generics when the size or shape is part of correctness. ## See also - [Contracts](docs/guide/types/contracts.md) - [Structs](docs/guide/types/structs.md) - [Enums](docs/guide/types/enums.md) --- Source: https://vex-lang.org/docs/guide/types/map-set.md # Maps and Sets Vex ships prelude associative collections backed by a Swiss-table style hash map implementation. The current builtin surface lives in the compiler prelude and is available without imports. > **tip Prelude Types** `Map` and `Set` are prelude types. These types own their entries; lookup methods normally borrow them. ## `Map` `Map` stores unique keys with associated values using open addressing, control bytes, and quadratic probing. ### Constructors ```vex let! scores = Map.new(); let! fastPath = Map.withCapacity(1024); ``` `Map.withCapacity(n)` guarantees room for at least `n` elements without a rehash, including the Swiss-table load-factor budget. `Map.withCap(n)` remains the low-level legacy constructor whose argument is a raw bucket count. ### Compile-time constructor checks Inside `#const`, Map constructors use the same Vex source policy as native allocation for bucket rounding, load-factor capacity, padded entry size and target allocator limits. An empty reservation does not allocate that many compiler-host entries: ```vex let count = #const { let values = Map.withCapacity(1000000 as usize); values.len() }; // 0; the runtime receives only this scalar result ``` If a Map itself crosses into runtime, ordinary Vex construction still allocates its backing table. This is not a static, allocation-free hash table. Explicit builders retain their exact value; default randomized builders are not replaced with a compiler-generated seed. ### Mutation history at the runtime boundary The supported CTFE insert/remove/clear operations retain table-construction history, not just surviving key/value pairs. A removal-free build followed by clear becomes an empty table at its final grown capacity: the compiler uses the Vex source capacity/layout policy and emits no replay of those insertions. Histories containing removals can depend on the runtime hash seed. Their typed construction recipe preserves native insertion/removal order, tombstones and growth budget. Explicit builders keep their exact state; the default seed is still generated at runtime. A Map crossing into runtime needs ordinary allocation and hashing. A seed-dependent construction history may retain intermediate inserts and removes to reproduce the table state, so its startup cost can exceed inserting only the surviving pairs. Ordinary runtime Map operations do not record a CTFE history. Methods called during CTFE must still be const-capable. ### Custom keys during `#const` Custom Map keys need const-executable `Hash` and `Eq` implementations for CTFE. Integer, `bool` and `char` fields can forward to their prelude `hashInto` implementations; the compiler executes those Vex bodies with the selected Hasher contract: ```vex struct Key: Hash, Eq { id: i32 } const fn (self: &Key) op==(other: &Key): bool { return self.id == other.id; } const fn (self: &Key) op!=(other: &Key): bool { return self.id != other.id; } const fn (self: &Key) hashInto(state: &H!) { self.id.hashInto(state); } let found = #const { let! values = Map.new(); values.insert(Key { id: 7 }, 42); values.contains(&Key { id: 7 }) }; // true ``` The primitive feeds retain their domain tags and canonical little-endian encoding. Marking a feed `const` does not authorize arbitrary runtime Hasher methods, system randomness or I/O during CTFE. Direct use with a custom state requires its executed methods to be const-executable too. This guarantee does not cover string-field Hash forwarding or every Map method; for example, `removeEntry` remains runtime-only in the current CTFE surface. ### Basic usage ```vex let! scores = Map.new(); scores.insert("alice", 100); scores.insert("bob", 200); match scores.getOwned(&"alice") { Some(score) => { $println(score); }, None => { $println("missing"); }, }; if scores.contains(&"bob") { $println("bob exists"); } ``` ### Lookup model - `get(&key)` returns `Option<&V>` for zero-copy access. - `getOwned(&key)` returns `Option` when `V: Clone`. - `map[key]` is a read-only index shorthand for `get`, so it also returns `Option<&V>`. - Updates are done with `insert`, not with `map[key] = value` in the documented prelude surface. ### Core operations | Method | Return | Notes | | ---------------------------------- | ------------ | ------------------------------------ | | `Map.new()` | `Map` | Empty map | | `Map.withCapacity(capacity: usize)` | `Map` | Guarantee element capacity | | `Map.withCap(buckets: usize)` | `Map` | Legacy raw bucket capacity | | `insert(key: K, value: V)` | `bool` | `true` if the key was new | | `get(key: &K)` | `Option<&V>` | Borrowed lookup | | `getOwned(key: &K)` | `Option` | Cloned lookup when `V: Clone` | | `getOr(key: &K, fallback: &V)` | `&V` | Borrowed fallback lookup | | `getOrInsert(key: K, default: V)` | `&V!` | Insert-on-miss | | `contains(key: &K)` | `bool` | Membership check | | `remove(key: &K)` | `Option` | Removes and returns the stored value | | `removeEntry(key: &K)` | `Option<(K,V)>` | Transfers canonical key and value | | `getKeyValue(key: &K)` | `Option<(&K,&V)>` | Borrows canonical key and value | | `getOrInsertWith(key, factory)` | `&V!` | Constructs only on a miss | | `len()` | `usize` | Element count | | `capacity()` / `reserve(n)` | `usize` / `()` | Element-capacity management | | `retain(predicate)` | `()` | Drops rejected owners once | | `shrinkToFit()` | `()` | Rehashes into the smallest fit table | | `isEmpty()` | `bool` | Empty check | | `clear()` | `()` | Drops all entries | | `keys()` | `Vec` | Clones keys when `K: Clone` | | `values()` | `Vec` | Clones values when `V: Clone` | `insert` consumes its key and value. Replacing an equal key keeps the original stored key and drops the previous value. `remove` returns the value and drops the stored key; `removeEntry` transfers both owners. `clear` drops all entries while retaining table storage. Borrowed lookups cannot outlive the map or an operation that invalidates its storage. `getOr(&key, &fallback)` borrows either the stored value or the supplied fallback. Keep both possible sources alive for the returned reference. Use `getOrInsertWith` when constructing an absent value should be lazy. ## `Set` `Set` is the unique-element companion to `Map`. In the current prelude it is implemented as a thin wrapper around `Map`. ### Basic usage ```vex let! tags = Set.new(); tags.insert("vex"); tags.insert("compiler"); tags.insert("vex"); if tags.contains(&"vex") { $println("present"); } let removed = tags.remove(&"compiler"); ``` ### Core operations | Method | Return | Notes | | ------------------- | -------- | --------------------------------------- | | `Set.new()` | `Set` | Empty set | | `Set.withCapacity(n)` | `Set` | Guarantee element capacity | | `insert(elem: T)` | `bool` | `true` when the element was newly added | | `contains(elem: &T)` | `bool` | Membership check | | `remove(elem: &T)` | `bool` | `true` if an element was removed | | `get(elem: &T)` | `Option<&T>` | Borrow canonical stored value | | `take(elem: &T)` | `Option` | Transfer canonical stored value | | `capacity()` / `reserve(n)` | `usize` / `()` | Capacity management | | `retain(predicate)` / `shrinkToFit()` | `()` | Filter and reclaim storage | | `len()` | `usize` | Element count | | `isEmpty()` | `bool` | Empty check | | `clear()` | `()` | Removes all elements | Set lookup and removal take a borrowed key. `take(&key)` transfers the stored canonical element; `remove(&key)` drops it and reports whether it existed. ## Key requirements Map keys and set elements must support `Hash + Eq`. Hashing feeds the selected per-table `BuildHasher` state through `hashInto`; keys do not finalize hashes themselves. Equality and hash feeds must describe the same identity. In practice, builtin scalar types and `string` are the common key types used across the repo. ## Performance model The current prelude implementation is designed around Swiss-table techniques: - Open addressing with quadratic probing - SIMD-friendly control bytes - A target load factor of `7/8` before growth - Separate control and entry storage for better cache behavior ## See Also - [./vec](docs/guide/types/vec.md) - [./enums](docs/guide/types/enums.md) - [./contracts](docs/guide/types/contracts.md) --- Source: https://vex-lang.org/docs/guide/types/never-and-unit.md # Never and Unit Types Vex has two special types that represent "no value" in different ways: the **never type** (`never`) and the **unit type** (`()`). ## The Never Type (`never`) `never` is the **bottom type** -- a type with NO possible values. It represents computations that never complete normally. Functions that diverge (loop forever, panic, abort, or exit the program) have return type `never`. ### Where `never` Appears **Infinite loops:** ```vex fn runForever(): never { loop { processEvents() } // Unreachable -- loop never exits } ``` **Panic:** ```vex fn die(msg: string): never { $panic(msg) // Unreachable -- $panic never returns } ``` ### `never` Coercion `never` can coerce to ANY type. This is what makes early-return patterns work in expressions: ```vex fn requireValue(opt: Option): i32 { return match opt { Some(v) => v, // arm returns i32 None => $panic("none"), // arm returns never, which coerces to i32 } } ``` Because `$panic` returns `never`, it can be used in any expression position regardless of the expected type: ```vex let value = if valid { compute() } else { $panic("invalid state") // never coerces to the expected type } ``` ### `return`, `break`, `continue` and `never` The `return`, `break`, and `continue` expressions also produce `never`: ```vex let x = if condition { 42 } else { return 0 // return produces never, coerces to i32 } ``` ### `never` in Generic Code `never` can appear as a generic type parameter, making some types uninhabitable: ```vex // Result can never be Err -- it's always Ok fn infallible(): Result { return Ok(42) // Err(???) is impossible -- no value of type never exists } ``` ## The Unit Type (`()`) `()` is the **unit type** -- a zero-size type with exactly ONE value: `()`. It represents "no meaningful data" and is the default return type for functions without a return value. ### Functions Returning Unit ```vex // Implicit unit return fn printMessage(msg: string) { $println(msg) // implicitly returns () } // Explicit unit return fn doNothing(): () { return () } ``` ### Unit in Generics The `unit` keyword is the canonical spelling in generic and other nested value type positions. It denotes the same unit type as `()` but avoids ambiguity in generic grammar: ```vex // A key-only mapping can use unit as its value type. // This describes a modeling choice, not the internal layout of Set. // A callback that takes no useful data fn onEvent(callback: fn(unit): ()) { callback(()) } ``` ### Unit Size Unit has no payload bytes. A container still has its own bookkeeping and allocation policy; do not infer that `Vec` is represented only by a length or that `push` performs no container work. ```vex let! counter = Vec.new() counter.push(()) counter.push(()) let count = counter.len() // 2 logical elements ``` ### Unit vs Void (C) In C, `void` means "no type at all" -- you cannot have a variable of type `void`. In Vex, `()` is a real type with a real value: ```vex let x: () = () // Valid: x is a real value let items: [unit; 3] = [(), (), ()] // Array of three unit values, zero size ``` ## Comparison Table | Property | `never` | `()` | | ---------------- | ------------------------------- | -------------------------------------- | | Number of values | 0 (none) | 1 (`()`) | | Size in memory | No inhabited runtime value | 0 bytes | | Meaning | Computation never finishes | Computation finished with no result | | Coercion | Coerces to ANY type | Does not coerce | | Common use | Diverging functions, early exit | Default return, generic placeholder | | Can instantiate? | No -- impossible | Yes -- `()` | | C equivalent | `_Noreturn` / `[[noreturn]]` | `void` (but Vex's `()` is a real type) | ## Best Practices 1. Annotate diverging functions with `: never` return type for clarity and better compiler diagnostics. 2. Use `()` as the return type when a function performs side effects and has no meaningful return value -- or just omit the return type entirely. 3. Use `unit` as a generic or nested type placeholder when only one type parameter matters (for example, `Map` acts as a `Set`). 4. Remember that `never` coercions make early-return and panic patterns safe in expression contexts -- no need for awkward `unreachable!()` markers. --- Source: https://vex-lang.org/docs/guide/types/option-api.md # Option\ `Option` represents a present value, `Some(T)`, or an absent value, `None`. The prelude does not declare an `unwrap` method. ## Methods and types These signatures summarize `lib/runtime/VexArch/src/prelude/option.vx`. Methods with a by-value receiver consume the option according to its payload's ownership rules; `isSome`, `isNone`, `clone`, and `asRef` borrow it. `Option` is Copy only when its concrete payload supports Copy. | Method | Signature and result | | --- | --- | | `isSome`, `isNone` | `(&Option) -> bool` | | `or` | `(Option, T) -> T`: value or fallback payload | | `orElse`, `rescue` | `(Option, fn(): T) -> T`: value or computed fallback payload | | `map` | `(Option, fn(T): U) -> Option` | | `flatMap` | `(Option, fn(T): Option) -> Option` | | `filter` | `(Option, fn(T): bool) -> Option` | | `clone` | `(&Option) -> Option` where `T: Clone` | | `asRef` | `(&Option) -> Option<&T>` | | `asMut` | `(&Option!) -> Option<&T!>` | | `take` | `fn !(self: &Option!) take(): Option` | | `replace` | `fn !(self: &Option!) replace(value: T): Option` | `or` does **not** take another `Option` as a fallback for an `Option`; its fallback is the payload `T`. Likewise, `orElse` returns `T`, not another option. Use `match` when selecting between optional sources. `flatMap` is the name declared for Option-returning composition; the prelude does not declare an `andThen` alias. It also does not declare `okOr` or `okOrElse`; use an explicit `match` for conversions instead of assuming those methods exist. `take` returns the old option and leaves `None` behind. `replace(value)` returns the old option and leaves `Some(value)`. They use the mutating `fn !` marker. Check their ownership effects before using the old or replacement value; this marker is distinct from an `unsafe fn` declaration. Options also support `==` when `T: Eq`: two absent options compare equal; two present options compare their payloads; a present and absent option differ. ## A runnable example ```vex [option-example.vx] fn even_half(n: i32): Option { if n % 2 == 0 { return Some(n / 2); } return None; } fn main(): i32 { let value: Option = Some(10); let missing: Option = None; $println(value.isSome()); $println(missing.isNone()); $println(value.or(99)); $println(missing.orElse(|| 7)); let doubled: Option = value.map(|n: i32| n * 2); $println(doubled.or(0)); let half: Option = value.flatMap(even_half); $println(half.or(0)); let filtered: Option = value.filter(|n: i32| n > 20); $println(filtered.or(-1)); return 0; } ``` Run `vex run option-example.vx`. The expected stdout is: ```text true true 10 7 20 5 -1 ``` The closures use explicit parameter types. Some unannotated closures are inferred successfully, while others are not; annotate a parameter when inference is insufficient. See [Closures](docs/guide/types/closures.md#type-inference). ## Fallback and propagation A normal function argument such as `option.or(expensive())` is evaluated before calling `or`, even if the option is `Some`. The callback passed to `orElse` is called only for `None`. For the `??` operator, `option ?? expensive()` also evaluates the right side only for `None`; `option !> || expensive()` is another fallback form. See [Operators](docs/guide/advanced/operators-reference.md) for `??`, `!>`, and `?`. A `match` makes the paths explicit and can construct a result: ```vex fn require_value(option: Option): Result { return match option { Some(value) => Ok(value), None => Err(1), }; } ``` A `?` applied to `None` in a function returning an `Option` propagates `None`. ## Collecting options The following complete example uses an explicit `match` and a `Vec` to compact present values. It covers mixed, all-present, and all-absent input. The result contains the payloads themselves; retaining `Some` wrappers would produce a different element type. ```vex [collect-options.vx] fn collect(values: [Option; 4]): Vec { let! output = Vec.new(); let! i: usize = 0; while i < 4 { match values[i] { Some(value) => { output.push(value); }, None => {}, }; i = i + 1; } return output; } fn main(): i32 { let mixed: [Option; 4] = [Some(1), Some(2), None, Some(4)]; let all: [Option; 4] = [Some(1), Some(2), Some(3), Some(4)]; let none: [Option; 4] = [None, None, None, None]; let a = collect(mixed); let b = collect(all); let c = collect(none); if a.len() != 3 || a[0] != 1 || a[1] != 2 || a[2] != 4 { return 1; } if b.len() != 4 || b[0] != 1 || b[1] != 2 || b[2] != 3 || b[3] != 4 { return 2; } if c.len() != 0 { return 3; } $println(a.len()); $println(a[0]); $println(a[1]); $println(a[2]); $println(b.len()); $println(b[0]); $println(b[1]); $println(b[2]); $println(b[3]); $println(c.len()); return 0; } ``` The mixed output has length 3 and values `1, 2, 4`; the all-present output has length 4 and values `1, 2, 3, 4`; the all-absent output has length 0. The program prints those lengths and values in that order and exits 0; it returns a nonzero code if a check fails. Replacing each `None` with `0` instead would preserve positions and produce `[1, 2, 0, 4]`; that is a different operation. ## Transfer an owning payload out of a reusable slot `take` is useful for a pending task or cached value that is consumed once. `replace` installs a new payload and returns the old one, allowing the caller to process or release it explicitly. Neither operation clones the payload. ```vex [optional-slot.vx] fn runNext(pending: &Option!): usize { return match pending.take() { Some(command) => { $println(command); command.len() }, None => 0, }; } fn main(): i32 { let! pending: Option = Some("deploy".toString()); let previous = pending.replace("backup".toString()); match previous { Some(command) => { $println(f"replaced: {command}"); }, None => { return 1; }, }; if runNext(&pending!) != 6 || pending.isSome() { return 2; } if runNext(&pending!) != 0 { return 3; } let empty = pending.replace("verify".toString()); if empty.isSome() || runNext(&pending!) != 6 { return 4; } return 0; } ``` The program prints `replaced: deploy`, `backup`, and `verify`, then exits 0. Here processing a command prints its name. After `runNext`, the slot contains `None`, so a second call does no work. Replacing that empty slot installs a new owned string and returns `None`. Each successful `take` transfers the string to the match arm; the slot no longer owns that string. ## Related pages - [Result](docs/guide/types/result-api.md) - [Pattern Matching](docs/guide/types/pattern-matching.md) - [Error Handling](docs/guide/error-handling.md) --- Source: https://vex-lang.org/docs/guide/types/ordered-map.md # OrderedMap\ `OrderedMap` is the prelude's insertion-ordered owning hash map. It keeps average O(1) key lookup and removal while iteration follows the current insertion order. No import is required. Use `OrderedMap` when order is part of the data model: deterministic output, configuration, protocol fields, caches, or user-visible sequences. Prefer `Map` when order is irrelevant and minimum metadata/cache cost matters. `OrderedMap` follows insertion order, not key sort order. Replacing a value does not move its entry; use the explicit reordering methods when needed. ## Construction ```vex let! values = OrderedMap.new(); let! reserved = OrderedMap.withCapacity(256 as usize); let builder = DeterministicState.seed(42 as u64); let! reproducible = OrderedMap.withHasherCapacity( builder, 256 as usize, ); ``` `withCapacity(n)` guarantees node capacity for at least `n` live entries. `withHasher` and `withHasherCapacity` accept any `BuildHasher` policy. ## Lookup and ownership ```vex let! scores = OrderedMap.new(); scores.insert("alice".toString(), 95 as i32); scores.insert("bob".toString(), 87 as i32); let alice = "alice".toString(); match scores.get(&alice) { Some(score) => $println(*score), None => {}, }; match scores.getMut(&alice) { Some(score) => { *score = 96 as i32; }, None => {}, }; ``` `insert` transfers key and value ownership. A new key returns `true`. An equal key returns `false`, replaces only the value, and preserves both the first canonical stored key and its order position. Insertion and update do not require `Clone`. - `get` and `getMut` borrow a value; - `getKeyValue` borrows the canonical stored key and value; - `contains` performs a key lookup; - `removeValue` transfers the stored value and drops the canonical key; - `removeEntry` transfers both canonical owners; - `remove` is the boolean compatibility form and drops both removed owners. ## Ordered traversal ```vex let! fields = OrderedMap.new(); fields.insert("host".toString(), "localhost".toString()); fields.insert("port".toString(), "8080".toString()); let! entries = fields.iter(); while true { match entries.next() { Some(pair) => $println(pair.0, " = ", pair.1), None => break, }; }; ``` `iter`, `keys`, and `values` return allocation-free borrowed iterators in current order. `first` and `last` borrow the end pairs. `popFront` and `popBack` transfer an end pair out. `moveToFront(key)` and `moveToBack(key)` relink a present entry in O(1) after its average O(1) lookup. They return `false` for a missing key. ## Capacity and filtering - `capacity()` reports stable-node capacity; - `reserve(minimum)` pre-grows node and hash-index storage; - `clear()` drops live owners and retains allocations; - `retain(predicate)` visits entries once, drops rejects, and preserves survivor order without cloning or rehashing them; - `shrinkToFit()` compacts vacant stable slots in insertion order. It transfers owners once and rebuilds the private index from cached hashes, so user keys are neither cloned nor hashed again. ## Indexed compatibility access `getAtIndex`, `getAtIndexRef`, and `getAtIndexMut` address the current order. They traverse from the nearer end and cost O(min(i, n-i)). Use `iter()` for a full scan; `OrderedMap` deliberately optimizes stable O(1) removal/reordering instead of pretending that linked order also offers O(1) random indexing. ## Complexity | Operation | Time | |---|---:| | `get`, `getMut`, `contains`, `insert` | average O(1) | | `remove*` | average O(1) | | `moveToFront`, `moveToBack` | average O(1) including lookup | | `first`, `last`, `popFront`, `popBack` | O(1) | | iterator step | O(1) | | `retain`, `clear`, `shrinkToFit` | O(n) | | `getAtIndex*(i)` | O(min(i, n-i)) | The implementation owns each key/value pair exactly once in a stable node. A private Swiss-table index maps the caller-policy full hash to a collision-correct node chain; it uses an identity policy for that already hashed `u64`, avoiding a second cryptographic hash. Doubly linked stable-node indices maintain order and a free-slot stack reuses removed storage. ## Related pages - [Map and Set](docs/guide/types/map-set.md) - [Collections](docs/std/collections.md) - [Contracts reference](docs/guide/types/contracts-reference.md) --- Source: https://vex-lang.org/docs/guide/types/pattern-matching.md # Pattern Matching `match` selects an arm by the shape and value of its input. Patterns can bind payloads, destructure aggregates, classify integer intervals, and add boolean guards. Examples below are independent fragments unless a complete function is shown. ## `match` is an expression `match` returns a value, so it works naturally in assignments and returns. ```vex let x = 5; let label = match x { 0 => "zero", 1 | 2 => "small", _ => "other", }; ``` ## Common pattern forms ### Wildcards and bindings ```vex let value = 42; let result = match value { 0 => 0, n => n * 2, }; ``` ### Tuples and nested tuples A nested tuple pattern follows the same nesting as the value. ```vex let pair = (0, -2); let axis = match pair { (0, y) => y, (x, 0) => x, (x, y) => x + y, }; let nested = ((1, 2), 3); let total = match nested { ((a, b), c) => a + b + c, }; ``` ### Enums and payload extraction A variant pattern names the constructor and binds its payload. ```vex fn unwrapOrZero(opt: Option): i32 { return match opt { Some(v) => v, None => 0, }; } fn describe(res: Result): i32 { return match res { Ok(v) => v, Err(code) => code, }; } ``` ### Struct patterns Shorthand field patterns bind a field under its own name. ```vex struct Point { public: x: f32, y: f32, } fn distanceSquared(p: Point): f32 { return match p { Point { x, y } => x * x + y * y, }; } ``` ### Fixed-size array and slice-style patterns ```vex let values = [1, 2, 3]; match values { [a, b, c] => { $println(a); $println(b); $println(c); }, _ => { $println("unexpected shape"); }, }; ``` ## Ranges, guards, and or-patterns ### Or-patterns ```vex let x = 2; let kind = match x { 1 | 2 => "small", 3 => "three", _ => "other", }; ``` ### Range patterns `a..b` excludes the upper endpoint; `a..=b` includes it. ```vex let n = 9; let digits = match n { 0..10 => "single digit", 10..=99 => "two digits", _ => "large", }; ``` ### Guards Guards add a second condition after the pattern. ```vex let x = 5; let selected = match x { n if n > 3 => n, _ => 0, }; ``` ## Ownership and exhaustiveness A by-value match can transfer an owning payload into its selected arm. Matching a borrowed value keeps payload access borrowed; it does not create an owner that can outlive the original. Choose a borrowed parameter when the caller needs to retain the matched value. Account for every possible variant or add an intentional fallback. A guarded arm can fail even after its pattern matches, so preserve an unguarded path for remaining cases. Alternatives joined with `|` must provide consistent bindings used by the arm. Tuple, struct, and array patterns also work in `let` bindings. A tuple spells its full shape with `_` for ignored positions; an array rest is terminal (`..` to ignore, `...rest` to bind). For enum mismatch and early return, use `match` or `if let`. See [Advanced Patterns](docs/guide/types/advanced-patterns.md). ## Best Practices 1. Prefer `match` when you need exhaustive branching and value extraction in one place. 2. Use guards for extra conditions instead of encoding too much logic into the pattern itself. 3. Make payload ownership explicit at the function boundary and keep patterns close to the actual data shape. --- Source: https://vex-lang.org/docs/guide/types/pin.md # Pin documentation moved `Pin` is a compiler-enforced marker contract, not a generic `Pin` type. See [Pin — Move Prevention for Self-References](docs/guide/memory/pin.md) for the current documentation. --- Source: https://vex-lang.org/docs/guide/types/policies.md # Policies Policies are a language feature for attaching reusable field metadata to structs. They are not traits, contracts, or mixins. A policy describes metadata keys for named fields, and a struct applies that metadata with `with`. ## Basic Policy ```vex policy APIModel { id `json:"id"`, name `json:"name"` } struct User with APIModel { public: id: i32, name: string, } ``` The policy does not create fields. The target struct must still declare `id` and `name`. ## Multiple Policies ```vex policy JSONModel { id `json:"id"` } policy DatabaseModel { id `db:"user_id"` } struct User with JSONModel, DatabaseModel { id: i32, } ``` Policies can be stacked on the same struct. ## Policy Inheritance Policies can inherit from other policies with `with`. ```vex policy BaseModel { id `db:"id" indexed:"true"` } policy APIModel with BaseModel { id `json:"id"` name `json:"name"` } struct User with APIModel { id: i32, name: string, } ``` This gives the struct the merged metadata from both the parent and child policy. ## Override Rules Inline field tags on the struct override policy-provided tags. ```vex policy APIModel { id `json:"id" db:"user_id"` name `json:"name" validate:"required"` } struct User with APIModel { id: i32 `json:"userId"`, name: string `validate:"minlength:3"`, } ``` The effective metadata for `User.id` uses `json:"userId"`, not `json:"id"`. When multiple policies provide the same metadata key, later-applied metadata wins. ## Validation Rules The current compiler validates several policy failure modes: - unknown parent policy names - unknown applied policy names - missing struct fields required by a policy - circular policy inheritance So this is a real type-checked language feature, not just passive documentation syntax. ## Comptime Reflection Policies become visible through the normal compile-time reflection path. ```vex policy APIModel { id `json:"id"`, name `json:"name"` } struct User with APIModel { id: i32 `json:"userId"` name: string } fn main(): i32 { #for f in #Type.info().fields { $println( f.name, " -> json:", f.tag("json") ) } return 0 } ``` This makes policies useful for: - serialization metadata - schema generation - validation metadata - compile-time code generation ## When To Use Policies Use a policy when you need the same metadata shape applied across multiple structs. Do not use a policy when you are trying to share behavior or methods. Policies only carry metadata. ## Related - [Structs](docs/guide/types/structs.md) - [Comptime](docs/guide/advanced/comptime.md) - [Builtins](docs/guide/advanced/builtins.md) --- Source: https://vex-lang.org/docs/guide/types/primitives.md # Primitive Types Vex provides primitive types for integers, floats, booleans, characters, strings, pointers, and control-flow values such as `never`. ## Integer Types ### Signed Integers | Type | Size | Range | | ------ | -------- | ----------------- | | `i8` | 8 bits | -128 to 127 | | `i16` | 16 bits | -32,768 to 32,767 | | `i32` | 32 bits | -2³¹ to 2³¹-1 | | `i64` | 64 bits | -2⁶³ to 2⁶³-1 | | `i128` | 128 bits | -2¹²⁷ to 2¹²⁷-1 | ### Unsigned Integers | Type | Size | Range | | ------ | -------- | ----------- | | `u8` | 8 bits | 0 to 255 | | `u16` | 16 bits | 0 to 65,535 | | `u32` | 32 bits | 0 to 2³²-1 | | `u64` | 64 bits | 0 to 2⁶⁴-1 | | `u128` | 128 bits | 0 to 2¹²⁸-1 | ### Platform-Dependent Types | Type | Size | Description | | ------- | -------- | ------------------------------ | | `isize` | Platform | Pointer-sized signed integer | | `usize` | Platform | Pointer-sized unsigned integer | ### Integer limits The auto-imported Prelude exposes typed integer bounds through `Limits`: ```vex let byteMax: u8 = Limits.u8Max let signedMin: i64 = Limits.i64Min let indexMax: usize = Limits.usizeMax let wideMax: u128 = Limits.u128Max ``` Each signed and unsigned integer type has `Min` and `Max` members. The `isize`/`usize` values follow the selected compilation target, including during cross-compilation; they are not based on the machine running the compiler. `Limits.*` values are compile-time constants and do not emit a runtime lookup. For generic metaprogramming, the underlying typed operations are `#Type.minValue()` and `#Type.maxValue()`. Ordinary code should prefer the readable `Limits.*` surface. ### Integer representation helpers Integer helpers are grouped under `IntegerLimits`; primitive namespaces stay small and constants remain under `Limits`: ```vex let value: u32 = 0x01020304 let little = IntegerLimits.toLe(value) let big = IntegerLimits.toBe(value) let native = IntegerLimits.fromBe(big) let swapped = IntegerLimits.swapBytes(value) let ones = IntegerLimits.countOnes(value) let leading = IntegerLimits.leadingZeros(value) let trailing = IntegerLimits.trailingZeros(value) let rounded = IntegerLimits.nextPowerOfTwo(value) let power = IntegerLimits.isPowerOfTwo(value) let bytes: [u8; 4] = IntegerLimits.toLeBytes(value) let networkBytes: [u8; 4] = IntegerLimits.toBeBytes(value) ``` Endian selection is resolved at compile time. Conversion becomes either the identity operation or a byte swap; the final instruction sequence depends on the target and optimization. There is no runtime endianness branch. `toLeBytes` and `toBeBytes` are statically selected overload families returning the exact array width (`[u8; 1]`, `[u8; 2]`, `[u8; 4]`, `[u8; 8]`, or `[u8; 16]`). It does not allocate and does not return a tagged or dynamically sized wrapper. Generic integer APIs can share the Prelude type sets `SIGNED_INTEGER_TYPES`, `UNSIGNED_INTEGER_TYPES`, and `INTEGER_TYPES`. ### Usage ```vex let x: i32 = 42 let y: i64 = 42 // Explicit type suffix let a = 42i8 // i8 let b = 42u64 // u64 let c = 1000i128 // i128 // Explicit type annotation let d: u16 = 1000 // Numeric separators for readability let million = 1_000_000 let bytes = 0xFF_FF_FF_FF let binary = 0b1111_0000_1111_0000 ``` > **warning Overload Resolution Note** Unsuffixed integer literals can be inferred differently depending on context. In current examples and tests, they are commonly used as `i32` unless a wider type is required by surrounding code. At public API boundaries, prefer explicit annotations. ### Literals in Different Bases ```vex let decimal = 255 let hex = 0xFF // Hexadecimal let octal = 0o377 // Octal let binary = 0b11111111 // Binary // With type suffix let hex_byte = 0xFFu8 let binary_word = 0b1010_1010u16 ``` ## Floating-Point Types | Type | Size | Precision | Range | | ----- | ------- | ---------- | ---------- | | `f16` | 16 bits | ~3 digits | ±65,504 | | `bf16` | 16 bits | ~2–3 digits | approximately the `f32` exponent range | | `f32` | 32 bits | ~7 digits | ±3.4×10³⁸ | | `f64` | 64 bits | ~15 digits | ±1.8×10³⁰⁸ | ### Usage ```vex let pi = 3.14159 // f64 // Scientific notation let avogadro = 6.022e23 let planck = 6.626e-34 // Explicit type suffix let half = 0.5f32 // f32 let precise = 3.14159265358979f64 let single: f32 = 0.5 let precise: f64 = 3.14159265358979 ``` ### Compact floating-point storage: `f16` and `bf16` Both types use 16 bits. `f16` has more significand precision and a narrower exponent range; `bf16` keeps an exponent range similar to `f32` with fewer significand bits. They are useful when a buffer's storage format matters, such as tensor inputs. Choose the representation required by the consuming API. Use an explicit cast to narrow or widen a value: ```vex [compact-floats.vx] fn main(): i32 { let sample: f32 = 1.5; let half = sample as f16; let brain = sample as bf16; let fromHalf = half as f32; let fromBrain = brain as f32; if fromHalf != sample || fromBrain != sample { return 1; } $println(fromHalf); $println(fromBrain); return 0; } ``` The program prints `1.500000` twice and exits 0. The value `1.5` is exactly representable in all three formats. Other values may round during narrowing; widening afterward does not restore discarded precision. For a numerical algorithm, choose its accumulation type separately from its storage type and check error bounds over representative inputs. A smaller storage type alone does not promise faster arithmetic on every target. ## Character Type `char` is the single-character primitive type. ```vex let letter: char = 'A' let escape: char = '\n' ``` `char` is a scalar value, not an owned string or a UTF-8 byte slice. Use [Strings](docs/guide/types/strings.md) for text storage and byte indexing. ## `string` and `str` ```vex let owned: string = "Hello" let borrowed: str = "Hello" ``` Use `string` when you want an owned value. Use `str` for a borrowed string view. String literals can flow into either type depending on context. ### `string` `string` is the main owned text type used throughout the repo. ### `str` `str` is a borrowed string slice-like view used in parsing and APIs that do not need ownership. ## Boolean Type ```vex let yes: bool = true let no: bool = false let is_equal = 5 == 5 let is_greater = 10 > 5 ``` ## Unit and `never` The unit type is written as `()` and is usually omitted in function signatures. ```vex fn log_message() { $println("done") } ``` The `never` type represents computations that do not return. ```vex fn fail(message: string): never { $panic(message) } fn spin(): never { loop {} } ``` ## Pointers and raw pointer-like primitives Low-level code uses the canonical `Ptr` family. `Ptr` models an opaque C pointer and `Ptr` carries writable-pointee capability. The old `ptr`, `*T`, and `*T!` spellings are rejected after lint-assisted migration. Most code should prefer references, `Span`, and owned containers. See [Pointers](docs/guide/advanced/pointers.md). ## Casting Use `as` for explicit casts. ```vex let x: i32 = 42 let y: i64 = x as i64 let f: f64 = 3.14 let i: i32 = f as i32 ``` ## Guidance - Prefer explicit integer types at public API boundaries. - Use `usize` and `isize` for sizes and pointer-related indexing. - Use `string` for owned text and `str` for borrowed text views. - Treat low-level pointer primitives as boundary tools, not default application code. ## Next Steps - [Arrays](docs/guide/types/arrays.md) - Fixed-size arrays and indexing - [Structs](docs/guide/types/structs.md) - Named data types and methods - [Generics](docs/guide/types/generics.md) - Type parameters --- Source: https://vex-lang.org/docs/guide/types/range.md # Integer Ranges Ranges describe integer induction for `for` loops. Use `start..end` when the upper bound is excluded and `start..=end` when it is included. The endpoint type is part of the range; use an explicit integer type when its width matters. ## Exclusive and inclusive bounds Save this complete example as `ranges.vx`: ```vex [ranges.vx] fn main(): i32 { let! exclusive = 0; for value in 0..5 { exclusive += value; } let! inclusive = 0; for value in 0..=5 { inclusive += value; } $println(exclusive); $println(inclusive); if exclusive != 10 || inclusive != 15 { return 1; } return 0; } ``` Expected stdout is `10` followed by `15`, with exit status 0. Run it with `vex run ranges.vx`. For a collection with `len` elements, `0..len` is the usual index interval. It is empty when `len` is zero. Avoid rewriting it as `0..=len-1`: subtracting one from a zero unsigned length is not a valid way to express an empty range. ## Direction and step Use an explicit `while` loop when the induction requires a custom increment or a descending traversal. Keep the termination test and update together: ```vex [range-steps.vx] fn main(): i32 { let! even_total = 0; let! even = 0; while even < 10 { even_total += even; even += 2; } let! descending_total = 0; let! descending = 10; while descending > 0 { descending_total += descending; descending -= 1; } $println(even_total); $println(descending_total); if even_total != 20 || descending_total != 55 { return 1; } return 0; } ``` Expected stdout is `20` followed by `55`, exit status 0. The descending example includes 10 and excludes 0. Choose a nonzero update that moves toward the termination bound. Keep the update and bounds representable in their integer type. ## Bounded range values The prelude defines `Range` and `RangeInclusive` for bounded values: ```vex let indices: Range = 0..4; for index in indices { $println(index); } ``` The fragment prints 0 through 3 when placed inside a function. These are compiler-recognized integer cursors. Their existence does not imply a Rust-style iterator-adapter API: this guide does not provide `Range.collect`, `stepBy`, `rev`, `filter`, or `map` recipes without corresponding methods. Use an explicit loop when accumulating or transforming values. For example, a bounded collection can be constructed with ordinary ownership: ```vex [range-collection.vx] fn main(): i32 { let! squares = Vec.new(); for value in 0..4 { squares.push(value * value); } $println(squares.len()); for value in squares { $println(*value); } return 0; } ``` Expected stdout is `4`, `0`, `1`, `4`, and `9`, each on its own line, with exit status 0. This example uses a borrowed `Vec` iterator; the vector remains the owner of its elements. ## Open-ended syntax A range with an omitted endpoint is allowed only directly as the iterator of an ordinary `for` loop in the current language contract. It is not a first-class `RangeFrom`, `RangeTo`, or `RangeFull` object that can be stored and collected later. Bound the work explicitly: ```vex for index in 5.. { if index == 8 { break; } $println(index); } ``` This fragment prints 5, 6, and 7. Do not rely on integer overflow to end an open-ended loop. ## Numeric domain Range induction requires exact integer endpoint types. Floating-point range values such as `0.0..1.0` are not the supported iteration API. For a fixed number of floating samples, use an integer index and compute each sample from that index: ```vex for index in 0..10 { let sample: f64 = (index as f64) / 10.0; $println(sample); } ``` This performs exactly ten iterations. Floating-point rounding still affects each sample; deriving samples from the index avoids accumulating an increment as loop state. ## Patterns and slicing are separate uses An interval in a `match` arm classifies a value; it does not construct an iterator: ```vex fn grade(score: i32): str { return match score { 0..60 => "below threshold", 60..=100 => "passing", _ => "invalid score", }; } ``` Collection slicing follows the collection's API and bounds policy. A `Span.slice(start, end)` produces a borrowed view and clamps the requested bounds in the current prelude. It does not allocate or extend the owner's lifetime. See [Span](docs/guide/memory/span-t.md) and [Strings](docs/guide/types/strings.md) for their different element and byte boundaries. ## Custom iterables A source-defined iterable uses the `IntoIterator.iter()` and `Iterator.next()` contracts. Implementing `next()` alone does not define the `..` operator or create range syntax for an arbitrary type. See [Contracts](docs/guide/types/contracts-reference.md) and [Loops](docs/guide/basics/loops.md) for iteration and item ownership. ## Related pages - [Loops and labels](docs/guide/basics/loops.md) - [Pattern matching](docs/guide/types/pattern-matching.md) - [Vectors](docs/guide/types/vec.md) --- Source: https://vex-lang.org/docs/guide/types/raw-pointers.md # Canonical Raw Pointers Raw pointers are unchecked addresses used at FFI, allocator, runtime, and hardware boundaries. Vex has one source-level raw-pointer family: `Ptr`. The old `ptr`, `*T`, `*T!`, `Ptr.of`, and `asRaw` spellings are not part of the language surface. Most application code should still prefer references, owned containers, or `Span`. The code blocks are independent fragments. An address used in an access example must still refer to live, initialized storage; do not reuse an address after the allocation example has freed it. ## Pointer types | Syntax | Meaning | | --- | --- | | `Ptr` | readable pointer to `T` | | `Ptr` | pointer with writable-pointee capability | | `Ptr` | opaque C-compatible pointer | | `Ptr` | opaque pointer with writable-pointee capability | `Ptr` lowers directly to the target pointer representation. `Opaque` is a pointee marker, not a value type and not a hidden allocation. ```vex let raw = Mem.alloc(64) // Ptr let typed = raw as Ptr let writable = raw as Ptr Mem.free(raw, 64) ``` A pointer does not own its allocation and carries no length or lifetime. The code that allocates memory must preserve the allocator and byte size required to release it. ## Obtaining pointers From a reference: ```vex let value = 42 let raw = &value as Ptr ``` From the typed prelude: ```vex let! values = Ptr.allocN(4) let opaque = values.asOpaque() ``` Null pointers use typed constructors: ```vex let readable = Ptr.null() let writable = Ptr.nullMut() let opaque = Ptr.null() ``` ## Reading and writing Raw access is unsafe because the compiler cannot prove address validity: ```vex let! value = 0 let raw = &value as Ptr unsafe { raw.write(42) $println(raw.read()) } ``` Before access, prove that the pointer is non-null, aligned, live, initialized for reads, within allocation bounds, and valid under Vex's aliasing rules. ## Pointer arithmetic Do not convert a pointer to an integer merely to perform element arithmetic. Prefer: - `offset(index)`, `add`, `sub`, `readAt`, and `writeAt` for element units; - `RawBuf.at(offset)`, `load`, and `store` for byte units; - `Span` when the extent is known and should be checked. ```vex let item = unsafe { typed.readAt(3) } let! bytes = RawBuf.of(raw.asOpaque()) bytes.store(12, 99) ``` ## Casting and alignment ```vex let memory = Mem.allocAligned(64, 32) let words = memory as Ptr unsafe { words.write(7) } Mem.freeAligned(memory) ``` An explicit `as Ptr` cast changes the compiler's pointee contract, not the underlying allocation. It cannot repair alignment, extend a lifetime, initialize bytes, or transfer ownership. Pointee erasure remains visible as `asOpaque()`. ## FFI ownership ```vex extern "NATIVE" from "foreign_objects" { fn foreignCreate(): Ptr fn foreignDestroy(value: Ptr) } let handle = unsafe { foreignCreate() } unsafe { foreignDestroy(handle) } ``` Always destroy memory with the allocator that created it. Do not pass a C block to `Mem.free`, and do not pass a VexArch block to C `free`, unless the API explicitly guarantees allocator compatibility. ## Safety checklist 1. Keep raw pointer scopes short and audited. 2. Preserve allocation size and allocator identity. 3. Check nullness, extent, alignment, and initialization. 4. Keep capability changes and pointee casts explicit. 5. Convert a valid raw range to `Span` as early as possible. --- Source: https://vex-lang.org/docs/guide/types/result-api.md # Result\ `Result` represents either `Ok(T)` or `Err(E)`. Use it when the caller needs to distinguish a value from a failure. The prelude does not declare `unwrap` or `expect` methods. ## Methods and types These signatures summarize `lib/runtime/VexArch/src/prelude/result.vx`. By-value methods consume the result according to its concrete payload's ownership rules. `Result` is Copy only when both payloads support Copy. | Method | Signature and result | | --- | --- | | `isOk`, `isErr` | `(Result) -> bool` | | `or` | `(Result, T) -> T`: success value or fallback payload | | `orElse`, `rescue` | `(Result, fn(E): T) -> T`: success value or payload computed from the error | | `map` | `(Result, fn(T): U) -> Result` | | `mapErr` | `(Result, fn(E): E2) -> Result` | | `flatMap` | `(Result, fn(T): Result) -> Result` | | `clone` | `(&Result) -> Result` where both payloads implement `Clone` | `orElse` and `rescue` return a **payload**, not a replacement `Result`. To choose another fallible operation, use `match` and return the desired `Result`. The prelude does not declare `andThen`, `filter`, `ok`, `err`, or `swap` as Result methods; do not assume those names are aliases. ## A runnable example ```vex [result-example.vx] fn checked_half(n: i32): Result { if n % 2 == 0 { return Ok(n / 2); } return Err(9); } fn main(): i32 { let ok: Result = Ok(10); let err: Result = Err(5); $println(ok.isOk()); $println(err.isErr()); $println(ok.or(99)); $println(err.orElse(|e: i32| e + 1)); let doubled: Result = ok.map(|n: i32| n * 2); $println(doubled.or(0)); let changed: Result = err.mapErr(|e: i32| e + 10); $println(changed.orElse(|e: i32| e)); let half: Result = ok.flatMap(checked_half); $println(half.or(0)); return 0; } ``` Run `vex run result-example.vx`. The expected stdout is: ```text true true 10 6 20 15 5 ``` The closures annotate their parameters to make the success and error types visible at the call site. A callback for `orElse` receives the error type and returns a success value. See [Closures](docs/guide/types/closures.md#type-inference). ## Fallback and propagation `result.or(expensive())` evaluates the argument before `or` is called. `result.orElse(|error: E| fallback(error))` calls its closure only for `Err`. For the `??` operator, `result ?? expensive()` evaluates the right side only for `Err`. The rescue form `result !> |error: E| fallback(error)` exposes the error to the fallback. A `?` propagates an `Err` from a function returning an appropriate `Result`; see [Operators](docs/guide/advanced/operators-reference.md). Do not assume automatic conversion between different error types without checking the compiler and the relevant conversion implementation. To return another `Result` on failure, use a match: ```vex fn recover(primary: Result): Result { return match primary { Ok(value) => Ok(value), Err(_) => Ok(0), }; } ``` ## Multi-step operations Distinguish a failed first step from failure after a previous step succeeded. If a withdrawal fails, do not attempt to refund it. If a later deposit fails after a successful withdrawal, compensation can also fail and must have its own reported outcome. The complete example below uses in-memory test outcomes to make the branches visible. It is a control-flow exercise, not a payment implementation: ```vex [compensation.vx] struct Ledger { source: i32, destination: i32, refund_attempts: i32, } fn withdraw(ledger: &Ledger!, succeeds: bool): Result { if !succeeds { return Err(1); } ledger.source = ledger.source - 10; return Ok(10); } fn deposit(ledger: &Ledger!, amount: i32, succeeds: bool): Result { if !succeeds { return Err(2); } ledger.destination = ledger.destination + amount; return Ok(amount); } fn refund(ledger: &Ledger!, amount: i32, succeeds: bool): Result { ledger.refund_attempts = ledger.refund_attempts + 1; if !succeeds { return Err(3); } ledger.source = ledger.source + amount; return Ok(amount); } // 0 = completed, 1 = withdrawal failed, 2 = refunded, 3 = refund failed. fn transfer(ledger: &Ledger!, first_ok: bool, second_ok: bool, refund_ok: bool): i32 { let amount = match withdraw(ledger, first_ok) { Ok(value) => value, Err(_) => { return 1; }, }; match deposit(ledger, amount, second_ok) { Ok(_) => { return 0; }, Err(_) => { return match refund(ledger, amount, refund_ok) { Ok(_) => 2, Err(_) => 3, }; }, }; } fn check(first: bool, second: bool, refund_ok: bool, outcome: i32, source: i32, destination: i32, refunds: i32): bool { let! ledger = Ledger { source: 100, destination: 0, refund_attempts: 0 }; let result = transfer(&ledger, first, second, refund_ok); return result == outcome && ledger.source == source && ledger.destination == destination && ledger.refund_attempts == refunds; } fn main(): i32 { if !check(false, true, true, 1, 100, 0, 0) { return 1; } if !check(true, true, true, 0, 90, 10, 0) { return 2; } if !check(true, false, true, 2, 100, 0, 1) { return 3; } if !check(true, false, false, 3, 90, 0, 1) { return 4; } $println("four paths ok"); return 0; } ``` Starting from source `100` and destination `0`, the four checks cover: | Withdrawal | Deposit | Refund | Outcome | Source / destination | Refund attempts | | --- | --- | --- | --- | --- | --- | | Fails | Not attempted | Not attempted | Withdrawal failed (`1`) | 100 / 0 | 0 | | Succeeds | Succeeds | Not attempted | Completed (`0`) | 90 / 10 | 0 | | Succeeds | Fails | Succeeds | Refunded (`2`) | 100 / 0 | 1 | | Succeeds | Fails | Fails | Refund failed (`3`) | 90 / 0 | 1 | The program prints `four paths ok` and exits 0 when all four checks pass; a failed check exits nonzero. The model assumes each failed operation makes no change and has no ambiguous result; real services may fail after committing. Compensation is not an atomic transaction: interruptions, retries, and concurrent operations require durable transaction support or an explicitly designed recovery protocol. A `Result` chain alone does not provide it. ## Related pages - [Option](docs/guide/types/option-api.md) - [Pattern Matching](docs/guide/types/pattern-matching.md) - [Error Handling](docs/guide/error-handling.md) --- Source: https://vex-lang.org/docs/guide/types/strings.md # Strings Vex uses two string-facing types in normal code: - `str`: a borrowed string view - `string`: an owned string value Both are available from the prelude. You do not need an `import`. ## `str` vs `string` Use `str` when you only need to read text. Use `string` when you need to return, store, concatenate, or otherwise own the result. ```vex fn greet(name: str): string { return "Hello, " + name; } fn main(): i32 { let label: str = "vex"; let message: string = greet(label); $println(message); return 0; } ``` In current Vex docs, prefer the lowercase spelling `string`. Some older tests in the repository still use `String` while naming is being normalized. ## Literals and cheap reads String literals are the easiest way to produce text: ```vex let site = "vex.dev"; let prefix = "https://"; let full = prefix + site; ``` Common read-only operations are available directly on string values used throughout the repo: ```vex let url = "https://example.com/api/v1/users"; let ok_prefix = url.startsWith("https://"); let ok_suffix = url.endsWith("users"); let has_api = url.contains("/api/"); let idx = url.indexOf("example"); ``` ## Conversions and formatting Vex code typically converts non-string values with `.toString()`: ```vex let count = 42; let line = "count=" + count.toString(); $println(line); ``` That pattern is used broadly in the examples and standard library tests. For composed output, use the built-in length-delimited formatter: ```vex let count: i32 = 42; let name: str = "Vex"; let line = $format("{} processed {:04} items", name, count); $println(line); ``` `{}` uses `Display.toString()` for user types. `{:?}` and `{:#?}` use `Debug.debug()`. Width, alignment, fill, radix, zero-padding, and precision are applied after the selected representation is produced. Radix formatting is prefix-free by default. Add `#` when the representation must carry its base prefix; zero padding is inserted after that prefix: ```vex $assert($format("{:x}", 255) == "ff"); $assert($format("{:#x}", 255) == "0xff"); $assert($format("{:08x}", 255) == "000000ff"); $assert($format("{:#08x}", 255) == "0x0000ff"); ``` The same rule applies to binary (`b`/`0b`) and octal (`o`/`0o`); uppercase hexadecimal changes the digits, not the lowercase `0x` prefix. Formatting is freestanding across every compiler-owned path: Vex carries exact byte lengths, uses the pure-Vex VexArch number formatters, and never routes a value through C `printf`/`snprintf`/`puts`. `$format` allocates its final owned string once. Text precision and width are Unicode-scalar aware and never split a UTF-8 sequence. A user type must implement the exact `Display.toString()` or `Debug.debug()` contract requested by the placeholder; unsupported structural values are compile-time errors rather than ABI-guessed fallback output. `$dbg` shares the same exact `Debug` contract. It evaluates its operand once, writes a labelled line to stderr, flushes it, and returns the original value: ```vex let parsed = $dbg(parseHeader(input)) // stderr: [DBG] // `parsed` is the single value produced by parseHeader(input). ``` ## Common operations ### Concatenation The `+` operator is the most common way to build new owned strings: ```vex let part1 = "Hello, "; let part2 = "World!"; let combined = part1 + part2; ``` ### Search ```vex let haystack = "Lorem ipsum dolor sit amet"; let found = haystack.contains("amet"); let pos = haystack.indexOf("ipsum"); ``` ### Trimming and case conversion ```vex let padded = " hello world "; let trimmed = padded.trim(); let upper = trimmed.toUpper(); let lower = upper.toLower(); ``` ### Repeat ```vex let token: string = "ab"; let repeated = token.repeat(4); ``` ## Bytes, text, and borrowed views `len()` and ordinary indexing describe UTF-8 bytes. A byte index is not a Unicode character index. The formatter's Unicode-scalar-aware width and precision rules are a separate operation; they do not change the units of string indexing. A borrowed `str` view must not outlive the storage it references. A view of a literal can refer to static text, while a view of an owned `string` depends on that owner remaining alive. Copying the small view does not copy the text. Use an explicit owned conversion when the result must survive its source. ## Ownership guidance - Accept `str` in APIs that only inspect text. - Return `string` when you create a fresh value. - Use concatenation and `.toString()` for straightforward text building. - Reach for template literals when you need multi-line structured output. ## Internal model The owned string implementation can use different representations for short and longer text. Treat its allocation strategy and binary layout as internal. Use the documented byte/string operations instead of casting its fields at an FFI boundary. ## See also - [Template Literals](docs/guide/basics/template-literals.md) - [`Vec`](docs/guide/types/vec.md) - [FFI](docs/guide/ffi.md) --- Source: https://vex-lang.org/docs/guide/types/structs.md # Structs Structs group named fields into a value. They are the main record type in Vex. Behavior is declared outside the struct with receiver methods. ## Define and construct a struct ~~~vex struct Point { public: x: i32, y: i32, } fn main(): i32 { let point = Point { x: 3, y: 4 }; $println(point.x + point.y); return 0; } ~~~ Field declarations are grouped under visibility sections. Use public for fields that callers may read or write, readonly for fields that callers may read but not write, and private for module-internal fields. When a struct is part of a module API, export the struct declaration as well. ~~~text export struct Account { private: internal_id: i64, readonly: balance: f64, public: name: string, } ~~~ Keep the visibility choice close to the type definition. It is part of the data model, not a comment about how the type happens to be used today. ## Methods Methods use an external receiver: ~~~vex struct Rectangle { public: width: i32, height: i32, } fn (rectangle: &Rectangle) area(): i32 { return rectangle.width * rectangle.height; } fn main(): i32 { let rectangle = Rectangle { width: 5, height: 7 }; $println(rectangle.area()); return 0; } ~~~ The receiver is an ordinary typed parameter inside parentheses. A call such as rectangle.area() supplies that parameter automatically. A mutable receiver is written with !: ~~~text fn (rectangle: &Rectangle!) resize(width: i32, height: i32) { rectangle.width = width rectangle.height = height } ~~~ Mutation through a receiver requires a mutable binding at the call site and an exclusive mutable borrow. ## Associated functions An associated function is qualified by the type name and has no receiver: ~~~vex struct Point { public: x: i32, y: i32, } fn Point.origin(): Point { return Point { x: 0, y: 0 }; } fn main(): i32 { let point = Point.origin(); $println(point.x + point.y); return 0; } ~~~ Use associated functions for constructors and type-level operations. Use receiver methods when an existing value is the subject of the operation. ## Callable constructors A function can share its name with its result type. Constructor overloads are ordinary source-defined functions; their bodies supply initialization policy: ~~~vex struct Counter { value: i64 } fn Counter(): Counter { return Counter { value: 73 }; } fn Counter(value: i64): Counter { return Counter { value: value + 1 }; } fn main(): i32 { let first = Counter(); let second = Counter(40); return if first.value == 73 && second.value == 41 { 0 } else { 1 }; } ~~~ Overload selection and generic arguments are resolved before code generation. The backend does not replace a selected constructor with zero-initialization because a type is registered in the Prelude. `Vec()` and `Channel(n)` use their Vex constructor bodies. Box construction remains integrated with VUMM's compiler-managed ownership strategy. ## Generic structs Structs may have type parameters: ~~~vex struct Container { public: value: T, } fn main(): i32 { let container = Container { value: 42 }; $println(container.value); return 0; } ~~~ A generic owner carries its concrete type arguments into its fields and methods. `Container` and `Container` therefore have different payload ownership requirements. See [Generics](docs/guide/types/generics.md). ## Structs and ownership A struct owns its fields unless a field is a reference or another explicitly borrowed type. Passing a struct by value may move it: ~~~text fn consume(point: Point) { ... } fn inspect(point: &Point) { ... } ~~~ Use an immutable reference when the callee only needs to read the value. Use a mutable reference when it must update the value. See [Ownership](docs/guide/memory/ownership.md) and [Borrowing](docs/guide/memory/borrowing.md) for the rules that govern these calls. ## Structs and contracts Contracts describe required methods and can be attached to a struct declaration: ~~~text contract Area { area(): i32; } struct Rectangle: Area { public: width: i32, height: i32, } ~~~ This declaration fragment also requires an `area` receiver implementation. See [Contracts](docs/guide/types/contracts.md) for a complete conformance example. ## Guidance - Keep data representation and behavior easy to find. - Make fields public only when callers should depend on direct field access. - Prefer associated functions for construction instead of exposing an invalid intermediate state. - Use references for read-only inspection and avoid unnecessary moves. - Give constructors responsibility for establishing the type's invariants. ## Next steps - [Enums](docs/guide/types/enums.md) - [Tuples](docs/guide/types/tuples.md) - [Generics](docs/guide/types/generics.md) - [Contracts](docs/guide/types/contracts.md) - [Ownership](docs/guide/memory/ownership.md) --- Source: https://vex-lang.org/docs/guide/types/tuples.md # Tuples Tuples group multiple values of possibly different types into a single compound value. They are fixed-size, ordered, and heterogeneous. ## Syntax and Construction ```vex // Parenthesized comma-separated values let pair = (1, "hello") let triple = (true, 3.14, 'x') // Explicit type annotation let coord: (f64, f64) = (10.0, 20.0) // Nested tuples let nested = ((1, 2), "three", (4.0, 5.0)) ``` ## The Unit Type: `()` The empty tuple `()` is Vex's **unit type** -- a zero-size type with exactly one value. It represents "no meaningful value" and is the default return type of functions that don't return anything. ```vex // Function returning nothing fn doSomething() { // Implicitly returns () } // Explicitly fn explicitUnit(): () { return () } ``` ## Tuple Field Access Access tuple elements by position using dot-index syntax: ```vex let pair = (42, "answer") let num: i32 = pair.0 // 42 let text: string = pair.1 // "answer" // Mutable tuple fields let! mut = (1, 2) mut.0 = 99 mut.1 = 100 ``` ## Destructuring Tuples can be destructured in `let` bindings and `match` arms: ```vex let point = (10, 20) // Destructuring let let (x, y) = point // x = 10, y = 20 // Destructure tuple arguments inside the function fn distanceSquared(first: (f64, f64), second: (f64, f64)): f64 { let (x1, y1) = first let (x2, y2) = second let dx = x2 - x1 let dy = y2 - y1 return dx * dx + dy * dy } let squared = distanceSquared((0.0, 0.0), (3.0, 4.0)) // 25.0 ``` `let`, `match`, and `for` support nested tuple patterns. Successive bindings can make a deeply nested shape easier to read. Destructuring does not erase reference lifetimes. Returning a selected reference retains the lifetime of that element, rather than automatically borrowing every sibling. Returning a reference to a local owner is still rejected. Alternative (`|`) patterns conservatively retain all possible source lifetimes: the returned reference must remain valid for whichever alternative matches. ## Pattern Matching with Tuples Tuples are first-class patterns in `match` expressions: ```vex [axes.vx] fn axis(point: (i32, i32)): str { return match point { (0, 0) => "origin", (0, _) => "y-axis", (_, 0) => "x-axis", (_, _) => "neither axis", }; } fn main(): i32 { $println(axis((0, -2))); $println(axis((-2, 0))); $println(axis((0, 0))); $println(axis((3, 4))); return 0; } ``` The program prints `y-axis`, `x-axis`, `origin`, and `neither axis`, with exit code 0. The first coordinate is x and the second is y. Nested tuple patterns are also supported in `match`: ```vex let nested = ((1, 2), 3); let total = match nested { ((a, b), c) => a + b + c }; ``` ## Returning Multiple Values Since functions return a single value, tuples are the idiomatic way to return multiple values: ```vex fn divideAndRemainder(a: i32, b: i32): (i32, i32) { return (a / b, a % b) } let (quotient, remainder) = divideAndRemainder(17, 5) // quotient = 3, remainder = 2 ``` ## Tuple Comparison Tuples support equality comparisons when their corresponding element types support `Eq`: ```vex let a = (1, "abc") let b = (1, "abc") let c = (2, "xyz") let same = a == b // true: every corresponding element is equal let diff = a == c // false ``` Equality compares corresponding elements. Tuple ordering (`<`, `>`, `<=`, `>=`) is not provided; write an explicit comparison policy when an algorithm needs lexicographic or domain-specific ordering. ## Copy and Move Semantics A tuple is `Copy` if ALL its element types are `Copy`: ```vex // All primitive types are Copy -> tuple is Copy let a = (1, 2.0, true) let b = a // Copy, a still usable // Contains Box (non-Copy) -> tuple is NOT Copy let c = (1, Box.new(42)) let d = c // Move, c is consumed ``` ## Tuples vs Structs | Feature | Tuple | Struct | | ------------- | ------------------------------- | ------------------------- | | Field access | `.0`, `.1`, `.2` position-based | `.fieldName` name-based | | Type identity | `(T1, T2)` structural | Named type | | Best for | Quick, ad-hoc grouping | Meaningful, reusable data | | Destructuring | `let (a, b) = t` | `let S { x, y } = s` or a `match` pattern | Use tuples for short-lived, positionally-meaningful groupings (return values, coordinate pairs). Use structs when fields have semantic meaning and the type is reused. ## Tuple Arity Use `()` for unit and pairs, triples, or larger tuples for positional grouping. Use a named wrapper when one field needs a distinct domain identity. Prefer a named struct once larger tuples become difficult to distinguish by position. ```vex // 0-element: unit let nothing = () // 2-element: pair let pair = (1, "a") // 3-element: triple let triple = (1, 2, 3) // 4+ element let quad = (1, 2.0, true, 'x') ``` ## Related Pages - [Arrays](docs/guide/types/arrays.md) -- homogeneous fixed-size collection - [Structs](docs/guide/types/structs.md) -- named-field composite type - [Pattern Matching](docs/guide/types/pattern-matching.md) -- destructuring tuples --- Source: https://vex-lang.org/docs/guide/types/unions.md # Unions > **A value of one of several types.** `A | B` does not require separately named variants; this does not imply the runtime representation has no tag. ## Syntax ```vex fn process(data: string | i32) { // data can be either string or i32 } ``` Union types canonicalize automatically: `A | B` ≡ `B | A`, duplicates removed. ## Pattern Matching ```vex fn printParam(param: string | i32) { match param { string => $println("String: " + param), i32 => $println("Int: " + param.toString()), } } ``` The compiler checks **exhaustiveness** — missing a variant is a compile error. ## Upcasting Values implicitly upcast into union types: ```vex let val: string | i32 | f64 = 42; // i32 → string|i32|f64 let val2: string | i32 | f64 = "hi"; // string → string|i32|f64 ``` ## Memory Layout A runtime union needs enough information to identify its active alternative. In the current LLVM lowering, the compiler uses a tag and, when needed, aligned payload storage. Tag width depends on the number of alternatives; payload size and alignment depend on the target and alternatives. The exact field representation, padding, and ABI are implementation details, not a portable promise or a C `union` layout. Inspect and test the compiler build and target before using a union at a foreign boundary. The source implementation is in `crates/vex-compiler/src/codegen_hir/context/types/named.rs`; this description is source-based and has not independently verified every release or target. ## Unions vs Enums | Feature | Union (`A \| B`) | Enum | |---------|:----------------:|:----:| | Named variants | No | Yes | | Payload types | Yes | Yes | | Exhaustive check | Yes | Yes | | Representation | Runtime tag and payload in the current lowering | Depends on enum and target; do not assume a niche optimization | | Wrap third-party types | Alternatives can be existing types | A named variant can carry an existing type | ## See Also - [Pattern Matching](docs/guide/types/pattern-matching.md) - [Enums](docs/guide/types/enums.md) - [Contracts](docs/guide/types/contracts.md) --- Source: https://vex-lang.org/docs/guide/types/variadics.md # Variadic Functions Vex supports typed variadic functions and, separately, platform C variadics. They have different ownership rules and calling conventions. ## Typed Vex packs Place a typed pack last in the parameter list: ```vex fn count(values: ...T): usize { return values.len(); } let three = count(10, 20, 30); let empty = count(); ``` Each argument is checked against the element type. Ordinary argument coercion rules apply, including constructor-based conversions where available. Fixed parameters may precede the pack: ```vex fn countAfter(prefix: T, values: ...T): usize { return values.len(); } let remaining = countAfter(10, 20, 30); ``` This is a typed, homogeneous pack, not C varargs. Vex transports a data pointer and element count through its own ABI. Preparing the pack does not require allocating a Vec; individual elements can still allocate according to their normal construction or clone semantics. Instance methods use the same pack rules. Borrowed, mutable and by-value receivers keep their ordinary ownership semantics; the receiver is not an element of the pack. Receiver evaluation precedes argument evaluation, and each expression runs once. Method-local generic element types and indirect aggregate returns use the same typed ABI as free functions. Fixed-arity overloads retain their normal specificity over a matching variadic alternative. ## Ownership and element access A by-value pack owns its elements. Passing move-only values transfers them to the callee, which drops them when it exits, including on early return. Passing borrowed elements, as in `values: ...&T`, does not transfer ownership of their referents. Iteration observes elements through references. The pack also exposes the borrowed Span API, including `get`, `first`, `last`, `slice` and `splitAt`. These operations do not turn the pack into a second owner. ```vex fn firstOrZero(values: ...i32): i32 { match values.get(0) { Some(value) => return *value, None => return 0, } } ``` References and views into an owned pack must not escape the callee: ```vex // Rejected: values cease to be owned by this callee when it returns. fn invalid(values: ...i32): Span { return values.slice(0, values.len()); } ``` The same restriction applies when a view is wrapped in another aggregate. To keep data beyond the call, produce independently owned data instead. A pack's borrowed method view is not a general implicit pack-to-Span conversion. ## Compile-time calls Typed packs also work in const functions. Every supplied argument is evaluated in source order and checked against the element type; an omitted tail creates an empty pack, not a missing required argument. ```vex const fn packSum(values: ...i64): i64 { let! total: i64 = 0; for value in values { total += value; } return total; } let empty = #const { packSum() }; // 0 let widened = #const { packSum(-7 as i8, 2 as i16) }; // -5 ``` Compile-time iteration borrows the callee-owned element slots, just as native iteration does. Repeated iteration does not consume the pack, and returning an element reference cannot extend the pack's lifetime. Borrowed element arguments retain their original caller storage. Fixed leading parameters and ordinary instance-method receivers use the same argument preparation. Only const-capable methods can run during CTFE; a shared pack view does not make an ordinary Span method const-capable. Foreign C varargs use the target ABI and are not compile-time calls. The evaluator's private pack storage is not a persistent array that can escape its evaluation frame. ## C-compatible variadics An untyped trailing `...` in an extern declaration uses the selected platform's C variadic ABI. Place user-package foreign declarations in a `.vxc` boundary: ```vex extern "LIBC" { fn printf(format: Ptr, ...): i32; fn snprintf(buf: Ptr, size: usize, format: Ptr, ...): i32; } ``` These are unsafe foreign calls. The caller must supply the correct promoted C argument types and valid pointers; a format string is not a Vex type-checking contract. In particular, Vex `str` and `string` are not C string pointers. Prepare NUL-terminated storage explicitly and keep it alive for the call. Typed Vex packs do not add a libc dependency. An explicit foreign declaration and its use are a separate FFI choice. ## Formatting builtins `$print`, `$println` and `$panic` are compiler-provided operations with their own argument handling. They are not examples of the C variadic ABI. ## Ownership at the call boundary Typed source calls use Vex's function-call ABI. The callee owns the pack's initialized element slots and destroys those elements when the pack's scope ends. A `Copy` element needs no destruction; an owning element transfers its cleanup responsibility into the pack. Returning early still ends that scope. Borrowed elements have two lifetimes to distinguish: the pack owns their reference slots, while each reference's pointee remains owned by the caller. Copying a reference out does not extend the pointee's lifetime. A `Span` over the pack's slots cannot outlive the pack itself. Use an owned `Vec` when a result needs to retain independent element storage beyond the call. ## Related pages - [Functions](docs/guide/basics/functions.md) - [Span](docs/guide/memory/span-t.md) - [Lifetimes](docs/guide/memory/lifetimes.md) - [Ownership workflows](docs/guide/memory/ownership-workflows.md) --- Source: https://vex-lang.org/docs/guide/types/vec.md # Vec\ — Dynamic Arrays `Vec` is the standard growable contiguous collection in Vex. It is the default choice when you need owned, mutable, resizable sequence storage. ## Creating Vectors ```vex let! nums = Vec.new(); let! names = Vec.new(); let! reserved = Vec.withCapacity(100); let! hinted = Vec.withCap(16); ``` Use `let!` when you plan to mutate the vector. Both `Vec.withCapacity(...)` and `Vec.withCap(...)` are present in the current prelude. ## Common Mutation Operations | Method | Current Surface | | ---------------------- | ------------------- | | `push(value)` | append element | | `pop()` | `Option` | | `insert(index, value)` | `bool` success flag | | `remove(index)` | `Option` | | `clear()` | remove all elements | | `set(index, value)` | replace and drop old value; panic out of bounds | | `trySet(index, value)` | `false` out of bounds; otherwise replace and drop old value | | `extendSpan(view)` | clone an external contiguous view | | `extendWithin(a, b)` | clone this Vec's range `[a, b)` onto its tail | Example: ```vex let! nums = Vec.new(); nums.push(10); nums.push(20); nums.push(30); let last = nums.pop(); ``` ## Access Patterns | Method | Current Surface | | ------------------------ | --------------- | | `get(index)` | `Option<&T>` | | `getUnchecked(index)` | `&T` | | `getRef(index)` | `&T` | | `tryGet(index)` | `Option<&T>` | | `tryGetRef(index)` | `Option<&T>` | | `copyAt(index)` | `T` | | `tryCopyAt(index)` | `Option` | | `getOr(index, fallback)` | `T` | | `first()` / `last()` | `Option<&T>` | `get(...)` and `tryGet(...)` are the preferred safe access paths. `getRef(...)` is currently an unchecked compatibility alias for `getUnchecked(...)`, so it should be treated as low-level access rather than a safe borrow helper. `copyAt` is an unchecked shallow read. `tryCopyAt` and `getOr` add a bounds branch, but do not add cloning. These operations reject element types that need destruction: a shared vector cannot transfer ownership out while retaining the same element. Use them for `Copy` elements in ordinary application code. For an owning `T`, borrow with `get` and call its `clone` policy explicitly, or transfer ownership with `remove`/`pop`. `trySet` consumes the replacement value even when the index is invalid; use an explicit bounds check first if the caller must retain that value on failure. ## Basic Example ```vex let! nums = Vec.new(); nums.push(10); nums.push(20); match nums.get(0) { Some(v) => { $println(v); } None => { $println("empty"); } } ``` ## Copying vs Borrowing Use the right accessor for the ownership model you want: - use `get(...)` or `tryGet(...)` when you want a bounds-checked borrowed view - use `getRef(...)` only when the index proof is already established - use `copyAt(...)` when you want an owned copy of a copyable element - use `getOr(...)` when a fallback value keeps the call site simpler ## Capacity and Growth `Vec.withCapacity(n)` is useful when you roughly know the final size and want to reduce reallocation churn. `Vec.withCap(n)` is a prelude alias for the same operation. ```vex let! values = Vec.withCapacity(10); values.push(1); values.push(2); ``` ## Bulk prefix commits `appendPrefix(values, count)` appends the initialized prefix of a fixed Copy array and grows the Vec when required. Bulk algorithms that already reserved a proven upper bound can use `tryAppendPrefix(values, count)` instead: it never allocates, returns `false` without mutation when spare capacity is insufficient, and may preserve a fixed SIMD value as one full-width store while committing only `count` elements to the logical length. ```vex let! output = Vec.withCapacity(64); let packed: [i32; 4] = [10, 30, 0, 0]; if !output.tryAppendPrefix(packed, 2 as usize) { $panic("reserved capacity invariant violated"); } ``` Both operations require `T: Copy`; ownership-bearing values should use `push`, `extendSpan`, or a Clone-aware package API. ## Extending from a view or from self Use `extendSpan(view)` for an externally borrowed `Span`. Use `extendWithin(start, end)` when the source range belongs to the destination Vec itself: ```vex let! values = Vec.withCapacity(4); values.push(10); values.push(20); values.push(30); values.push(40); values.extendWithin(1 as usize, 4 as usize); // [10, 20, 30, 40, 20, 30, 40] ``` The index-based self-source API is deliberate. Passing a `Span` borrowed from `values` back into a call that mutably borrows `values` would create overlapping shared and exclusive call arguments. `extendWithin` expresses the same operation without weakening the borrow checker or LLVM alias guarantees. It reserves the complete destination capacity before reading the range; Copy values use one bulk transfer and owning values preserve `Clone` semantics. ## Interop with `Span` For zero-copy, non-owning views over contiguous memory, prefer [Span\](docs/guide/memory/span-t.md). The current prelude exposes both `asPtr()` and `asSpan()` on `Vec`. ```vex let! values = Vec.new(); values.push(10); values.push(20); let view = values.asSpan(); let raw = values.asPtr(); ``` Use `Vec` when you need ownership and growth, and `Span` when you need a view. A view or element borrow must end before an operation that can relocate, replace, or destroy its backing elements. Reserving capacity can reduce growth but does not waive the exclusive mutable-borrow requirement. Iteration through `Vec.iter()` yields `&T`, so `for value in values` borrows elements rather than transferring them. `pop` and `remove` transfer elements; `clear` destroys them and retains the capacity. Dropping the vector destroys its remaining elements and releases its storage. ## Practical Guidelines 1. Use `Vec` as the default owned sequence container. 2. Keep the binding mutable with `let!` if you plan to call `push`, `pop`, `insert`, or `remove`. 3. Prefer safe accessors first; only use unchecked access when the proof is obvious. 4. Reach for `withCapacity(...)` in tight loops or builder-style code. ## Notes - The method names and receiver contracts follow the VexArch prelude. - Several accessors accept multiple integer index forms in current usage. ## Ownership in practice - [Ownership workflows](docs/guide/memory/ownership-workflows.md) — complete borrowed-parser and owned-report examples --- Source: https://vex-lang.org/docs/guide/verification-evidence.md # Verification Evidence A feature's presence in source, a passing analysis check, and a program that runs on a target are different facts. A status label alone does not establish all of them. Record the exact compiler binary and source revision, target, inputs, commands, exit status, standard output and error, and retained test artifacts before applying a result to your build. ## Validation Layers | Layer | What a passing check can establish | What it does not establish | | --- | --- | --- | | Source inspection | An implementation or test exists in the inspected tree. | That it was built, executed, or included in a release. | | Parser and semantic analysis | The tested input was accepted or produced the expected diagnostic. | Native code generation, linking, or runtime behavior. | | Code generation and linking | The tested target produced and linked an artifact. | That the artifact runs correctly on a device. | | Native execution | The exact program and inputs produced the recorded result on the recorded host. | Other inputs, compiler builds, operating systems, concurrency schedules, or GPU devices. | | Hardware execution | The tested workload ran on the identified device and driver. | Correctness or performance on other hardware or for other workloads. | | Performance measurement | A specified workload was measured with a specified setup. | A general speedup or guarantee for other inputs and machines. | A compiler version string is useful but is not a binary identity: different builds can report the same version. A source commit also does not identify a dirty checkout. Save the binary hash and record source changes and dependencies as well as `vex --version` and the target. ## Reproducing Documentation Checks The documentation checkout's `README.md` lists the available commands. For example, from `web/documentation` in a matching source checkout: ```sh bun run test:geometry /absolute/path/to/vex bun run test:contracts /absolute/path/to/vex bun run test:bit /absolute/path/to/vex bun run test:lessons /absolute/path/to/vex ``` These commands run the named fixtures, not the entire manual. The Python checks above extract examples from the documentation, use isolated temporary directories, compare expected results, and print the evidence directory. Their retained results include binary hashes, stdout, stderr, exit status, and timeouts. The lesson runner also saves per-lesson output and results but does not currently record a binary hash; record it separately. Some checks require checkout sources or host tools: consult the README and the individual script before running them. A successful test of fixed samples is not exhaustive proof of an API or of production safety. ## Evidence for this documentation edition This documentation targets **0.4.0**. The documentation repository's `DOCUMENTATION_RELEASE_AUDIT.md` and `audit/` directory retain the compiler identities, source inventories, example results and release checks used to prepare it. Development-artifact results remain attached to those identities; a published release report should identify the actual distributed artifact. Use those records to reproduce a specific check. Use the guides themselves for complete programs, expected behavior and the API contracts those programs illustrate. ## Retaining a Selected Suite For a bounded suite of native alias, bit, contract, compensation, geometry, and graph examples plus the sequential FIFO model, provide a compiler and a **new** evidence directory: ```sh bun run test:docs-evidence /absolute/path/to/vex /absolute/path/to/new-evidence-directory ``` The runner records both checkout states, binary hash and version, host information, per-check results and logs, and the individual checks' temporary evidence beneath that directory. It does not establish that the binary was built from either recorded checkout. It does not run the complete documentation, GPU, network, FFI, or multi-platform suite. For release automation, check out the matching documentation revision alongside the compiler and retain the resulting evidence artifact. ## Before Shipping 1. Pin the actual compiler and dependency sources or release artifacts; retain version, binary hash, target, and configuration. 2. Run the specific positive and negative fixtures that cover your use, then your own integration tests on every deployment target. 3. Retain stdout, stderr, exit status, timeout, and build/test logs. Record toolchain and hardware identities when those affect the result. 4. Treat device execution, concurrency and recovery, foreign ABI, and performance as separate gates when your application depends on them. 5. If the evidence is absent or the test covers a different revision or target, report the result as unverified for your case. The [language status](docs/guide/language-status.md) and [platform support](docs/guide/platform-support.md) pages are navigation aids. They do not replace a release-specific test report. --- Source: https://vex-lang.org/docs/guide/versioning.md # Versioning and Stability This edition targets **Vex 0.4.0**. A release version identifies the compiler and library distribution; specialist features retain the support boundaries described in their pages and release notes. ## Current release Use the 0.4.0 compiler package when following this edition. Confirm the actual executable before comparing behavior: ~~~bash vex --version ~~~ A suffix such as `-rc.39` identifies a release candidate, not the final `0.4.0` artifact. Two local builds can also report the same version while containing different changes. The [verification evidence guide](docs/guide/verification-evidence.md) records the build used for documentation checks; the release notes and published artifacts identify the distribution available to users. ## Version policy Vex follows a SemVer-inspired policy. Before 1.0, minor releases may contain breaking language, compiler, or standard-library changes. | Change | Typical release level | Pre-1.0 expectation | | --- | --- | --- | | Backward-compatible bug fix | Patch | Still verify generated code and runtime behavior. | | New or changed feature | Minor | May require source changes. | | Major compatibility break | Major | Reserved for broad migrations, but not the only possible breaking change before 1.0. | Release candidates should be treated as testable snapshots. Pin the compiler in CI and record the target platform when reporting a result. ## Stability labels - **Implemented:** The documented language or API surface exists; its page defines the supported behavior and limits. - **Verified example:** A named example has a recorded result for an identified compiler, target, and test layer. This is evidence about that example, not a maturity label for an entire subsystem. - **Experimental:** The compiler accepts the surface, but runtime, backend, or library behavior is still changing. - **Partial:** The main surface exists, while important integration or edge cases remain unfinished. - **Planned:** The concept is documented for direction only and should not be used as current syntax. These labels are not release qualification: a feature can pass semantic analysis while native code generation or runtime execution remains untested. ## Upgrading safely 1. Read the changelog and compare the compiler version with `vex --version`. 2. Run `vex lint` on the project before and after upgrading. 3. Run the project's tests on every target platform it supports. 4. Recheck pages marked Experimental or Partial in the language-status matrix. 5. Keep a small set of representative source examples in CI. Design notes and old migration documents may describe intended syntax. They are not authoritative when they disagree with compiler checks or the current language guide. ## Reporting a compatibility problem Include the compiler version, platform, command, source file, and complete diagnostic. If the problem is in the compiler or bundled runtime rather than the user program, record it in the repository issue tracker and link the report from the relevant documentation page. --- Source: https://vex-lang.org/docs/guide/why-vex.md # Why Vex? Vex brings ownership, concurrency, typed compile-time programming, and data-parallel operations into one systems language. Its value is in how these features work together: the same program can expose a small application API and still express storage lifetimes, native interfaces, and target-specific computation where those details matter. This guide helps you evaluate that model for a project. The [capability map](docs/guide/language-status.md) connects the 0.4.0 language surface to its guides. The [example collection](docs/guide/examples.md) shows how those features work together in concrete programs. ## Make state changes visible Immutable bindings are the default. Use `let!` for a binding that changes and `&T!` for a mutable borrow. Ownership and borrowing connect a function's interface to the lifetime of the values it accesses. This matters when a program passes a buffer through several layers: a reader can distinguish ownership transfer, a temporary view, and permission to modify the owner. A `Span` remains a view rather than an allocation or a lifetime extension; a raw pointer requires additional reasoning at the unsafe boundary. Start with [Ownership](docs/guide/memory/ownership.md), [Borrowing](docs/guide/memory/borrowing.md), and [Span](docs/guide/memory/span-t.md). ## Keep application code and systems code in the same language Structs, enums, generics, and contracts provide ordinary data modeling and reusable interfaces. `Option` and `Result` make absence and recoverable failure part of those interfaces. Native providers and typed pointers cover interoperability without making every caller manage an ABI. For example, an application-facing wrapper can validate input, call a native library, and convert its result into a Vex value. The wrapper still needs an explicit ownership and cleanup contract; selecting an FFI provider does not make foreign memory safe automatically. Follow [Your first project](docs/guide/first-project.md), then [Error handling](docs/guide/error-handling.md) and [Your first native call](docs/guide/ffi-first-native.md). ## Describe concurrency and its lifetime together `go`, channels, `async fn`, and `await` let you describe concurrent work in Vex. A useful design also says who owns each task's input, how results are collected, and what happens on cancellation or shutdown. Channels are useful when transferring work or results between tasks. Async functions are useful when an operation may suspend. Neither construct alone establishes a throughput improvement or freedom from deadlock: capacity, ordering, shared state, and the runtime on the selected target still matter. The [concurrency guide](docs/guide/concurrency/overview.md) introduces the model; [fan-in](docs/guide/concurrency/fan-in.md) develops a concrete completion and cancellation flow. ## Express data parallelism without promising a machine instruction Arrays, tensors, masks, and graph functions expose operations that the compiler can lower through Silicon IR. This makes shape and elementwise intent visible before machine-specific lowering. The generated code depends on element type, dimensions, dependencies, optimization settings, and backend. An array expression is not a promise of one SIMD instruction, and a graph function is not proof that a workload ran on a GPU. Compare outputs with a scalar reference, then inspect or measure the target path you intend to use. See [SIMD and tensors](docs/guide/simd/index.md), [GPU graph functions](docs/guide/gpu/graph-functions.md), and [benchmarking](docs/guide/benchmarks.md). ## Reuse typed semantics at compile time Compile-time evaluation and structural declaration generation allow a program to compute values and generate typed declarations within explicit boundaries. This can eliminate repeated declaration boilerplate while retaining normal type checking. It also introduces a build-time cost that should be measured when generation becomes large. Start with [Compile-time evaluation](docs/guide/advanced/comptime.md) and continue to [Structural declaration generation](docs/guide/advanced/comptime-declarations.md). ## Evaluate Vex for your project | Your requirement | What to investigate | | --- | --- | | A command-line application | Complete the first-project flow, then check the required file, process, and text APIs on the deployment platform. | | A network service | Check the HTTP/TLS API subset, concurrency behavior, cancellation, resource limits, and protocol tests your service needs. | | A compute pipeline | Establish reference outputs and numeric tolerances before comparing CPU or GPU throughput. | | A native-library integration | Verify target ABI, artifact packaging, ownership, callbacks, and shutdown using the actual library version. | | Reusable libraries | Review generic constraints, exported types, error behavior, and source compatibility for the selected compiler. | | An existing codebase | Compare the integration and migration cost with the specific benefit Vex would provide. | A representative vertical slice is more useful than a language feature score: build a small part of the intended application, exercise its failure paths, and retain the compiler version, target, inputs, and results. Use the same algorithm and workload when comparing another implementation. Compiler architecture, absence of a tracing collector, and source brevity are not substitutes for measured compile time, latency, memory use, or binary size. ## Further reading - [Build language tools in Vex](docs/guide/tooling/language-tools.md) - [Standard library overview](docs/guide/stdlib.md) - [Platform support](docs/guide/platform-support.md) - [Versioning and stability](docs/guide/versioning.md) - [Verification evidence](docs/guide/verification-evidence.md) --- Source: https://vex-lang.org/docs/hdl/design-examples.md # VexHDL Design Examples These illustrative designs connect hardware interfaces, state transitions, and verification cases. The FIFO is an executable software reference model; the UART and bus examples explain the corresponding hardware protocols. --- ## 1. FIFO (First-In, First-Out) Buffer This is a language-independent reference model for a synchronous FIFO. It is **not** VexHDL syntax or a synthesis-ready circuit. The FIFO accepts requests from the occupancy at the start of the clock edge: | Starting state | Write and read both requested | Accepted transfers | | --- | --- | --- | | Empty | Both | Write only; there is no same-cycle bypass | | Partially occupied | Both | One write and one read | | Full | Both | Read only; the newly freed slot is not reused on that edge | Reset takes priority over requests and clears the pointers and count; it does not have to clear the stored bits. Data returned by a read is valid only when that read is accepted. Each pointer wraps explicitly at `depth - 1`, including non-powers of two. A hardware implementation needs `max(1, ceil(log2(depth)))` pointer bits and `max(1, ceil(log2(depth + 1)))` count bits for `depth >= 1`. The one-bit minimum avoids zero-width hardware fields, including at depth 1. ```python [fifo-model.py] class Fifo: def __init__(self, depth): if depth < 1: raise ValueError("depth must be at least 1") self.depth = depth self.mem = [None] * depth self.wr_ptr = self.rd_ptr = self.count = 0 def step(self, reset, wr_en, rd_en, data): """Advance one edge; return (write accepted, read accepted, read data).""" if reset: self.wr_ptr = self.rd_ptr = self.count = 0 return False, False, None write = bool(wr_en and self.count < self.depth) read = bool(rd_en and self.count > 0) value = self.mem[self.rd_ptr] if read else None if write: self.mem[self.wr_ptr] = data self.wr_ptr = (self.wr_ptr + 1) % self.depth if read: self.rd_ptr = (self.rd_ptr + 1) % self.depth self.count += int(write) - int(read) return write, read, value @property def empty(self): return self.count == 0 @property def full(self): return self.count == self.depth ``` For an actual circuit, decide whether memory supports this read behavior and what it returns during an unaccepted read; these choices depend on the memory primitive. Do not expose the stale contents as valid data when `empty` is true. The model does not establish VexHDL parser, simulator, synthesis, or device support. The documentation's `test:fifo-model` compares this exact model against a separate queue across depths 1, 2, 16, 17, and 32, including reset, full and empty simultaneous requests, and pointer wrap. --- ## 2. UART TX Controller This illustrative transmitter sends an 8-bit word least-significant bit first, with one start bit, one stop bit and no parity. A request is accepted only in `IDLE`; requests while active are ignored. Keep `tx_data` stable at the accepting clock edge, and use `tx_done`/`tx_active` in the producer protocol. The integer divider requires `BAUD_RATE > 0` and `1 <= CLK_FREQ / BAUD_RATE <= 65536` for the shown 16-bit counter. Actual baud is `CLK_FREQ / CLKS_PER_BIT`, so check its relative error against the receiver's tolerance. For the defaults, the divider is 434, not an exact fractional baud generator. Reset aborts an in-flight frame and restores idle-high output. This is a state-machine sketch, not a device-qualified UART core: ```vexhdl export enum TxState { IDLE, START_BIT, DATA_BITS, STOP_BIT, } export graph uart_tx #( CLK_FREQ: Param = 50_000_000, BAUD_RATE: Param = 115_200, )( clk: In, rst: In, tx_start: In, tx_data: In>, tx_active: Out, tx_out: Out, tx_done: Out, ) { param CLKS_PER_BIT: U32 = CLK_FREQ / BAUD_RATE; let! state: TxState = TxState::IDLE; let! clk_count: U<16> = 0; let! bit_index: U<3> = 0; let! data_reg: U<8> = 0; let! r_tx_out: Bool = true; let! r_active: Bool = false; let! r_done: Bool = false; on(PosEdge(clk), PosEdge(rst)) { if rst { state <- TxState::IDLE; clk_count <- 0; bit_index <- 0; r_tx_out <- true; r_active <- false; r_done <- false; } else { match (state) { TxState::IDLE => { r_tx_out <- true; r_done <- false; clk_count <- 0; bit_index <- 0; if tx_start { data_reg <- tx_data; r_active <- true; state <- TxState::START_BIT; } else { r_active <- false; } } TxState::START_BIT => { r_tx_out <- false; // Start bit is low if (clk_count < CLKS_PER_BIT - 1) { clk_count <- clk_count + 1; } else { clk_count <- 0; state <- TxState::DATA_BITS; } } TxState::DATA_BITS => { r_tx_out <- data_reg[bit_index]; if (clk_count < CLKS_PER_BIT - 1) { clk_count <- clk_count + 1; } else { clk_count <- 0; if (bit_index < 7) { bit_index <- bit_index + 1; } else { bit_index <- 0; state <- TxState::STOP_BIT; } } } TxState::STOP_BIT => { r_tx_out <- true; // Stop bit is high if (clk_count < CLKS_PER_BIT - 1) { clk_count <- clk_count + 1; } else { clk_count <- 0; r_done <- true; r_active <- false; state <- TxState::IDLE; } } } } } tx_out = r_tx_out; tx_active = r_active; tx_done = r_done; } ``` --- ## 3. AXI-Lite Slave Interface A register-bank design must preserve independent channel handshakes. The old example wrote on simultaneous `AWVALID`/`WVALID` and could overwrite a stalled response; that is not a correct reusable peripheral. A transfer occurs only at an edge where a channel's `VALID` and `READY` are both asserted. Address and data can arrive in either order. A response must remain valid, with stable payload, until accepted. These requirements come from the [Arm AMBA AXI specification, A3 and B1](https://developer.arm.com/-/media/Arm%20Developer%20Community/PDF/IHI0022H_amba_axi_protocol_spec.pdf). For a conservative one-outstanding-write design, use separate address and data holding slots. Capture each only on its handshake. Once both are full and the response slot is free, perform one write, consume the slots and publish the response. Stop accepting new work when storage is occupied. Apply byte write strobes, validate address decoding and return the appropriate response status. For reads, retain the selected data and response while `RVALID && !RREADY`. This is a proposed architecture to implement in the chosen HDL, not a tested VexHDL module. Its acceptance tests should include: | Scenario | Expected result | | --- | --- | | Address arrives before data, and vice versa | Exactly one write after both accepted | | Response consumer stalls | Stable response; no lost or repeated transaction | | Partial byte strobe | Only selected bytes change | | Invalid register address | Defined error response; unrelated registers unchanged | | Reset during a transaction | State follows the specified reset/recovery protocol | Retain waveforms and assertions for these cases before synthesis. A successful compile does not establish bus-protocol correctness. --- Source: https://vex-lang.org/docs/hdl/expressions-operators.md # VexHDL Expressions and Operators Guide This guide details VexHDL's expression syntax, binary/unary operators, bit slicing/concatenation, and built-in namespace functions. --- ## 1. Number Literals VexHDL supports flexible integer and bit-vector literals: * **Simple Integers**: Decimal numbers (e.g. `42`, `1000`). * **Radix-Based Literals**: Formatted as `'`. Radixes include binary (`b`), octal (`o`), decimal (`d`), and hexadecimal (`h`). * `8'hFF`: 8-bit hex literal representing `255`. * `16'd450`: 16-bit decimal literal. * **4-State Literals (Z & X)**: Radix literals can contain `x`/`X` (unknown) and `z`/`Z` (high impedance) characters. * `4'b10z1`: 4-bit literal containing `1`, `0`, `Z`, `1` states. * `8'b00xx_zzzz`: 8-bit literal with lower bits high-impedance and middle bits unknown. --- ## 2. Operators ### 2.1 Unary Operators Unary operators operate on a single operand: | Operator | Name | Description | Example | | :--- | :--- | :--- | :--- | | `~` | Bitwise Not | Flips every bit of the operand | `let mask = ~4'b1010; // 4'b0101` | | `!` | Logical Not | Inverts boolean state | `let is_false = !is_true;` | | `-` | Arithmetic Negation | Inverts sign of the number (2's complement) | `let negative_v = -data_in;` | | `&` | And-Reduction | Performs bitwise AND across all bits of the operand | `let all_ones = &byte_val;` | | `\|` | Or-Reduction | Performs bitwise OR across all bits of the operand | `let has_one = \|byte_val;` | | `^` | Xor-Reduction | Performs bitwise XOR across all bits (parity check) | `let parity = ^byte_val;` | ### 2.2 Binary Operators Binary operators operate on two operands: * **Arithmetic**: Addition `+`, Subtraction `-`, Multiplication `*`, Division `/`, Modulo `%`. * **Bitwise Logic**: Bitwise And `&`, Bitwise Or `|`, Bitwise Xor `^`. * **Logical**: Logic And `&&`, Logic Or `||`. * **Shifting**: * Logical Left-Shift `<<` (fills with `0`). * Logical Right-Shift `>>` (fills with `0`). * Arithmetic Right-Shift `>>>` (preserves sign bit). * **Comparisons**: * Inequalities: `<`, `<=`, `>`, `>=`. * Equality: `==` (equality check, propagates `X/Z`), `!=` (inequality check). * Case Equality: `===` (strict equality comparison of `0`, `1`, `X`, and `Z` bits without propagation), `!==` (strict inequality). ### 2.3 Ternary Operator Conditional selector: ```vexhdl let result: U<8> = select_flag ? val_a : val_b; ``` --- ## 3. Bit Manipulation * **Bit Selection**: Extracts a single bit from a bus. ```vexhdl let lsb: Bool = data_bus[0]; ``` * **Bit Slicing (Part-Select)**: Extracts a sub-bus slice using `[msb:lsb]` syntax. ```vexhdl let upper_nibble: U<4> = data_bus[7:4]; ``` * **Concatenation**: Chains multiple signals into a single bus using `{a, b, ...}` syntax. ```vexhdl let combined_bus: U<8> = {upper_nibble, lower_nibble}; ``` * **Replication**: Repeats a signal `N` times using `{N{expr}}` syntax. ```vexhdl let clear_vector: U<8> = {8{false}}; // 8'b0000_0000 ``` --- ## 4. Built-in Namespaces VexHDL provides standard helper functions organized inside static namespaces: ### 4.1 `Sim` (Simulation Only) * `Sim.delay(ticks)`: Halts execution of the calling thread for `ticks` simulation steps. * `Sim.print(format, args...)`: Prints formatted messages to Tauri Studio's output terminal (supports `%d`, `%h`, `%b`). * `Sim.assert(condition, message)`: Verifies runtime condition; raises simulation error on failure. * `Sim.finish()`: Stops simulation runner. ### 4.2 `Math` (Compile-time Elaboration) * `Math.clog2(val)`: Calculates ceiling log2 of `val` (useful for calculating address widths from memory depth). ```vexhdl param ADDR_WIDTH: U<32> = Math.clog2(1024); // Evaluates to 10 ``` ### 4.3 `Bit` & `Gate` (Hardware Primitives) * `Gate` namespace exposes cell-level logic gate primitives for netlist structures (e.g. `Gate.and(a, b)`). ### 4.4 `Mem` (Memory Access) * Exposes primitives for writing to and reading from `Reg` memories with specific clock triggers. --- Source: https://vex-lang.org/docs/hdl/getting-started.md # VexHDL Getting Started Start with one clock domain, an explicit reset, and a small stateful design. A counter or FIFO makes the relationship between inputs, clock edges, and outputs visible before you add external buses or multiple clocks. ## Choose your toolchain - For a systems program, use the [Vex first-project guide](docs/guide/first-project.md). - For Vex HDL Studio, select an installer for your operating system on the [release page](https://github.com/vex-org/releases/releases/tag/v0.1.0) or [Download](https://www.vex-lang.org/download), then follow that package's project and toolchain instructions. - For a VexHDL source checkout, use its build and simulation commands. Keep the compiler, simulator, project format, and external tools from a compatible toolchain configuration. ## Specify a four-entry FIFO Before writing a circuit, define its observable behavior. Use the [FIFO reference model](docs/hdl/design-examples.md#_1-fifo-first-in-first-out-buffer) with depth four and no empty-state bypass. At each clock edge, accept a write only when the FIFO started that edge with space, and accept a read only when it started with data. Reset takes priority over both requests. This sequence gives a small, repeatable testbench plan: | Edge | Request | Accepted operation | Count after the edge | Read value | | --- | --- | --- | --- | --- | | 0 | Reset | Reset | 0 | No valid read | | 1 | Write 10 | Write | 1 | No valid read | | 2 | Write 20 and read | Both | 1 | 10 | | 3 | Read | Read | 0 | 20 | | 4 | Read | Neither | 0 | No valid read | | 5 | Write 30 and read | Write only | 1 | No valid read | | 6 | Read | Read | 0 | 30 | Drive requests before the sampling edge and observe outputs according to the chosen memory's latency. Assert both the returned value and whether a transfer was accepted; a stale bus value while empty is not a successful read. ## Translate the contract into hardware A depth-four FIFO needs read/write pointers, a count that can represent zero through four, storage for four elements, and logic for accepted reads/writes. Derive `empty` and `full` from the count. Update the pointers and count from accepted operations, not raw request signals. Separate the next-state calculations from the clocked register updates. The [process guide](docs/hdl/procedural-control.md) explains combinational and sequential blocks; the [syntax guide](docs/hdl/syntax-reference.md) introduces ports and widths. Choose the memory's read-during-write behavior explicitly before selecting a hardware primitive. ## Extend the testbench After the sequence above, cover pointer wrap, full-state reads and writes, consecutive traffic, and reset while data remains buffered. Test a non-power-of- two depth separately because pointer wrap must respect the configured depth. Keep an independent queue model to compare accepted transactions with the hardware's output stream. Simulation and synthesis answer different questions. Use [Transpiler Integration](docs/hdl/transpiler-integration.md) when adding a device, external modules, timing constraints, or synthesis tools. Preserve the interface contract when replacing the simple storage model with a device memory block. --- Source: https://vex-lang.org/docs/hdl/index.md # VexHDL VexHDL describes digital hardware through modules, ports, clocked state, and combinational logic. Its project includes a compiler, simulator, synthesis integration, and the desktop Vex HDL Studio environment. The programming-language compiler and the HDL toolchain serve different purposes. A Vex `graph fn` describes a data-parallel software computation; a VexHDL `graph` describes a hardware module and its connections. ## Choose the product | Product | Use it for | Start here | | --- | --- | --- | | Vex language CLI | Systems programs, libraries, concurrency, and numerical code | [First Vex project](docs/guide/first-project.md) | | VexHDL compiler and simulator | Hardware modules, signal behavior, and circuit testbenches | [HDL getting started](docs/hdl/getting-started.md) and the instructions for your source checkout | | Vex HDL Studio | A desktop environment for HDL projects | Select the matching installer and release notes on the [release page](https://github.com/vex-org/releases/releases/tag/v0.1.0) or [Download](https://www.vex-lang.org/download) | The pages here use illustrative designs to explain hardware behavior. Use the project format and tool commands supplied with your chosen HDL toolchain; software CLI commands and Vex package manifests are not interchangeable with Studio project instructions. ## Build a hardware design in layers 1. **Define the interface.** Give every port a direction, width, and clock-domain meaning. State when an input is sampled and when an output is valid. 2. **Specify state transitions.** Separate combinational calculations from state updated on a clock edge. Define reset behavior and priority explicitly. 3. **Exercise the protocol.** Simulate ordinary transactions, empty/full states, reset during activity, and boundary widths or counts. 4. **Choose the implementation flow.** Synthesis and place-and-route need a device, timing constraints, and the appropriate external tools. The [FIFO reference model](docs/hdl/design-examples.md#_1-fifo-first-in-first-out-buffer) illustrates simultaneous requests and occupancy boundaries. The UART example shows a clock divider and a multi-cycle state machine. The AXI discussion explains how separate channels create independent obligations. ## Simulation, synthesis, and physical behavior Simulation evaluates the design's behavioral model. Synthesis maps eligible logic into a hardware representation; placement, routing, timing analysis, and board constraints determine whether that implementation meets a device-level requirement. A successful compiler check does not replace those stages. Clock-domain crossings, reset release, memory read behavior, and signal timing need explicit design choices. Treat assertions and static checks as ways to expose a violated contract, and keep electrical and timing validation tied to the actual implementation. ## Explore the concepts - [Getting Started](docs/hdl/getting-started.md) - [Syntax Reference](docs/hdl/syntax-reference.md) - [Procedural and Control Flow](docs/hdl/procedural-control.md) - [Design Examples](docs/hdl/design-examples.md) - [Safety Policies](docs/hdl/safety-policies.md) - [Transpiler Integration](docs/hdl/transpiler-integration.md) --- Source: https://vex-lang.org/docs/hdl/procedural-control.md # VexHDL Procedural and Control Flow Guide This document covers VexHDL's procedural execution blocks (processes) and control structures, detailing conditional branching, pattern matching, loops, and simulation-time concurrency. --- ## 1. Process Blocks Hardware behavior is described inside process blocks. VexHDL categorizes processes based on their sensitivity list and timing characteristics. ### 1.1 Combinational Process (`comb`) * Re-evaluated by the simulator when a read signal changes. * Only blocking assignments (`=`) are allowed inside this block. * Blocking assignments define evaluation order within a process; zero-time simulation may still require delta-cycle settling. Physical gates have propagation delay. ```vexhdl let comb is_zero: Bool; comb { if data_bus == 0 { is_zero = true; } else { is_zero = false; } } ``` ### 1.2 Sequential Process (`on`) * Triggered only on specified edges of clock or reset signals. * Uses non-blocking assignments (`<-`). ```vexhdl on(PosEdge(clk), PosEdge(rst)) { if rst { r_out <- 0; } else { r_out <- next_val; } } ``` ### 1.3 Latch Process (`latch`) * Synthesizes transparent latches. ```vexhdl latch { if gate_enable { latch_out = d_in; } // Note: missing else branch infers memory/latch state. } ``` ### 1.4 Simulation Initial Process (`initial`) * Runs exactly once at time step 0 during simulation. * Used to drive initial inputs or sequences in testbenches. Ignored during synthesis. ```vexhdl initial { clk = false; rst = true; Sim.delay(10); rst = false; } ``` --- ## 2. Conditional Statements ### 2.1 `if-else` Standard conditional structure: ```vexhdl if (sel == 2'b01) { out = a; } else if (sel == 2'b10) { out = b; } else { out = c; } ``` ### 2.2 `case` Statements (Normal, `casez`, `casex`) VexHDL supports three variants of the `case` statement, supporting don't-care comparison matching: * **`case` (Normal)**: Strict bitwise comparison of `0`, `1`, `X`, and `Z` values. * **`casez`**: Treats high-impedance `Z` bits (or `?`) in the patterns as don't-care values. * **`casex`**: Treats both `X` and `Z` bits in the patterns as don't-care values. ```vexhdl // CaseZ example: matching priority encoder casez (encoded_input) { 4'b1??? => out = 3; 4'b01?? => out = 2; 4'b001? => out = 1; 4'b0001 => out = 0; default => out = 0; } ``` A wildcard match can conceal an unknown or undriven control signal. Use an explicit invalid-input check when `X` must expose a design error. ### 2.3 `match` Statements (Pattern Matching) VexHDL supports Rust-like pattern matching for struct fields, enums, and values: * **Exhaustive Variant Checks:** Variants are scoped with `Enum::Variant`. * **Wildcards:** `_` matches all remaining paths. ```vexhdl next_state = current_state; // default avoids retaining an unintended comb value match (current_state) { State::IDLE => { if start { next_state = State::INIT; } } State::INIT => { next_state = State::RUN; } _ => { next_state = State::IDLE; } } // Classify a nonnegative temperature with explicit, contiguous bounds. if temperature <= 50 { fan_speed = 0; } else if temperature <= 100 { fan_speed = 1; } else if temperature <= 150 { fan_speed = 2; } else { fan_speed = 3; } ``` --- ## 3. Loops Loops are unrolled during compilation/synthesis or run dynamically during simulation. ### 3.1 `for` Loops Used for structured iteration. ```vexhdl for i in 0..8 { out_vector[i] = in_vector[7 - i]; // Reverse bit-order } ``` ### 3.2 `repeat(count)` Loops Repeats a statement block `count` times. ```vexhdl repeat(8) { clk = !clk; Sim.delay(5); } ``` ### 3.3 `forever` Loops Runs an infinite loop. Primarily used inside clock generation threads. ```vexhdl forever { clk = !clk; Sim.delay(10); } ``` --- ## 4. Simulation Concurrency & Synchronization VexHDL provides advanced statements for managing time-synchronization and thread forks in simulation: * **`fork ... join`**: Fork-join blocks run multiple statement blocks concurrently as parallel threads during simulation. ```vexhdl fork { // Thread 1: Wait and print Sim.delay(50); Sim.print("Thread 1 completed!"); } { // Thread 2: Clock stimulus repeat(5) { clk = !clk; Sim.delay(10); } Sim.print("Thread 2 completed!"); } join ``` * **`wait(condition)`**: Halts thread execution until a condition expression evaluates to `true`. ```vexhdl wait(ready_flag == true); // Continue execution once flag is set ``` --- Source: https://vex-lang.org/docs/hdl/safety-policies.md # VexHDL Safety, Verification, and Policy System This document outlines VexHDL's safety checks (including the V-VUMM analyzer), formal verification constructs, and the parameterized policy system. --- ## 1. V-VUMM Static Safety Analyzer The **V-VUMM (Vex-HDL Value & Usage Memory Manager)** analyzer performs static checks during semantic compiler analysis to catch critical hardware bugs before synthesis. ### 1.1 Multiple Driver Protection (`E023: HirDriverConflict`) * **Rule**: A signal (wire or reg) can only be driven by a single process or continuous assignment. * If a signal is written to by two different sequential blocks, combinational blocks, or continuous assignments, the compiler throws `E023`. * **Example (Multiple Drivers)**: ```vexhdl let! r_val: U<8>; on(PosEdge(clk_A)) { r_val <- val_a; } on(PosEdge(clk_B)) { r_val <- val_b; } // E023 Error! ``` ### 1.2 Unintentional Latch Prevention (`W002: WarnInferredLatch`) * **Rule**: All signals written inside a combinational (`comb`) block must be explicitly assigned a value along every execution path. * Missing assignments (e.g. an `if` block without an `else` branch, or a `case` block without a `default`) generate latches, causing timing problems. * **Example (Latch Inferred)**: ```vexhdl let comb next_state: State; comb { if (start) { next_state = State::RUN; } // W002 Warning: next_state is not assigned if start is false! } ``` ### 1.3 Clock Domain Crossing Protection (`W004: WarnClockDomainCrossing`) * **Rule**: Registers driven in clock domain `A` cannot be read directly inside a block driven in clock domain `B` without synchronization. * The compiler scans clock domains bidirectionally. Unsynchronized domain crossings emit `W004`. * **Example (CDC crossing)**: ```vexhdl let! r_data_a: U<8> on PosEdge(clk_a); let! r_data_b: U<8> on PosEdge(clk_b); on(PosEdge(clk_b)) { r_data_b <- r_data_a; // W004 Warning: Unsynchronized CDC crossing! } ``` * **Struct CDC Splitting Check**: In addition to standard signals, the compiler ensures different fields of the same struct are not driven by multiple conflicting clocks. If `my_struct.f1` is driven by `clk_A` and `my_struct.f2` is driven by `clk_B`, warning `W004` is raised. ### 1.4 Combinational Loop Detection (`E025: HirCombLoop`) * **Rule**: Continuous assignments and combinational blocks must not form circular dependency paths. * The compiler constructs a directed graph of combinational dependencies and uses a DFS-based cycle-detection algorithm. * **Example (Combinational Loop)**: ```vexhdl let a: Bool; let b: Bool; a = b; b = a; // E025 Error: combinational feedback loop detected ``` ### 1.5 Async Reset Polarity Check (`E024: HirAsyncPattern`) * **Rule**: Edge-triggered async resets must check the correct polarity in their conditional statements inside the block. * For `PosEdge(rst)`, the block must start with `if (rst)`. For `NegEdge(rst)`, it must check `if (!rst)`. * **Example (Mismatched Polarity)**: ```vexhdl let clk: Bool; let rst: Bool; let! q: U<8>; on(PosEdge(clk), PosEdge(rst)) { if (!rst) { // E024 Error: Active-high reset trigger requires check `if rst` q <- 0; } else { q <- d; } } ``` ### 1.6 Uninitialized Signal & Register Read Check (`W006`) * **Rule**: Floating combinational wires must be driven before being read, and registers must have an initial value or reset branch if read. * Detects some missing initialization/reset paths. This does not prove freedom from physical metastability; clock-domain crossing needs a separately validated synchronization protocol. * **Example (Uninitialized Read)**: ```vexhdl let a: Bool; let b: Bool; a = b; // W006 Warning: read on unassigned wire `b` ``` ### 1.7 Width Truncation Warning (`W001: WarnWidthTruncation`) * **Rule**: Assigning a high-width expression to a smaller-width target bus emits a truncation warning. * **Example (Width Truncation)**: ```vexhdl let a: U<8>; let b: U<16>; a = b; // W001 Warning: width truncation from 16 to 8 bits ``` ### 1.8 Array Out-of-Bounds Check (`E027: HirOutOfBounds`) * **Rule**: Constant indices used to index arrays must be strictly within the array's declared depth. * **Example (Out-of-Bounds)**: ```vexhdl let! ram: [U<8>; 16]; let val: U<8>; val = ram[20]; // E027 Error: index 20 is out of bounds for array of depth 16 ``` ### 1.9 Clock/Reset Collision Check (`W007: WarnClockResetCollision`) * **Rule**: Signals classified as clock or reset sources cannot be driven/written as data signals inside procedural blocks or continuous assignments. * **Example (Clock/Reset Collision)**: ```vexhdl let clk: Bool; let rst: Bool; on(PosEdge(clk)) { clk <- 1; // W007: clock/reset also driven as data } ``` ### 1.10 Assignment Style Verification (`W005: WarnAssignStyle`) * **Rule**: Sequential registers (`let!`) should be updated with non-blocking assignments (`<-` / `NonBlockingAssign`) inside sequential blocks, while combinational wires should use blocking assignments (`=` / `BlockingAssign`). * **Example (Mismatched Assignment Style)**: ```vexhdl let! reg_val: U<8>; on(PosEdge(clk)) { reg_val = 1; // W005 Warning: blocking assignment '=' used for register } ``` ### 1.11 Port Width Mismatch Warning (`W008: WarnMismatchedPorts`) * **Rule**: Port connections to instantiated sub-modules must have identical bit widths. * **Example (Mismatched Ports)**: ```vexhdl graph sub(a: In>, y: Out>) { y = a; } graph top(a16: In>, y16: Out>) { inst: sub(a: a16, y: y16); // W008 Warning: port width mismatch in instance } ``` ### 1.12 Fork-Join Racing Error (`E028: HirParallelRacing`) * **Rule**: Parallel execution blocks inside a `fork-join` block must not write to the same signal. * **Example (Fork-Join Racing)**: ```vexhdl let! q: U<8>; fork_join { { q <- 1; } { q <- 2; } // E028 Error: parallel race condition on signal `q` } ``` --- ## 2. Formal Verification and Debugging VexHDL supports simulation and formal verification primitives directly in the syntax: * **`assert(condition)`**: Verifies that `condition` is true. Synthesizes to formal assertions or simulation checks. * **`assume(condition)`**: Assumes that `condition` is true during formal verification (acting as an input constraint). * **`cover(condition)`**: Instructs formal tools to prove that `condition` is reachable during testing. * **`force(signal, value)`**: Procedurally forces a signal to a value in simulation, ignoring its normal drivers. * **`release(signal)`**: Removes a procedural force, returning the signal to its normal drivers. --- ## 3. Parameterized Policy & Contract System The Policy system allows designers to attach metadata, synthesis constraints, and layout parameters directly to hardware graphs, ports, and signals using the `@attach` decorator. ### 3.1 Declaring a Policy Policies are declared using the `policy` keyword, supporting default arguments and inheritance: ```vexhdl // Base policy for timing constraints policy TimingConstraints { setup_slack: Int = 10, hold_slack: Int = 2, } // Inherited policy for critical paths policy CriticalPath : TimingConstraints { max_delay_ns: Float = 1.2, } ``` ### 3.2 Attaching Policies (`@attach`) You can attach policies to graphs, ports, or signal declarations: ```vexhdl @attach(CriticalPath(setup_slack = 12, max_delay_ns = 1.0)) export graph critical_adder( in_a: In>, in_b: In>, out_sum: Out>, ) { out_sum = in_a + in_b; } ``` During compilation, these policies are resolved into a flat metadata map on the High-Level Intermediate Representation (`HirGraph::metadata`), making them available to downstream consumers. A metadata key has no physical effect unless the selected exporter/tool implements it. Inspect emitted constraints and reports before relying on timing, pin or placement policies. --- ## 4. VUPPS: Vex Unified Physical Policy Standard The **Vex Unified Physical Policy Standard (VUPPS)** standardizes physical, electrical, safety, layout, and simulation constraints directly bound to VexHDL designs. The proposed schema organizes attributes under seven domain namespaces. These are project policy categories, not an external certification or evidence that every downstream tool consumes every key. ### 4.1 VUPPS Domains #### 1. `silicon` (ASIC & Physical Layout) Targeted at sub-micron and nanometer nodes (e.g., TSMC, SkyWater). * `process_node`: String (e.g., `"TSMC_N3P"`, `"SKY130"`). * `power_domain`: String identifying UPF power rails. * `clock_tree`: Object defining timing targets: * `max_skew_ps`: Float (maximum clock skew in picoseconds). * `max_latency_ps`: Float (maximum insertion delay). * `floorplan`: Object containing macro coordinates and cell placement density. * `isolation`: Object declaring level shifters and isolation cells. #### 2. `safety_class` (High-Reliability & Mission-Critical Systems) Describes redundancy and fault-response intent. Policy metadata does not establish functional-safety certification or a quantified fault-coverage result. * `redundancy`: Enum (`"None"`, `"DMR"`, `"TMR"`). * **TMR (Triple Modular Redundancy)**: The inspected HIR transform targets register signals carrying `safety_class.redundancy = "TMR"` metadata and adds replicas/voting logic. This is not proof of independent physical fault domains or fault coverage. * `seu_mitigation`: Enum (`"None"`, `"HammingECC"`, `"TripleRegisters"`). * `temp_range`: Enum (`"Commercial"`, `"Industrial"`, `"Military"`). * `fail_safe_state`: String defining fallback values on lock detection. #### 3. `board` (PCB Assembly & System-Level Mapping) Controls high-level physical boards, packaging, and routing. * `footprint`: String indicating standard footprints (e.g., `"LQFP-48"`, `"BGA-256"`). * `routing`: Object defining trace limits: * `impedance_ohm`: Float. * `max_length_mm`: Float. * `layers`: Integer (minimum board layers required). #### 4. `elec` (Electrical & IO Standards) Electrical conditioning constraints at the pin/package boundary. * `iostd`: String standard (e.g., `"LVCMOS33"`, `"LVDS"`). * `drive`: Integer (output drive strength in mA). * `slew`: Enum (`"Fast"`, `"Slow"`). * `pull`: Enum (`"None"`, `"Up"`, `"Down"`) or Object containing pull strength values. * `decouple_uf`: Float (decoupling capacitance target for power pins). #### 5. `synth` (Logic Synthesis Directives) Controls logic optimization, mapping, and netlist extraction. * `keep`: Boolean (prevents synthesis pruning). * `ram_style`: Enum (`"Auto"`, `"Block"`, `"Distributed"`, `"Ultra"`). * `clock_gating`: Boolean synthesis intent; the Verilog emitter can attach an attribute, whose physical effect depends on the synthesis tool. * `scan_chain`: Boolean scan intent; an emitted attribute does not itself insert or validate a test-access architecture. #### 6. `sim` (Simulation Modeling & Timing Checks) Directs simulation runtime environment and behavior: * `trace`: Enum (`"None"`, `"VCD"`, `"FST"`). Filters trace signal outputs to optimize disk write speed and log file size. * `clock_skew_ps`: Float. Simulates clock delay tree offsets on crossing clock boundaries. * `setup_hold_check`: Boolean. Automatically monitors timing violations near clock edges, raising timing violations or transitioning registers to metastable (`X`) state during simulation. #### 7. `circuit` (tscircuit & Board Assembly Code Gen) Binds logical modules to PCB layout engines like **tscircuit**: * `package_name`: String (BOM catalog name, e.g., `"STM32F405RGT6"`). * `component_type`: String (e.g., `"Microcontroller"`, `"Resistor"`, `"Capacitor"`). * `net_class`: String (routing class). ### 4.2 Multi-Target Physical Constraint Outputs The source contains SDC, UPF and tscircuit generators. Their supported fields and invocation paths differ; inspect the emitted artifact rather than assuming that every policy is enforced automatically: 1. **Synopsys Design Constraints (SDC)**: Extracted from `silicon.clock_tree` to generate clock periods and uncertainty. 2. **Unified Power Format (UPF)**: Extracted from `silicon.power_domain` to map power rails. 3. **tscircuit Code**: A TypeScript React component representing the board layout, routing paths, pull-up/down resistors (from `elec.pull`), and series current-limiting resistors (from `elec.limit`). Generated constraints and board code need downstream tool acceptance and engineering review. A default voltage, footprint or resistor value in a code generator is not validation for a chosen device or board. --- Source: https://vex-lang.org/docs/hdl/syntax-reference.md # VexHDL Syntax Reference This page introduces VexHDL types and declarations through illustrative hardware designs. Choose the project and build commands for your HDL toolchain as described in [Getting Started](docs/hdl/getting-started.md). --- ## 1. Type System VexHDL separates data types into **Scalar Types** (representing values) and **Signal Types** (representing hardware nets/registers). ### 1.1 Scalar Types Scalar types represent logic values, integers, and fixed-point values: | Type | Syntax | Description | Example | | :--- | :--- | :--- | :--- | | **Boolean** | `Bool` | 1-bit boolean flag (`true`/`false`) | `let active: Bool = true;` | | **Unsigned Integer** | `U` | Unsigned bit-vector of width `N` | `let count: U<8> = 0;` | | **Signed Integer** | `I` | Two's-complement signed bit-vector of width `N` | `let temp: I<16> = -45;` | | **Fixed Point** | `F` | Fixed-point number of width `N` with `M` fractional bits | `let ratio: F<16, 8> = 1.5;` | | **String** | `Str` | Simulation-only string type (primarily for logging) | `let name: Str = "UART";` | | **Custom** | `CustomName` | A type alias declared via `type` keyword | `let s: State = State::IDLE;` | ### 1.2 Signal Types The `Wire(Option)`, `Reg(...)` and `Tri(...)` forms below describe internal AST categories, not literal declarations to paste into a design. Signal types wrap scalar types to specify physical hardware properties (routing wires vs. memory cells): * **`Wire(Option)`**: Represents a combinational wire/net. If width is omitted, it defaults to a 1-bit signal. * **`Reg(Option, Option)`**: Represents a sequential storage element (registers or multi-word memories). * `Reg(Some(8), None)`: An 8-bit register. * `Reg(Some(16), Some(1024))`: A memory array of 1024 words, each 16 bits wide (RAM block). * **`Tri(Width)`**: Represents a tri-state bus capable of driving high-impedance `Z` states. ### 1.3 Compound Types * **Arrays**: Declared using the syntax `[T; N]` where `T` is a type and `N` is a constant width expression. ```vexhdl let data_bus: [U<8>; 4]; // An array of four 8-bit unsigned values ``` * **Type Aliases**: Declared using the `type` keyword. ```vexhdl type Byte = U<8>; export type Word = U<16>; ``` --- ## 2. Structs and Enums ### 2.1 Structs Structs are collection of named fields of different types. They can be exported to other files using the `export` keyword. ```vexhdl export struct Pixel { r: U<8>, g: U<8>, b: U<8>, } // Instantiate struct literal let p: Pixel = Pixel { r: 255, g: 0, b: 0 }; ``` ### 2.2 Enums Enums are user-defined types containing a set of named variants. ```vexhdl export enum State { IDLE, INIT, RUN, DONE, } ``` > [!IMPORTANT] > To access enum variants, you must use double-colon scoping: `State::IDLE`, `State::RUN`. Raw variant names are not allowed. --- ## 3. Module Declarations (`graph`) For the shift-register sketch below, require `DEPTH >= 1`; otherwise the output index and register array are invalid. A hardware module is defined using the `graph` keyword (or its alias `module`). A module is composed of compile-time constants (parameters), port mappings, and internal logic. ```vexhdl export graph shift_register #( DEPTH: Param> = 4, // Compile-time generic parameters )( clk: In, // 1-bit input clock rst: In, // 1-bit input reset d_in: In, // 1-bit data input d_out: Out, // 1-bit data output ) { // Internal registers let! regs: [Bool; DEPTH] = {DEPTH{false}}; on(PosEdge(clk)) { if rst { regs <- {DEPTH{false}}; } else { // Shift operations regs[0] <- d_in; for i in 1..DEPTH { regs[i] <- regs[i-1]; } } } d_out = regs[DEPTH-1]; } ``` ### 3.1 Port Directions * **`In` / `In`**: Read-only input port. * **`Out` / `Out`**: Write-only output port (except within the module body driving it). * **`InOut`**: Bidirectional port (tri-state buffer driver). --- ## 4. Signal Declarations VexHDL uses different declaration keywords to ensure compile-time safety and prevent multiple-driver issues. ### 4.1 `let` (Combinational Wires) * Declares a combinational net. * Must be assigned using `=` (blocking assignment). * Simulation re-evaluates dependent logic; physical propagation delay is not zero. ```vexhdl let op_add: U<8> = val_a + val_b; ``` ### 4.2 `let!` (Sequential Registers) * Declares a sequential memory element (Flip-Flops or RAM). * Must be driven only inside `on(...)` process blocks. * Must be assigned using `<-` (non-blocking assignment). ```vexhdl let! state: State = State::IDLE; ``` ### 4.3 `param` (Local Constants) * Declares local compile-time constants. ```vexhdl param BAUD_RATE: U<32> = 115200; ``` --- Source: https://vex-lang.org/docs/hdl/transpiler-integration.md # VexHDL Transpiler, Synthesis, and Integration Guide This guide details VexHDL's interoperability with Verilog and VHDL, external module imports, simulator bypass rules, synthesis pipeline, and timing verification. --- ## 1. Foreign Language Interface (`extern`) VexHDL allows you to import existing Verilog or VHDL modules directly into your project. This is useful for reusing legacy IP (like memory controllers or clock managers). ### 1.1 Importing Verilog Modules Use `extern "verilog"` block pointing to the source file: ```vexhdl extern "verilog" from "ip_cores/fifo_mem.v" { // Declarations match Verilog module ports and parameters module fifo_mem #( DATA_WIDTH: U32 = 8, ADDR_WIDTH: U32 = 4, )( clk: Input, wr_en: Input, rd_en: Input, data_in: Input[DATA_WIDTH], data_out: Output[DATA_WIDTH], full: Output, empty: Output, ); } ``` ### 1.2 Importing VHDL Entities Use `extern "vhdl"` block: ```vexhdl extern "vhdl" from "ip_cores/sp_ram.vhd" { module sp_ram #( width: U32 = 16, depth: U32 = 256, )( clk: Input, we: Input, addr: Input[8], di: Input[width], do: Output[width], ); } ``` --- ## 2. Compilation and Simulation Bypass Rules The inspected compiler and driver impose these integration boundaries; they do not establish compatibility with every synthesis tool or foreign IP block: 1. **Single-Language Target Constraint**: You cannot mix `extern "verilog"` and `extern "vhdl"` in the same project. If both are present, the compiler throws `E030: SirUnsynthesizable` error. 2. **Simulation Bypass**: * If a project contains only VexHDL, the built-in simulator may be available, subject to the current simulator implementation and target setup. * Foreign module bodies require a compatible external simulator. The driver contains detection and external-runner paths, but the selected simulator must be installed and configured for the emitted language. Keep its command, version, log and waveform in the validation record; do not infer a successful invisible fallback from source acceptance. --- ## 3. Synthesis and Place & Route Pipeline The compiler has Verilog, VHDL and BLIF emitters, with representation limits. Foreign Verilog suppresses VHDL output; foreign VHDL suppresses Verilog output. BLIF output is unavailable when foreign modules or unresolved blackboxes would otherwise be lost. The hardware driver's foreign-source snapshot path currently accepts Verilog, not VHDL. A typical FPGA flow has separate artifacts: ```text VexHDL source + foreign RTL → compatible generated RTL → synthesis netlist → target-specific place and route + timing reports → device bitstream packaging → programmer + selected board ``` For an iCE40-style flow, Yosys and nextpnr are examples of the middle tools. The placement output is not automatically a programmable bitstream; packaging is a separate target-specific step. Tool availability, device database, pin/clock constraints and programmer configuration are part of the project. Do not substitute this schematic for Studio release instructions or assume that another FPGA family uses the same formats and commands. ## 4. SDF Timing Verification post-synthesis The sibling VexHDL implementation contains an SDF parser, delay annotation and setup/hold checks in `vex-hdl-sim`. The driver accepts an explicit SDF input. These are implemented components, not proof that every cell model, timing arc, conditional check or annotation in a vendor-generated SDF is supported. Before relying on a timing simulation: 1. Use the netlist, SDF and cell models from the same build. 2. Check hierarchy/instance matching and the simulator's time units. 3. Confirm expected annotations were applied and unsupported records reported. 4. Exercise a deliberately violating fixture to verify the relevant checker. 5. Retain the selected tool's static timing reports as well as simulation logs. A simulation with no reported violations covers only its driven stimulus and implemented timing checks; it does not establish timing closure for all paths. ## Source Ownership These details were inspected in the separate VexHDL source tree: - `crates/vex-hdl-compiler/src/lib.rs`: foreign-language selection and emitter gating. - `crates/vex-hdl-driver/src/lib.rs`: foreign source snapshots and external simulation. - `crates/vex-hdl-sim/src/sdf.rs` and `src/lib.rs`: SDF parsing/annotation and timing checks. The Vex language 0.4.0 documentation target does not change the independently versioned Studio compatibility matrix on the [HDL overview](docs/hdl/index.md). --- Source: https://vex-lang.org/docs/index.md # Vex Documentation ## Start with the language Working with an assistant? [Use the Vex skill and Markdown exports](docs/guide/ai-tools.md) to give it the same maintained references used by this guide. The guide is organized as a progression rather than a catalogue of isolated features: 1. Read the [introduction](docs/guide/introduction.md) to understand Vex's design and the current implementation boundary. 2. Follow [installation](docs/guide/installation.md) to select a compiler, then build and test [your first project](docs/guide/first-project.md). 3. Learn the core language through [syntax](docs/guide/basics/syntax.md), [variables](docs/guide/basics/variables.md), [functions](docs/guide/basics/functions.md), and [control flow](docs/guide/basics/control-flow.md). 4. Continue with [types](docs/guide/types/primitives.md), [enums](docs/guide/types/enums.md), [ownership](docs/guide/memory/ownership.md), and [error handling](docs/guide/error-handling.md). 5. Use the specialist sections for [concurrency](docs/guide/concurrency/overview.md), [SIMD and tensors](docs/guide/simd/index.md), [GPU and SIR](docs/guide/gpu/index.md), [FFI](docs/guide/ffi.md), and [tooling](docs/guide/tooling/full-toolchain.md). 6. Continue with [compile-time evaluation](docs/guide/advanced/comptime.md) and [structural declaration generation](docs/guide/advanced/comptime-declarations.md) when you need typed metaprogramming. Complete examples identify their files and expected behavior. Conceptual fragments explain part of a larger program and may use application-defined names. Specialist pages distinguish implemented APIs from proposed designs and identify the platform or execution constraints that affect their use. ## Find the right reference - [Capability map](docs/guide/language-status.md) connects language features, libraries and tools to their guides. - [Example collection](docs/guide/examples.md) organizes complete programs and composition guides by the task you want to build. - [Architecture](docs/architecture/index.md) describes the compiler pipeline, runtime, and intermediate representations. - [Reference](docs/references/index.md) documents command behavior for the CLI, test runner, documentation generator, and package tools. - [Standard library](docs/std/index.md) combines usage guides with API inventories generated from library source. --- Source: https://vex-lang.org/docs/references/compiler-testing-tools.md # Compiler testing tools Application tests use [`vex test`](docs/references/vex-test-reference.md). Compiler development also has dedicated tools for generated inputs, deterministic reproduction and compiler-phase benchmarks. These tools are built from a compiler source checkout; their presence in that checkout does not make them part of every downloaded compiler archive. ## Grammar-aware fuzzing with Steel Dome `tools/vex-fuzzer` builds the `vex-steel-dome` executable. Its command families cover structured source generation, raw-input crash checks, parser stress, seed replay, corpus management, minimization and regression of retained cases. It also exposes SIR-focused testing modes. Build it with the LLVM/Rust dependencies described in [Contributing](docs/guide/contributing.md), from the compiler checkout root: ```sh cargo build --release -p vex-steel-dome --target-dir target target/release/vex-steel-dome --help ``` Use `.exe` on Windows. Record the tool binary and compiler/oracle configuration alongside the source revision. A seed identifies a sequence for a particular generator version; it is not a permanent replacement for retaining the actual generated source. ### Start with a bounded campaign ```sh target/release/vex-steel-dome fuzz --preset smoke --iterations 16 --threads 1 --seed 42 --output ./fuzz-results --json ``` The structured and `codegen-stress` modes exercise different input strategies. Inspect the selected mode and oracle in the result before interpreting it. Keep normal compiler rejection separate from a crash, unexpected diagnostic or behavior mismatch. The result of a small campaign describes those generated cases; its iteration count is not a language-coverage percentage. ### Retain inputs before minimizing For a campaign finding, use its saved source as `reproducer.vx` and rerun that source or the promoted regression. The `replay` command also provides a deterministic source-generation workflow of its own: ```sh target/release/vex-steel-dome replay --seed 42 --iterations 16 --print --output ./replay-42 target/release/vex-steel-dome crash ./reproducer.vx --lexer target/release/vex-steel-dome minimize ./reproducer.vx --output ./reproducer-minimal.vx ``` Retain the files emitted by `replay` when using that workflow. Its generated sequence is specific to the replay command; a fuzz campaign's saved input is the reproduction artifact for that campaign. Confirm that minimization preserves the same observable failure, then add that input to a focused regression. A smaller input that fails in a different phase is not the same reproduction. ### Keep a useful corpus ```sh target/release/vex-steel-dome corpus --dir ./corpus --stats target/release/vex-steel-dome corpus --dir ./corpus --import ./replay-42 target/release/vex-steel-dome regression --dir ./crashes --verbose target/release/vex-steel-dome promoted-regression --dir ./fuzz-results/interesting --verbose ``` Keep passing edge cases as well as failures. Include identifiers, literals, deep nesting, large declarations, generic bounds, malformed delimiters and target-sensitive operations. Label cases with their expected outcome and the compiler phase they are meant to exercise. ## Compiler-phase benchmarks `tools/vex-bench` is a Cargo benchmark package, not a `vex-bench` command-line application. Its declared benches include parser work and compile-time staging: ```sh cargo bench -p vex-bench --bench parser_benchmark --target-dir target cargo bench -p vex-bench --bench ctfe_staging_benchmark --target-dir target ``` Keep input size and shape, warm/cold cache conditions, compiler profile and machine configuration with the measurement. Parser throughput and CTFE staging cost answer different questions from native program throughput. For application timing, use the [benchmarking guide](docs/guide/benchmarks.md) and `BenchCtx` instead. ## A regression should explain the contract Record: 1. The smallest source that still exercises the intended behavior. 2. Whether success means acceptance, a specific diagnostic or a runtime result. 3. The command, target, optimization settings and tool identities. 4. Exact outputs and process status, with bounded resource use. 5. The relationship to the original generated input and any minimized case. The same method applies when building a language tool with the [Vex-written tooling libraries](docs/guide/tooling/language-tools.md). It keeps parser recovery, source reconstruction, protocol correctness and code generation as separate contracts that can be tested directly. --- Source: https://vex-lang.org/docs/references/index.md # References This section contains command- and toolchain-level references. Use it when you need operational detail rather than tutorial-style guidance. ## What Lives Here - CLI command behavior - test runner behavior - package manager and native linking notes - docs tooling references ## Available References - [vex-cli Reference](docs/references/vex-cli-reference.md) - [vex-test Reference](docs/references/vex-test-reference.md) - [vex-doc Reference](docs/references/vex-doc-reference.md) - [vex-pm Reference](docs/references/vex-pm-reference.md) - [vex-pm Native FFI Pipeline](docs/references/vex-pm-native-ffi.md) - [Compiler testing tools](docs/references/compiler-testing-tools.md) - [Build language tools in Vex](docs/guide/tooling/language-tools.md) ## Suggested Usage 1. Read the [Guide](docs/guide/introduction.md) first for language semantics. 2. Use the reference pages when you need exact command behavior or implementation-facing notes. 3. Jump to [Architecture](docs/architecture/index.md) when you need crate-level orientation. --- Source: https://vex-lang.org/docs/references/vex-cli-reference.md # vex-cli Reference This document describes `vex-cli` architecture, command pipeline, and extension points. --- ## Purpose `vex-cli` is the primary developer-facing command-line entry for: - compile (`vex compile`) - run (`vex run`) - test (`vex test`) - semantic analysis and verified cleanup (`vex lint`) - toolchain integration with diagnostics, optimizer remarks, and package/native resolution --- ## Command Surface Main command modules are under: - `tools/vex-cli/src/commands/compile.rs` - `tools/vex-cli/src/commands/run.rs` - `tools/vex-cli/src/commands/test.rs` - `tools/vex-cli/src/commands/lint.rs` - `tools/vex-cli/src/commands/pipeline.rs` ### `vex compile` Responsibilities: 1. Resolve dependencies via `vex-pm` 2. Build compiler pipeline via `CompilerDriver` 3. Generate object file from LLVM module 4. Link executable with: - the target-selected embedded native support pack, when required - target system libraries activated by reachable VexArch providers - native package linker args (`vex_pm::get_native_linker_args_for_source(...)`) 5. Emit optional artifacts such as LLVM IR (`.ll`) and CFG output ### `vex run` Responsibilities: 1. Resolve deps + compile module 2. Link a temporary executable from the fused module, embedded native support, and manifest-owned native dependencies 3. Execute and report timings ### Comptime staging modes `vex compile`, `vex run`, and `vex ir` accept: ```bash --comptime-staging disabled|analyze|apply-known ``` The inspected 0.4.0 CLI defaults to `apply-known`. This mode applies evaluator-proven values only where the typed materializer can preserve the program's semantics; residual and unsupported cases keep their original HIR. `analyze` observes staging opportunities without applying replacements. `disabled` turns off opportunistic staging; it does not turn an explicit compile-time expression into a runtime expression. See [Compile-time evaluation](docs/guide/advanced/comptime.md) for the strict-boundary and supported-materialization rules. `vex lint` and `vex test` retain the observation-only `--analyze-comptime` option. In test mode it selects `analyze` for generated test and benchmark compilation. Without that option, those child `compile` commands inherit the compiler's ordinary `apply-known` default. Lint analysis and LSP's `analyzeComptime` setting are observation-only. Compile and run additionally accept `--comptime-telemetry FILE`. It requires a non-disabled `--comptime-staging` mode and writes a versioned JSON report. The inspected telemetry schema is version 5; consumers should check `schema` and `schema_version` rather than assuming a fixed field layout. The report separates policy discovery, persistent-cache lookup, record decode, semantic validation, installation and publication from frontend, fusion, LLVM, object and native-link phases. Missing phases are `null`, and telemetry cannot implicitly enable staging or affect semantic query identity. ### `vex test` Responsibilities: 1. Discover `*.test.vx` / `_test.vx` 2. Generate test runner main when needed 3. Execute each test function with pass/fail markers 4. Handle compile errors and summarize results ### `vex lint` Responsibilities: 1. Resolve a `.vx`/`.vxc` file, package directory, or nearest `vex.json` 2. Run correctness analysis and the shared `vex-lint` semantic registry without LLVM 3. Apply manifest and CLI rule/group levels with CLI precedence 4. Emit deterministic text, canonical JSON, or SARIF 2.1.0 diagnostics, including suppression metadata 5. Plan revision-bound edits, reject conflicts, and verify semantics for up to four passes 6. Atomically write only a fully verified workspace, or print it with `--diff` Core options are `--fix`, `--diff`, `--format text|json|sarif`, `--deny-warnings`, `--allow`, `--warn`, `--deny`, `--only`, `--target`, `--explain-boxing` and `--explain-arena`. `--analyze-comptime` adds an observation-only staging summary on stderr. `--timings` adds opt-in per-rule telemetry to JSON/SARIF; normal runs have no clock-read overhead. The former `check`, `analyze` and `fix` compatibility commands have been removed. `--write-baseline PATH` atomically records the current lint set for staged CI; `--baseline PATH` loads it. Matching findings remain in every output format but do not fail lint warning/deny gates. Correctness errors are never baselined. `lint.baseline` in `vex.json` provides a package-relative default. Directory inventory is package-scoped: nested manifests and transient test/benchmark runners are not merged into the target. Ordinary lint uses the diagnostics-oriented HIR path and skips codegen module flattening. Full semantic fingerprints are reserved for verified `--fix`/`--diff` runs. Canonical forms: ```bash vex lint [TARGET] vex lint --fix [TARGET] vex lint --diff [TARGET] ``` `--fix` writes only after the in-memory result reaches a verified fixed point. `--diff` runs the same planner and verifier but prints the patch. Syntax-only migrations can operate beside an unrelated pre-existing correctness error; semantic fixes require their proving phase and cannot introduce or alter a correctness failure. Rule configuration is read from the nearest `vex.json`. CLI rule/group levels override manifest levels. Local `vex-lint: allow-file` and `allow-next` directives use stable symbolic IDs and are included in JSON metadata. The current registry also covers resolved `Result`/`Future` misuse, target-aware numeric ranges, allocation effects, and exported API audits. Performance, API, and pedantic rules are opt-in through the `performance`, `library`, `pedantic`, and `strict` profiles. Semantic body rules share one lazy, revision-bound fact graph with exact call identities and transitive effect summaries. See [Linting and Verified Fixes](docs/guide/tooling/lint.md) for the complete rule table, configuration, exit codes, suppression syntax, and stability boundary. --- ## Compiler Integration `vex-cli` delegates language pipeline to `CompilerDriver`: - parsing - lowering - type/borrow checks - codegen This keeps command handlers thin while preserving shared compilation behavior. --- ## Linking Model VexArch source semantics are rehydrated from the embedded VRI and lowered into the same backend module as user and prelude code. They are not linked from a runtime bitcode module, object, static archive, or dynamic library. At native link stage, `vex-cli` merges: 1. a requested-target native support object only when that port requires one; 2. system libraries activated by reachable `SYSTEM`/`LIBC` providers; 3. native args from package manifests (`vex-pm`). The native support pack is distinct from VexArch language semantics. The inspected build includes target-specific assembly support and, on macOS, an Objective-C CoreML bridge. These native ABI integrations are not a separate Vex runtime bitcode module. Ordinary Vex cross-boundary optimization happens before object emission inside the fused module. --- ## Execution Model `vex run` compiles to a temporary executable and runs it as a subprocess. Native dependencies are resolved via the system linker and dynamic loader at runtime. `vex compile` produces a standalone binary from the fused user/prelude/VexArch module plus the explicit target/native link plan. Release packages do not ship a separate Vex runtime library or `vex_runtime.bc`. --- ## Diagnostics and UX `vex-cli` supports: - JSON/non-JSON output modes - optimization remarks - sanitizer flags - structured test and benchmark results - lock-file aware dependency workflows --- ## Key Extension Points - Add new command: `tools/vex-cli/src/commands/` - Extend CLI flags: command handler signatures + argument parser wiring - Add new link behavior: compile/run link stage argument builders - Add test behavior: `tools/vex-cli/src/commands/test.rs` --- ## Operational Notes - Native linking behavior is package-manifest driven (`vex.json/native`) - `tools/vex-cli/build.rs` prepares compiler-owned target native support and platform bridges. User package native dependencies are selected separately from their manifests during compile/run planning. --- ## Related References - [Linting and Verified Fixes](docs/guide/tooling/lint.md) - [vex-pm Reference](docs/references/vex-pm-reference.md) - [vex-pm Native FFI Pipeline](docs/references/vex-pm-native-ffi.md) --- Source: https://vex-lang.org/docs/references/vex-doc-reference.md # vex-doc Reference This document describes `vex-doc` — the documentation generator for Vex projects. --- ## Purpose `vex-doc` generates API documentation from Vex source files (`.vx`). It supports: - **JSON** — Machine-readable documentation model - **Markdown** — Single-page human-readable docs - **Multi-page** — Per-type pages with index - **VitePress** — Multi-page + sidebar.json + config.mts - **Docusaurus** — Multi-page + sidebars.js + _category_.json --- ## Command Usage ```bash # Single-page markdown (default) vex doc src/main.vx # JSON output vex doc --format json src/main.vx # Multi-page to directory vex doc --format multipage -o docs/api src/ # VitePress-ready docs vex doc --format vitepress -o docs/api src/ # Docusaurus-ready docs vex doc --format docusaurus -o docs/api src/ ``` ### CLI Flags | Flag | Description | Default | |------|-------------|---------| | `INPUT` | Source file or directory | required | | `-o, --output` | Output file or directory | stdout / `docs/api` | | `-f, --format` | Output format | `markdown` | | `--json` | Shorthand for `--format json` | — | ### Supported Formats | Format | Output | Use Case | |--------|--------|----------| | `json` | Single JSON file | CI/CD pipelines, custom renderers | | `markdown` / `md` | Single .md file | README integration, quick preview | | `multipage` | Directory of .md files | Static site hosting | | `vitepress` | .md + .vitepress/ config | VitePress documentation sites | | `docusaurus` | .md + sidebars.js | Docusaurus documentation sites | --- ## Architecture ### Pipeline ``` .vx source → Parser (Rowan CST) → Generator → DocModel (JSON) → Composer ↓ ┌───────────────┼───────────────┐ ↓ ↓ ↓ Markdown VitePress Docusaurus (single page) (multi-page) (multi-page) ``` ### Crate Structure ``` tools/vex-doc/src/ ├── lib.rs # Public API: generate_json_model(), generate_markdown_content() ├── generator.rs # Raw Rowan CST → DocModel extraction (core engine) ├── doc_model.rs # Data model: DocItem, DocType, FieldItem, GenericParam, etc. ├── markdown.rs # Single-page markdown composer ├── multi_page.rs # Multi-page + VitePress + Docusaurus composers ├── parser.rs # Doc comment parser (@param, @return, @example, etc.) ├── naming.rs # Name resolution utilities └── rowan_generator.rs # Thin delegate to generator.rs ``` --- ## DocModel Schema The `DocModel` is the central data structure passed from generator to composers. ### DocItem Fields | Field | Type | Description | |-------|------|-------------| | `id` | `String` | Unique identifier (e.g., `Point`, `Point.new`) | | `kind` | `String` | Item kind: `fn`, `struct`, `enum`, `contract`, `const`, `type`, `policy` | | `name` | `String` | Display name (e.g., `Point.new`) | | `location` | `Location` | Source file, line, col, end_line, end_col | | `signature` | `String` | Full signature string | | `docs` | `DocContent` | Parsed doc comments (summary, details, @param, @return, etc.) | | `parent_id` | `Option` | Parent type for methods (e.g., `"Point"`) | | `relations` | `Vec` | Contract implementations | | `params` | `Vec` | Function parameters with types | | `return_type` | `Option` | Return type | | `fields` | `Vec` | Struct fields (name, type, visibility, doc, tag) | | `variants` | `Vec` | Enum variants (name, payload types, doc) | | `receiver` | `Option` | Method receiver (self_name, type_name, is_ref, is_mut) | | `visibility` | `Option` | `"export"`, `"public"`, `"private"` | | `generic_params` | `Vec` | Type parameters with bounds and defaults | | `where_clauses` | `Vec` | Where clause predicates | | `is_async` | `Option` | Async function flag | | `is_gpu` | `Option` | GPU function flag | | `is_unsafe` | `Option` | Unsafe function flag | | `is_const` | `Option` | Const function flag | ### GenericParam | Field | Type | Description | |-------|------|-------------| | `name` | `String` | Parameter name (e.g., `T`) | | `bounds` | `Vec` | Contract bounds (e.g., `["Display", "Clone"]`) | | `default` | `Option` | Default type (e.g., `"i32"`) | | `is_const` | `bool` | Whether this is a const generic | | `const_type` | `Option` | Type for const params (e.g., `"usize"`) | ### TypedParam | Field | Type | Description | |-------|------|-------------| | `name` | `String` | Parameter name | | `ty` | `DocType` | Type information | | `default_value` | `Option` | Default value expression | | `is_variadic` | `bool` | Whether parameter is variadic (`...`) | --- ## Doc Comment Syntax `vex-doc` recognizes the following doc comment tags: ```vex /// Summary line /// /// Detailed description paragraph. /// /// @param name - Parameter description /// @return Description of return value /// @example let x = Point.new(1.0, 2.0); /// @deprecated Use NewThing instead /// @see OtherType /// @throws ErrorType - When something fails /// @since 1.2.0 /// @note Important information ``` ### Supported Tags | Tag | Description | |-----|-------------| | `@param` | Parameter documentation | | `@return` / `@returns` | Return value description | | `@example` | Example text on the same line as the tag | | `@deprecated` | Deprecation notice | | `@see` | Custom tag commonly used to name related items | | `@throws` / `@raises` | Custom error-description tags; they do not define Vex exception semantics | | `@since` | Custom introduction-version tag | | `@note` | Custom additional-information tag | | `@link` | Custom tag; automatic inline symbol resolution is not established | The parser gives dedicated fields to `param`, `return`/`returns`, `deprecated`, and `example`. Other tags are retained as custom key/value entries; how they appear depends on the output composer. A multiline block after `@example` is not collected as one example by the inspected parser. Keep a short example on the tag line, or put complete programs in a manually maintained guide and link to it from the API description. Generation extracts syntax and documentation comments. It does not compile or execute example programs, establish a public facade for every discovered item, or prove the resulting links are valid in a deployed site. Check the generated model, visibility, and rendered targets before publishing it. --- ## Generator Details ### CST Traversal Strategy The generator uses **raw Rowan CST traversal** (not typed AST wrappers) because: 1. The typed AST wrappers had SyntaxKind mismatches (`FUNCTION` vs `NODE_FUNCTION`) 2. Type extraction needed to handle both keyword tokens (`KW_I32`) and node types (`NODE_PATH_TYPE`) 3. Receiver patterns in Vex (`fn (self: &Type) method()`) require custom traversal ### Key Helper Functions | Function | Purpose | |----------|---------| | `get_fn_name()` | Extracts function name, handling receivers and qualified names (`Vec.new`) | | `get_type_text_any()` | Extracts type text after `:` — handles both keyword tokens and type nodes | | `extract_return_type()` | Finds return type after `R_PAREN → COLON` | | `extract_receiver()` | Parses `NODE_RECEIVER` for self name, type, ref/mut | | `extract_type_params()` | Extracts generic params with bounds from `NODE_TYPE_PARAMS` | | `extract_where_clauses()` | Extracts where predicates from `NODE_WHERE_CLAUSE` | | `extract_fn_flags()` | Detects `async`, `gpu`, `unsafe`, `const` keywords before `fn` | | `extract_default_value()` | Parses `= expr` for param/type param defaults | --- ## Multi-Page Output Structure ``` output_dir/ ├── index.md # API overview with cross-links ├── container.md # One page per struct ├── shape.md # One page per enum ├── iterator.md # One page per contract ├── functions.md # All standalone functions ├── constants.md # All constants (if any) ├── types.md # All type aliases (if any) │ ├── .vitepress/ # VitePress only │ ├── sidebar.json # Auto-generated sidebar │ └── config.mts # Ready-to-use VitePress config │ ├── sidebars.js # Docusaurus only └── _category_.json # Docusaurus only ``` --- ## Extension Points | What | Where | |------|-------| | Add new item kind | `generator.rs` — add `SyntaxKind::NODE_*` match + extractor | | Add new DocItem field | `doc_model.rs` — add field, update all initializers in `generator.rs` | | Add new doc tag | `parser.rs` — add tag pattern matching | | New output format | `multi_page.rs` — add `generate_*()` function, wire in `doc.rs` CLI | | Custom page template | `multi_page.rs` — modify `generate_type_page()` / `generate_category_page()` | --- ## Related References - [vex-cli Reference](docs/references/vex-cli-reference.md) - [vex-pm Reference](docs/references/vex-pm-reference.md) --- Source: https://vex-lang.org/docs/references/vex-pm-deep-dive.md # Package Manager — Deep Dive The package manager uses a JSON `vex.json` manifest. This page explains package identity, dependency selection, workspaces, and native artifacts for the 0.4.0 documentation. Start with [Your first project](docs/guide/first-project.md) for a complete application and test before adding external dependencies. ## Manifest `vex new` creates a project with a `vex.json`; `vex init` creates one in an existing directory. The manifest's top-level package fields include `name`, `version`, and `dependencies`. Other supported fields include optional entry points, testing, workspace, native, and code-generation configuration. See the [package-manager reference](docs/references/vex-pm-reference.md) and the manifest parser for the current schema. ```json { "name": "my-project", "version": "0.1.0", "dependencies": {} } ``` Older TOML examples using `vex.toml`, `[package]`, `[features]`, or `[workspace.dependencies]` do not describe this JSON manifest parser. Do not assume they can be copied into a current project. A manifest field being accepted also does not prove every toolchain command consumes that field. ## Dependency Resolution and Lock Files The development CLI exposes top-level commands such as `vex add`, `vex remove`, `vex list` and `vex update`; use their `--help` output for arguments. A manifest dependency is a version string or an object with a required `version` and optional `headers`. Workspace replacements are a separate mechanism; do not copy TOML `path`, `git`, `branch`, `features` or `optional` examples into this dependency shape without verifying the installed version. `vex.lock` is JSON. It records versions, resolved locations and integrity information, and can include a canonical Git source and commit. Their presence is not unconditional: lock generation may lack a commit or a verified content hash when the relevant checkout or Git database is unavailable. A lock file's existence alone is therefore not evidence of a fully reproducible build. Use locked mode where supported and verify that the required metadata and source are available; see the [package-manager reference](docs/references/vex-pm-reference.md). ## Workspaces Workspace configuration is stored in the `workspace` field of the root `vex.json`, with member paths and optional replace/exclude directives. The current CLI exposes `vex workspace init`, `add`, `remove`, `list`, `sync`, and `replace`; these are distinct from the top-level build and test commands. From a directory where `workspace-demo` does not already exist: ```bash vex new workspace-demo cd workspace-demo vex workspace init vex new core vex workspace add core vex workspace list ``` `workspace list` should list `core`, and the root `vex.json` should contain the following field alongside its package metadata: ```json "workspace": { "members": ["core"] } ``` This is a manifest fragment, not a complete JSON document. The child has its own `core/vex.json`, source directory, and tests. The five CLI invocations above completed successfully on the compiler identified in the [evidence guide](docs/guide/verification-evidence.md); this checked scaffold creation and membership, not external dependency resolution or every member's native build. `workspace add` expects the member directory to exist. It can create a minimal manifest when the directory has none, but `vex new core` provides the normal source and test scaffold. Membership describes the workspace; imports still need to name an available package or source module. Use the package's manifest and the [modules guide](docs/guide/modules.md) to make those dependencies explicit. ## Native Dependencies Manifest-owned native features and their target-specific artifacts are separate from ordinary package dependencies. For declarations, ownership, artifact types and target selection, see the [native FFI pipeline](docs/references/vex-pm-native-ffi.md) and [FFI guide](docs/guide/ffi.md). Validate native linking on each intended target. ## Publishing, Registries and Build Scripts Earlier versions of this page presented `vex pm publish`, a registry endpoint, TOML feature syntax and automatic `build.vx` scripts as current workflows. Those examples are not established by the development CLI and manifest schema above. Do not use them as release instructions; consult the actual release's documentation and command help for any supported publishing or build workflow. ## Related - [Package-manager reference](docs/references/vex-pm-reference.md) - [CLI reference](docs/references/vex-cli-reference.md) - [Testing](docs/guide/tooling/testing.md) --- Source: https://vex-lang.org/docs/references/vex-pm-native-ffi.md # vex-pm Native FFI Pipeline Reference This page documents the implemented manifest-driven native link pipeline shared by `vex compile` and `vex run`. ## Source contract A package requests a native feature from a `.vxc` boundary: ```vex extern "NATIVE" from "sqlite" { fn sqlite3_libversion(): Ptr; } ``` The `from` value is a feature name, not a filename or linker flag. The nearest `vex.json` that owns the declaration defines the artifacts. ## Manifest schema ```json { "name": "database-app", "version": "0.1.0", "native": { "useSystemLibC": true, "features": { "sqlite": { "x86_64-unknown-linux-gnu": { "path": "native/libsqlite3.a", "type": "static" }, "macos.arm64": { "path": "native/libsqlite3.dylib", "type": "dynamic" }, "windows-x86_64": { "path": "native/sqlite3.dll", "type": "dynamic", "importLib": "native/sqlite3.lib" }, "all": { "path": "native/portable.bc", "type": "bitcode" } } } } } ``` `native.useSystemLibC` defaults to `true`. Setting it to `false` selects the freestanding libc policy for that package. Each platform dependency contains: | Field | Required | Meaning | |---|---:|---| | `path` | yes | Artifact path, relative to the owning manifest or absolute | | `type` | yes | `static`, `dynamic`, or `bitcode` | | `importLib` | Windows dynamic only | Link-time `.lib` paired with a runtime DLL | `importLib` is canonical. The parser accepts the legacy `import_lib` alias during migration. ## Target key precedence For a target, `vex-pm` tries: 1. exact target triple; 2. `.`; 3. `-`; 4. `-` such as `linux-musl` or `windows-msvc`; 5. ``; 6. `all`. The first match wins. A missing match is `E0FFI02`. `dynamic` cannot use the target-independent `all` key. Windows dynamic features require `importLib`. WASM rejects dynamic native features. ## Used-only activation Codegen records a native requirement only when reachable code calls an extern function or takes its address. It carries both the feature name and declaration file. `vex-pm` then: 1. finds the declaration's owning manifest; 2. groups requests deterministically by manifest and feature; 3. resolves only those features for the requested target; 4. stages only the selected artifacts; 5. returns structured linker arguments, runtime files, and activated dependency metadata. Importing a boundary without using its functions has zero native link and deployment effect. There is no environment-variable feature activation and no package-wide “link all features” scan in the compile/run path. ## Artifact behavior ### Static The selected artifact is copied to the package native staging directory and passed to the linker by path. ### Bitcode The selected `.bc` artifact is staged and passed as a linker input. ### Dynamic - Linux/macOS: Vex adds the staging search path and library name, then deploys the runtime library beside the produced executable. - Windows: Vex links the staged `importLib` and deploys the DLL. - macOS and Linux post-processing is performed only on a compatible host. Unsupported cross-host mutation fails explicitly with `E0FFI09`. Runtime deployment happens for both `vex compile` and `vex run` because both commands consume the same extern link plan. ## Freestanding diagnostics A reachable `LIBC` provider is rejected before linking. `SYSTEM` and `NATIVE` are not categorically forbidden: their actual target contracts determine compatibility. If an activated static native feature leaves known libc or TLS symbols unresolved, Vex emits `E0FFI07` naming that exact activated feature. Unused manifest features are never considered by this classifier. ## Determinism - Requests are sorted and deduplicated. - Manifests and feature names use ordered collections in plan construction. - Link arguments and runtime files are deduplicated. - System libraries are emitted in stable order. This makes link behavior independent of parallel module traversal. ## Important APIs ### `vex-pm` - `NativeTarget::from_triple` - `NativeFeatureRequest` - `resolve_native_link_plan` - `NativeLinker::process_features` - `NativeLinkPlan` - `check_active_linker_error` ### `vex-cli` - `native_plan::resolve_extern_link_plan` - `native_plan::deploy_runtime_files` The CLI plan also merges `LIBC`, `SYSTEM`, and `VEX` provider requirements with native feature results. ## Diagnostics | Code | Meaning | |---|---| | `E0904` | No owning manifest/native configuration for a requested feature | | `E0FFI01` | Requested feature is absent from the owning manifest | | `E0FFI02` | No artifact matches the target | | `E0FFI03` | Reachable libc call in a freestanding build | | `E0FFI04` | Dynamic native feature on WASM | | `E0FFI05` | Dynamic artifact declared under `all` | | `E0FFI06` / `E0FFI08` | Missing Windows import library | | `E0FFI07` | Activated static feature depends on hosted libc/TLS symbols | | `E0FFI09` | Unsupported cross-host dynamic-library post-processing | ## Related - [FFI](docs/guide/ffi.md) - [Freestanding](docs/guide/freestanding.md) - [vex-pm Reference](docs/references/vex-pm-reference.md) --- Source: https://vex-lang.org/docs/references/vex-pm-reference.md # vex-pm Reference `vex-pm` owns package manifests, dependency resolution, lock/cache behavior, target-aware package files, and manifest-owned native artifacts. ## Core modules - `manifest.rs`: `Manifest`, `NativeConfig`, `PlatformDependency`, testing, and workspace configuration. - `resolver.rs`: package dependency graph resolution. - `lockfile.rs`: integrity checks and deterministic locked selection. - `cache.rs`: local package and git caches. - `build.rs`: dependency source paths and compatibility build integration. - `platform.rs`: package-level platform file selection. - `native_linker.rs`: target-native artifact selection, staging, link plans, and diagnostics. ## Manifest responsibilities A `vex.json` can define package metadata, dependencies, entry modules, test/workspace settings, and native features. ```json { "name": "codec-wrapper", "version": "1.0.0", "dependencies": {}, "native": { "useSystemLibC": true, "features": { "codec": { "linux.x86_64": { "path": "native/libcodec.a", "type": "static" }, "windows-x86_64": { "path": "native/codec.dll", "type": "dynamic", "importLib": "native/codec.lib" } } } } } ``` Native features are requested explicitly by `extern "NATIVE" from "codec"` declarations. The artifact type lives in the manifest, not in Vex source syntax. ## Dependency resolution `resolve_dependencies_for_build(locked)` behaves as follows: - `locked=true`: requires a valid `vex.lock`; - `locked=false`: uses a valid lock or resolves again when needed. The result contains package source directories and platform-file mappings. Lock entries may include canonical source metadata and an exact commit. Generation can leave commit or integrity metadata unavailable; verify the lock and selected source before treating a build as reproducible. ## Target-aware source selection Vex source resolution recognizes target variants for `.vx` and `.vxc` files. The compiler import resolver uses this precedence: 1. OS and architecture suffix; 2. OS suffix; 3. architecture suffix; 4. generic file. Architecture aliases such as `x86_64`/`x64` and `aarch64`/`arm64` are accepted. Source routing chooses Vex code without inventing an ABI environment; native manifest routing independently chooses an exact-target binary artifact. ## Native planning The compile/run path does not aggregate every native feature in every dependency. It starts with the exact `NATIVE` requirements recorded by codegen. `resolve_native_link_plan`: 1. finds the owning manifest for each declaration file; 2. groups and sorts requests by manifest and feature; 3. chooses the best target entry; 4. stages only selected artifacts; 5. returns link arguments, runtime files, activated dependency metadata, and libc policy. Supported artifact types are `static`, `dynamic`, and `bitcode`. Windows dynamic artifacts require `importLib`; the old `import_lib` spelling remains a read-only compatibility alias. The compatibility `NativeLinker::process` API can still process an entire config for package-manager workflows. Compiler and runner correctness relies on `process_features`, which is used-only. ## Freestanding policy `native.useSystemLibC: false` declares a freestanding libc policy. A reachable `LIBC` extern is rejected by the CLI before linking. If an activated static feature exposes unresolved hosted libc/TLS symbols, the linker classifier reports that exact feature. The package manager does not reinterpret OS libraries as libc. `SYSTEM` libraries and manifest-owned native artifacts remain explicit link-plan inputs. ## Cache and determinism - package/git cache uses the configured Vex cache root; - lock validation prevents dependency drift in locked builds; - native requests use ordered, deduplicated manifest/feature sets; - only active target artifacts are copied into native staging; - runtime files and linker arguments are deduplicated. ## Related - [vex-pm Native FFI Pipeline](docs/references/vex-pm-native-ffi.md) - [FFI](docs/guide/ffi.md) - [vex-cli Reference](docs/references/vex-cli-reference.md) --- Source: https://vex-lang.org/docs/references/vex-test-reference.md # `vex test` reference ```text vex test [OPTIONS] [PATTERN] ``` ## Discovery | File/function | Meaning | | --- | --- | | `*.test.vx`, `*_test.vx`, `*_bench.vx` | Discoverable source under a selected directory | | `test_*`, `Test*` | Test function | | `bench_*`, `Benchmark*` | Benchmark function | `PATTERN` accepts an existing directory, an existing regular `.vx` file, or a quoted glob such as `"lib/std/net/tests/*.test.vx"`. Existing literal paths take precedence over glob syntax, including filenames containing brackets and directories whose names end in `.vx`. With no argument, discovery starts in the current directory. A file glob can select any ordinary `.vx` filename. A matched directory selects its conventionally named test/benchmark sources recursively. Recursive `**` globs are supported. Automatic traversal skips generated runners, hidden directories, `target`, `node_modules`, `vex-builds` and `archived`. It does not follow discovered directory symlinks; pass a directory symlink explicitly to select that root. Source-file symlinks are accepted and deduplicated by their resolved path. Pipes, sockets and devices are never opened as test sources. A missing explicit path, invalid/unmatched glob, or unreadable selected source is an error with a nonzero exit status, not an empty successful run. A real empty directory or a `--run` filter selecting no functions remains a valid empty selection. Neither is evidence that tests passed. Accepted test signatures are zero arguments or one `&TestCtx!` argument. Zero-argument `bool` uses `true` as success; integer status uses `0`; context tests use sealed `failed()`/`skipped()` state. Async tests are awaited from a generated async main. A discovered file with a custom `main` is rejected. ## Options | Option | Purpose | | --- | --- | | `-q`, `--quiet` | Zero-noise successful output | | `-v`, `--verbose` | Detailed execution output | | `--run ` | Filter test names | | `--no-parallel` | Serialize test files | | `--timeout ` | Bound runtime for each generated test-file runner | | `--failfast` | Stop after first failure | | `--short` | Select short-mode behavior | | `--json` | Structured result output | | `-O0` … `-O3` | Generated runner optimization level | | `--analyze-comptime` | Print comptime staging telemetry | Benchmark-only options: | Option | Purpose | | --- | --- | | `--bench` | Select benchmarks instead of tests | | `--benchtime ` | Target measurement duration (default and maximum `1s`) | | `--count ` | Repeat benchmark measurement | | `--benchmem` | Report allocation counters | Use `vex test --help` as the authoritative flag list for the installed CLI. The tables above focus on the unit-test and benchmark workflows taught here. ### Design tests around behavior Assert normal, empty, malformed and boundary behavior directly. Keep process status and complete results with the test inputs. A coverage percentage does not replace an assertion about the returned value, cleanup or error path. For compiler fuzzing and deterministic replay, see the separate [compiler testing tools](docs/references/compiler-testing-tools.md). ## Runtime limits and results Benchmark measurement targets are capped at one second, and each benchmark runner has a two-second process budget. A larger requested duration does not extend those limits. For tests, the runtime watchdog starts when the generated runner enters `main`; it covers the whole file, not a separate budget per function. Compilation has a separate 180-second watchdog and process startup has its own deadline. These are not charged to `--timeout`. Runtime timeout terminates the runner's process group, including its child processes. Completed test results survive a later timeout: a reported `PASS`, `FAIL` or `SKIP` keeps its status and measured duration. Only tests without a complete result record receive `timeout`. The CLI retains partial stdout/stderr for diagnosis. Test completion and process completion are separate. A file may print all its test results and then hang while waiting for detached tasks, or terminate abnormally during finalization. Such a run exits nonzero and reports a **file execution error**; it does not invent an additional failed test or rewrite completed outcomes. `--failfast` stops on file errors as well as test failures. In `--json` output, `passed`, `failed`, `skipped`, `total` and `results` describe actual test functions. A skipped test has status `skip` and counts toward `skipped` and `total`, not `passed` or `failed`. An all-skipped run succeeds but is summarized as `SKIP`, not as evidence of passing tests. Calling `skip()` after `err()` does not suppress the failure. Retain the process status and validate the JSON result before feeding it to automation. Store stderr separately from the machine-readable result. The additive `file_errors` array contains objects with `file`, `status` (`timeout` or `runtime_error`), `message` and diagnostic `details`. It is empty on a clean run. Automation must check the CLI exit status and `file_errors`, not just `failed == 0`: all tests can pass while finalization fails. Compilation failures remain `compile_error` test results, not runtime timeouts. The API reference for `TestCtx` and `BenchCtx` is on the [`testing` package page](docs/std/testing.md). --- Source: https://vex-lang.org/docs/std/bit.md # Bit operations Bit operations are compiler builtins; there is no `bit` package to import. Use `Math.*` for integer counts and byte reversal, and `Bit.*` for masked extraction and deposition. | Operation | API | Meaning | | --- | --- | --- | | Population count | `Math.popcount(value)` | Count set bits in the integer's width | | Leading zero count | `Math.clz(value)` | Count zeros before the highest set bit | | Trailing zero count | `Math.ctz(value)` | Count zeros after the lowest set bit | | Byte reversal | `Math.bswap(value)` | Reverse byte order without changing width | | Masked extraction | `Bit.pext(value, mask)` | Pack selected `u64` bits into the low positions | | Masked deposition | `Bit.pdep(value, mask)` | Spread low `u64` bits into the mask's set positions | ## Integer width matters The `Math` integer operations preserve the operand's integer type. An explicit width makes a wire-format or bitset calculation independent of literal inference: ```vex let flags: u32 = 0b1011; let count: u32 = Math.popcount(flags); // 3 let leading: u32 = Math.clz(4 as u32); // 29 let trailing: u64 = Math.ctz(8 as u64); // 3 let reversed: u32 = Math.bswap(0x12345678 as u32); // 0x78563412 ``` These expressions illustrate the builtin signatures; they are not a complete program. `Bit.popcnt32`, `Bit.lzcnt32`, `Bit.bswap32`, and `Bit.rotl64` are not members of the current builtin namespace. ## Choosing a masked operation Use `pext` when a sparse flag layout needs a compact index. Use `pdep` to place that compact representation back into a known layout. Bits outside the mask are discarded; the operation is reversible only within the selected positions. The [Bit namespace guide](docs/guide/bit.md) includes a complete program, worked binary examples, and round-trip identities. ## Execution and containers The compiler chooses instructions or software lowering from the target's capabilities. A builtin name does not promise one instruction or a particular latency. The current `Bit.pext` and `Bit.pdep` signatures are scalar `(u64, u64) -> u64`; they do not imply Tensor or Span overloads. See [Math integer operations](docs/guide/math.md#bit-operations) for the width-preserving operations and [SIMD](docs/guide/simd/index.md) for container execution rules. --- Source: https://vex-lang.org/docs/std/cli.md # CLI applications The `cli` package provides a deterministic command schema, typed argv parser, generated help, action dispatch and fallible prompt helpers. Parsing does not use a process-global registry. ## Build a command tree ```vex import { App, Arg, CliError, Command, Context, Flag } from "cli"; import { args as processArgs } from "sys/args"; fn build(context: &Context): Result<(), CliError> { let jobs = match context.getInt("jobs") { Ok(Some(value)) => value, Ok(None) => 1, Err(cliErr) => return Err(cliErr), }; $println("workers: " + jobs.toString()); return Ok(()); } fn main(): i32 { let app = App.new("tool") .version("1.0.0") .about("Build projects") .flag(Flag.boolean("verbose", "v").persistent(true)) .addCommand( Command.new("build") .alias("b") .arg(Arg.new("input").required(true)) .flag( Flag.integer("jobs", "j") .env("TOOL_JOBS") .defaultValue("4") ) .action(build) ); match app.run(processArgs()) { Ok(_) => return 0, Err(cliErr) => { $eprintln(cliErr.toString()); return 1; } } } ``` `-h`/`--help` and `--version` are application controls. `-v` is intentionally available to the schema for conventional verbose flags. ## Flags and arguments Flag constructors are: - `Flag.boolean(name, short)`; - `Flag.stringValue(name, short)`; - `Flag.integer(name, short)`; - `Flag.count(name, short)`. Flags support `alias`, `required`, `defaultValue`, `env`, `persistent`, `repeatable`, `possibleValue`, `validator`, `conflictsWith`, and `requiresFlag`. Boolean flags accept positive and `--no-...` spellings. Value-less short flags can be clustered, while a value-taking short flag consumes the token suffix or next argv value. Arguments support `required`, `defaultValue`, `env`, `possibleValue`, `validator`, and a final `variadic` argument. `--` terminates option parsing. Resolution precedence is command line, then non-empty environment value, then explicit default. `Context.wasProvided` remains true only for actual command-line occurrences. Boolean absence is not converted into a fake `false`. Handle `Ok(None)` or add `.defaultValue("false")` when the schema requires a resolved value. ## Parse once or prepare `App.parse(&argv)` validates the complete schema and returns a `Context` without printing or running an action. Repeated parsers should validate once: ```vex let prepared = match app.prepare() { Ok(value) => value, Err(cliErr) => return Err(cliErr), }; let first = prepared.parse(&firstArgv); let second = prepared.parse(&secondArgv); ``` `PreparedApp` also provides `run`, `helpText`, and `helpTextFor`. ## Typed context access Use `getBool`, `getInt`, `getString`, `getStrings`, `getCount`, `getArg`, and `getArgs`. Repeatable and variadic accessors preserve input order. Command and flag aliases always resolve to canonical names in the context. ## Deterministic help `helpText()` renders root help. `helpTextFor(&argv)` resolves aliases and renders the selected canonical command path. Output is ANSI-free and includes aliases, argument/value shapes, possible values, env/default/required metadata, relationships and inherited persistent flags. Read-only formatting preserves the schema's owned strings: `toString()` and `debug()` do not consume names or error payloads. `Flag.defaultValue()` and `Arg.defaultValue()` return an independent `Option` and can be called repeatedly. When building your own diagnostic from borrowed metadata, use its `.asStr()` view; passing an owned string to the consuming `+` overload transfers ownership. ## Prompts and terminal style `input`, `confirm`, and `choose` return `Result<_, IoError>`. Empty/default and malformed/error states are not conflated. `choose` borrows its option vector. Prompt output is ANSI-free; the explicit `style` functions are opt-in when the application knows color output is appropriate. ## Current advanced boundary The core API covers schema, parsing, help and dispatch. Shell completion, hidden/deprecated migration metadata, typo suggestions, schema-generated man pages and explicit config-file integration are staged on the same command model. They are not silently emulated by ambient global configuration. ## Validation checkpoint — 2026-09-06 The native O0 and O3 suites each pass **26/26** tests, including repeated reads of non-inline default strings and metadata. This checkpoint covers parser/schema, help and ownership regressions; it is not a cross-platform or interactive terminal qualification, and no new benchmark result is claimed. --- Source: https://vex-lang.org/docs/std/collections.md # `collections` — supplemental owning containers Vex provides `Vec`, `Map`, `Set`, `OrderedMap`, and `Deque` in the prelude. The `collections` package adds higher-level access policies through `Stack`, `PriorityQueue`, and `LinkedList`. It does not duplicate prelude hash-table or ring-buffer storage. Every container owns its stored values. Insertion transfers ownership, removal transfers it back to the caller, and peeking/iteration borrows without cloning. There is no reference-counting or manual thread-lifetime API. ## Map and Set Prelude `Map` uses 16-byte Swiss-table control groups and Vex's ordinary fixed-array/`Mask<16>` SIMD lowering. `getKeyValue` borrows the canonical stored key together with its value; `removeEntry` transfers both owners. ```vex let! counts = Map.new(); let count = counts.getOrInsertWith("vex".toString(), fn(): i32 { return 0; }); *count = *count + 1; ``` Unlike eager `getOrInsert`, `getOrInsertWith` runs its factory only on a miss and still performs a single lookup/insertion probe. `Set.get` borrows the canonical stored representative; `Set.take` removes and returns its owner. `Map.withCapacity(n)` and `Map.withHasherCapacity(builder, n)` guarantee room for at least `n` live elements, accounting for the Swiss-table 7/8 load limit. `capacity`, `reserve`, `retain`, and `shrinkToFit` use element counts and never clone retained owners. The legacy `withCap`/`cap` pair is the explicit raw bucket-count compatibility surface. `Set` delegates the same capacity and retention semantics to its canonical Map storage. ## OrderedMap Prelude `OrderedMap` is the insertion-ordered map. Each canonical key and value is owned once in a stable node; a private Swiss index maps cached full hashes to collision-correct node chains, and reciprocal links maintain order. Equal-key updates replace only the value, preserving the first key and its position. Insertion, update, lookup, removal and reordering require no `Clone`. `iter`, `keys`, and `values` borrow in current order. `first`/`last` borrow end pairs, while `popFront`/`popBack` transfer owners. `moveToFront` and `moveToBack` relink after average O(1) lookup. `removeValue` transfers the value, `removeEntry` transfers both canonical owners, and `remove` is the boolean dropping form. `reserve`, `retain`, and `shrinkToFit` preserve ownership. Compaction moves entries once and rebuilds the private index from cached hashes, so user keys are not cloned or hashed again. `getAtIndex*` traverses from the nearer end in O(min(i,n-i)); use the O(1)-step iterator for scans. `OrderedMap` is insertion-ordered, not a sorted/B-tree collection. ## Deque `Deque` is a tag-free owning circular buffer with amortized O(1) operations at both ends. It is available without an import. ```vex let! pending = Deque.withCapacity(256); pending.pushBack(job); match pending.popFront() { Some(next) => run(next), None => {}, }; ``` `pushFront`/`pushBack` and `popFront`/`popBack` transfer ownership. `front`, `back`, and `get` borrow. `frontMut`, `backMut`, and `getMut` return exclusive borrows to proven-live positions. `reserve()` grows in advance, `clear()` drops live values while retaining storage, and `iter()` visits logical front-to-back order even when the physical buffer wraps. `asSlices()` exposes that order as at most two borrowed contiguous spans. `shrinkToFit()` reclaims unused heap capacity; arena storage remains owned by its bulk-reclaimed region. Only live positions are initialized; there is no `Option` tag per capacity slot. Wrapped growth transfers at most two contiguous runs with bulk memory operations and preserves the allocator region captured at construction. ## Stack `Stack` is the small LIFO surface over the canonical Vex `Vec` storage. It provides `push`, `pop`, borrowed `peek`, exclusive `peekMut`, `truncate`, capacity management, `shrinkToFit`, `clear`, and bottom-to-top borrowed iteration. ## PriorityQueue Priority queues are max-heaps by default. Use `min()` or `minWithCapacity()` when the smallest value must be selected first. ```vex import { PriorityOrder, PriorityQueue } from "collections"; let! ready = PriorityQueue.withCapacity(1024); ready.push(task); match ready.pop() { Some(highest) => dispatch(highest), None => {}, }; ``` `push` and `pop` are O(log n), while `peek` is O(1). Borrowed iteration exposes heap layout; it is intentionally not sorted. ### Type-based custom ordering ```vex struct ByScore: PriorityOrder {} inline fn (self: &ByScore) higher(left: &Task, right: &Task): bool { return left.score > right.score; } let! ready = PriorityQueue.withOrderCapacity(ByScore {}, 1024); ``` Ordering is a monomorphized type policy. The heap invokes the concrete policy type; it does not require a boxed comparator. Inlining and final call overhead depend on the compiler and optimization target. `fromVecWithOrder` consumes and heapifies a `Vec` in O(n). ### Linear construction and merge ```vex let! heap = PriorityQueue.fromVec(values); // max-heap, O(n) let! timers = PriorityQueue.minFromVec(deadlines); // min-heap, O(n) heap.append(&other!); // moves owners, empties other, rebuilds once ``` Construction consumes the Vec and reuses its allocation. `append` is O(n+m) and uses the destination's ordering policy; the source may be a min-heap or a max-heap because the combined storage is rebuilt bottom-up. ### Bounded top-k operations ```vex let removed = heap.pushPop(candidate); match heap.replaceTop(replacement) { Some(previous) => consume(previous), None => {}, // the empty heap kept replacement }; ``` `pushPop` has the same selected-value result as pushing and immediately popping, but keeps the heap length fixed. If the candidate would itself be selected, it is returned after one comparison and the heap is untouched; otherwise the root is replaced and sifted once. `replaceTop` replaces a non-empty root without allocating or cloning. On an empty queue it inserts the supplied value and returns `None`, so that case can allocate. `retain(predicate)` evaluates the predicate once per value and restores heap order in O(n). `removeAt(index)` removes an arbitrary heap-layout owner and repairs in O(log n). `tryReplaceAt(index, value)` returns the previous owner on success or returns `value` in `Err` for an invalid index, so failed mutation never loses ownership. Repair selects upward or downward traversal from the changed node. Use `drainPriority()` to move owners out in priority order without auxiliary storage. `intoPriorityVec()` consumes the queue and reuses its existing `Vec` allocation for priority-ordered materialization. ## LinkedList `LinkedList` is a stable-index doubly linked list for workloads that need O(1) operations at both ends. `pushFront`, `pushBack`, `popFront`, and `popBack` transfer ownership. Removed node slots are retained and reused; `peekFrontMut` and `peekBackMut` provide exclusive end borrows. `clear()` drops all live values without discarding that pool. Prefer `Vec`, `Deque`, or `PriorityQueue` when contiguous storage expresses the workload. `LinkedList` is specialized: its extra links and indirect accesses are not a general replacement for cache-friendly arrays. ## Complexity summary | Container operation | Time | |---|---:| | Deque push/pop at either end | amortized O(1) | | OrderedMap key lookup/insert/remove/reorder | average O(1) | | OrderedMap iterator step / indexed compatibility access | O(1) / O(min(i,n-i)) | | Stack push/pop | amortized O(1) | | PriorityQueue peek | O(1) | | PriorityQueue push/pop/replace | O(log n) | | PriorityQueue fromVec/append/retain rebuild | O(n) or O(n+m) | | LinkedList operations at either end | O(1) | ## Current native baseline Apple M2 Max, `-O3`, 2026-08-21; median of three 300 ms rounds. Map and Set use a fixed deterministic builder and pre-sized tables so the rows are reproducible. | Transaction | ns/op | |---|---:| | Map remove + insert + lookup | 27.31 | | Map lookup | 8.31 | | Map remove + insert | 18.57 | | Map lazy entry hit | 8.95 | | Map lazy entry miss + remove/reuse | 20.10 | | Set remove + insert + contains | 25.25 | | Set contains | 8.29 | | Deque push-back + pop-front | 2.32 | | Deque push-front + pop-back | 2.85 | | Stack push + pop | 4.49 | | PriorityQueue push + pop | 17.98 | | PriorityQueue fused reject | 2.09 | | PriorityQueue fused random top-k | 3.51 | | LinkedList push-back + pop-front | 9.34 | | OrderedMap lookup (1,024 entries) | 12.71 | | OrderedMap remove + reinsert | 68.27 | OrderedMap traversed 1,024 entries in 2.577 us (5.92 GB/s of key/value payload) in its 100 ms optimizer-safe smoke gate. Local figures are regression baselines, not cross-language claims. Deque hot helpers are bounded and monomorphized inline. No loop-unroll policy, container-name compiler branch, C FFI, or legacy `.bc` archive is used. --- Source: https://vex-lang.org/docs/std/collections_reference.md # Collections API reference For imports, examples and ownership decisions, see [Collections](docs/std/collections.md). The API inventory below is distinct from dated benchmark results in the guide. The canonical low-level containers `Vec`, `Map`, `Set`, `OrderedMap`, and `Deque` are VexArch prelude types. The `collections` package exports `Stack`, `PriorityQueue`, and `LinkedList`. ## `Map` and `Set` No import is required. - `Map.get` / `getMut`: borrow a value. - `Map.getKeyValue`: borrow the canonical stored key and value with one probe. - `Map.insert`: transfer key and value; replace an existing value in place. - `Map.remove`: transfer the value and drop the stored key. - `Map.removeEntry`: transfer both stored owners. - `Map.getOrInsertWith`: invoke a zero-argument factory only on a miss. - `Map.withCapacity` / `withHasherCapacity`: guarantee element capacity at the 7/8 load limit; `capacity`, `reserve`, `retain`, and `shrinkToFit` use element counts. Legacy `withCap` / `cap` explicitly use raw bucket counts. - `Set.get`: borrow the stored representative; `Set.take`: transfer it out. - `Set.capacity` / `reserve` / `retain` / `shrinkToFit`: delegate to the same canonical Map storage. Map probing uses portable Vex fixed-array/Mask SIMD; there is no C hash-table shim or container-name-specific compiler lowering. ## `OrderedMap` No import is required. - `new`, `withCapacity`, `withHasher`, `withHasherCapacity`: owning insertion-ordered construction. - `insert`: return whether the key is new; an update preserves the canonical stored key and order position. - `get`, `getMut`, `getKeyValue`, `contains`: borrowed average O(1) lookup. - `removeValue`, `removeEntry`, `remove`: value transfer, pair transfer, or boolean dropping removal. - `iter`, `keys`, `values`: allocation-free borrowed current-order traversal. - `first`, `last`, `popFront`, `popBack`: O(1) order-end access/transfer. - `moveToFront`, `moveToBack`: average O(1) lookup and constant-time relink. - `capacity`, `reserve`, `retain`, `clear`, `shrinkToFit`: stable-slot capacity and mutation without key cloning; compaction reuses cached hashes. - `getAtIndex`, `getAtIndexRef`, `getAtIndexMut`: compatibility current-order access in O(min(i,n-i)). The type is insertion-ordered rather than key-sorted. Sorted range maps/sets remain a separate future B-tree family. ## `Deque` No import is required. | API | Semantics | |---|---| | `Deque.new()` | Empty owning deque with a small initial capacity. | | `Deque.withCapacity(n)` | Empty deque; `n == 0` performs no allocation. | | `pushFront(value)` / `pushBack(value)` | Transfer ownership into either end; amortized O(1). | | `popFront()` / `popBack()` | Transfer ownership out through `Option`; amortized O(1). | | `front()` / `back()` | Borrow an end through `Option<&T>`. | | `get(index)` | Borrow a logical front-relative index. | | `frontMut()` / `backMut()` / `getMut(index)` | Exclusively borrow a live value. | | `len()` / `isEmpty()` / `capacity()` | Constant-time state queries. | | `reserve(minimum)` | Ensure total capacity; preserves order and allocator region. | | `shrinkToFit()` | Reclaim unused heap capacity; arena allocations remain bulk-owned. | | `clear()` | Drop every live owner exactly once and retain storage. | | `iter()` | Borrow front-to-back without allocation. | | `for item in deque` | Use the same borrowed logical order as `iter()`, including across ring wrap. | | `asSlices()` | Borrow logical contents as one or two contiguous `Span` values. | ## `Stack` Import `Stack` from `collections`. It exposes `new`, `withCapacity`, `push`, `pop`, borrowed `peek`, exclusive `peekMut`, `truncate`, `len`, `isEmpty`, `capacity`, `reserve`, `shrinkToFit`, `clear`, and a borrowed bottom-to-top `iter` over canonical `Vec` storage. ## `PriorityQueue>` Import `PriorityQueue`; custom policies additionally import `PriorityOrder`. - `new` / `withCapacity`: max heap. - `min` / `minWithCapacity`: min heap. - `fromVec` / `minFromVec`: consuming O(n) Floyd heap construction. - `withOrder` / `withOrderCapacity` / `fromVecWithOrder`: monomorphized custom ordering with no runtime comparator pointer. - `push` / `pop`: O(log n); `peek`: O(1). - `removeAt`: remove a heap-layout owner and repair in O(log n). - `tryReplaceAt`: replace and repair, or return the supplied owner in `Err`. - `replaceTop`: replace the selected extremum and return its previous owner; an empty heap inserts instead and returns `None`, potentially allocating. - `pushPop`: fused fixed-length push-then-pop semantics. - `append`: transfer another heap and rebuild once in O(n+m). - `retain`: evaluate once per owner and rebuild in O(n). - `drainPriority`: transfer owners in priority order without a second buffer. - `intoPriorityVec`: consume the queue and reuse its allocation for priority-ordered materialization. - `iter`: borrow heap layout; iteration is intentionally not priority-sorted. ## `LinkedList` Import `LinkedList` from `collections`. `pushFront`, `pushBack`, `popFront`, and `popBack` are O(1); `peekFront` and `peekBack` borrow. `clear` retains the stable-index node pool, `peekFrontMut` / `peekBackMut` borrow exclusively, and `iter` walks front-to-back. Value-taking insertion transfers ownership. Owner-returning removals return that value; boolean removals, `clear`, and rejected values in `retain` drop owners instead. Borrowed queries allocate nothing. None of these APIs requires application developers to manage reference counts or thread lifetimes. --- Source: https://vex-lang.org/docs/std/compress/brotli.md # Brotli The Brotli codec is implemented in pure Vex and is intended for bounded whole-buffer compression and decompression of web-oriented payloads. ## Usage ```vex import { compress, decompress, CompressOptions, CompressionFormat, } from "compress"; let encoded = compress( source.asSpan(), CompressOptions.forFormat(CompressionFormat.Brotli).withLevel(6), )?; let decoded = decompress( encoded.asSpan(), CompressionFormat.Brotli, source.len(), )?; ``` Levels 1–11 are accepted. Levels 1–5 prioritize fast uncompressed metablocks; levels 6–11 attempt LZ77-compressed metablocks and fall back when compression would expand the block. ## Decoder coverage and safety The decoder handles compressed and uncompressed metablocks, prefix codes, back-references and the RFC static dictionary transformations used by the test corpus. Every decode goes through an explicit output ceiling. Truncated input, invalid distance/prefix data and insufficient output space fail without publishing partial output through the safe facade. Backward references preserve Brotli overlap semantics without a scalar modulo loop: the decoder copies at most one existing period, then doubles the initialized prefix through non-overlapping `Mem.copy` operations. This keeps the implementation pure Vex and lets the shared memory backend select the target's best legal copy width. When a context map selects only one literal tree, decoding bypasses redundant context calculation and tree-pointer dispatch. Encoder match positions are local to each 64 KiB metablock, keeping the complete hash table at 64 KiB; wide match tails use endian-stable XOR plus trailing-zero count. The checked-in decoder fixtures include streams produced by Brotli 1.1.0 at qualities 0, 4, 6 and 11 (quality 9 produced the same fixture as 6). These external encoder qualities are distinct from this package's accepted 1–11 compression options. The package does not claim bit-for-bit parity with Google's encoder; interoperability and decoded content are the contract. Fixture presence is not evidence of a fresh run on the current release. `brotliCompress` and `brotliDecompress` are low-level `RawBuf` kernels for specialized callers. A streaming Brotli writer is not currently exposed. --- Source: https://vex-lang.org/docs/std/compress/gzip.md # Gzip, Deflate and Zlib The Gzip codec implements RFC 1952 framing over the package's pure-Vex Deflate core. Zlib uses the same core with RFC 1950 framing. ## One-shot API ```vex import { compress, decompress, CompressOptions, CompressionFormat, } from "compress"; let encoded = compress( source.asSpan(), CompressOptions.forFormat(CompressionFormat.Gzip).withLevel(6), )?; let decoded = decompress( encoded.asSpan(), CompressionFormat.Gzip, source.len(), )?; ``` Gzip and Zlib accept levels 1–9. The safe facade checks size arithmetic and requires an explicit decompressed-output ceiling. ## Streaming writer `GzipWriter` owns an `io.Stream`, incrementally tracks CRC-32/ISIZE, buffers 64 KiB Deflate chunks and propagates `IoError` from partial writes and close. ```vex import { GzipWriter } from "compress/gzip/writer"; import { openWrite } from "io/stream"; let stream = openWrite("archive.gz")?; let! writer = GzipWriter.new(stream, 6); writer.write(RawBuf.of(source.asPtr()), source.len() as i64)?; writer.close()?; ``` `close()` finalizes the Deflate stream and writes the trailer. The writer owns the wrapped stream. ## Checksums and low-level API `crc32` and `crc32Update` provide one-shot and incremental CRC-32. The hot path uses the width-polymorphic `Crypto.crc32` semantic operation. Large buffers are split into four dependency-independent 4 KiB stripes and restored to canonical byte order with a fixed GF(2) combine matrix. The compiler selects native CRC instructions when the target proves support; the package contains no C codec dependency or architecture-name dispatch. `adler32`/`adler32Update` serve Zlib framing. Deflate match tables store positions relative to each 65,535-byte block, so very large application streams cannot overflow a global i32 position. Level 6 uses a measured four-byte hash-fill stride inside accepted matches; levels 7-9 retain exhaustive insertion for their stronger ratio contract. Raw `gzipCompress`/`gzipDecompress` and `zlibCompress`/`zlibDecompress` kernels remain available to specialized callers. Ordinary code should use the typed facade. Official Gzip tooling validates generated streams in the interoperability gate. --- Source: https://vex-lang.org/docs/std/compress/index.md # `compress` `compress` provides pure-Vex LZ4, Zstandard, Gzip, Brotli and Zlib codecs. The public API accepts borrowed `Span` input, returns an owned `Vec` or writes into caller-reusable storage, validates levels, and reports typed errors. No C codec library or manual allocation is required. ## Quick start ```vex import { compress, decompress, CompressOptions, CompressionFormat, } from "compress"; let text = "compress me"; let source = unsafe { Span.of(text.asPtr() as Ptr, text.len()) }; let encoded = compress( source, CompressOptions.forFormat(CompressionFormat.Zstd).withLevel(3), )?; // The ceiling is mandatory: malformed input cannot request unbounded memory. let decoded = decompress( encoded.asSpan(), CompressionFormat.Zstd, 1 * 1024 * 1024 as usize, )?; ``` For repeated operations, reuse the output allocation: ```vex let! encoded = Vec.new(); let written = compressInto( source, &encoded, CompressOptions.forFormat(CompressionFormat.Lz4), )?; let! decoded = Vec.new(); decompressInto( encoded.asSpan(), &decoded, CompressionFormat.Lz4, 1 * 1024 * 1024 as usize, )?; ``` `compressInto` and `decompressInto` leave the destination at its exact logical length on success and empty it on every failure, including invalid-level and known-size limit rejection before a codec runs. Source/destination overlap is staged safely. For frames without a trusted decoded-size field, decompression begins with a small source-proportional allocation and grows geometrically only when a codec reports destination exhaustion. It never reserves `maxOutputBytes` eagerly; that value remains a hard security ceiling rather than an allocation request. ## Formats and level ranges | Format | Encoder levels | Decoder | Typical use | |---|---:|:---:|---| | LZ4 frame | 1–65537 acceleration | Yes | latency-sensitive caches and transport | | Zstandard | 1–22 | Yes | general-purpose ratio/speed balance | | Gzip/Deflate | 1–9 | Yes | HTTP and `.gz` interoperability | | Brotli | 1–11 | Yes | web payloads | | Zlib/Deflate | 1–9 | Yes | RFC 1950 consumers and legacy formats | Use `CompressOptions.forFormat(format)` for production defaults. Invalid levels return `CompressionErrorKind.InvalidLevel`; they are never silently clamped. ## Error and resource contract `CompressionError` contains: - `kind`: stable programmatic classification; - `codecCode`: the underlying pure-Vex kernel diagnostic; - `limit`: the configured output ceiling when relevant. The decoder requires `maxOutputBytes`. This is part of the security contract, not a tuning hint. `CompressionErrorKind.OutputLimitExceeded` is distinct from malformed input. Checked size arithmetic rejects impossible inputs before allocation. ## Reusable Zstandard encoder `ZstdEncoder` owns and retains its match/FSE workspace. Vex releases the workspace automatically; application code never receives allocator pointers. ```vex let! encoder = ZstdEncoder.withLevel(7)?; let! output = Vec.new(); encoder.compressInto(first.asSpan(), &output)?; encoder.compressInto(second.asSpan(), &output)?; ``` `workspaceCapacity()` is available for observability. It does not transfer ownership. ## Interoperability and boundaries The package is tested against the official `zstd`, `gzip`, `brotli` and `lz4` command-line decoders. Truncated input, malformed headers, checksum failures, output ceilings, empty payloads and multi-block frames are covered by package tests. Current advanced boundaries: - Zstandard dictionary compression is not exposed; - Zstandard accepts one ordinary frame, not concatenated or skippable frames; - Gzip and LZ4 have stream writers; Zstandard and Brotli currently use the bounded whole-buffer facade; - low-level `RawBuf` kernels remain exported for codec/runtime specialists, but ordinary application code should use the safe facade above. See the format pages for exact codec behavior and implementation details. ## Validation checkpoint — 2026-09-06 All 63 ordinary package tests pass on native macOS arm64 at both O0 and O3 with compiler caches disabled. This includes a repaired Deflate encoder scratch-buffer overflow: the distance-code table now allocates and initializes the same 120 bytes, independently of the 1,144-byte literal-code table. The regression covers levels 6–9, five input sizes, exact round trips, and sentinels before and after the caller-owned encoded/decoded buffers. Existing gzip, zlib, streaming, checksum and multiblock tests also pass. No allocator safety check was relaxed. These are correctness results, not new throughput figures or fresh external-decoder/cross-platform qualification. --- Source: https://vex-lang.org/docs/std/compress/lz4.md # LZ4 LZ4 is the low-latency choice for caches, transport buffers and transient data. The package supports both raw blocks and interoperable LZ4 frames. ## Safe frame API ```vex import { compress, decompress, CompressOptions, CompressionFormat, } from "compress"; let encoded = compress( source.asSpan(), CompressOptions.forFormat(CompressionFormat.Lz4), )?; let decoded = decompress( encoded.asSpan(), CompressionFormat.Lz4, source.len(), )?; ``` The facade writes LZ4 frames, validates headers and XXH32 checksums, supports multi-block payloads and enforces the caller's output limit. ## Streaming writer `Lz4Writer` owns an `io.Stream`, writes the frame header lazily, divides input into bounded blocks and propagates `IoError`. ```vex import { Lz4Writer } from "compress/lz4/writer"; import { openWrite } from "io/stream"; let stream = openWrite("payload.lz4")?; let! writer = Lz4Writer.new(stream); writer.write(payload.asStr())?; writer.close()?; ``` The current streaming writer emits valid uncompressed LZ4 frame blocks. The one-shot facade chooses compressed or raw blocks according to size. ## Low-level API `compress`/`decompress` in the `compress/lz4` submodule operate on raw LZ4 blocks. `compressFrame`/`decompressFrame` operate on frames; `maxCompressedSize` and `maxFrameCompressedSize` provide destination bounds. These `RawBuf` functions are intended for codec implementers. Generated frames are checked by the official LZ4 tool and round-tripped against the original bytes. --- Source: https://vex-lang.org/docs/std/compress/zstd.md # Zstandard The pure-Vex Zstandard implementation reads and writes RFC 8878 frames. The recommended entry points are the common `compress`/`decompress` facade and the workspace-reusing `ZstdEncoder`. ## Reusable encoding ```vex import { decompress, CompressionFormat, ZstdEncoder, } from "compress"; let! encoder = ZstdEncoder.withLevel(3)?; let! encoded = Vec.new(); encoder.compressInto(source.asSpan(), &encoded)?; let decoded = decompress( encoded.asSpan(), CompressionFormat.Zstd, source.len(), )?; ``` Levels 1–22 are accepted. The encoder owns one reusable workspace and grows it only when the input requires more capacity. ## Implemented frame features - raw, run-length and compressed blocks; - multi-block frames and a rolling 128 KiB match window; - repeat offsets; - predefined, RLE and custom FSE sequence tables; - compressed and raw literal decoding, including Huffman literal streams; - optional frame checksum validation; - bounded backward bit readers and checked frame-content-size parsing. The encoder currently emits raw literal sections; sequence streams use FSE. Dictionary compression, concatenated frames and skippable frames are explicit future extensions. ## Low-level kernels `zstdCompress`, `zstdDecompress` and `zstdGetFrameContentSize` operate on `RawBuf` and capacities. They preserve negative codec diagnostics and exist for runtime or codec implementers. Application code should prefer `ZstdEncoder` or the common safe facade, which performs checked sizing, alias staging and typed error conversion. ## Verification Package tests cover all public levels, empty and multi-block inputs, custom FSE tables, repeated offsets, malformed/truncated streams and output ceilings. Generated frames are validated and decoded by the official Zstandard tool. --- Source: https://vex-lang.org/docs/std/context.md # context — request lifetime and cancellation `context` carries cooperative cancellation, monotonic deadlines and small request metadata through a call tree. Contexts are immutable persistent handles: deriving a child never mutates its parent or siblings. ```vex import { Context } from "context"; import { Error, ErrorKind } from "errors"; import { Duration } from "time"; fn serve(request: &Context): Result { match request.check() { Result.Err(cause) => return Result.Err(cause), Result.Ok(_) => { /* continue */ }, } match request.valueStringView("request-id") { Some(id) => return Result.Ok("request " + id), None => return Result.Ok("anonymous request"), } } let root = Context.background(); let timed = root.withTimeout(Duration.seconds(5)); let request = timed.withValue("request-id", "req-42"); let result = serve(&request); ``` ## Roots and derivation ```vex let root = Context.background(); let placeholder = Context.todo(); let absolute = root.withDeadline(deadline); // deadline: Instant let relative = root.withTimeout(Duration.milliseconds(250)); let tagged = relative.withValue("attempt", 3 as i64); ``` `Context.todo()` behaves like a background root but remains distinguishable through `kind()` for diagnostics. `withDeadline` accepts an absolute monotonic `Instant`; wall-clock `Time` and raw Unix timestamps cannot be mixed into this API. An earlier inherited deadline always wins. Zero and negative timeout durations are already expired, with the typed `TimedOut` cause and zero remaining duration. Deadline creation does not spawn a timer or thread. Cooperative consumers observe expiry at `isDone()`, `cause()`, `check()` or `remaining()` calls. When a context is passed to a context-aware TCP operation, VexArch registers the same absolute monotonic deadline with that in-flight operation and actively wakes the parked task at expiry. ## Cancellation ```vex let root = Context.background(); let (request, cancel) = root.withCancelCause( Error.withKind("server shutdown", ErrorKind.Closed), ); // Pass `request` or a clone to workers. let first = cancel.cancel(); // true: this caller published the event let again = cancel.cancel(); // false: cancellation is idempotent $assert(request.isDone(), "worker must observe cancellation"); match request.cause() { Some(cause) => $println(cause.messageView()), None => $panic("missing cancellation cause"), } ``` `CancelHandle.cancel()` is thread-safe. Exactly one concurrent caller publishes the event; other callers return only after the timestamp and immutable typed cause are visible. Child cancellation and parent cancellation remain separate events. `cause()` returns whichever cancellation or deadline occurred first. `withCancel()` is the convenience form using `ErrorKind.Canceled`. Context-aware TCP accept, connect, read and write bind the nearest cancellation identity directly to the generation-owned runtime operation. `cancel()` scans only on this exceptional path and wakes matching parked operations; ordinary context creation, polling and successful context-free I/O pay no subscription or callback allocation. ## Cooperative checkpoints Use `check()` at meaningful boundaries in request handlers and long-running loops: ```vex let! offset = 0 as usize; while offset < input.len() { match request.check() { Result.Err(cause) => return Result.Err(cause), Result.Ok(_) => { /* process the next bounded chunk */ }, } offset = offset + processChunk(input, offset); } ``` `processChunk` in the fragment must consume at least one byte and no more than the remaining input on every successful iteration; handle an error or zero-progress result before advancing. Cancellation checks alone do not make a stalled processing loop progress. `check()` returns the same typed `Error` as `cause()`. It does not panic, block, allocate a notification channel or introduce a scheduler dependency. ## Values The current safe value surface supports `i64` and owned `string` entries: ```vex let first = root.withValue("attempt", 0 as i64); let second = first.withValue("request-id", "req-42"); match second.valueI64("attempt") { Some(value) => $assert(value == 0, "zero is a valid value"), None => $panic("attempt missing"), } let borrowed: Option = second.valueStringView("request-id"); let owned: Option = second.valueString("request-id"); ``` Absence is always `None`; integer zero and an empty string are ordinary values. `valueStringView` is allocation-free and tied to the context borrow. `valueString` returns an owned copy. Values are for shallow cross-cutting metadata, not application state or dependency injection. Arbitrary typed payloads are intentionally unavailable until Vex has safe existential storage, exact generic drop glue and borrowed downcasting. Use an explicit typed request struct for domain data. ## Cost model Each derivation creates one persistent node in the active request arena. Cloning a handle shares the chain through VUMM; developers never select or manage `Rc`/`Arc`. Cancellation state and request values use separate persistent chains. Every node caches its effective deadline and nearest cancellation state, so adding value nodes does not slow down polling. M2 Max O3 medians (500 ms, three runs, 2026-08-23): | Operation | Median | |---|---:| | context clone | 8.87 ns | | cancelable child creation and publication | 119.18 ns | | active cancellation poll | 2.05 ns | | active poll below 256 value nodes | 2.07 ns | | cooperative `check` below 256 value nodes | 4.94 ns | | cached deadline lookup below 256 value nodes | 1.21 ns | | latest value lookup at depth 256 | 5.00 ns | | oldest value lookup at depth 256 | 1.70 us | Value lookup is newest-to-oldest and O(depth). Keep metadata chains shallow; the 256-node row is an explicit adversarial regression baseline. ## API summary | API | Meaning | |---|---| | `Context.background()` / `Context.todo()` | Create a root | | `withCancel()` / `withCancelCause(error)` | Derive a cancelable child and handle | | `withDeadline(Instant)` / `withTimeout(Duration)` | Derive a monotonic deadline | | `isDone()` | Cheap boolean poll | | `cause()` / `check()` | Retrieve or propagate the typed earliest cause | | `deadline()` / `timeout()` / `remaining()` | Inspect effective timing | | `withValue(key, i64\|string)` | Add persistent metadata | | `valueI64`, `valueString`, `valueStringView` | Typed lookup | | `containsKey` / `kind` | Metadata and diagnostic inspection | The source distribution includes a generated `lib/std/context/REFERENCE.md` with complete signatures. --- Source: https://vex-lang.org/docs/std/contracts.md # Contracts `std/contracts` supplies the explicit, higher-level protocols that do not belong to the compiler-owned prelude. It has no runtime state, allocation, I/O, FFI or platform dependency. ```vex import { From, TryFrom, Collection, Stack } from "contracts"; ``` ## Conversion - `From.fromValue(value)` performs an explicit infallible construction. - `Into.intoValue(value)` consumes `Self` and produces `T`. - `TryFrom.tryFromValue(value)` returns `Result`. - `TryInto.tryIntoValue(value)` consumes `Self` and returns `Result`. - `Default.defaultValue()` constructs the type's explicit default. These are static requirements. Generic code calls them through the type parameter: ```vex fn convert>(value: T): U { return U.fromValue(value); } ``` The compiler seals the type-parameter ordinal plus exact contract/member identity and resolves the concrete inherent implementation during monomorphization. There is no runtime interface object or string lookup. Conversion contracts do not add implicit coercions. Vex's implicit conversion rules remain constructor-driven and compiler-checked. ## Collections - `Collection` defines `len`, `isEmpty` and `clear`. - `Growable` defines target-native capacity, minimum-capacity `reserve`, and `shrinkToFit`. - `Stack` composes `Collection + Growable` and provides owning LIFO mutation plus borrowed `peek`/`peekMut`. - `Queue` composes `Collection + Growable` and provides owning FIFO mutation plus borrowed `front`/`frontMut`. - `Indexable` composes `Collection` and provides borrowed read, mutable borrow and replacement. All counts and capacities use `usize`. Read APIs borrow elements rather than forcing clones. ## Other exports `Ordering` is the package-owned `Less | Equal | Greater` enum. `PackedType` describes block encoders/decoders suitable for SIR CPU SIMD and GPU dispatch. Operators, formatting, lifecycle, ownership, `Iterator`, `IntoIterator` and safety capabilities are canonical prelude contracts. They are intentionally not re-exported here. ## Verification The 2026-08-25 checkpoint reported warning-denied lint and the complete fixture matrix at O0 and O3. That dated result does not identify or qualify a later release binary. See the repository's dated contracts sign-off for the compiler and package evidence. --- Source: https://vex-lang.org/docs/std/crypto/encryption.md # Encryption (`crypto` AEAD & Symmetric) ## AES-GCM Authenticated encryption with checked AES-128-GCM and AES-256-GCM facades. The AES-128 facade requires a 16-byte key and the AES-256 facade a 32-byte key; both require a 12-byte nonce and use a 16-byte authentication tag. Backend selection depends on the target and build. ### Nonce and key lifecycle **Never repeat a nonce for two encryption operations under the same key**, including across processes, machines, crashes, and restores. A valid 12-byte length is not proof of uniqueness. The caller owns this policy: `seal` checks lengths but does not maintain a nonce registry. Reusing a GCM key/nonce pair can compromise confidentiality and authentication; see [RFC 5116 sections 3.1 and 5.1.1](https://www.rfc-editor.org/rfc/rfc5116.html#section-3.1). One deterministic allocation design for a 12-byte nonce is a 4-byte writer identifier followed by an 8-byte counter in a fixed byte order. It requires a durable coordinator, not just an in-memory counter: 1. Provision a secret key from an operating-system CSPRNG or a managed key service. Keep it out of records and logs. `Crypto.secureRand()` is the target entropy primitive used by Vex's non-cryptographic `rand` seeding; `Rng` output must not be used for keys or security-sensitive randomness. Check the target implementation and deployment before relying on it. 2. For each key, assign writer identifiers uniquely across all writers that might ever encrypt under it. Persist those assignments and never reassign an identifier with an old counter state. A randomly chosen writer identifier alone is not a uniqueness guarantee. 3. Before encryption, atomically reserve a counter or a disjoint range in durable storage for that key and writer. The durable reservation must commit before any nonce in the range is used. Never return unused values to the pool: burn them after a crash, failed seal, or uncertain outcome. Independent workers must not share a counter without atomic allocation. 4. After a restart, resume only from durable allocation state. Treat restored snapshots, cloned machines, storage rollback, failed commits, split brain, and lost allocation state as unsafe: stop encryption until a new key or provably disjoint allocation is installed. Rotate the key before counter exhaustion and before the algorithm's applicable per-key invocation and data limits; a 64-bit counter is not permission to use a key for 2^64 messages. 5. Store or transmit the nonce, ciphertext and tag, key identifier, and the exact AAD bytes or an unambiguous way to reconstruct them. Nonces and AAD are not secret; AAD is authenticated but not encrypted. Encode multiple AAD fields unambiguously, for example with fixed widths or length prefixes. The combined `seal` result contains ciphertext followed by the tag; the nonce is managed separately. 6. On `open` failure, reject the whole record and do not use or expose plaintext. Authentication alone does not prevent replay: add a protocol-specific replay policy if needed. Handle failure without disclosing secrets. Random 96-bit nonces have collision probability, so randomness is not the deterministic uniqueness policy above. A random-nonce design needs a documented per-key invocation limit and collision-risk analysis across all writers; consult the applicable [NIST GCM recommendation](https://csrc.nist.gov/pubs/sp/800/38/d/final). ### API fixture (test keys only) The following complete fixture uses two different **fixed test nonces** to demonstrate the API and rejection of a modified tag. Fixed keys and fixed nonces must not be copied into an application. It is not an implementation or test of durable allocation, crash recovery, or multi-worker coordination. For a source checkout, put a `crypto` symlink next to this file pointing to `lib/std/crypto`, then run `vex run aead-example.vx` with the tested compiler and library sources. ```vex [aead-example.vx] import { Aes128Gcm, CryptoErrorKind } from "./crypto/src/lib.vx"; fn bytes(value: &[u8; N]): Span { return unsafe { Span.of(value as Ptr, N) }; } fn main(): i32 { // Test vectors only: real keys and nonces must follow the lifecycle policy above. let key = [0x19u8; 16]; let nonce1 = [0x27u8; 12]; let nonce2 = [0x28u8; 12]; let aad = [0x35u8; 9]; let plaintext = [0x43u8; 47]; let! first = match Aes128Gcm.seal(bytes(&key), bytes(&nonce1), bytes(&aad), bytes(&plaintext)) { Ok(value) => value, Err(_) => { $panic("seal failed"); }, }; let second = match Aes128Gcm.seal(bytes(&key), bytes(&nonce2), bytes(&aad), bytes(&plaintext)) { Ok(value) => value, Err(_) => { $panic("seal failed"); }, }; let opened = match Aes128Gcm.open(bytes(&key), bytes(&nonce2), bytes(&aad), second.asSpan()) { Ok(value) => value, Err(_) => { $panic("open failed"); }, }; if opened.len() != plaintext.len() { $panic("wrong plaintext length"); } let! i = 0 as usize; while i < plaintext.len() { if opened[i] != plaintext[i] { $panic("wrong plaintext"); } i = i + 1 as usize; } $println(opened.len()); first[first.len() - 1 as usize] = first[first.len() - 1 as usize] ^ 1; match Aes128Gcm.open(bytes(&key), bytes(&nonce1), bytes(&aad), first.asSpan()) { Ok(_) => { $panic("tampered tag accepted"); }, Err(failure) => { match failure.kind { CryptoErrorKind.AuthenticationFailed => { $println("authentication failed"); }, _ => { $panic("unexpected error"); }, } }, }; return 0; } ``` Expected program output is `47` and then `authentication failed`. A local macOS arm64 development build ran this fixture against the checkout's crypto source; this single run is not a cryptographic audit or evidence for other targets. See [rand](docs/std/rand.md) for the distinction between simulation PRNGs and cryptographic randomness. ## ChaCha20-Poly1305 Portable AEAD cipher with checked combined and detached APIs. ```vex import { ChaCha20Poly1305 } from "crypto"; let sealed = ChaCha20Poly1305.seal(key, nonce, aad, plaintext); let opened = match sealed { Ok(value) => ChaCha20Poly1305.open(key, nonce, aad, value.asSpan()), Err(failure) => Err(failure), }; ``` ## Raw AES Low-level AES block cipher for custom constructions. ```vex import { aes128EncryptBlock, aes256EncryptBlock } from "crypto"; ``` These `RawBuf` block functions are low-level building blocks. Prefer the checked facades for application data. AEAD open verifies the complete tag before decrypting and clears reusable output on authentication failure. Raw CTR callers must also respect the complete counter space. Vex validates it before writing: GCM/J0 CTR reserves the pre-incremented counter correctly, and the initial-counter variant accepts a final `u32::MAX` block once but never a wrapping second block. Raw byte offsets are target-width `usize`; public protocol lengths remain explicit `u64` values until they pass this validation. ## Implementation Details | File | Purpose | |------|---------| | `aes.vx` | AES key expansion, target-independent round semantics and CTR | | `aes_gcm.vx` | GCM with reflected four-block GHASH aggregation | | `chacha20.vx` | ChaCha20 quarter-round stream cipher | | `poly1305.vx` | Poly1305 MAC with 130-bit accumulator | | `aead.vx` | Unified AEAD interface combining cipher + MAC | --- Source: https://vex-lang.org/docs/std/crypto/hashing.md # Hashing (`crypto` Hashes) `crypto` provides pure-Vex streaming and one-shot hash implementations. Prefer the camelCase public API shown below; low-level `*To` functions write into caller-owned buffers and require the documented capacity. ## SHA-256 / SHA-384 / SHA-512 SHA-256 produces a 32-byte digest, SHA-384 produces 48 bytes, and SHA-512 produces 64 bytes. The corresponding `*Hex` helpers return twice that many ASCII hexadecimal characters; they do not return raw digest bytes. ```vex import { sha256Hex, sha512Hex } from "crypto"; let digest256 = sha256Hex("Hello, Vex!"); let digest512 = sha512Hex("Hello, Vex!"); $println("SHA-256: ", digest256); ``` On proven AArch64 SHA2 targets, SHA-256's target-independent four-round and four-word schedule operations lower to native `SHA256H/H2/SU0/SU1` instructions. Other targets execute the exact portable fixed-flow contract; application source does not branch on architecture names. ## SHA-1 (Legacy) Available for protocols that explicitly require legacy SHA-1 compatibility. Do not choose it for new collision-resistant signatures or integrity designs. Its presence here does not imply support for SHA-1 certificates in `tls`. ```vex import { sha1Hex } from "crypto"; let digest = sha1Hex(data); ``` ## BLAKE2b BLAKE2b provides a modern variable-length digest. Choose a hash according to the protocol you are implementing; do not silently replace a protocol-mandated SHA algorithm. ```vex import { blake2bHex } from "crypto"; let digest = blake2bHex(data); ``` ## HMAC The package exposes explicit SHA-1, SHA-256 and SHA-384 HMAC operations. Choose the variant required by the protocol; `hmacSha384Hex` returns the SHA-384 variant, while `hmacSha256Hex` and its verifier are shown below. ```vex import { hmacSha256Hex, hmacVerifySha256Hex } from "crypto"; let mac = hmacSha256Hex(key, message); let accepted = hmacVerifySha256Hex(key, message, mac); ``` --- Source: https://vex-lang.org/docs/std/crypto/index.md # crypto — Overview A pure-Vex cryptographic package with checked algorithm facades. It has no OpenSSL or libsodium dependency. Application code should prefer the checked `Aes128Gcm`, `Aes256Gcm`, `ChaCha20Poly1305`, `HkdfSha256`, `HkdfSha384`, `Pbkdf2Sha256`, `Argon2id`, `X25519`, and `Ed25519` facades; raw `RawBuf` functions exist for protocol and runtime integration and require the caller to uphold buffer dimensions. ## Module Map | Category | Algorithms | Files | |----------|-----------|-------| | **Hashes** | SHA-1, SHA-256, SHA-384, SHA-512, BLAKE2b | `sha1.vx`, `sha256.vx`, `sha512.vx`, `blake2b.vx` | | **MACs** | HMAC-SHA1, HMAC-SHA256, HMAC-SHA384 | `hmac.vx` | | **AEAD** | AES-GCM, ChaCha20-Poly1305 | `aes_gcm.vx`, `chacha20.vx`, `poly1305.vx`, `aead.vx` | | **Symmetric** | AES (128/256) | `aes.vx` | | **KDF** | Argon2id, PBKDF2, HKDF | `argon2id.vx`, `pbkdf2.vx`, `hkdf.vx` | | **Signatures** | Ed25519 | `ed25519.vx` | | **Key Exchange** | X25519 (ECDH) | `x25519.vx` | | **Field Math** | Curve25519 field | `field25519.vx` | | **Encoding** | Hex, Base64 | `hex.vx`, `base64.vx` | | **Utilities** | Byte ops, SIMD helpers | `bytes.vx`, `simd.vx`, `utils.vx` | ## Design Principles 1. **Vex implementations**: algorithms are visible to the compiler; actual inlining and vectorization depend on the selected build and target 2. **Hardware Acceleration**: When `Crypto.*` builtins are available (AES-NI, ARMv8 CE), they are used transparently 3. **Software Fallbacks**: Portable fixed-flow implementations preserve the same `Crypto.*` semantics when a target lacks a native instruction 4. **Failure safety**: checked AEAD open operations release no unauthenticated plaintext and clear reusable output on failure 5. **Constant-flow primitives**: tag comparison, AES portable fallback and polynomial multiplication avoid secret-dependent lookup tables and branches 6. **Target-width raw memory**: every byte offset crossing a `RawBuf` boundary is a canonical `usize`. Algorithms may retain wider logical counters or block indices, but never narrow them implicitly while addressing memory. ## Raw integration boundary Checked facades are the application API. Raw functions exist for runtimes and protocol implementations that already own exact storage; their capacities and aliasing requirements are explicit caller obligations. They fail closed rather than truncate an unaddressable `u64` length. In particular, CTR requests are validated before their first output write, so a counter stream can never wrap and reuse keystream bytes. The initial-counter AES-CTR form permits its final `u32::MAX` block exactly once and rejects any request beyond that boundary. --- Source: https://vex-lang.org/docs/std/crypto/kdf.md # Key Derivation & Signatures (`crypto` KDF & PKI) The examples below are API fragments. Byte inputs such as `password`, `salt`, `message`, and private/public keys are borrowed `Span` values whose owners must remain live for the call. Checked operations return typed errors; a service should propagate or handle them at its application boundary. ## Argon2id — Password Hashing Argon2id is a memory-hard password derivation function. Its resistance to password guessing depends on the chosen memory/time costs and the deployment's resource budget; the algorithm name alone is not a password-storage policy. ```vex import { Argon2id, Argon2Parameters } from "crypto"; // password and salt are Span values. let parameters = Argon2Parameters.recommended(); let hash = match Argon2id.derive(password, salt, parameters, 32) { Ok(value) => value, Err(error) => { $panic(error); }, }; ``` `recommended()` currently chooses 64 MiB (`memoryKiB = 65536`), three passes, and four lanes, matching the memory-constrained option in [RFC 9106 section 4](https://www.rfc-editor.org/rfc/rfc9106.html#section-4). Benchmark costs on the authentication service and bound concurrent derivations. Store the salt, algorithm/version, cost parameters and output alongside the account record so verification can reproduce the same derivation and upgrade old parameters. Salts are not secrets; choose a fresh cryptographically random salt for each password record. The facade returns derived bytes, not a complete self-describing password-record format. ## PBKDF2 Legacy-compatible password derivation. Use Argon2id for new applications. ```vex import { Pbkdf2Sha256 } from "crypto"; let key = match Pbkdf2Sha256.derive(password, salt, iterations, 32) { Ok(value) => value, Err(error) => { $panic(error); }, }; ``` ## HKDF HKDF extracts and expands existing keying material. `info` binds output to a protocol purpose, such as separate encryption and authentication keys. It does not add password-guessing resistance and must not replace a password KDF. See [RFC 5869 section 3](https://www.rfc-editor.org/rfc/rfc5869.html#section-3). ```vex import { HkdfSha256 } from "crypto"; let derived = match HkdfSha256.derive(salt, inputKeyMaterial, info, 32) { Ok(value) => value, Err(error) => { $panic(error); }, }; ``` `HkdfSha256` supports at most `255 * 32` output bytes per expansion; invalid lengths return a typed error. Choose the output length required by the consuming algorithm and use distinct, unambiguous `info` values for different purposes. ## Ed25519 — Digital Signatures Ed25519 signs messages with a 32-byte private seed. `publicKey` returns a 32-byte public key and `sign` returns a 64-byte signature. Keep the seed secret; a signature does not encrypt the message. ```vex import { Ed25519 } from "crypto"; // privateSeed and message are Span values; the seed must be 32 bytes. let publicKey = match Ed25519.publicKey(privateSeed) { Ok(value) => value, Err(error) => { $panic(error); }, }; let signature = match Ed25519.sign(privateSeed, message) { Ok(value) => value, Err(error) => { $panic(error); }, }; ``` Verification uses `Ed25519.verify(publicKey, message, signature)` with byte spans and returns `Result`. Treat only `Ok(true)` as acceptance: `Ok(false)` is an invalid signature, while `Err` reports a dimension or other API error. The implementation checks canonical encodings and rejects small-order points. Verification of a signature does not establish who owns the supplied public key; that binding belongs to the protocol. ## X25519 — Key Exchange Elliptic-curve Diffie-Hellman over Curve25519 for establishing shared secrets. ```vex import { X25519 } from "crypto"; let sharedSecret = match X25519.sharedSecret(myPrivateKey, peerPublicKey) { Ok(value) => value, Err(error) => { $panic(error); }, }; ``` Both inputs and the shared-secret output are 32 bytes. X25519 alone does not authenticate the peer. Use the result within an authenticated key-exchange protocol and derive application keys with its prescribed KDF and context; do not treat the raw shared value as a complete secure channel. See [RFC 7748 section 6](https://www.rfc-editor.org/rfc/rfc7748.html#section-6). Protocol owners that already have fixed storage should avoid a temporary `Vec` and use the exact caller-owned API: ```vex let! publicKeyStorage = [0u8; 32]; let! publicOut = unsafe { Span.of(&publicKeyStorage as Ptr, 32 as usize) }; X25519.publicKeyTo(privateKey, &publicOut!)?; let! sharedSecretStorage = [0u8; 32]; let! sharedOut = unsafe { Span.of(&sharedSecretStorage as Ptr, 32 as usize) }; X25519.sharedSecretTo(privateKey, peerPublicKey, &sharedOut!)?; ``` Both destinations must be exactly 32 bytes and must not overlap either input. The shared-secret path rejects RFC 7748's all-zero, non-contributory result and clears the destination before returning `InvalidPublicKey`. Neither path allocates. ## Curve performance architecture X25519 and Ed25519 share the pure-Vex 5×51 field implementation. Multiplication uses Vex `u128` values, allowing the backend to select native wide multiply instructions without a C/Rust FFI boundary. Squaring has its own symmetric schedule, small coefficients avoid sparse full-field multiplication, and the inversion chain reuses its field slot. On the 2026-08-18 Apple M2 Max O3 development run, X25519 public-key derivation measured 33.8–35.7 µs with zero allocations. Ed25519 uses a constant-flow four-bit window: every table entry is visited in public order and arithmetic limb masks perform the selection, so no secret digit becomes a memory index or branch. The same run measured 1 KiB signing at 159.6–162.3 µs and verification at 125.0–128.6 µs, both with zero allocation. These measurements are regression baselines, not API promises. --- Source: https://vex-lang.org/docs/std/crypto/reference.md # std::crypto API Reference Public declarations reachable through the documented package entry points. Signatures follow the source snapshot; consult the module guide for support and qualification boundaries. ## Application entry points Start with [checked cryptographic facades](docs/std/crypto/index.md), [AEAD ownership and nonce policy](docs/std/crypto/encryption.md), [hashes](docs/std/crypto/hashing.md), and [key derivation/signatures](docs/std/crypto/kdf.md). `export` marks a declaration in its defining source module; it does not classify a raw kernel or test helper as an application-level facade. ### Digest32 Import: `"crypto"`. ```vex export contract Digest32 { reset()!; update(data: str)!; updateRaw(data: RawBuf, len: u64)!; sum(out: Ptr, out_len: u64)!; } ``` ### Mac32 Import: `"crypto"`. ```vex export contract Mac32 { reset()!; update(data: str)!; updateRaw(data: RawBuf, len: u64)!; final(out: Ptr, out_len: u64)!; } ``` ### ChaCha20Poly1305 Import: `"crypto"`. ```vex export struct ChaCha20Poly1305 ``` ### Aes128Gcm Import: `"crypto"`. ```vex export struct Aes128Gcm ``` ### Aes256Gcm Import: `"crypto"`. ```vex export struct Aes256Gcm ``` ### HkdfSha256 Import: `"crypto"`. ```vex export struct HkdfSha256 ``` ### HkdfSha384 Import: `"crypto"`. ```vex export struct HkdfSha384 ``` ### Pbkdf2Sha256 Import: `"crypto"`. ```vex export struct Pbkdf2Sha256 ``` ### X25519 Import: `"crypto"`. ```vex export struct X25519 ``` ### Ed25519 Import: `"crypto"`. ```vex export struct Ed25519 ``` ### Argon2Parameters Import: `"crypto"`. ```vex export struct Argon2Parameters ``` Public Argon2 cost policy. Memory is expressed in KiB, matching RFC 9106. **Implements:** `Copy` **Public fields:** - `timeCost`: `u64` - `memoryKiB`: `u64` - `parallelism`: `u64` ### Argon2id Import: `"crypto"`. ```vex export struct Argon2id ``` Type-safe Argon2id facade. RawBuf kernels remain available for protocol implementations, while application code should use this Span/Vec surface. ### CryptoError Import: `"crypto"`. ```vex export struct CryptoError ``` Allocation-free cryptographic operation failure. `requested` and `limit` are byte counts unless the operation documents another unit. **Implements:** `Copy` **Public fields:** - `kind`: `CryptoErrorKind` - `requested`: `u64` - `limit`: `u64` ### Fe25519 Import: `"crypto"`. ```vex export struct Fe25519 ``` Field element in 5x51-bit limbs **Implements:** `Copy` **Public fields:** - `l`: `[u64; 5]` ### Poly1305 Import: `"crypto"`. ```vex export struct Poly1305 ``` ### Sha1 Import: `"crypto"`. ```vex export struct Sha1 ``` ### Sha256 Import: `"crypto"`. ```vex export struct Sha256 ``` ### Sha512 Import: `"crypto"`. ```vex export struct Sha512 ``` **Public fields:** - `h`: `[u64; 8]` - `buf`: `[u8; 128]` - `bufLen`: `u64` - `totalLen`: `u64` ### Sha384 Import: `"crypto"`. ```vex export struct Sha384 ``` SHA-384 shares SHA-512's compression function and block size, but uses the independent FIPS 180-4 initial state and truncates the digest to 48 bytes. Keeping a single `Sha512` engine avoids a second cryptographic kernel drifting away from the standard. ### CryptoErrorKind Import: `"crypto"`. ```vex export enum CryptoErrorKind ``` **Variants:** - `InvalidKeyLength` - `InvalidNonceLength` - `InvalidTagLength` - `InvalidSignatureLength` - `MessageTooLarge` - `CounterExhausted` - `AuthenticationFailed` - `InvalidPublicKey` - `InvalidParameter` - `OutOfMemory` ### aeadEncrypt Import: `"crypto"`. ```vex export fn aeadEncrypt(key: RawBuf, nonce: RawBuf, aad: RawBuf, aadLen: u64, plaintext: RawBuf, ptLen: u64, out: RawBuf): Result<[u8; 16], CryptoError> ``` Encrypt with ChaCha20-Poly1305 AEAD (RFC 8439). key: 32 bytes, nonce: 12 bytes. Writes ciphertext to `out` (same length as plaintext). Returns 16-byte authentication tag. **Returns:** `Result<[u8; 16], CryptoError>` ### aeadDecrypt Import: `"crypto"`. ```vex export fn aeadDecrypt(key: RawBuf, nonce: RawBuf, aad: RawBuf, aadLen: u64, ciphertext: RawBuf, ctLen: u64, tag: RawBuf, out: RawBuf): Result<(), CryptoError> ``` Decrypt with ChaCha20-Poly1305 AEAD (RFC 8439). key: 32 bytes, nonce: 12 bytes. Returns `Ok(())` after authentication and decryption, or a typed `CryptoError`. Authentication failure clears `ctLen` output bytes. The early oversized-AAD error returns before touching output; do not infer that every error clears it. This raw API cannot validate allocation extents: callers must supply the exact readable/writable byte ranges below and uphold aliasing requirements. Prefer the checked `ChaCha20Poly1305` facade for application records. **Returns:** `Result<(), CryptoError>` ### aes256ExpandKey Import: `"crypto"`. ```vex export fn aes256ExpandKey(key: RawBuf): [u8; 240] ``` Expand an AES-256 key once for internal multi-block constructions. Callers must securely erase the returned 240-byte schedule. **Returns:** `[u8; 240]` ### aes128ExpandKey Import: `"crypto"`. ```vex export fn aes128ExpandKey(key: RawBuf): [u8; 176] ``` Expand an AES-128 key once for internal multi-block constructions. Callers must securely erase the returned 176-byte schedule. **Returns:** `[u8; 176]` ### aes128EncryptBlockWithRk Import: `"crypto"`. ```vex export fn aes128EncryptBlockWithRk(rkb: RawBuf, input: RawBuf, out: RawBuf) ``` ### aes128EncryptBlock Import: `"crypto"`. ```vex export fn aes128EncryptBlock(key: RawBuf, input: RawBuf, out: RawBuf) ``` AES-128 encrypt one 16-byte block. key: 16 bytes, input: 16 bytes. ### aes256EncryptBlockWithRk Import: `"crypto"`. ```vex export fn aes256EncryptBlockWithRk(rkb: RawBuf, input: RawBuf, out: RawBuf) ``` ### aes256EncryptBlock Import: `"crypto"`. ```vex export fn aes256EncryptBlock(key: RawBuf, input: RawBuf, out: RawBuf) ``` AES-256 encrypt one 16-byte block. key: 32 bytes, input: 16 bytes. ### aes256CtrXorWithRk Import: `"crypto"`. ```vex export fn aes256CtrXorWithRk(rkb: RawBuf, counter0: RawBuf, input: RawBuf, len: u64, out: RawBuf): Result<(), CryptoError> ``` AES-256 CTR using a caller-owned expanded schedule. **Returns:** `Result<(), CryptoError>` ### aes256CtrXor Import: `"crypto"`. ```vex export fn aes256CtrXor(key: RawBuf, counter0: RawBuf, input: RawBuf, len: u64, out: RawBuf): Result<(), CryptoError> ``` AES-256 CTR XOR helper (counter block is 16-byte J0-like block). Uses inc32 in big-endian per GCM convention. **Returns:** `Result<(), CryptoError>` ### aes128CtrXorWithRk Import: `"crypto"`. ```vex export fn aes128CtrXorWithRk(rkb: RawBuf, counter0: RawBuf, input: RawBuf, len: u64, out: RawBuf): Result<(), CryptoError> ``` AES-128 CTR XOR helper (counter block is a 16-byte J0-like block). Like AES-GCM's CTR construction, the supplied block is incremented before it is encrypted for the first segment. **Returns:** `Result<(), CryptoError>` ### aes128CtrXor Import: `"crypto"`. ```vex export fn aes128CtrXor(key: RawBuf, counter0: RawBuf, input: RawBuf, len: u64, out: RawBuf): Result<(), CryptoError> ``` **Returns:** `Result<(), CryptoError>` ### aes128CtrXorFromInitialCounter Import: `"crypto"`. ```vex export fn aes128CtrXorFromInitialCounter(key: RawBuf, counter0: RawBuf, input: RawBuf, len: u64, out: RawBuf) ``` ### aes128GcmEncrypt Import: `"crypto"`. ```vex export fn aes128GcmEncrypt(key: RawBuf, nonce12: RawBuf, aad: RawBuf, aadLen: u64, plaintext: RawBuf, ptLen: u64, out: RawBuf): Result<[u8; 16], CryptoError> ``` AES-128-GCM encrypt with the NIST 96-bit nonce fast path. **Returns:** `Result<[u8; 16], CryptoError>` ### aes128GcmDecrypt Import: `"crypto"`. ```vex export fn aes128GcmDecrypt(key: RawBuf, nonce12: RawBuf, aad: RawBuf, aadLen: u64, ciphertext: RawBuf, ctLen: u64, tag: RawBuf, out: RawBuf): Result<(), CryptoError> ``` AES-128-GCM authenticated decryption. Plaintext is released only after the complete tag has been verified in constant time. **Returns:** `Result<(), CryptoError>` ### aes256GcmEncrypt Import: `"crypto"`. ```vex export fn aes256GcmEncrypt(key: RawBuf, nonce12: RawBuf, aad: RawBuf, aadLen: u64, plaintext: RawBuf, ptLen: u64, out: RawBuf): Result<[u8; 16], CryptoError> ``` AES-256-GCM encrypt with one key expansion per complete operation. **Returns:** `Result<[u8; 16], CryptoError>` ### aes256GcmDecrypt Import: `"crypto"`. ```vex export fn aes256GcmDecrypt(key: RawBuf, nonce12: RawBuf, aad: RawBuf, aadLen: u64, ciphertext: RawBuf, ctLen: u64, tag: RawBuf, out: RawBuf): Result<(), CryptoError> ``` **Returns:** `Result<(), CryptoError>` ### argon2idDerive Import: `"crypto"`. ```vex export fn argon2idDerive(password: RawBuf, pwdLen: u64, salt: RawBuf, saltLen: u64, timeCost: u64, memoryKiB: u64, parallelism: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` Argon2id derivation (recommended default). **Returns:** `Result<(), CryptoError>` ### argon2idDeriveEx Import: `"crypto"`. ```vex export fn argon2idDeriveEx(password: RawBuf, pwdLen: u64, salt: RawBuf, saltLen: u64, secret: RawBuf, secretLen: u64, ad: RawBuf, adLen: u64, timeCost: u64, memoryKiB: u64, parallelism: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` Argon2id derivation with optional secret/ad fields (RFC-style inputs). **Returns:** `Result<(), CryptoError>` ### argon2iDerive Import: `"crypto"`. ```vex export fn argon2iDerive(password: RawBuf, pwdLen: u64, salt: RawBuf, saltLen: u64, timeCost: u64, memoryKiB: u64, parallelism: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` Argon2i derivation (data-independent indexing). **Returns:** `Result<(), CryptoError>` ### argon2iDeriveEx Import: `"crypto"`. ```vex export fn argon2iDeriveEx(password: RawBuf, pwdLen: u64, salt: RawBuf, saltLen: u64, secret: RawBuf, secretLen: u64, ad: RawBuf, adLen: u64, timeCost: u64, memoryKiB: u64, parallelism: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` Argon2i derivation with optional secret/ad fields. **Returns:** `Result<(), CryptoError>` ### argon2dDerive Import: `"crypto"`. ```vex export fn argon2dDerive(password: RawBuf, pwdLen: u64, salt: RawBuf, saltLen: u64, timeCost: u64, memoryKiB: u64, parallelism: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` Argon2d derivation (data-dependent indexing). **Returns:** `Result<(), CryptoError>` ### argon2dDeriveEx Import: `"crypto"`. ```vex export fn argon2dDeriveEx(password: RawBuf, pwdLen: u64, salt: RawBuf, saltLen: u64, secret: RawBuf, secretLen: u64, ad: RawBuf, adLen: u64, timeCost: u64, memoryKiB: u64, parallelism: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` Argon2d derivation with optional secret/ad fields. **Returns:** `Result<(), CryptoError>` ### base64Encode Import: `"crypto"`. ```vex export fn base64Encode(src: RawBuf, len: u64): string ``` Base64 encode raw bytes (RFC 4648, padded). **Returns:** `string` ### base64EncodeString Import: `"crypto"`. ```vex export fn base64EncodeString(s: str): string ``` Base64 encode string bytes as UTF-8 byte sequence. **Returns:** `string` ### blake2bTo Import: `"crypto"`. ```vex export fn blake2bTo(data: RawBuf, len: u64, out: Ptr, outLen: u64) ``` Compute BLAKE2b hash to caller-provided output buffer. outLen must be in [1, 64]. ### blake2bHex Import: `"crypto"`. ```vex export fn blake2bHex(data: str): string ``` **Returns:** `string` ### ctEq Import: `"crypto"`. ```vex export fn ctEq(a: RawBuf, aLen: u64, b: RawBuf, bLen: u64): bool ``` Constant-time equality over two byte slices (64-bit SWAR accelerated). Returns false on length mismatch. **Returns:** `bool` ### xorInto Import: `"crypto"`. ```vex export fn xorInto(dst: RawBuf, a: RawBuf, b: RawBuf, len: u64) ``` XOR two sources into destination: dst[i] = a[i] ^ b[i] (64-bit SWAR accelerated) ### xorInPlace Import: `"crypto"`. ```vex export fn xorInPlace(dst: RawBuf, src: RawBuf, len: u64) ``` In-place XOR: dst[i] ^= src[i] (64-bit SWAR accelerated) ### zeroize Import: `"crypto"`. ```vex export fn zeroize(buf: RawBuf, len: u64) ``` Zeroize sensitive buffer memory. The compiler lowers this to a volatile memset so the stores survive dead-store elimination before deallocation. ### chacha20Block Import: `"crypto"`. ```vex export fn chacha20Block(key: RawBuf, nonce: RawBuf, counter: u32, out: RawBuf) ``` Generate one 64-byte ChaCha20 block. ### chacha20Xor Import: `"crypto"`. ```vex export fn chacha20Xor(out: RawBuf, input: RawBuf, len: u64, key: RawBuf, nonce: RawBuf, counter: u32): Result<(), CryptoError> ``` XOR stream with input using 4-way SIMD parallel block pass (256 bytes per iteration). **Returns:** `Result<(), CryptoError>` ### pointIdentity Import: `"crypto"`. ```vex export fn pointIdentity(out: &ExtPoint!) ``` ### pointDouble Import: `"crypto"`. ```vex export fn pointDouble(p: &ExtPoint, out: &ExtPoint!) ``` ### pointAdd Import: `"crypto"`. ```vex export fn pointAdd(p: &ExtPoint, q: &ExtPoint, out: &ExtPoint!) ``` ### scalarMul Import: `"crypto"`. ```vex export fn scalarMul(scalar: RawBuf, point: &ExtPoint, out: &ExtPoint!) ``` ### pointEncode Import: `"crypto"`. ```vex export fn pointEncode(p: &ExtPoint, out: RawBuf) ``` ### basepointExt Import: `"crypto"`. ```vex export fn basepointExt(out: &ExtPoint!) ``` ### ed25519PublicKey Import: `"crypto"`. ```vex export fn ed25519PublicKey(pubOut: RawBuf, privateKey: RawBuf) ``` Ed25519 key pair generation. privateKey: 32 random bytes. Writes 32-byte public key to pubOut. ### ed25519Sign Import: `"crypto"`. ```vex export fn ed25519Sign(sigOut: RawBuf, privateKey: RawBuf, message: RawBuf, msgLen: u64) ``` Ed25519 sign a message. Writes 64-byte signature to sigOut. privateKey: 32 bytes, message: raw bytes. ### ed25519SignHex Import: `"crypto"`. ```vex export fn ed25519SignHex(privateKey: RawBuf, message: RawBuf, msgLen: u64): string ``` Ed25519 sign returning hex(signature[64]). **Returns:** `string` ### ed25519Verify Import: `"crypto"`. ```vex export fn ed25519Verify(signature: RawBuf, publicKey: RawBuf, message: RawBuf, msgLen: u64): bool ``` Ed25519 verify: returns true iff signature is valid. **Returns:** `bool` ### ed25519PublicKeyHex Import: `"crypto"`. ```vex export fn ed25519PublicKeyHex(privateKey: RawBuf): string ``` Ed25519 public key generation returning hex. **Returns:** `string` ### ed25519BasepointHex Import: `"crypto"`. ```vex export fn ed25519BasepointHex(): string ``` Diagnostic helper: return encoded Ed25519 basepoint. **Returns:** `string` ### ed25519MulBaseHex Import: `"crypto"`. ```vex export fn ed25519MulBaseHex(scalar: RawBuf): string ``` Diagnostic helper: encode scalar*B for a raw 32-byte scalar. **Returns:** `string` ### feZero Import: `"crypto"`. ```vex export fn feZero(out: &Fe25519!) ``` ### feOne Import: `"crypto"`. ```vex export fn feOne(out: &Fe25519!) ``` ### feCopy Import: `"crypto"`. ```vex export fn feCopy(f: &Fe25519, out: &Fe25519!) ``` Copy a field element (creates a new value from a reference) ### feFromBytes Import: `"crypto"`. ```vex export fn feFromBytes(b: RawBuf, out: &Fe25519!) ``` ### feToBytes Import: `"crypto"`. ```vex export fn feToBytes(f: &Fe25519, out: RawBuf) ``` ### feAdd Import: `"crypto"`. ```vex export fn feAdd(a: &Fe25519, b: &Fe25519, out: &Fe25519!) ``` ### feSub Import: `"crypto"`. ```vex export fn feSub(a: &Fe25519, b: &Fe25519, out: &Fe25519!) ``` ### feMul Import: `"crypto"`. ```vex export fn feMul(a: &Fe25519, b: &Fe25519, out: &Fe25519!) ``` ### feMulSmall Import: `"crypto"`. ```vex export fn feMulSmall(a: &Fe25519, coefficient: u64, out: &Fe25519!) ``` Multiply by a single machine-word coefficient. This is the canonical constant/small-coefficient path for field formulas: it preserves the same reduction semantics as `feMul` without manufacturing a sparse field element and paying for its zero products. ### feSq Import: `"crypto"`. ```vex export fn feSq(a: &Fe25519, out: &Fe25519!) ``` ### feInvert Import: `"crypto"`. ```vex export fn feInvert(z: &Fe25519, out: &Fe25519!) ``` ### feCSwap Import: `"crypto"`. ```vex export fn feCSwap(a: &Fe25519!, b: &Fe25519!, swap: u64) ``` ### hexEncode Import: `"crypto"`. ```vex export fn hexEncode(src: RawBuf, len: u64): string ``` Encode raw bytes to lowercase hex string. **Returns:** `string` ### hexDecodeTo Import: `"crypto"`. ```vex export fn hexDecodeTo(hex: str, out: RawBuf, outCap: u64): u64 ``` Decode hex string to bytes into caller-provided output buffer. Returns number of written bytes, or 0 on invalid hex/out-of-capacity. **Returns:** `u64` ### hkdfExtract Import: `"crypto"`. ```vex export fn hkdfExtract(salt: RawBuf, saltLen: u64, ikm: RawBuf, ikmLen: u64, prk: Ptr): Result<(), CryptoError> ``` HKDF-Extract: PRK = HMAC-SHA256(salt, IKM) If salt is empty (saltLen==0), uses 32 zero bytes as default salt. **Returns:** `Result<(), CryptoError>` ### hkdfExpand Import: `"crypto"`. ```vex export fn hkdfExpand(prk: RawBuf, prkLen: u64, info: RawBuf, infoLen: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` HKDF-Expand: derive output keying material from PRK. prk: 32 bytes (from hkdfExtract), outLen ≤ 255*32 = 8160 bytes. **Returns:** `Result<(), CryptoError>` ### hkdf Import: `"crypto"`. ```vex export fn hkdf(salt: RawBuf, saltLen: u64, ikm: RawBuf, ikmLen: u64, info: RawBuf, infoLen: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` One-shot HKDF: Extract + Expand. **Returns:** `Result<(), CryptoError>` ### hkdfExtractSha384 Import: `"crypto"`. ```vex export fn hkdfExtractSha384(salt: RawBuf, saltLen: u64, ikm: RawBuf, ikmLen: u64, prk: Ptr): Result<(), CryptoError> ``` HKDF-Extract with HMAC-SHA384. An empty salt is represented by one SHA-384 digest-length block of zero bytes, as required by RFC 5869. **Returns:** `Result<(), CryptoError>` ### hkdfExpandSha384 Import: `"crypto"`. ```vex export fn hkdfExpandSha384(prk: RawBuf, prkLen: u64, info: RawBuf, infoLen: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` HKDF-Expand with HMAC-SHA384. The RFC 5869 limit is 255 digest blocks. **Returns:** `Result<(), CryptoError>` ### hkdfSha384 Import: `"crypto"`. ```vex export fn hkdfSha384(salt: RawBuf, saltLen: u64, ikm: RawBuf, ikmLen: u64, info: RawBuf, infoLen: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` **Returns:** `Result<(), CryptoError>` ### hmacSha1To Import: `"crypto"`. ```vex export fn hmacSha1To(key: RawBuf, keyLen: u64, data: RawBuf, dataLen: u64, out: Ptr) ``` HMAC-SHA1 (RFC 2104). SHA-1 is retained solely for interoperating with protocol profiles such as SRTP AES_CM_128_HMAC_SHA1_80; new application protocols should use HMAC-SHA256 instead. ### hmacSha256To Import: `"crypto"`. ```vex export fn hmacSha256To(key: RawBuf, keyLen: u64, data: RawBuf, dataLen: u64, out: Ptr) ``` ### hmacSha256PartsTo Import: `"crypto"`. ```vex export fn hmacSha256PartsTo(key: RawBuf, keyLen: u64, first: RawBuf, firstLen: u64, second: RawBuf, secondLen: u64, third: RawBuf, thirdLen: u64, out: Ptr) ``` Allocation-free HMAC-SHA256 over three discontiguous byte segments. This is the shared kernel for HKDF/PBKDF2; no secret-bearing concatenation buffer or per-round allocator traffic is required. ### hmacSha384PartsTo Import: `"crypto"`. ```vex export fn hmacSha384PartsTo(key: RawBuf, keyLen: u64, first: RawBuf, firstLen: u64, second: RawBuf, secondLen: u64, third: RawBuf, thirdLen: u64, out: Ptr) ``` Allocation-free HMAC-SHA384 over three discontiguous byte segments. SHA-384 uses SHA-512's 128-byte block size and a 48-byte digest. ### hmacSha384To Import: `"crypto"`. ```vex export fn hmacSha384To(key: RawBuf, keyLen: u64, data: RawBuf, dataLen: u64, out: Ptr) ``` ### hmacSha384Hex Import: `"crypto"`. ```vex export fn hmacSha384Hex(key: str, data: str): string ``` **Returns:** `string` ### hmacSha256Hex Import: `"crypto"`. ```vex export fn hmacSha256Hex(key: str, data: str): string ``` **Returns:** `string` ### hmacVerifySha256Hex Import: `"crypto"`. ```vex export fn hmacVerifySha256Hex(key: str, data: str, expectedHex: str): bool ``` **Returns:** `bool` ### pbkdf2Sha256 Import: `"crypto"`. ```vex export fn pbkdf2Sha256(password: RawBuf, pwdLen: u64, salt: RawBuf, saltLen: u64, iterations: u64, out: RawBuf, outLen: u64): Result<(), CryptoError> ``` PBKDF2 with HMAC-SHA256 as PRF. Password and salt are raw buffers, iterations >= 1, output written to `out`. **Returns:** `Result<(), CryptoError>` ### pbkdf2Sha256Hex Import: `"crypto"`. ```vex export fn pbkdf2Sha256Hex(password: str, salt: str, iterations: u64, dkLen: u64): Result ``` Convenience: PBKDF2-SHA256 with string inputs, returns hex-encoded output. **Returns:** `Result` ### newPoly1305 Import: `"crypto"`. ```vex export fn newPoly1305(key: RawBuf, key_len: usize): Poly1305 ``` **Returns:** `Poly1305` ### poly1305Auth Import: `"crypto"`. ```vex export fn poly1305Auth(key: RawBuf, key_len: usize, message: RawBuf, msg_len: usize): [u8; 16] ``` **Returns:** `[u8; 16]` ### newSha1 Import: `"crypto"`. ```vex export fn newSha1(): Sha1 ``` **Returns:** `Sha1` ### sha1To Import: `"crypto"`. ```vex export fn sha1To(data: RawBuf, len: u64, out: Ptr) ``` ### sha1Hex Import: `"crypto"`. ```vex export fn sha1Hex(data: str): string ``` **Returns:** `string` ### newSha256 Import: `"crypto"`. ```vex export fn newSha256(): Sha256 ``` **Returns:** `Sha256` ### sha256To Import: `"crypto"`. ```vex export fn sha256To(data: RawBuf, len: u64, out: Ptr) ``` ### sha256Hex Import: `"crypto"`. ```vex export fn sha256Hex(data: str): string ``` **Returns:** `string` ### sha512Hex Import: `"crypto"`. ```vex export fn sha512Hex(data: str): string ``` **Returns:** `string` ### sha512To Import: `"crypto"`. ```vex export fn sha512To(data: RawBuf, len: u64, out: Ptr) ``` ### sha384Hex Import: `"crypto"`. ```vex export fn sha384Hex(data: str): string ``` **Returns:** `string` ### sha384To Import: `"crypto"`. ```vex export fn sha384To(data: RawBuf, len: u64, out: Ptr) ``` ### xorBlocks Import: `"crypto"`. ```vex export fn xorBlocks(dst: RawBuf, a: RawBuf, b: RawBuf, bytes: u64) ``` ### addU32Blocks Import: `"crypto"`. ```vex export fn addU32Blocks(dst: RawBuf, a: RawBuf, b: RawBuf, words: u64) ``` ### rotrU32Blocks Import: `"crypto"`. ```vex export fn rotrU32Blocks(dst: RawBuf, src: RawBuf, words: u64, shift: u32) ``` ### x25519 Import: `"crypto"`. ```vex export fn x25519(out: RawBuf, scalar: RawBuf, point: RawBuf) ``` Scalar multiplication: result = scalar * point on Curve25519. Both scalar and point are 32 bytes (little-endian). Result written to out (32 bytes). ### x25519Basepoint Import: `"crypto"`. ```vex export fn x25519Basepoint(out: RawBuf, privateKey: RawBuf) ``` Generate X25519 public key from private key. Private key: 32 random bytes (will be clamped internally). Uses basepoint u=9. ### x25519Hex Import: `"crypto"`. ```vex export fn x25519Hex(myPrivate: RawBuf, theirPublic: RawBuf): string ``` Compute X25519 shared secret, returns hex string. **Returns:** `string` ### ChaCha20Poly1305.sealDetachedInto ```vex export fn ChaCha20Poly1305.sealDetachedInto(key: Span, nonce: Span, aad: Span, plaintext: Span, output: &Vec!): Result<[u8; 16], CryptoError> ``` Encrypt into caller-reusable storage and return a detached 128-bit tag. Source/output overlap is staged before any resize; output is empty on error. **Returns:** `Result<[u8; 16], CryptoError>` ### ChaCha20Poly1305.openDetachedInto ```vex export fn ChaCha20Poly1305.openDetachedInto(key: Span, nonce: Span, aad: Span, ciphertext: Span, tag: Span, output: &Vec!): Result ``` Authenticate before releasing plaintext into caller-reusable storage. The output is securely erased and emptied on every failure. **Returns:** `Result` ### ChaCha20Poly1305.sealInto ```vex export fn ChaCha20Poly1305.sealInto(key: Span, nonce: Span, aad: Span, plaintext: Span, output: &Vec!): Result ``` Encrypt to the conventional `ciphertext || tag` representation. **Returns:** `Result` ### ChaCha20Poly1305.openInto ```vex export fn ChaCha20Poly1305.openInto(key: Span, nonce: Span, aad: Span, sealed: Span, output: &Vec!): Result ``` Open a conventional `ciphertext || tag` value. **Returns:** `Result` ### ChaCha20Poly1305.seal ```vex export fn ChaCha20Poly1305.seal(key: Span, nonce: Span, aad: Span, plaintext: Span): Result, CryptoError> ``` **Returns:** `Result, CryptoError>` ### ChaCha20Poly1305.open ```vex export fn ChaCha20Poly1305.open(key: Span, nonce: Span, aad: Span, sealed: Span): Result, CryptoError> ``` **Returns:** `Result, CryptoError>` ### Aes256Gcm.sealDetachedInto ```vex export fn Aes256Gcm.sealDetachedInto(key: Span, nonce: Span, aad: Span, plaintext: Span, output: &Vec!): Result<[u8; 16], CryptoError> ``` AES-256-GCM detached encryption with the checked/reusable contract. **Returns:** `Result<[u8; 16], CryptoError>` ### Aes256Gcm.openDetachedInto ```vex export fn Aes256Gcm.openDetachedInto(key: Span, nonce: Span, aad: Span, ciphertext: Span, tag: Span, output: &Vec!): Result ``` **Returns:** `Result` ### Aes256Gcm.sealInto ```vex export fn Aes256Gcm.sealInto(key: Span, nonce: Span, aad: Span, plaintext: Span, output: &Vec!): Result ``` **Returns:** `Result` ### Aes256Gcm.openInto ```vex export fn Aes256Gcm.openInto(key: Span, nonce: Span, aad: Span, sealed: Span, output: &Vec!): Result ``` **Returns:** `Result` ### Aes256Gcm.seal ```vex export fn Aes256Gcm.seal(key: Span, nonce: Span, aad: Span, plaintext: Span): Result, CryptoError> ``` **Returns:** `Result, CryptoError>` ### Aes256Gcm.open ```vex export fn Aes256Gcm.open(key: Span, nonce: Span, aad: Span, sealed: Span): Result, CryptoError> ``` **Returns:** `Result, CryptoError>` ### Aes128Gcm.sealDetachedInto ```vex export fn Aes128Gcm.sealDetachedInto(key: Span, nonce: Span, aad: Span, plaintext: Span, output: &Vec!): Result<[u8; 16], CryptoError> ``` AES-128-GCM detached encryption for protocols such as TLS 1.3. **Returns:** `Result<[u8; 16], CryptoError>` ### Aes128Gcm.openDetachedInto ```vex export fn Aes128Gcm.openDetachedInto(key: Span, nonce: Span, aad: Span, ciphertext: Span, tag: Span, output: &Vec!): Result ``` **Returns:** `Result` ### Aes128Gcm.sealInto ```vex export fn Aes128Gcm.sealInto(key: Span, nonce: Span, aad: Span, plaintext: Span, output: &Vec!): Result ``` **Usage contract:** The combined result is ciphertext followed by the tag; it does not contain the nonce. Keep nonce allocation and key lifetime at the application boundary. See [AEAD nonce lifecycle](docs/std/crypto/encryption.md#nonce-and-key-lifecycle). **Returns:** `Result` ### Aes128Gcm.openInto ```vex export fn Aes128Gcm.openInto(key: Span, nonce: Span, aad: Span, sealed: Span, output: &Vec!): Result ``` **Usage contract:** Only a successful result authenticates and releases plaintext. A valid tag does not itself enforce replay policy. Inputs are borrowed; the successful owning output can outlive them. **Returns:** `Result` ### Aes128Gcm.seal ```vex export fn Aes128Gcm.seal(key: Span, nonce: Span, aad: Span, plaintext: Span): Result, CryptoError> ``` **Usage contract:** The combined result is ciphertext followed by the tag; it does not contain the nonce. Keep nonce allocation and key lifetime at the application boundary. See [AEAD nonce lifecycle](docs/std/crypto/encryption.md#nonce-and-key-lifecycle). **Returns:** `Result, CryptoError>` ### Aes128Gcm.open ```vex export fn Aes128Gcm.open(key: Span, nonce: Span, aad: Span, sealed: Span): Result, CryptoError> ``` **Usage contract:** Only a successful result authenticates and releases plaintext. A valid tag does not itself enforce replay policy. Inputs are borrowed; the successful owning output can outlive them. **Returns:** `Result, CryptoError>` ### HkdfSha256.extract ```vex export fn HkdfSha256.extract(salt: Span, inputKeyMaterial: Span): Result<[u8; 32], CryptoError> ``` Extract a fixed 32-byte pseudorandom key without exposing raw pointers. **Returns:** `Result<[u8; 32], CryptoError>` ### HkdfSha256.expandInto ```vex export fn HkdfSha256.expandInto(prk: Span, info: Span, outputLength: usize, output: &Vec!): Result ``` Expand a 32-byte PRK into caller-reusable storage. RFC 5869's 8160-byte maximum is enforced before allocation or output mutation. **Returns:** `Result` ### HkdfSha256.deriveInto ```vex export fn HkdfSha256.deriveInto(salt: Span, inputKeyMaterial: Span, info: Span, outputLength: usize, output: &Vec!): Result ``` One-shot HKDF-SHA256 derivation into caller-reusable storage. **Returns:** `Result` ### HkdfSha256.derive ```vex export fn HkdfSha256.derive(salt: Span, inputKeyMaterial: Span, info: Span, outputLength: usize): Result, CryptoError> ``` **Usage contract:** Returns an independent owning byte vector. Length failure is typed; use distinct context values for distinct protocol purposes. See [HKDF guidance](docs/std/crypto/kdf.md#hkdf). **Returns:** `Result, CryptoError>` ### HkdfSha384.extract ```vex export fn HkdfSha384.extract(salt: Span, inputKeyMaterial: Span): Result<[u8; 48], CryptoError> ``` Extract a fixed 48-byte SHA-384 pseudorandom key through safe spans. **Returns:** `Result<[u8; 48], CryptoError>` ### HkdfSha384.expandInto ```vex export fn HkdfSha384.expandInto(prk: Span, info: Span, outputLength: usize, output: &Vec!): Result ``` Expand a 48-byte PRK into caller-reusable storage. RFC 5869's 12240-byte SHA-384 maximum is enforced before allocation or output mutation. **Returns:** `Result` ### HkdfSha384.deriveInto ```vex export fn HkdfSha384.deriveInto(salt: Span, inputKeyMaterial: Span, info: Span, outputLength: usize, output: &Vec!): Result ``` **Returns:** `Result` ### HkdfSha384.derive ```vex export fn HkdfSha384.derive(salt: Span, inputKeyMaterial: Span, info: Span, outputLength: usize): Result, CryptoError> ``` **Returns:** `Result, CryptoError>` ### Pbkdf2Sha256.deriveInto ```vex export fn Pbkdf2Sha256.deriveInto(password: Span, salt: Span, iterations: u64, outputLength: usize, output: &Vec!): Result ``` PBKDF2-HMAC-SHA256 into reusable storage. Iteration count and RFC output block limit are validated before output mutation; all intermediate U/T blocks are securely erased by the kernel. **Returns:** `Result` ### Pbkdf2Sha256.derive ```vex export fn Pbkdf2Sha256.derive(password: Span, salt: Span, iterations: u64, outputLength: usize): Result, CryptoError> ``` **Returns:** `Result, CryptoError>` ### X25519.publicKeyTo ```vex export fn X25519.publicKeyTo(privateKey: Span, output: &Span!): Result ``` Derive an X25519 public key from an exact 32-byte private scalar. **Returns:** `Result` ### X25519.publicKeyInto ```vex export fn X25519.publicKeyInto(privateKey: Span, output: &Vec!): Result ``` Derive an X25519 public key into reusable owned storage. **Returns:** `Result` ### X25519.publicKey ```vex export fn X25519.publicKey(privateKey: Span): Result<[u8; 32], CryptoError> ``` **Returns:** `Result<[u8; 32], CryptoError>` ### X25519.sharedSecretTo ```vex export fn X25519.sharedSecretTo(privateKey: Span, peerPublicKey: Span, output: &Span!): Result ``` **Usage contract:** Returns 32 on success. The all-zero shared result clears the destination and returns InvalidPublicKey. Dimension/overlap checks run before the operation; the raw span still requires valid live backing storage. X25519 alone does not authenticate the peer. Compute a contributory X25519 shared secret. RFC 7748 permits callers to reject an all-zero result; this safe API always rejects it in constant time so low-order public keys cannot silently collapse the handshake secret. The caller-owned output is exact-width, allocation-free, and zeroed before returning `InvalidPublicKey` for a non-contributory peer. **Returns:** `Result` ### X25519.sharedSecretInto ```vex export fn X25519.sharedSecretInto(privateKey: Span, peerPublicKey: Span, output: &Vec!): Result ``` Compute a contributory X25519 shared secret into reusable owned storage. **Returns:** `Result` ### X25519.sharedSecret ```vex export fn X25519.sharedSecret(privateKey: Span, peerPublicKey: Span): Result<[u8; 32], CryptoError> ``` **Returns:** `Result<[u8; 32], CryptoError>` ### Ed25519.publicKey ```vex export fn Ed25519.publicKey(privateSeed: Span): Result<[u8; 32], CryptoError> ``` Derive the RFC 8032 public key for an exact 32-byte private seed. **Returns:** `Result<[u8; 32], CryptoError>` ### Ed25519.signInto ```vex export fn Ed25519.signInto(privateSeed: Span, message: Span, output: &Vec!): Result ``` Deterministically sign a message into caller-reusable storage. The private seed and message may alias the output; both are staged before resize. **Returns:** `Result` ### Ed25519.sign ```vex export fn Ed25519.sign(privateSeed: Span, message: Span): Result<[u8; 64], CryptoError> ``` **Returns:** `Result<[u8; 64], CryptoError>` ### Ed25519.verify ```vex export fn Ed25519.verify(publicKey: Span, message: Span, signature: Span): Result ``` **Usage contract:** Accept only Ok(true). Ok(false) means signature rejection; invalid dimensions produce a typed error. Public-key identity/trust is a separate application responsibility. Strict verification: canonical encodings, canonical S, and non-small-order R/public-key points are required. Dimension errors are typed; a well-formed but invalid signature returns `Ok(false)`. **Returns:** `Result` ### Argon2Parameters.new ```vex export fn Argon2Parameters.new(timeCost: u64, memoryKiB: u64, parallelism: u64): Argon2Parameters ``` **Returns:** `Argon2Parameters` ### Argon2Parameters.recommended ```vex export fn Argon2Parameters.recommended(): Argon2Parameters ``` RFC 9106's memory-constrained recommendation: 64 MiB, three passes and four lanes. Applications should benchmark and increase memory when their deployment budget permits it. **Returns:** `Argon2Parameters` ### Argon2id.deriveInto ```vex export fn Argon2id.deriveInto(password: Span, salt: Span, parameters: Argon2Parameters, outputLength: usize, output: &Vec!): Result ``` Derive into caller-reusable storage. Input/output aliases are staged before Vec growth and every failure leaves `output` empty and securely erased. **Returns:** `Result` ### Argon2id.deriveExInto ```vex export fn Argon2id.deriveExInto(password: Span, salt: Span, secret: Span, associatedData: Span, parameters: Argon2Parameters, outputLength: usize, output: &Vec!): Result ``` RFC 9106 extended derivation with an optional secret (pepper) and associated data. The secret is mixed into H0 and is never copied to output. **Returns:** `Result` ### Argon2id.derive ```vex export fn Argon2id.derive(password: Span, salt: Span, parameters: Argon2Parameters, outputLength: usize): Result, CryptoError> ``` **Returns:** `Result, CryptoError>` ### Argon2id.deriveEx ```vex export fn Argon2id.deriveEx(password: Span, salt: Span, secret: Span, associatedData: Span, parameters: Argon2Parameters, outputLength: usize): Result, CryptoError> ``` **Returns:** `Result, CryptoError>` ### CryptoError.new ```vex export fn CryptoError.new(kind: CryptoErrorKind, requested: u64, limit: u64): CryptoError ``` **Returns:** `CryptoError` ### CryptoError.message ```vex export fn (self: &CryptoError) message(): str ``` **Returns:** `str` ### Poly1305.new ```vex export fn Poly1305.new(key: RawBuf, key_len: usize): Poly1305 ``` **Returns:** `Poly1305` ### Poly1305.update ```vex export fn (self: &Poly1305!) update(data: RawBuf, len: usize) ``` ### Poly1305.finalize ```vex export fn (self: &Poly1305!) finalize(): [u8; 16] ``` **Returns:** `[u8; 16]` ### Sha1.new ```vex export fn Sha1.new(): Sha1 ``` **Returns:** `Sha1` ### Sha1.reset ```vex export fn (self: &Sha1!) reset()! ``` **Receiver:** `self: &Sha1!` *(mutable reference)* ### Sha1.update ```vex export fn (self: &Sha1!) update(data: str) ``` ### Sha1.updateRaw ```vex export fn (self: &Sha1!) updateRaw(data: RawBuf, len: u64) ``` ### Sha1.sum ```vex export fn (self: &Sha1!) sum(out: Ptr, out_len: u64)! ``` ### Sha256.new ```vex export fn Sha256.new(): Sha256 ``` **Returns:** `Sha256` ### Sha256.reset ```vex export fn (self: &Sha256!) reset()! ``` **Receiver:** `self: &Sha256!` *(mutable reference)* ### Sha256.update ```vex export fn (self: &Sha256!) update(data: str) ``` ### Sha256.updateRaw ```vex export fn (self: &Sha256!) updateRaw(data: RawBuf, len: u64) ``` ### Sha256.sum ```vex export fn (self: &Sha256!) sum(out: Ptr, out_len: u64)! ``` ### Sha256.snapshotTo ```vex export fn (self: &Sha256) snapshotTo(out: Ptr, outLen: u64): bool ``` Writes the digest of the current state without consuming or finalizing it. Hash-state cloning is deliberately explicit instead of making `Sha256` `Copy`: callers can take protocol snapshots without enabling accidental silent duplication of cryptographic state. The temporary state is erased before this function returns. **Returns:** `bool` ### Sha512.new ```vex export fn Sha512.new(): Sha512 ``` **Returns:** `Sha512` ### Sha512.init ```vex export fn (self: &Sha512!) init() ``` **Receiver:** `self: &Sha512!` *(mutable reference)* ### Sha384.new ```vex export fn Sha384.new(): Sha384 ``` **Returns:** `Sha384` ### Sha512.update512 ```vex export fn (self: &Sha512!) update512(data: str) ``` ### Sha512.updateRaw512 ```vex export fn (self: &Sha512!) updateRaw512(data: RawBuf, len: u64) ``` ### Sha512.sum512 ```vex export fn (self: &Sha512!) sum512(out: Ptr, outLen: u64) ``` ### Sha384.update384 ```vex export fn (self: &Sha384!) update384(data: str) ``` ### Sha384.updateRaw384 ```vex export fn (self: &Sha384!) updateRaw384(data: RawBuf, len: u64) ``` ### Sha384.sum384 ```vex export fn (self: &Sha384!) sum384(out: Ptr, outLen: u64) ``` ### Sha384.reset384 ```vex export fn (self: &Sha384!) reset384() ``` Resets a SHA-384 state to its FIPS 180-4 initial value. **Receiver:** `self: &Sha384!` *(mutable reference)* ### Sha384.snapshotTo ```vex export fn (self: &Sha384) snapshotTo(out: Ptr, outLen: u64): bool ``` Writes the digest of the current state without consuming or finalizing it. The explicitly cloned temporary state is erased before returning. --- --- *Generated by vex-doc v2.0 • 2026-10-28* --- Source: https://vex-lang.org/docs/std/db/connection.md # Connections, statements and results ## `Connection` Every constructor returns `Result`. | API | Purpose | |---|---| | `Connection.sqlite(path)` | Open SQLite | | `Connection.postgres(conninfo)` | Open optional PostgreSQL provider | | `Connection.mysql(conninfo)` | Open optional MySQL provider | | `Connection.redis(conninfo)` | Open optional Redis provider | | `Connection.mongo(conninfo)` | Open optional MongoDB provider | | `Connection.open(driver, conninfo)` | Typed generic constructor | | `exec(sql)` | One-shot statement, returning affected rows | | `execParams(sql, params)` | One-shot typed parameter statement | | `query(sql)` | One-shot result cursor | | `queryParams(sql, params)` | One-shot typed parameter cursor | | `queryValue(sql)` | First column as owning `Option` | | `prepare(sql)` | Reusable provider plan | | `beginTransaction()` | RAII transaction guard | `DbCapabilities` exposes only callable public features: `sql()`, `preparedStatements()`, `binaryParams()` and `transactions()`. ## Typed parameters `DbValue` variants are `Null`, `Bool`, `I64`, `F64`, `Text`, `Bytes` and `Json`. Payload lengths are exact; embedded NUL bytes in text parameters are preserved because the native ABI receives an explicit length. ```vex let! params = Vec.new(); params.push(DbValue.Text("Ada".toString())); params.push(DbValue.I64(37 as i64)); match connection.execParams( "INSERT INTO users (name, age) VALUES (?, ?)", ¶ms, ) { Result.Ok(rows) => $println(rows), Result.Err(err) => $panic(err.message()), } ``` ## `PreparedStatement` Prepared statements are cloneable shared owners. Clones refer to the same native plan. Exactly one `QueryResult` may be active; re-entry returns `DbErrorKind.InvalidState` instead of racing or allocating a second hidden plan. | API | Purpose | |---|---| | `parameterCount()` | Exact placeholder count | | `query()` | Zero-parameter query | | `queryParams(params)` | Typed reusable query | | `exec()` | Zero-parameter execution | | `execParams(params)` | Typed reusable execution | Drop the active result before reusing the statement. The result retains both the statement and connection, so returning a cursor from a helper is safe. ## `QueryResult` | API | Return | |---|---| | `next()` | `Result` | | `rowsAffected()` | `i64` | | `columnCount()` | `usize` | | `columnName(index)` | `Result` | | `columnType(index)` | `Result` | | `isNull(index)` | `Result` | | `length(index)` | `Result` | | `text(index)` | `Result, DbError>` | | `bytes(index)` | `Result>, DbError>` | | `getI64/getF64/getBool(index)` | typed optional scalar | Reading a column before `next()` or outside its bounds returns a typed error. Typed SQLite scalars use native readers; textual providers fall back to allocation-free Vex parsing. Public text and byte results are owning copies. ## Transactions ```vex let! transaction = match connection.beginTransaction() { Result.Ok(value) => value, Result.Err(err) => $panic(err.message()), }; // Execute through transaction.connection(). match transaction.commit() { Result.Ok(_) => { /* committed */ } Result.Err(err) => $panic(err.message()), } ``` An active transaction rolls back on drop. A committed or rolled-back guard rejects a second finish operation. --- Source: https://vex-lang.org/docs/std/db/index.md # `db` — typed database access `db` provides owning connections, result cursors, reusable prepared statements, transactions and a compile-time mapped SQL query builder. ## Provider status | Provider | Public constructor | Availability and evidence | |---|---|---| | SQLite | `Connection.sqlite(path)` | default native provider; local synchronous test evidence | | PostgreSQL | `Connection.postgres(conninfo)` | optional provider; integration matrix pending | | MySQL/MariaDB | `Connection.mysql(conninfo)` | optional provider; integration matrix pending | | Redis | `Connection.redis(conninfo)` | optional provider; integration matrix pending | | MongoDB | `Connection.mongo(conninfo)` | optional provider; integration matrix pending | The checked-in default native artifact contains SQLite and links its platform library. The Vex API calls a native C provider layer; it is not a pure-Vex PostgreSQL driver or an async connection pool. An unavailable provider returns `DbErrorKind.Unsupported`; it never silently falls back to another database. ## Quick start This application fragment opens an in-memory database, creates a table, inserts one parameterized row and reads it back. Place it inside a function; the example terminates on setup failure to keep the successful path visible. A service should return the typed `DbError` to its caller instead of panicking. ```vex import { Connection, DbValue } from "db"; let connection = match Connection.sqlite(":memory:") { Result.Ok(value) => value, Result.Err(err) => $panic(err.message()), }; match connection.exec("CREATE TABLE users (id INTEGER, name TEXT)") { Result.Ok(_) => { /* ready */ } Result.Err(err) => $panic(err.message()), } let! values = Vec.new(); values.push(DbValue.I64(1 as i64)); values.push(DbValue.Text("Ada".toString())); match connection.execParams("INSERT INTO users (id, name) VALUES (?, ?)", &values) { Result.Ok(_) => {}, Result.Err(err) => $panic(err.message()), }; let! rows = match connection.query("SELECT id, name FROM users ORDER BY id") { Result.Ok(value) => value, Result.Err(err) => $panic(err.message()), }; while match rows.next() { Result.Ok(value) => value, Result.Err(err) => $panic(err.message()) } { match rows.text(1 as usize) { Result.Ok(Some(name)) => $println(name), Result.Ok(None) => $println("NULL"), Result.Err(err) => $panic(err.message()), } } ``` The query prints `Ada`. Values are bound separately from SQL text, so a name containing quotes does not change the statement structure. Connections and results use RAII. No `close()` or `free()` call is required. ## Hot-loop performance Prepare repeated SQL once. A `PreparedStatement` reuses the provider plan, parameter scratch storage and native result container: ```vex import { Connection, DbValue } from "db"; let statement = match connection.prepare("SELECT ? + 1") { Result.Ok(value) => value, Result.Err(err) => $panic(err.message()), }; let! params = Vec.new(); params.push(DbValue.I64(41 as i64)); let result = statement.queryParams(¶ms); ``` On the 2026-08-18 M2 Max O3 baseline, prepared select + typed i64 decode is about 244 ns versus 625 ns for one-shot prepare/query/finalize. Prepared update is about 387 ns versus 1.35 us for the one-shot parameterized path. These historical measurements describe that host and workload, not a 0.4.0 release performance guarantee. ## Safety model - SQL values use `DbValue`; raw fragments are explicit. - SQLite accepts exactly one statement per call. - `NULL`, empty text and empty bytes remain distinct. - A cursor owns its connection lifetime. - A prepared cursor also owns its statement lifetime and prevents concurrent reuse of the same native plan. - Text/bytes returned publicly are owning values. Provider row buffers do not escape. See [Connection and prepared statements](docs/std/db/connection.md) and [compile-time ORM](docs/std/db/orm.md). --- Source: https://vex-lang.org/docs/std/db/orm.md # Compile-time SQL mapping with `Db` `Db` maps documented model fields at compile time. There is no runtime field reflection. The current ORM is intentionally a strict SQL core, not a facade that claims joins, relation loading or schema diffing before they exist. ## Models ```vex struct User { public: id: i64 `db:"id" pk:"true"` name: string `db:"name"` email: Option `db:"email"` age: i32 `db:"age"` active: bool `db:"active"` score: f64 `db:"score"` } ``` Supported mapped fields are `string`, `bool`, `i32`, `u32`, `i64`, `f32`, `f64` and `Option` of those types. Fields tagged `rel` are excluded from the flat row/schema mapping. ## Construction and migration ```vex let! users = match Db.of(&connection, "users") { Result.Ok(value) => value, Result.Err(err) => $panic(err.message()), }; match users.autoMigrate() { Result.Ok(_) => { /* CREATE TABLE IF NOT EXISTS completed */ } Result.Err(err) => $panic(err.message()), } ``` `Db.of` accepts only safe unquoted table identifiers and SQL-capable drivers. `autoMigrate` creates a missing table; it is not a schema-diff engine. ## Querying ```vex let! args = Vec.new(); args.push(DbValue.I64(18 as i64)); args.push(DbValue.Bool(true)); match users.filterRaw("age >= ? AND active = ?", &args) { Result.Ok(_) => { /* bound */ } Result.Err(err) => $panic(err.message()), } match users.orderBy("name", false) { Result.Ok(_) => { /* ascending */ } Result.Err(err) => $panic(err.message()), } users.limit(100 as usize).offset(20 as usize); let! output = Vec.new(); match users.find(&output!) { Result.Ok(appended) => $println(appended), Result.Err(err) => $panic(err.message()), } ``` Available operations: | API | Behavior | |---|---| | `filterRaw(clause, arguments)` | Explicit SQL predicate plus typed values | | `filter1Raw(clause, argument)` | One typed predicate value | | `orderBy(column, descending)` | Validated identifier ordering | | `limit(n)` / `offset(n)` | Driver-correct pagination | | `find(out)` | Append decoded rows | | `first(out)` | Decode at most one row | | `countRows()` | Native typed count decode | | `create(value)` | Parameterized insert | | `update(field, value)` | Parameterized update | | `delete()` | Scoped delete | | `allRows()` | Explicitly authorize an unfiltered update/delete | | `beginTransaction()` | Begin through the owned connection | `filterRaw` is named raw because the clause is developer SQL. Values must still travel separately as `DbValue`. Update/delete without a predicate fail unless `allRows()` is called explicitly. ## Deliberate boundaries Relation loading, joins, groups, schema diffs, hooks and a hidden global prepared cache are not current APIs. They remain future work and are not emulated through stringly typed placeholders. --- Source: https://vex-lang.org/docs/std/db/reference.md # `db` API reference This page lists the current public source surface. All fallible operations use `Result`; nullable columns use `Option` inside that result. Import the types from `"db"`. See [provider availability](docs/std/db/index.md#provider-status) before choosing a driver; enum membership does not imply a configured native provider. ## Enums ### `DbDriver` `Sqlite`, `Postgres`, `Mysql`, `Redis`, `Mongo`. ### `DbErrorKind` `Connect`, `Execution`, `NotFound`, `InvalidParameter`, `Unsupported`, `Decode`, `Closed`, `InvalidState`, `OutOfMemory`, `Unknown`. ### `DbValue` `Null`, `Bool(bool)`, `I64(i64)`, `F64(f64)`, `Text(string)`, `Bytes(Vec)`, `Json(string)`. ### `DbColumnType` `Null`, `Bool`, `I64`, `F64`, `Text`, `Bytes`, `Json`, `Unknown`. ## `DbError` - `DbError.new(kind, message)` - `kind()` / `isKind(kind)` - `message()` / `messageView()` - `toString()` / `debug()` - `clone()` ## `DbCapabilities` - `sql()` - `preparedStatements()` - `binaryParams()` - `transactions()` ## `Connection` - constructors: `sqlite`, `postgres`, `mysql`, `redis`, `mongo`, `open` - metadata: `driver`, `capabilities` - one-shot operations: `exec`, `execParams`, `query`, `queryParams`, `queryValue` - reusable operation: `prepare` - transaction: `beginTransaction` - `clone` ## `PreparedStatement` - `parameterCount()` - `query()` / `queryParams(params)` - `exec()` / `execParams(params)` - `clone()` ## `QueryResult` - `rowsAffected()` - `columnCount()` / `columnName(index)` / `columnType(index)` - `next()` - `isNull(index)` / `length(index)` - `text(index)` / `bytes(index)` - `getI64(index)` / `getF64(index)` / `getBool(index)` ## `Transaction` - `isActive()` - `connection()` - `commit()` / `rollback()` An active transaction rolls back on drop. Use explicit `commit()` or `rollback()` when the caller must observe the provider error; drop cannot return a rollback error to application code. ## `Db` - `Db.of(connection, table)` - `filterRaw`, `filter1Raw`, `orderBy`, `limit`, `offset`, `allRows` - `find`, `first`, `countRows` - `create`, `update`, `delete`, `autoMigrate` - `beginTransaction` See [the ORM guide](docs/std/db/orm.md) for supported field types and raw-fragment rules. ## Common result and ownership contracts | Operation | Result | Meaning | | --- | --- | --- | | `Connection.sqlite(path)` | `Result` | Owns the opened provider connection | | `connection.exec(sql)` / `execParams(sql, &values)` | `Result` | Rows affected; bind values separately from SQL structure | | `connection.query(sql)` | `Result` | Owns a cursor and keeps the connection alive | | `connection.prepare(sql)` | `Result` | Reusable provider statement with connection ownership | | `rows.next()` | `Result` | Mutates cursor; false is end-of-rows, not failure | | `rows.text(column)` | `Result, DbError>` | Zero-based column; None is SQL NULL, Some("") is empty text | | `rows.bytes(column)` | `Result>, DbError>` | Owns returned bytes; no borrowed provider row buffer escapes | | `rows.getI64(column)` | `Result, DbError>` | Typed nullable extraction; invalid column/conversion is an error | | `transaction.commit()` / `rollback()` | `Result<(), DbError>` | Mutates the active transaction and reports provider failure | The text/byte results remain valid after advancing or dropping the cursor. `queryValue(sql)` returns `Result, DbError>` as a convenience; use an explicit cursor when row presence and SQL NULL must be distinguished. --- Source: https://vex-lang.org/docs/std/encoding.md # encoding — strict binary and percent codecs The `encoding` package provides RFC 4648 Hex, Base64, Base64URL and Base32 codecs, explicit RFC 3986/form percent decoding, and bounded ASN.1 DER views. `Der.parse`, `Der.elementAt`, `Der.childAt` and primitive accessors are allocation-free. They reject BER indefinite lengths, non-minimal lengths/high tags/OIDs, malformed primitive values, forged offsets, parent-boundary escapes and unbounded direct-child walks with typed offsets. ## Quick start ```vex import { Hex, Base64, Base64Url, Base32, Percent } from "encoding"; let hex = Hex.encode("hello"); // "68656c6c6f" let b64 = Base64.encode("hello"); // "aGVsbG8=" let token = Base64Url.encode("hello"); // "aGVsbG8" let b32 = Base32.encode("foo"); // "MZXW6===" let path = Percent.encode("a+b c/%"); // "a%2Bb%20c%2F%25" ``` ## Decode untrusted input with `Result` ```vex import { Base64, DecodeErrorKind } from "encoding"; let value = match Base64.tryDecode(input) { Result.Ok(decoded) => decoded, Result.Err(error) => { if error.isKind(DecodeErrorKind.InvalidByte) { $println(f"invalid byte at {error.position}"); } return 1; }, }; ``` `tryDecode` is the canonical API. It distinguishes valid empty output from an error and reports a stable category, exact position, offending byte and required capacity where applicable. Convenience `decode` methods return `""` on error. Convenience `decodeTo` methods return `0`. Use them only when the empty-result ambiguity is acceptable. ## Allocation-free output The following fragment uses fixed caller-owned storage. `token` is a `string` and the surrounding function returns a compatible `Result` so `?` can propagate a decode error: ```vex let! storage: [u8; 128] = [0; 128]; let output = RawBuf.of(&storage as Ptr); let written = Base64Url.tryDecodeTo(token.asStr(), output, 128 as u64)?; // Only storage[0..written] contains decoded bytes; keep storage alive while reading it. ``` Strict caller-buffer decoders first validate the complete input and capacity, then write. A failure leaves the output buffer untouched. ## SIMD without a platform-specific API Long Base64 and Base32 inputs use the same public API on every target. The implementation expresses register transforms with ordinary `[u8; 16]` operators, constant `shuffle`, lane-wise shift schedules and `Mask<16>` comparisons. The compiler lowers that semantic graph to the target backend; library code does not branch on CPU names and does not call a C/Rust codec. Complete blocks are loaded only after their exact readable range is proven. Base64 transforms 12 input bytes to 16 output bytes and decodes 16 symbols to 12 bytes. Base32 transforms 10 bytes to 16 symbols and decodes 16 symbols to 10 bytes. Repeating bit roles remain vector data rather than manually unrolled mask pipelines. Exact-capacity tails stay scalar, so vector speed does not weaken bounds or padding rules. Strict decoding remains two-phase: vector validation and length calculation finish before output mutation, then the valid payload is decoded. If a vector contains an invalid lane, only that cold block falls back to scalar inspection to retain the exact `DecodeError.position`. On an Apple M2 Max with O3 and caller-owned 64 KiB buffers, the 2026-08-21 development baseline is approximately 7.85 GB/s Base64 encode, 3.76 GB/s strict Base64 decode, 12.0 GB/s Base32 encode and 3.39 GB/s strict Base32 decode. These are regression baselines for that machine, not cross-platform guarantees. The native assembly gate verifies that AArch64 uses register `tbl` shuffles and `ushl` lane shifts. Optimized entryless/library artifacts run the same stock LLVM O-level pipeline as executables and enforce explicit inline contracts after external-function merging, so the public caller does not retain a hot block-helper call merely because the artifact has no `main`. ## Canonical input rules - `Base64` requires standard alphabet and canonical padding. - `Base64Url` accepts padded and unpadded URL-safe input, but rejects standard `+` and `/` characters. - Base64 and Base32 reject non-zero unused trailing bits. - Base32 accepts uppercase or lowercase alphabet bytes and only RFC 4648 padding shapes. - Hex requires an even number of ASCII hexadecimal digits. These checks reject malformed padding and unused bits. Some accepted spellings still decode to the same bytes: Base64URL accepts both padding styles, and Base32 accepts both letter cases. A protocol requiring one canonical textual representation must choose a spelling and compare against its canonical re-encoding; successful decoding alone does not enforce that policy. ## Percent versus form decoding ```vex import { Percent, FormUrl } from "encoding"; Percent.decode("a+b"); // "a+b" — RFC 3986 FormUrl.decode("a+b"); // "a b" — HTML form semantics ``` Generic URL percent decoding never silently rewrites `+`. Form behavior must be selected explicitly. Exact serializers can plan and fill one destination. This fragment assumes `input: str` and a surrounding `fn main(): i32` for its error returns: ```vex let required = match FormUrl.encodedLength(input) { Ok(n) => n, Err(error) => return error.code(), }; let! output = Vec.zeroedBytes(required); match FormUrl.tryEncodeTo(input, RawBuf.of(output.asMutPtr() as Ptr), required as u64) { Ok(written) => { $println(written); }, Err(error) => return error.code(), }; ``` `tryEncodeTo` checks the encoded size against the supplied capacity. The caller still owns the raw pointer's validity, writable extent, lifetime and any aliasing requirements. Advanced serializers that have already proved the exact length may use unsafe `encodeToUnchecked`; its output buffer must contain at least `encodedLength(input)` writable bytes. The unsafe form avoids a redundant validation scan but does not weaken UTF-8 or output length planning at the caller boundary. ## API overview | Namespace | Owned methods | Caller-buffer methods | | --- | --- | --- | | `Hex` | `encode`, `encodeBytes`, `tryDecode`, `decode`, `isValid` | `encodeTo`, `tryDecodeTo`, `decodeTo` | | `Base64` | `encode`, `tryDecode`, `decode` | `encodeTo`, `tryDecodeTo`, `decodeTo` | | `Base64Url` | `encode`, `encodePadded`, `tryDecode`, `decode` | `encodeTo`, `encodeToPadded`, `tryDecodeTo`, `decodeTo` | | `Base32` | `encode`, `tryDecode`, `decode` | `encodeTo`, `tryDecodeTo`, `decodeTo` | | `Percent` | `encode`, `tryDecode`, `decode`, `encodedLength` | `tryEncodeTo`, `tryDecodeTo` | | `FormUrl` | `tryDecode`, `decode`, `encodedLength` | `tryEncodeTo`, `tryDecodeTo` | Standalone function names remain forwarding compatibility shims. New code should use namespace methods. ## Decode errors `DecodeErrorKind` contains: - `InvalidLength` - `InvalidByte` - `InvalidPadding` - `NonCanonical` - `OutputTooSmall` - `InputTooLarge` - `AllocationFailed` The error object and its `code()`, `message()` and `isKind()` helpers do not allocate. ## Verification ```bash vex test lib/std/encoding vex test lib/std/encoding -O2 vex lint lib/std/encoding --deny-warnings vex test lib/std/encoding --bench -O2 --benchmem ``` Strict caller-buffer decoders validate all input and destination capacity before the first store. This is regression-tested across Hex, Base64, Base64URL, Base32, Percent and FormUrl, so malformed input cannot leave a partial decoded prefix in application-owned memory. --- Source: https://vex-lang.org/docs/std/errors.md # errors `errors` is Vex's owned diagnostic layer for adding context across abstraction boundaries. Prefer a precise `Result` and a domain error enum inside a library. Convert to `Error` when an API needs one dynamic, inspectable error type. The package is platform-independent and freestanding: it imports no libc, OS, I/O, or native ABI surface. ## Typed construction Messages are presentation. Stable program logic uses `ErrorKind` or an explicit domain code; changing message wording never changes identity. ```vex import { Error, ErrorKind } from "errors"; let missing = Error.withKind("config.toml is absent", ErrorKind.NotFound); let protocol = Error.withCode("peer rejected the frame", 731); let generic = Error.new("operation failed"); if missing.isKind(ErrorKind.NotFound) { // recover } ``` `Error.fromKind(kind)` creates the canonical default message for a kind. The available kinds are `Other`, `NotFound`, `PermissionDenied`, `TimedOut`, `Canceled`, `Closed`, `EndOfFile`, `InvalidInput`, `Unsupported`, `AlreadyExists`, and `ConnectionRefused`. ## Context and causal chains `context` consumes the old error and adds one owned outer node. It performs one box allocation, does not clone the existing tail, and does not copy already rendered messages. ```vex let failure = Error.withKind("unexpected end of file", ErrorKind.EndOfFile) .context("read audit log") .context("serve request"); $println("{}", failure.messageView()); // serve request $println("{}", failure.depth()); // 3 $println("{}", failure.renderChain()); ``` `messageView(): str`, `source(): Option<&Error>`, and `rootCause(): &Error` borrow without allocation. `message(): string` deliberately returns an owned copy. `clone()` copies the local node and VUMM-shares the immutable source chain, so it is O(1) regardless of causal depth. `toString()` formats only the current layer. `renderChain()` formats all layers once: ```text serve request caused by: read audit log caused by: unexpected end of file ``` `isKind` and `hasCode` inspect the complete chain. A domain code remains on the node that produced it: a contextual wrapper displays its own message while `hasCode` can still find the lower-level code. `containsMessage` is only a text-search helper and must not drive recovery logic. ## Independent failures Use `ErrorGroup` when several operations fail independently. A group owns a vector of complete `Error` chains; it never flattens messages or invents a cause relationship. ```vex import { Error, ErrorGroup, ErrorKind } from "errors"; let! failures = ErrorGroup.new(); failures.push(Error.withKind("config missing", ErrorKind.NotFound)); failures.push(Error.withCode("backend refused", 731).context("save user")); if failures.isKind(ErrorKind.NotFound) { // at least one retained chain has this kind } match failures.get(1) { Some(failure) => $println("{}", failure.renderChain()), None => { } } ``` `ErrorGroup.fromErrors(Vec)` transfers an existing vector without cloning. `get` borrows; group cloning copies the independent outer nodes and shares their immutable causal tails. ## API summary | Type/API | Ownership and cost | |---|---| | `Error.new`, `withKind`, `withCode`, `fromKind` | create one owned node | | `Error.context` | consumes the source; one box allocation | | `messageView`, `source`, `rootCause` | borrowed, zero allocation | | `message`, `toString` | return an owned string | | `renderChain` | O(total message bytes + depth) rendering | | `clone` | O(1) local copy; VUMM-shared immutable source chain | | `isKind`, `hasCode`, `containsMessage` | O(depth) inspection | | `ErrorGroup.new`, `fromErrors`, `push` | owned independent failures | | `ErrorGroup.get` | borrowed indexed lookup | | `ErrorGroup.isKind`, `hasCode` | traverse every retained chain | The former `StdError`, sentinel constructors, integer `KIND_*` helpers, message-derived identity, and fixed-arity `join2`/`join3` APIs were removed. They exposed storage, cloned causal chains, or destroyed structure. ## Current validation status The 2026-08-23 checkpoint reported 10/10 focused executable tests at O0 and O3 and clean lint. Its bounded O3 clone benchmark for a 64-source error was 5.38 ns on the recorded Apple Silicon host. This is historical evidence, not a fresh release result. The record is `docs/std/errors_SIGNOFF_2026-08-23.md` in the compiler repository. --- Source: https://vex-lang.org/docs/std/errors_reference.md # errors API reference This page is a compact reference for the current `errors` package. For design, ownership guidance, and examples, see [errors](docs/std/errors.md). ## ErrorKind ```vex export enum ErrorKind impl Copy { Other, NotFound, PermissionDenied, TimedOut, Canceled, Closed, EndOfFile, InvalidInput, Unsupported, AlreadyExists, ConnectionRefused, } ``` ## Error `Error` implements `Display` and `Debug`, exposes an explicit `clone()` method, and keeps its fields private. | API | Signature | |---|---| | create generic | `Error.new(message: string): Error` | | create typed | `Error.withKind(message: string, kind: ErrorKind): Error` | | create coded | `Error.withCode(message: string, code: i32): Error` | | canonical typed | `Error.fromKind(kind: ErrorKind): Error` | | add context | `(self: Error).context(message: string): Error` | | owned message | `(&Error).message(): string` | | borrowed message | `(&Error).messageView(): str` | | classification | `(&Error).kind(): ErrorKind` | | domain code | `(&Error).code(): i32` | | immediate source | `(&Error).source(): Option<&Error>` | | deepest source | `(&Error).rootCause(): &Error` | | node count | `(&Error).depth(): usize` | | semantic match | `(&Error).isKind(target: ErrorKind): bool` | | code match | `(&Error).hasCode(target: i32): bool` | | text search | `(&Error).containsMessage(needle: str): bool` | | current display | `(&Error).toString(): string` | | full display | `(&Error).renderChain(): string` | | local copy | `(&Error).clone(): Error` | `context` consumes the previous error and returns a new owning outer node. `message()` returns an owned string; `messageView()`, `source()` and `rootCause()` borrow storage owned by the error chain. Keep that owner live while using the returned view/reference, or clone the value you need to retain. Domain code `0` means “not supplied”; `hasCode(0)` is always false. Codes stay on their producing node; `hasCode` traverses sources to find them. ## ErrorGroup `ErrorGroup` implements `Display` and `Debug`, exposes `clone()`, and represents independent failures rather than a causal chain. | API | Signature | |---|---| | empty accumulator | `ErrorGroup.new(): ErrorGroup` | | transfer vector | `ErrorGroup.fromErrors(errors: Vec): ErrorGroup` | | add failure | `(&ErrorGroup!).push(failure: Error)` | | count | `(&ErrorGroup).len(): usize` | | empty check | `(&ErrorGroup).isEmpty(): bool` | | borrowed lookup | `(&ErrorGroup).get(index: usize): Option<&Error>` | | kind traversal | `(&ErrorGroup).isKind(target: ErrorKind): bool` | | code traversal | `(&ErrorGroup).hasCode(target: i32): bool` | | full display | `(&ErrorGroup).toString(): string` | | clone outer nodes | `(&ErrorGroup).clone(): ErrorGroup` | No compatibility aliases are provided for the removed `StdError`, sentinel, `KIND_*`, `CODE_*`, or fixed-arity join APIs. --- Source: https://vex-lang.org/docs/std/filter.md # `filter` — stable, allocation-aware filtering The `filter` package selects values from borrowed contiguous data while making allocation and alias behavior explicit. It provides a fresh-output convenience API, caller-owned storage reuse, and fixed or dynamic mask compaction. Output order is stable in every API. ## Predicate filtering ```vex import { filter, filterInto } from "filter"; fn isReady(value: &Job): bool { return value.ready; } let ready = filter(jobs.asSpan(), isReady); let! scratch = Vec.withCapacity(jobs.len()); let written = filterInto(jobs.asSpan(), &scratch!, isReady); ``` `filter` constructs a fresh `Vec`. `filterInto` replaces the logical contents of the supplied destination and reuses its allocation when capacity is sufficient. It returns the destination's final length. The predicate runs exactly once for every source element. A borrowed Copy value is copied at no ownership cost; an ownership-bearing value requires `Clone` and every retained value is cloned exactly once. If the source is the destination's complete live view, `filterInto` uses the in-place `Vec.retain` path and keeps existing owners. Partial overlap is safely staged before the destination is mutated. ## Fixed-mask filtering Use a fixed `Mask` when selection has already been computed as a vector predicate: ```vex import { filterByMask, filterByMaskInto } from "filter"; let values: [i32; 8] = [4, -1, 8, 0, 3, -6, 9, 2]; let keep = values > [0, 0, 0, 0, 0, 0, 0, 0]; let positive = filterByMask(values, keep); let! reusable = Vec.withCapacity(8); let count = filterByMaskInto(values, keep, &reusable!); ``` The mask is compacted once through the canonical `Mask.compress` operation. Selected lanes occupy the output prefix in their original order. The returned count is exact, and the reusable API commits that initialized prefix with one bulk copy rather than an element-by-element `push` loop. Fixed-mask filtering accepts numeric Copy lanes. It does not claim SIMD authority for ownership-bearing structs; use predicate filtering for those values. ## Dynamic-mask filtering Dynamic comparisons produce a packed `Mask` whose logical length follows the input. The same API accepts a `Span` plus that mask: ```vex let keep = samples.asSpan() >= threshold; let! reusable = Vec.withCapacity(samples.len()); let count = filterByMaskInto(samples.asSpan(), &keep, &reusable!); let selected = filterByMask(samples.asSpan(), &keep); ``` The source and mask lengths must match. The implementation processes full blocks at `#Target.simdLanes()`, extracts each packed predicate with `Mask.block`, compacts it with the same `Mask.compress`, and uses a single fixed-width store when spare Vec capacity covers the complete block. The final short block reads no source lane past the logical end. ## Allocation and alias guarantees | Operation | Allocation policy | |---|---| | `filter` | one fresh upper-bound result allocation | | `filterInto`, independent source | no allocation when destination capacity covers the source length | | `filterInto`, exact self-view | in-place, no allocation | | `filterInto`, partial overlap | temporary staging to preserve unread values and ownership | | `filterByMask` | one fixed-capacity result allocation | | `filterByMaskInto` | no allocation when destination capacity covers `N` | | dynamic `filterByMask` | one source-upper-bound result allocation | | dynamic `filterByMaskInto` | no allocation when destination capacity covers the source length | Reusable destinations retain their allocator or arena binding. Fresh results capture the active allocation region when they are constructed. Capacity is reserved before old destination contents are cleared, so an allocation failure cannot destroy the previous logical value. ## CPU and GPU semantics `Mask.compress` has one backend-independent meaning: stable selected prefix, exact `usize` count, and a deterministic zero tail in its fixed-array result. CPU SIMD and GPU SIMT backends legalize that semantic operation according to their hardware; the `filter` API does not expose architecture names or a backend switch. Dynamic masks use packed-word extraction plus the same fixed-register compact contract; they do not silently fall back to a per-lane compatibility loop. See the [SIMD/SIMT unified execution contract](docs/guide/simd/simd-simt-contract.md) for the cross-backend compaction rules. ## Choosing an API - Use `Span.filter` for the shortest fresh-output spelling. - Use `filter` when package-level discoverability is preferable. - Use `filterInto` in loops, parsers, and services that can reuse a destination. - Use `filterByMaskInto` when a numeric fixed-block comparison already produced a `Mask` and storage reuse matters. - Use the Span/Mask overload when a dynamic comparison already produced a packed runtime mask. --- Source: https://vex-lang.org/docs/std/fs/file.md # File I/O `File` is a move-only owning descriptor. Dropping it closes the descriptor; `close()` is available when the error or exact release point matters and is idempotent. ## Opening files Use `OpenOptions` when behavior must be explicit: ```vex import { OpenOptions } from "fs"; let options = OpenOptions.new() .read(true) .write(true) .create(true); match options.open("state.bin") { Ok(file) => { let! opened = file; match opened.metadata() { Ok(info) => $println(info.len()), Err(error) => $println(error.toString()), } let _ = opened.close(); }, Err(error) => $println(error.toString()), } ``` Available options are `read`, `write`, `append`, `truncate`, `create`, atomic `createNew`, and the creation `mode`. Invalid combinations fail with `IoErrorKind.InvalidInput` before a provider call. Convenience constructors include `File.open`, `File.create`, `File.openReadWrite`, `File.openAppend` and `File.temp`. ## Streaming operations `File` implements the canonical `io` reader, writer, random-access reader, random-access writer, seeker and closer contracts. Core methods include: - `read` and `write`: partial `usize` operations; - `readByte`, `writeByte` and `writeStr`; - `readAt` and `writeAt`: native positional operations without changing the shared seek cursor; - `seek`, `tell`, `size`, `truncate`, `flush` and `sync`; - `metadata`, `filePath`, `isOpen` and `close`. Use `bufReader(file)`, `bufWriter(file)`, `copyBuffer` and other `io` adapters for reusable buffering. The filesystem package intentionally does not carry package-local reader or writer implementations. `readExactAt`, `writeAllAt` and `SectionReader` are likewise supplied by `io` and compose directly with `File`. `writeAt` intentionally rejects a `File` opened with append mode: append and an explicit offset cannot have one portable meaning across POSIX and Windows. Open a read/write handle when the offset is part of the operation. ## Whole-file operations `readBytes` and `readFile` consume the complete input. For untrusted or externally controlled files, use `readBytesLimit` or `readFileLimit`; an oversized input is rejected instead of silently truncated. `writeFile` and `appendFile` complete the requested write or return an error. Other one-shot operations include `copyFile`, `renameFile`, `removeFile`, `createDir`, `removeDir`, `cwd`, `chdir`, `changeMode`, `createSymlink`, `hardlink` and `readSymlink`. ## Memory mapping `mapRead` returns an owning `MappedRegion` with bounds-checked `readByte` and `copyTo`. The mapping is automatically released. Raw `mmap`/`munmap` methods remain explicit unsafe compatibility boundaries for low-level code. --- Source: https://vex-lang.org/docs/std/fs/index.md # fs — filesystem The `fs` package is Vex's canonical synchronous filesystem boundary. It combines owned file and mapping handles, portable metadata, native path handling, directory streaming and bounded whole-file helpers. Byte I/O composes with the contracts and adapters from `io`; `fs` does not maintain a second buffering stack. ```vex import { Path, readFileLimit } from "fs"; let config = Path("config/../config/app.toml").clean(); match readFileLimit(config.toString(), 1024 as usize * 1024 as usize) { Ok(content) => $println(content), Err(error) => $println(error.toString()), } ``` ## Public areas - `Path`: lexical cleaning, joining and inspection plus filesystem canonicalization. - `OpenOptions` and `File`: validated opening, RAII descriptors, partial I/O, `ReaderAt`/`WriterAt` positional I/O, seeking, metadata, sync and mapping. - Whole-file helpers: complete and explicitly bounded byte/string reads, writes, appends, copy, rename and removal. - `Metadata`, `FileType` and `Permissions`: one portable surface over macOS, Linux and Windows providers. - `DirCursor`, collection and pagination helpers: bounded O(n) traversal, recursive walk/create/remove and temporary-directory lookup. - Links and temporary files: native symlink, hard-link, readlink and race-resistant temporary-file operations. ## Error and limit policy Operations that can fail return `Result<_, IoError>`. `tryExists` preserves permission and provider failures; `exists` intentionally collapses them to `false` as a convenience. Code reading untrusted files or directories should prefer `readFileLimit`, `readBytesLimit`, `readDirVecLimit` or `DirCursor` and choose an application-specific bound. ## Random-access I/O `File` is an `io.ReaderAt` and `io.WriterAt` provider. `readAt` and `writeAt` perform native offsetted I/O, so they do not mutate the descriptor's sequential cursor and compose directly with `io.readExactAt`, `io.writeAllAt` and `io.SectionReader`. This is deliberately one shared `io` contract rather than a second filesystem-specific random-access API. This fragment requires an existing readable/writable `archive.bin` with at least 16 bytes and a surrounding function returning `Result<_, IoError>`. ```vex import { File } from "fs"; import { readExactAt, writeAllAt } from "io"; let! file = File.openReadWrite("archive.bin")?; let! header: [u8; 16] = [0; 16]; readExactAt(&file!, &header[0]!, header.len(), 0 as u64)?; let marker: [u8; 2] = [0x56 as u8, 0x58 as u8]; writeAllAt(&file!, &marker[0], marker.len(), 64 as u64)?; ``` An append-mode handle intentionally rejects `writeAt`: append semantics and an explicit offset cannot have one portable meaning across all targets. Use `File.openReadWrite` when an offset is part of the operation. ## Platform boundary Paths are public UTF-8 values. Windows providers use wide Win32 APIs and preserve drive-relative, rooted and UNC semantics. macOS and Linux use explicit target-routed providers. Native structs, handles, errno values and libc constants do not escape the package. --- Source: https://vex-lang.org/docs/std/fs/paths.md # Paths and directories ## Path `Path` is an owned native-path value. `clean()` performs lexical O(n) normalization without consulting the filesystem; `canonicalize()` resolves the filesystem, follows links according to the native provider and returns an absolute path or an `IoError`. ```vex import { Path } from "fs"; let source = Path("src/./frontend/../main.vx").clean(); $println(source.toString()); // src/main.vx match source.canonicalize() { Ok(absolute) => $println(absolute.toString()), Err(error) => $println(error.toString()), } ``` The surface includes `asStr`, `len`, `join`, `parent`, `fileName`, `extension`, `stem`, `withExtension`, `components`, `exists`, `isReadable`, `isWritable`, `isAbsolute`, `isRelative`, `isDir`, `isFile` and `isSymlink`. Windows behavior is native rather than POSIX-shaped: drive-relative paths, rooted paths, mixed separators and UNC prefixes remain distinct. Public paths stay UTF-8 while the provider uses UTF-16 wide Win32 APIs. ## Directory collection - `readDir` fills caller-provided `DirList` storage. - `readDirVecLimit` collects at most an explicit number of entries. - `readDirVec` collects the full directory and is intended for trusted sizes. - `readDirPage` provides stateless offset/limit pagination. Its returned page reserves the validated provider count before copying native entries, so a full page has no incidental `Vec` growth step. Dot entries are excluded. Provider counts are validated before Vec lengths are committed. ## Streaming traversal `DirCursor` is the preferred API for large or untrusted directories. It opens the provider once, advances monotonically in O(n), and closes automatically. ```vex import { DirCursor } from "fs"; match DirCursor.open(".", 256 as usize) { Ok(cursor) => { let! stream = cursor; match stream.nextPage() { Ok(entries) => $println(entries.len()), Err(error) => $println(error.toString()), } let _ = stream.close(); }, Err(error) => $println(error.toString()), } ``` `mkdirAll`, `removeAll` and `walkDir` provide recursive operations. `walkDir` stops when its callback returns `false` and reports whether the walk completed. --- Source: https://vex-lang.org/docs/std/fs/reference.md # std::fs API Reference Public declarations reachable through the documented package entry points. Signatures follow the source snapshot; consult the module guide for support and qualification boundaries. ## Application entry points Start with the [file-system overview](docs/std/fs/index.md), [owning File and mappings](docs/std/fs/file.md), and [paths](docs/std/fs/paths.md). Import application APIs from `"fs"`; native provider declarations and test helpers below are implementation inventory, not portable entry points. ### DirList Import: `"fs"`. ```vex export struct DirList ``` Read all entries in a directory. Returns a fixed-size buffer of up to 64 entries. Usage: let! list = DirList { items: uninit, count: 0 }; readDir("/tmp", &list!); let! i: i64 = 0; while i < list.count { $println(list.items[i].name()); i = i + 1; } **Public fields:** - `items`: `[DirEntry; 64]` - `count`: `usize` ### DirCursor Import: `"fs"`. ```vex export struct DirCursor ``` Owning O(n) directory stream. A cursor opens the provider once, advances monotonically, and closes automatically on scope exit. **Implements:** `Drop` ### DirEntry Import: `"fs"`. ```vex export struct DirEntry ``` **Implements:** `Clone` & `Copy` & `Display` **Public fields:** - `name_buf`: `[u8; 256]` - `entry_type`: `u8` - `_pad`: `[u8; 7]` - `inode`: `u64` ### OpenOptions Import: `"fs"`. ```vex export struct OpenOptions ``` Validated, zero-allocation file-open configuration. All builder methods consume and return the small Copy value, so a complete configuration is resolved at the call site without heap allocation. **Implements:** `Copy` ### File Import: `"fs"`. ```vex export struct File ``` **Implements:** `Reader` & `ReaderAt` & `Writer` & `WriterAt` & `ByteReader` & `ByteWriter` & `StringWriter` & `Seeker` & `Closer` & `Drop` & `Display` & `Debug` **Public fields:** - `fd`: `i32` - `path`: `string` ### MappedRegion Import: `"fs"`. ```vex export struct MappedRegion ``` Owning read-only memory mapping. The region is unmapped automatically and cannot be copied, preventing double-unmap and descriptor-lifetime coupling. **Implements:** `Drop` ### Path Import: `"fs"`. ```vex export struct Path ``` **Implements:** `Display` & `Clone` & `Eq` & `Debug` ### Permissions Import: `"fs"`. ```vex export struct Permissions ``` Wraps a raw POSIX mode bitmask with ergonomic boolean helpers. Examples: let p = Permissions { mode: 0o644 }; p.canRead() // true p.canWrite() // true (owner) p.canExec() // false p.isReadOnly() // false **Implements:** `Clone` & `Copy` & `Display` & `Debug` & `Eq` ### Metadata Import: `"fs"`. ```vex export struct Metadata ``` Immutable metadata snapshot. Every field comes from the same provider call, avoiding the race and syscall amplification of the former FileInfo API. **Implements:** `Clone` & `Copy` & `Display` & `Debug` **Public fields:** - `byteLength`: `u64` - `modifiedSeconds`: `i64` - `accessedSeconds`: `i64` - `createdSeconds`: `i64` - `permissionBits`: `u32` - `kindValue`: `FileType` - `ownerId`: `i64` - `groupId`: `i64` - `inodeValue`: `u64` - `deviceValue`: `u64` - `links`: `u64` ### FileType Import: `"fs"`. ```vex export enum FileType ``` Portable file kind derived from one native metadata snapshot. **Variants:** - `File` - `Directory` - `Symlink` - `Other` ### readDir Import: `"fs"`. ```vex export fn readDir(path: string, out: &DirList!): Result ``` List contents of a directory (fills caller-provided buffer). Returns up to 64 entries. For larger directories, use raw vex_fs_readdir. **Returns:** `Result` ### mkdirAll Import: `"fs"`. ```vex export fn mkdirAll(path: string): Result<(), IoError> ``` Create all directories along a path (like `mkdir -p`). **Returns:** `Result<(), IoError>` ### removeAll Import: `"fs"`. ```vex export fn removeAll(path: string): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### tempDir Import: `"fs"`. ```vex export fn tempDir(): string ``` Get the system temporary directory path. **Returns:** `string` ### readDirVecLimit Import: `"fs"`. ```vex export fn readDirVecLimit(path: string, maxEntries: usize): Result, IoError> ``` Read directory entries into a Vec with explicit upper bound. This function paginates via vex_fs_readdir_from to collect up to `maxEntries` entries, avoiding single-batch truncation behavior. **Returns:** `Result, IoError>` ### readDirVec Import: `"fs"`. ```vex export fn readDirVec(path: string): Result, IoError> ``` Read all directory entries into a Vec. Callers handling untrusted or very large directories should use `readDirVecLimit` or `DirCursor` instead. **Returns:** `Result, IoError>` ### readDirPage Import: `"fs"`. ```vex export fn readDirPage(path: string, offset: usize, limit: usize): Result, IoError> ``` Read one page of directory entries starting from `offset` (non-dot entries). Returns up to `limit` entries. **Returns:** `Result, IoError>` ### newDirCursor Import: `"fs"`. ```vex export fn newDirCursor(path: string, pageSize: usize): Result ``` Create a new directory cursor. **Returns:** `Result` ### walkDir Import: `"fs"`. ```vex export fn walkDir(root: string, callback: fn (DirEntry, string): bool): Result ``` Recursively walk a directory tree, calling `callback(entry, fullPath)` for each entry (excluding "." and ".."). If the callback returns `false`, traversal stops immediately. Returns `Ok(0)` on complete traversal, `Ok(1)` if stopped early. **Returns:** `Result` ### openFile Import: `"fs"`. ```vex export fn openFile(path: string): Result ``` Function-form constructors for code that prefers package-level operations. **Returns:** `Result` ### createFile Import: `"fs"`. ```vex export fn createFile(path: string): Result ``` **Returns:** `Result` ### openReadWrite Import: `"fs"`. ```vex export fn openReadWrite(path: string): Result ``` **Returns:** `Result` ### openAppend Import: `"fs"`. ```vex export fn openAppend(path: string): Result ``` **Returns:** `Result` ### readBytes Import: `"fs"`. ```vex export fn readBytes(path: string): Result, IoError> ``` Read the entire file as bytes using the canonical partial-read-safe loop. **Returns:** `Result, IoError>` ### readBytesLimit Import: `"fs"`. ```vex export fn readBytesLimit(path: string, maximum: usize): Result, IoError> ``` Read a complete file while enforcing an explicit allocation ceiling. **Returns:** `Result, IoError>` ### readFile Import: `"fs"`. ```vex export fn readFile(path: string): Result ``` Read the entire file as strict UTF-8 text. **Returns:** `Result` ### readFileLimit Import: `"fs"`. ```vex export fn readFileLimit(path: string, maximum: usize): Result ``` **Usage contract:** Returns an independent UTF-8 string and closes the file on success or failure. Invalid UTF-8, an exceeded ceiling, read errors and close errors remain errors; it is not a binary-data reader. Read strict UTF-8 text while enforcing an explicit byte ceiling. **Returns:** `Result` ### writeFile Import: `"fs"`. ```vex export fn writeFile(path: string, content: string): Result<(), IoError> ``` Write complete text to a file, creating or truncating it. **Returns:** `Result<(), IoError>` ### appendFile Import: `"fs"`. ```vex export fn appendFile(path: string, content: string): Result<(), IoError> ``` Append complete text, creating the file when needed. **Returns:** `Result<(), IoError>` ### copyFile Import: `"fs"`. ```vex export fn copyFile(src: string, dst: string): Result ``` Copy a file through the canonical Reader/Writer contracts. Partial writes, zero-progress providers and invalid byte counts are handled by std/io. **Returns:** `Result` ### renameFile Import: `"fs"`. ```vex export fn renameFile(oldpath: string, newpath: string): Result<(), IoError> ``` Rename or move a file within the provider's supported filesystem scope. **Returns:** `Result<(), IoError>` ### removeFile Import: `"fs"`. ```vex export fn removeFile(path: string): Result<(), IoError> ``` Delete a file. **Returns:** `Result<(), IoError>` ### exists Import: `"fs"`. ```vex export fn exists(path: string): bool ``` Check if a file exists. **Returns:** `bool` ### tryExists Import: `"fs"`. ```vex export fn tryExists(path: string): Result ``` Check existence without conflating absence with permission/provider errors. **Returns:** `Result` ### createDir Import: `"fs"`. ```vex export fn createDir(path: string): Result<(), IoError> ``` Create a directory (mode 0755). **Returns:** `Result<(), IoError>` ### removeDir Import: `"fs"`. ```vex export fn removeDir(path: string): Result<(), IoError> ``` Remove an empty directory. **Returns:** `Result<(), IoError>` ### cwd Import: `"fs"`. ```vex export fn cwd(): Result ``` Get current working directory. **Returns:** `Result` ### chdir Import: `"fs"`. ```vex export fn chdir(path: string): Result<(), IoError> ``` Change current working directory. **Returns:** `Result<(), IoError>` ### changeMode Import: `"fs"`. ```vex export fn changeMode(path: string, mode: u32): Result<(), IoError> ``` Set file permissions (chmod). **Returns:** `Result<(), IoError>` ### tempFile Import: `"fs"`. ```vex export fn tempFile(): Result ``` **Returns:** `Result` ### createSymlink Import: `"fs"`. ```vex export fn createSymlink(target: string, linkpath: string): Result<(), IoError> ``` Create a symbolic link pointing to `target` at `linkpath`. **Returns:** `Result<(), IoError>` ### symlink Import: `"fs"`. ```vex export fn symlink(target: string, linkpath: string): Result<(), IoError> ``` Function-form alias for `createSymlink`. **Returns:** `Result<(), IoError>` ### hardlink Import: `"fs"`. ```vex export fn hardlink(oldpath: string, newpath: string): Result<(), IoError> ``` Create a hard link from `oldpath` to `newpath`. **Returns:** `Result<(), IoError>` ### readSymlink Import: `"fs"`. ```vex export fn readSymlink(path: string): Result ``` Read the target path of a symbolic link. **Returns:** `Result` ### readlink Import: `"fs"`. ```vex export fn readlink(path: string): Result ``` Function-form alias for `readSymlink`. **Returns:** `Result` ### Path Import: `"fs"`. ```vex export fn Path(value: string): Path ``` ### Permissions Import: `"fs"`. ```vex export fn Permissions(mode: u32): Permissions ``` Create from a raw POSIX mode value (e.g. 0o755). ### metadata Import: `"fs"`. ```vex export fn metadata(path: string): Result ``` Query metadata while following the final symbolic link. **Returns:** `Result` ### symlinkMetadata Import: `"fs"`. ```vex export fn symlinkMetadata(path: string): Result ``` Query metadata for the link itself rather than its target. **Returns:** `Result` ### pathIsDir Import: `"fs"`. ```vex export fn pathIsDir(path: string): bool ``` Convenience predicates intentionally collapse provider errors to false. Use `metadata`/`symlinkMetadata` when the distinction matters. **Returns:** `bool` ### pathIsFile Import: `"fs"`. ```vex export fn pathIsFile(path: string): bool ``` **Returns:** `bool` ### pathIsSymlink Import: `"fs"`. ```vex export fn pathIsSymlink(path: string): bool ``` **Returns:** `bool` ### DirCursor.open ```vex export fn DirCursor.open(path: string, pageSize: usize): Result ``` **Returns:** `Result` ### DirCursor.close ```vex export fn (self: &DirCursor!) close(): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### DirCursor.nextPage ```vex export fn (self: &DirCursor!) nextPage(): Result, IoError> ``` Fetch next page from cursor. Returns empty Vec when completed. **Returns:** `Result, IoError>` ### DirEntry.clone ```vex export fn (self: &DirEntry) clone(): DirEntry ``` **Returns:** `DirEntry` ### DirEntry.name ```vex export fn (self: &DirEntry) name(): string ``` Returns the entry name without retaining or exposing the fixed native ABI buffer. Directory providers always NUL-terminate the 256-byte field. **Returns:** `string` ### DirEntry.toString ```vex export fn (self: &DirEntry) toString(): string ``` **Returns:** `string` ### DirEntry.isDir ```vex export fn (self: &DirEntry) isDir(): bool ``` **Returns:** `bool` ### DirEntry.isFile ```vex export fn (self: &DirEntry) isFile(): bool ``` **Returns:** `bool` ### DirEntry.isSymlink ```vex export fn (self: &DirEntry) isSymlink(): bool ``` **Returns:** `bool` ### OpenOptions.new ```vex export fn OpenOptions.new(): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.readOnly ```vex export fn OpenOptions.readOnly(): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.writeOnly ```vex export fn OpenOptions.writeOnly(): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.readWrite ```vex export fn OpenOptions.readWrite(): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.read ```vex export fn (self: OpenOptions) read(enabled: bool): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.write ```vex export fn (self: OpenOptions) write(enabled: bool): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.append ```vex export fn (self: OpenOptions) append(enabled: bool): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.truncate ```vex export fn (self: OpenOptions) truncate(enabled: bool): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.create ```vex export fn (self: OpenOptions) create(enabled: bool): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.createNew ```vex export fn (self: OpenOptions) createNew(enabled: bool): OpenOptions ``` **Returns:** `OpenOptions` ### OpenOptions.mode ```vex export fn (self: OpenOptions) mode(mode: u32): OpenOptions ``` Set creation permissions before the process umask is applied. **Returns:** `OpenOptions` ### OpenOptions.open ```vex export fn (self: OpenOptions) open(path: string): Result ``` **Returns:** `Result` ### MappedRegion.len ```vex export fn (self: &MappedRegion) len(): usize ``` **Returns:** `usize` ### MappedRegion.isEmpty ```vex export fn (self: &MappedRegion) isEmpty(): bool ``` **Returns:** `bool` ### MappedRegion.readByte ```vex export fn (self: &MappedRegion) readByte(index: usize): Option ``` Bounds-checked byte access that keeps raw pointers behind the fs boundary. **Returns:** `Option` ### MappedRegion.copyTo ```vex export fn (self: &MappedRegion) copyTo(offset: usize, destination: Ptr, count: usize): Result<(), IoError> ``` **Usage contract:** The mapped range is checked before copying; destination allocation extent/lifetime and non-overlap remain caller obligations. A non-null pointer alone does not prove them. The returned bytes are independent of the mapping. Copy a bounded region into caller-owned storage. **Returns:** `Result<(), IoError>` ### MappedRegion.asPtr ```vex export unsafe fn (self: &MappedRegion) asPtr(): Ptr ``` Escape hatch for parsers/codecs that need zero-copy typed access. The returned pointer is valid only while this region remains mapped. **Returns:** `Ptr` ### MappedRegion.unmap ```vex export fn (self: &MappedRegion!) unmap(): Result<(), IoError> ``` Release the mapping early. Calling this more than once is safe. **Returns:** `Result<(), IoError>` ### File.open ```vex export fn File.open(path: string): Result ``` Open an existing file for reading. Returns a Result containing the File or a Error. The returned File is automatically closed when dropped (Drop). **Returns:** `Result` ### File.create ```vex export fn File.create(path: string): Result ``` Create a new file for writing (or truncate if it already exists). Returns a Result containing the File or a Error. The returned File is automatically closed when dropped (Drop). **Returns:** `Result` ### File.openReadWrite ```vex export fn File.openReadWrite(path: string): Result ``` Open an existing file for reading and writing. Returns a Result containing the File or a Error. The returned File is automatically closed when dropped (Drop). **Returns:** `Result` ### File.openAppend ```vex export fn File.openAppend(path: string): Result ``` Open or create a file for appending data. Returns a Result containing the File or a Error. The returned File is automatically closed when dropped (Drop). **Returns:** `Result` ### File.openWith ```vex export fn File.openWith(path: string, options: OpenOptions): Result ``` Open a file using a validated options value. **Returns:** `Result` ### File.read ```vex export fn (self: &File!) read(buf: Ptr, len: usize): Result ``` Canonical std/io Reader implementation. **Returns:** `Result` ### File.write ```vex export fn (self: &File!) write(data: Ptr, len: usize): Result ``` Canonical std/io Writer implementation. **Returns:** `Result` ### File.flush ```vex export fn (self: &File!) flush(): Result<(), IoError> ``` File descriptors are unbuffered at this layer; durability is explicit via `sync`, so Writer.flush has no hidden fsync cost. **Returns:** `Result<(), IoError>` ### File.readByte ```vex export fn (self: &File!) readByte(): Result ``` **Returns:** `Result` ### File.writeByte ```vex export fn (self: &File!) writeByte(value: u8): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### File.writeStr ```vex export fn (self: &File!) writeStr(value: str): Result ``` **Returns:** `Result` ### File.readAt ```vex export fn (self: &File!) readAt(buf: Ptr, len: usize, offset: u64): Result ``` **Usage contract:** The sequential file cursor is unchanged. Use io.readExactAt for fixed-size records. A non-empty read returning zero means EOF. Zero-length requests succeed with count zero. Buffer validity, extent and lifetime remain caller obligations. Position-independent read — never changes the sequential file cursor. Safe to call concurrently on the same descriptor because it does not mutate the descriptor's seek position. **Returns:** `Result` ### File.writeAt ```vex export fn (self: &File!) writeAt(data: Ptr, len: usize, offset: u64): Result ``` **Usage contract:** The sequential file cursor is unchanged. Use io.writeAllAt for a complete write. Append-mode files reject positional writes. Zero-length requests succeed with count zero. Buffer validity, extent and lifetime remain caller obligations. Position-independent write — never changes the sequential file cursor. The method is intentionally unavailable for append-mode handles. Linux's historical `pwrite` + `O_APPEND` behaviour differs from POSIX positional semantics, so accepting it would make Vex's `WriterAt` contract target dependent. Open a read/write handle when an explicit offset is required. **Returns:** `Result` ### File.seek ```vex export fn (self: &File!) seek(position: SeekFrom): Result ``` Canonical std/io Seeker implementation. **Returns:** `Result` ### File.tell ```vex export fn (self: &File) tell(): Result ``` Get current file position. **Returns:** `Result` ### File.metadata ```vex export fn (self: &File) metadata(): Result ``` Query one coherent metadata snapshot for this open descriptor. Unlike a path query, this continues to describe the same opened object if its directory entry is renamed or replaced concurrently. **Returns:** `Result` ### File.size ```vex export fn (self: &File) size(): Result ``` Get file size in bytes from the descriptor metadata snapshot. **Returns:** `Result` ### File.truncate ```vex export fn (self: &File) truncate(length: u64): Result<(), IoError> ``` Truncate file to given length. **Returns:** `Result<(), IoError>` ### File.sync ```vex export fn (self: &File) sync(): Result<(), IoError> ``` Flush file data to disk. **Returns:** `Result<(), IoError>` ### File.close ```vex export fn (self: &File!) close(): Result<(), IoError> ``` Explicitly close the file. Safe to call multiple times. **Returns:** `Result<(), IoError>` ### File.drop ```vex export fn (self: &File!) drop() ``` Auto-close on scope exit (Drop contract). **Receiver:** `self: &File!` *(mutable reference)* ### File.toString ```vex export fn (self: &File) toString(): string ``` Human-readable representation (Display contract) — returns the file path. **Returns:** `string` ### File.debug ```vex export fn (self: &File) debug(): string ``` Debug representation (Debug contract). **Returns:** `string` ### File.filePath ```vex export fn (self: &File) filePath(): string ``` Return the file path. **Returns:** `string` ### File.isOpen ```vex export fn (self: &File) isOpen(): bool ``` Return true if the file is currently open (fd >= 0). **Returns:** `bool` ### File.mapRead ```vex export fn (self: &File) mapRead(len: usize, offset: u64): Result ``` Create an owning read-only private mapping. Closing the File after this call does not invalidate the region; the region's Drop owns the unmap. **Returns:** `Result` ### File.mmap ```vex export fn (self: &File) mmap(len: u64, offset: i64): Result, IoError> ``` Memory-map the file for read+write access. **Returns:** `Result, IoError>` ### File.mmapRead ```vex export fn (self: &File) mmapRead(len: u64, offset: i64): Result, IoError> ``` Memory-map the file for read-only access (MAP_PRIVATE). Safe for files opened with openFile() (O_RDONLY). **Returns:** `Result, IoError>` ### File.munmap ```vex export fn (self: &File) munmap(ptr: Ptr, len: u64): Result<(), IoError> ``` Unmap a memory region previously created via mmap() or mmapRead(). Symmetric with mmapRead/mmap — call this when done with the mapped region. **Returns:** `Result<(), IoError>` ### File.readAll ```vex export fn (self: &File!) readAll(): Result, IoError> ``` Read all remaining bytes from the file into a Vec<u8>. Reads from the current seek position until EOF. **Returns:** `Result, IoError>` ### File.temp ```vex export fn File.temp(): Result ``` **Returns:** `Result` ### Path.asStr ```vex export fn (self: &Path) asStr(): str ``` Borrows the native path spelling without allocating. **Returns:** `str` ### Path.len ```vex export fn (self: &Path) len(): usize ``` **Returns:** `usize` ### Path.toString ```vex export fn (self: &Path) toString(): string ``` **Returns:** `string` ### Path.debug ```vex export fn (self: &Path) debug(): string ``` **Returns:** `string` ### Path.clone ```vex export fn (self: &Path) clone(): Path ``` **Returns:** `Path` ### Path.op ```vex export fn (self: &Path) op==(rhs: &Path): bool ``` **Returns:** `bool` ### Path.join ```vex export fn (self: &Path) join(other: string): Path ``` Joins a component using the compile target's preferred separator. An absolute or explicitly volume-qualified right-hand path replaces `self`. **Returns:** `Path` ### Path.parent ```vex export fn (self: &Path) parent(): Path ``` Returns the lexical parent without touching the filesystem. **Returns:** `Path` ### Path.fileName ```vex export fn (self: &Path) fileName(): string ``` Returns the final component, or an empty string for a trailing separator. **Returns:** `string` ### Path.extension ```vex export fn (self: &Path) extension(): string ``` **Returns:** `string` ### Path.stem ```vex export fn (self: &Path) stem(): string ``` **Returns:** `string` ### Path.exists ```vex export fn (self: &Path) exists(): bool ``` **Returns:** `bool` ### Path.isReadable ```vex export fn (self: &Path) isReadable(): bool ``` **Returns:** `bool` ### Path.isWritable ```vex export fn (self: &Path) isWritable(): bool ``` **Returns:** `bool` ### Path.isAbsolute ```vex export fn (self: &Path) isAbsolute(): bool ``` A fully qualified path. Windows root-relative (`\foo`) and drive-relative (`C:foo`) spellings deliberately return false because they depend on process-local drive state. **Returns:** `bool` ### Path.isRelative ```vex export fn (self: &Path) isRelative(): bool ``` **Returns:** `bool` ### Path.isDir ```vex export fn (self: &Path) isDir(): bool ``` **Returns:** `bool` ### Path.isFile ```vex export fn (self: &Path) isFile(): bool ``` **Returns:** `bool` ### Path.isSymlink ```vex export fn (self: &Path) isSymlink(): bool ``` **Returns:** `bool` ### Path.canonicalize ```vex export fn (self: &Path) canonicalize(): Result ``` Resolves symlinks and returns an absolute native path. Provider errors are preserved; canonicalization never silently returns the uncanonical input. **Returns:** `Result` ### Path.withExtension ```vex export fn (self: &Path) withExtension(extension: string): Path ``` Replaces the final extension. An empty extension removes the existing one. **Returns:** `Path` ### Path.clean ```vex export fn (self: &Path) clean(): Path ``` Lexically resolves `.` and `..` without filesystem access. The target's volume/root prefix is preserved and separators in the result are native. **Returns:** `Path` ### Path.components ```vex export fn (self: &Path) components(): Vec ``` Splits the path while keeping a drive/UNC/root prefix as the first item. **Returns:** `Vec` ### Permissions.clone ```vex export fn (self: &Permissions) clone(): Permissions ``` **Returns:** `Permissions` ### Permissions.readOnly ```vex export fn Permissions.readOnly(): Permissions ``` Read-only file (0o444). **Returns:** `Permissions` ### Permissions.readWrite ```vex export fn Permissions.readWrite(): Permissions ``` Read-write file (0o644). **Returns:** `Permissions` ### Permissions.executable ```vex export fn Permissions.executable(): Permissions ``` Executable file (0o755). **Returns:** `Permissions` ### Permissions.canRead ```vex export fn (self: &Permissions) canRead(): bool ``` True if any entity (owner/group/other) can read. **Returns:** `bool` ### Permissions.canWrite ```vex export fn (self: &Permissions) canWrite(): bool ``` True if any entity (owner/group/other) can write. **Returns:** `bool` ### Permissions.canExec ```vex export fn (self: &Permissions) canExec(): bool ``` True if any entity (owner/group/other) can execute. **Returns:** `bool` ### Permissions.ownerCanRead ```vex export fn (self: &Permissions) ownerCanRead(): bool ``` True if the owner can read. **Returns:** `bool` ### Permissions.ownerCanWrite ```vex export fn (self: &Permissions) ownerCanWrite(): bool ``` True if the owner can write. **Returns:** `bool` ### Permissions.ownerCanExec ```vex export fn (self: &Permissions) ownerCanExec(): bool ``` True if the owner can execute. **Returns:** `bool` ### Permissions.isReadOnly ```vex export fn (self: &Permissions) isReadOnly(): bool ``` Convenience: no entity has write permission. **Returns:** `bool` ### Permissions.rawMode ```vex export fn (self: &Permissions) rawMode(): u32 ``` Raw mode bits. **Returns:** `u32` ### Permissions.op ```vex export fn (self: &Permissions) op==(rhs: &Permissions): bool ``` **Returns:** `bool` ### Permissions.toString ```vex export fn (self: &Permissions) toString(): string ``` **Returns:** `string` ### Permissions.debug ```vex export fn (self: &Permissions) debug(): string ``` **Returns:** `string` ### Metadata.len ```vex export fn (self: &Metadata) len(): u64 ``` **Returns:** `u64` ### Metadata.isEmpty ```vex export fn (self: &Metadata) isEmpty(): bool ``` **Returns:** `bool` ### Metadata.fileType ```vex export fn (self: &Metadata) fileType(): FileType ``` **Returns:** `FileType` ### Metadata.isFile ```vex export fn (self: &Metadata) isFile(): bool ``` **Returns:** `bool` ### Metadata.isDir ```vex export fn (self: &Metadata) isDir(): bool ``` **Returns:** `bool` ### Metadata.isSymlink ```vex export fn (self: &Metadata) isSymlink(): bool ``` **Returns:** `bool` ### Metadata.permissions ```vex export fn (self: &Metadata) permissions(): Permissions ``` **Returns:** `Permissions` ### Metadata.modified ```vex export fn (self: &Metadata) modified(): i64 ``` **Returns:** `i64` ### Metadata.accessed ```vex export fn (self: &Metadata) accessed(): i64 ``` **Returns:** `i64` ### Metadata.created ```vex export fn (self: &Metadata) created(): i64 ``` **Returns:** `i64` ### Metadata.uid ```vex export fn (self: &Metadata) uid(): i64 ``` **Returns:** `i64` ### Metadata.gid ```vex export fn (self: &Metadata) gid(): i64 ``` **Returns:** `i64` ### Metadata.inode ```vex export fn (self: &Metadata) inode(): u64 ``` **Returns:** `u64` ### Metadata.device ```vex export fn (self: &Metadata) device(): u64 ``` **Returns:** `u64` ### Metadata.linkCount ```vex export fn (self: &Metadata) linkCount(): u64 ``` **Returns:** `u64` ### Metadata.clone ```vex export fn (self: &Metadata) clone(): Metadata ``` **Returns:** `Metadata` ### Metadata.toString ```vex export fn (self: &Metadata) toString(): string ``` **Returns:** `string` ### Metadata.debug ```vex export fn (self: &Metadata) debug(): string ``` **Returns:** `string` --- Source: https://vex-lang.org/docs/std/geo.md # Geographic coordinates (`geo`) `geo` works with latitude/longitude coordinates: distances, bearings, routes, bounds, polygon membership, coordinate text and unit conversion. Import from `"geo"`. These operations use geographic degrees and metres. ## Coordinates and units `Coordinate` is a copyable value with public `latitude: f64` and `longitude: f64`. Latitude is in `[-90, 90]`, longitude in `[-180, 180]`. `isValidCoordinate` checks those ranges. Validate external input before using distance or polygon operations; constructing a `Coordinate` does not validate it. GeoJSON positions use **longitude first**. `fromGeoJSON([longitude, latitude])` converts that order to named fields; `toGeoJSON(point)` returns `[f64; 2]` in GeoJSON order. A numeric coordinate has no altitude or coordinate reference system tag. Convert other projections before passing them to this package. Distances are metres, areas square metres and speeds metres per second. `convertDistance`, `convertArea` and `convertSpeed` convert those base units to the requested enum variant. For example, `convertDistance(1000.0, DistanceUnit.Kilometer)` is `1.0`. Prefer the enum overloads for configuration: unknown distance/area unit strings panic, while unknown speed strings leave the input unchanged. ## Measure a journey This complete program checks coordinate order, spherical distance and unit conversion without files or network access. ```vex [geo-distance.vx] import { Coordinate, fromGeoJSON, isValidCoordinate, getDistance, getPreciseDistance, DistanceUnit, convertDistance } from "geo"; fn main() { let start = Coordinate { latitude: 0.0, longitude: 0.0 }; let finish = fromGeoJSON([1.0, 0.0]); if !isValidCoordinate(finish) { $panic("invalid coordinate"); } let metres = getDistance(start, finish); if metres != 111319.0 { $panic("unexpected rounded distance"); } let kilometres = convertDistance(metres, DistanceUnit.Kilometer); if kilometres < 111.0 || kilometres > 112.0 { $panic("wrong units"); } match getPreciseDistance(start, finish, 0.0) { Some(distance) => { if distance < 111000.0 || distance > 112000.0 { $panic("unexpected ellipsoid distance"); } }, None => { $panic("distance did not converge"); }, } $println("geo distance: PASS"); } ``` `getDistance` uses a spherical Haversine calculation. Its two-argument form rounds to the nearest metre; the third `accuracy` argument controls rounding, and `0.0` leaves the result unrounded. That argument is an output rounding increment, not a guarantee of measurement accuracy. `getPreciseDistance` uses the WGS84 Vincenty inverse calculation and returns `Option`: `None` means its iteration did not converge. Decide explicitly whether your application can fall back to spherical distance. Do not turn `None` into zero, which would incorrectly identify distinct points as coincident. `TimedCoordinate { coordinate, time }` stores time in **milliseconds**. `getSpeed(start, end)` divides distance by elapsed time and returns metres per second. Require a finite, positive elapsed interval before calculating speed. ## Work with a region ```vex [geo-region.vx] import { Coordinate, getBounds, isPointInBoundingBox, isPointInPolygon, wktToPolygon } from "geo"; fn main() { let polygon = match wktToPolygon("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))") { Some(points) => points, None => { $panic("invalid polygon text"); }, }; let point = Coordinate { latitude: 1.0, longitude: 1.0 }; let bounds = match getBounds(&polygon) { Some(value) => value, None => { $panic("empty polygon"); }, }; if !isPointInBoundingBox(point, bounds) { $panic("outside bounds"); } if !isPointInPolygon(point, &polygon) { $panic("outside polygon"); } $println("geo region: PASS"); } ``` WKT positions also use longitude first. `wktToPolygon` returns an owning `Vec` for the **exterior ring only**; it discards holes and extra dimensions. It is not a complete WKT geometry/schema validator. Validate the returned coordinates and your application's minimum point count for external input. Polygon membership uses ray crossings; choose an explicit boundary policy if points on an edge have business meaning. `getBounds` takes component-wise extrema and returns `None` for an empty collection. `getBoundsOfDistance(point, metres)` creates a spherical-radius box. `isPointInBoundingBox` includes its boundary and treats `minLng > maxLng` as an antimeridian crossing. A component-wise box from an arbitrary point set is not necessarily the smallest box across that meridian. ## Choose the operation | Task | API and result | | --- | --- | | Distance along a route | `getPathLength(&points): f64`; sums adjacent segments | | Nearest coordinate | `findNearest(origin, &points): Option` | | Preserve application records | `findNearestIndex` / `orderByDistanceIndices` with a coordinate callback | | Reorder coordinates | `orderByDistance` returns an owning vector | | Spherical centre | `getCenter(&points): Option` | | Centre of component bounds | `getCenterOfBounds(&points): Option` | | Bearing | `getGreatCircleBearing` / `getRhumbLineBearing`; degrees | | Compass label | `getCompassDirection`; a borrowed direction label | | Destination from bearing | `computeDestinationPoint(point, metres, bearing)` | | Radius membership | `isPointWithinRadius`; strict distance comparison | | Segment proximity | `getDistanceFromLine`, `isPointNearLine`, `isPointInLine` | | Polygon area | `getAreaOfPolygon`; spherical square metres | | Arc intersection | `getIntersectionOfLines`: unique crossing of two finite minor great-circle arcs, or `None` | | Degree/minute/second text | `sexagesimalToDecimal`, `decimalToSexagesimal`, `coordinateFromText` | Collection operations also accept distance callbacks. For application records, provide a `fn(&T): Coordinate` extractor and keep the returned indices associated with the same unchanged vector. This avoids copying records merely to sort by distance. ## Dynamic coordinate input The package also accepts arrays, vectors and maps. Numeric maps use `coordinateFromMap(&Map)`; text-map and value-map overloads convert their values before range checking. Coordinate-key helpers recognize aliases such as latitude/longitude and allow caller-supplied key lists. Use the checked conversion result instead of selecting an arbitrary missing key as `0.0`. `fromGeoJSON(&Vec)` can return `None` when two components are unavailable. Fixed-array overloads require sufficient coordinates. A returned coordinate still needs the validation appropriate to its conversion overload. Borrowed map/vector inputs remain owned by the caller; returned numeric coordinates are independent copyable values. See [collections](docs/std/collections.md), [string conversion](docs/std/strconv.md) and [Unicode](docs/std/unicode.md) for the surrounding data-processing pipeline. --- Source: https://vex-lang.org/docs/std/hash.md # Hashing The `hash` package provides allocation-free hashing over `str` and `Span`. Its public surface is grouped by algorithm and does not expose raw pointer-plus-length functions. ## Choose an algorithm | API | Best fit | Security boundary | | --- | --- | --- | | `XxHash3` | general-purpose fast 64-bit hashing | not collision-resistant | | `WyHash` | compact seeded hashing and short keys | not collision-resistant | | `Fnv1a` | stable identifiers and format compatibility | do not use for adversarial keys | | `SipHash` | untrusted hash-table keys | requires a secret random 128-bit key | | `Crc32c` | accidental-corruption checks | not protection against attackers | Use `std/crypto` when you need a cryptographic digest, MAC, password hash or signature. ## One-shot API ```vex import { Crc32c, Fnv1a, SipHash, WyHash, XxHash3 } from "hash"; let general = XxHash3.hash("hello"); let seeded = WyHash.hash("hello", 42 as u64); let stable64 = Fnv1a.hash("hello"); let stable32 = Fnv1a.hash32("hello"); let keyed = SipHash.hash("hello", secret0, secret1); let crc = Crc32c.checksum("hello"); ``` Each method above also accepts a borrowed `Span`. Seeded overloads exist for `WyHash` and `XxHash3`. ## Incremental API ```vex import { Crc32c, Fnv1a, SipHasher, XxHash3 } from "hash"; let! stable = Fnv1a.new(); stable.update("header"); stable.update(payload); let stableDigest = stable.finish(); let! keyed = SipHasher.new(secret0, secret1); keyed.update("header"); keyed.update(payload); let keyedDigest = keyed.finish(); let! fast = XxHash3.new(); fast.update("header"); fast.update(payload); let fastDigest = fast.finish(); let! crc = Crc32c.new(); crc.update("header"); crc.update(payload); let checksum = crc.finish(); ``` Chunks may be strings or byte spans and may split at any byte. Every hasher keeps bounded state. `XxHash3.new(seed)` selects the seeded form; its state is eight accumulator lanes plus a fixed 256-byte tail and never grows with the input. `finish()` is non-mutating and `reset()` preserves the constructor seed. `Crc32c.reset()` restores its initial Castagnoli state. CRC-32C processes safe little-endian 64-bit chunks through the compiler intrinsic, then its byte tail; the compiler selects hardware only when the target proves it legal. ## Compatibility and guarantees - `WyHash` matches final4 / 4.3. - `XxHash3` matches upstream XXH3 64-bit 0.8.x, seeded and unseeded. - XXH3 long inputs use target-independent fixed-vector operations. CPU backends select their legal SIMD instructions; applications do not choose an architecture implementation or link a native hash library. - `SipHash` implements SipHash-2-4. - `Crc32c` implements CRC-32C Castagnoli and uses hardware only when the target proves the required CPU feature. - One-shot and incremental methods allocate no memory. - There is no fixed-key SipHash helper: a public key would defeat collision-DoS protection. Legacy snake-case free functions and raw pointer overloads were removed. Use the grouped APIs shown above. ## Built-in collections The named algorithms remain separate from built-in table policy. Values implement `Hash.hashInto` and feed the state owned by each `Map` or `Set`; they do not return a pre-finalized hash. Hosted `Map.new` obtains a fresh 128-bit key through the target entropy capability, and deterministic tools can select `DeterministicState` explicitly. The portable default currently uses SipHash-1-3, while the public `std/hash.SipHash` API remains stable SipHash-2-4. The table algorithm and its output may evolve and are not serialization formats. Freestanding targets do not gain a hidden libc dependency: entropy enters only through the explicit target runtime boundary. --- Source: https://vex-lang.org/docs/std/http/client.md # HTTP/1 Client (`http`) `http` exposes a bounded, cancellation-aware HTTP/1.1 client. It uses the same scheduler and ownership model as the server: no blocking resolver is hidden inside an async request, and every connect, write, and read receives the caller's `Context`. ## Send one request Resolve the endpoint at the application boundary, then keep the HTTP authority and socket endpoint explicit. This permits virtual hosting without putting DNS on a scheduler worker. ```vex import { ClientRequest } from "http"; import { Context } from "context"; import { IoError, IoErrorKind, newIoError } from "io/error"; import { IpAddr, Ipv4Addr, SocketAddr } from "net"; import { Duration } from "time"; async fn healthCheck(): Result { let endpoint = SocketAddr(IpAddr.V4(Ipv4Addr.loopback()), 8080); let context = Context.background().withTimeout(Duration.seconds(2)); let request = ClientRequest.new("GET", "api.internal.example", "/health"); match await request.send(endpoint, &context) { Ok(response) => { if !response.ok() { return Result.Err(newIoError(IoErrorKind.InvalidData, "health endpoint failed")); } return Result.Ok(response.body); } Err(failure) => return Result.Err(failure), } } ``` `ClientRequest.host` becomes the `Host` field. `SocketAddr` selects the TCP peer. The client does not resolve a hostname or infer a port from a URL string. ## Request construction ```vex import { ClientRequest, HttpClient, HttpClientConfig } from "http"; let! request = ClientRequest.new("POST", "service.example", "/v1/items"); request.setHeader("Authorization", "Bearer token") .setContentType("application/json") .setBody("{\"name\":\"vex\"}"); let! config = HttpClientConfig.defaults(); config.maxResponseBodyBytes = 2 * 1024 * 1024; let client = HttpClient.new(config); // `await client.send(&request, endpoint, &context)` ``` The encoder owns `Host`, `Content-Length`, `Transfer-Encoding`, `Trailer`, and `Connection`. Supplying any of those through `setHeader` is rejected before a socket is opened, so the wire has one authority and one framing interpretation. The direct-origin transport accepts origin-form (`/path?query`) for ordinary methods, `*` only for `OPTIONS`, and authority-form for `CONNECT`. Absolute-form proxy targets, URI fragments, and method/form mismatches fail closed rather than being serialized accidentally. Stateless `send` uses `Connection: close`; an explicit `HttpSession` owns the `keep-alive` policy instead. ## API | API | Meaning | | --- | --- | | `ClientRequest.new(method, host, path)` | Creates an owning buffered request. | | `request.setHeader(name, value)` | Adds or replaces an application header. | | `request.setContentType(value)` | Sets `Content-Type`. | | `request.setBody(value)` | Sets the complete buffered body. | | `request.acceptCompressed()` | Advertises the pure-Vex `br`, `zstd`, `gzip`, and `deflate` decoders. | | `await request.send(endpoint, context)` | Uses default limits for one exchange. | | `await request.sendInto(endpoint, sink, context)` | Uses default limits and streams the transfer-decoded response into an `AsyncWriter`. | | `HttpClient.new(config)` | Creates a reusable, stateless policy object. | | `await client.connect(endpoint, context)` | Opens one exclusive reusable `HttpSession` with this policy. | | `await HttpSession.connect(endpoint, context)` | Opens one exclusive session with default limits. | | `await session.send(request, context)` | Performs one sequential keep-alive exchange. | | `await session.sendInto(request, sink, context)` | Streams one sequential response and preserves reuse only after a proven boundary. | | `await session.sendFrom(request, source, length, context)` | Streams one exact-length request and materializes the response; reuse requires both exact boundaries. | | `await session.sendFromInto(request, source, length, sink, context)` | Streams request and response bodies without materializing either. | | `await client.send(request, endpoint, context)` | Sends with explicit limits. | | `await client.sendFollowing(request, endpoint, redirectPolicy, context)` | Follows a finite same-origin redirect chain without a resolver or hidden DNS. | | `await client.sendFollowingResolved(request, endpoint, redirectPolicy, resolver, context)` | Follows cross-origin hops through an explicit async `HttpRedirectResolver`. | | `await client.sendInto(request, endpoint, sink, context)` | Decodes the final body into an `AsyncWriter` without materializing a response-sized string. | | `await client.sendFrom(request, endpoint, source, length, context)` | Streams an exact-length request over one stateless exchange. | | `await client.sendFromInto(request, endpoint, source, length, sink, context)` | Streams both directions over one stateless exchange. | | `response.ok()` / `response.isRedirect()` | Status-class helpers. | | `response.header(name)` | Case-insensitive response header lookup. | | `response.decodeContent(decoding)` | Atomically decodes an owning response under explicit byte/layer bounds. | The transport defaults are intentionally bounded: 4 MiB request bytes, 32 KiB response headers, 16 MiB transferred response body, 64 response fields, and 16 interim responses. `maxInformationalResponses` and `maxResponseHeaders` must remain in `1..=64`; every other limit must also be non-zero. Zero never means “unbounded”. Decoded content has a separate 16 MiB default described below. ## Follow redirects explicitly `send` still performs exactly one exchange. Redirect behavior is opt-in and bounded, so enabling it cannot silently add network work to an existing call. ```vex import { ClientRequest, HttpClient, HttpRedirectPolicy } from "http"; let request = ClientRequest.new("GET", "service.example", "/old/path"); let redirectPolicy = HttpRedirectPolicy.defaults(); // 10 hops let response = await HttpClient.new().sendFollowing( &request, endpoint, &redirectPolicy, &context, )?; ``` Same-origin means equal ASCII-case-insensitive scheme and host plus equal effective port. Such a hop keeps using the original caller-resolved `SocketAddr`; the HTTP layer performs no DNS. Relative and network-path `Location` values use `url::URL.resolve` (RFC 3986), query components are preserved, dot segments are normalized, and fragments never reach the request target. Cross-origin redirects require an explicit async authority boundary: ```vex import { HttpRedirectResolver } from "http"; struct AppEndpoints: HttpRedirectResolver { api: SocketAddr, } async fn (self: &AppEndpoints) resolve( host: str, port: u16, context: &Context, ): Result { let _ = context; if host == "api.example" && port == 80 { return Result.Ok(self.api); } return Result.Err(newIoError(IoErrorKind.NotFound, "unknown HTTP authority")); } let response = await client.sendFollowingResolved( &request, initialEndpoint, &redirectPolicy, &endpoints, &context, )?; ``` The resolver can use an application-owned pre-resolved map or a genuinely async resolver; it must not perform blocking DNS on a scheduler worker. Before any cross-origin resolver/connect, the client removes `Authorization`, `Proxy-Authorization`, `Cookie`, and `Cookie2` while preserving ordinary application headers. Redirect method/body behavior is fixed and testable: | Status | Next request | | --- | --- | | `301` / `302` | `POST` becomes bodyless `GET`; other methods are preserved. | | `303` | Becomes bodyless `GET`, except `HEAD` remains `HEAD`. | | `307` / `308` | Method and complete buffered body are replayed exactly. | The API follows only `301`, `302`, `303`, `307`, and `308` with exactly one `Location`. A missing `Location` returns the response unchanged. A zero or greater-than-64 hop policy, exhausted budget, duplicate/malformed `Location`, URL userinfo, cross-origin hop without a resolver, or non-`http` transport fails closed. `https` remains unsupported until the cancellation-aware TLS adapter lands. Redirect following is intentionally absent from `sendFrom`, `sendInto`, and `sendFromInto`: an `AsyncReader` or streamed response sink is not replayable by definition. A future streaming redirect surface must require an explicit body factory/replay contract rather than retaining or guessing ownership. ## Decode compressed content Compression is opt-in and composes with both one-shot and redirected owning responses: ```vex import { HttpContentDecoding } from "http"; let! request = ClientRequest.new("GET", "assets.example", "/manifest.json"); request.acceptCompressed(); let! response = await client.sendFollowing( &request, endpoint, &redirectPolicy, &context, )?; response.decodeContent(&HttpContentDecoding.defaults())?; ``` `acceptCompressed()` emits `Accept-Encoding: br, zstd, gzip, deflate`, exactly the pure-Vex codecs understood by `decodeContent`. The operation parses every `Content-Encoding` field as a strict comma-token list and reverses the coding order, so `Content-Encoding: gzip, br` decodes Brotli first and Gzip second. `identity` is a no-op. Unsupported tokens, empty elements and trailing commas are errors rather than guesses. `HttpContentDecoding.defaults()` allows 16 MiB of decoded output and four non-identity layers; the hard layer ceiling is 16. The transferred body remains independently bounded by `HttpClientConfig.maxResponseBodyBytes`. Every decode stage observes the decoded ceiling, preventing nested compression bombs. Unknown-size frames begin with a small source-proportional allocation and grow geometrically only after a typed codec capacity signal; the 16 MiB ceiling is not reserved for a tiny response. Mutation is atomic. On malformed content, unsupported coding or a limit error, the original encoded body and headers remain available for diagnostics. On success, the body becomes the decoded representation and stale wire `Content-Encoding`/`Content-Length` fields are removed; representation headers such as `Content-Type` remain. `sendInto` does not decode compressed content yet. Whole-buffer fallback would violate its allocation-bounded streaming contract, so streamed decompression waits for incremental codec readers that preserve `AsyncWriter` backpressure. ## Stream a response body `sendInto` is the bounded download/proxy path. It returns `ClientResponseHead` after the final body has been decoded into the supplied `AsyncWriter`; the response body itself is not retained by the client. The decoder uses a reused 16 KiB transport scratch buffer, preserves the same `Context` for both socket and sink writes, accepts fixed-length/chunked/close-delimited bodies, and enforces `maxResponseBodyBytes`. Here “decoded” means HTTP transfer framing (such as chunk sizes) has been removed. `Content-Encoding` compression is not decoded by this path; compressed representation bytes still reach the sink. ```vex import { ClientRequest, HttpClient } from "http"; import { AsyncWriter, IoError } from "io"; async fn download( endpoint: SocketAddr, destination: &W, context: &Context, ): Result where W: AsyncWriter { let request = ClientRequest.new("GET", "assets.example", "/release.bin"); let client = HttpClient.new(); let response = await client.sendInto(&request, endpoint, destination, context)?; return response.status; } ``` The destination observes normal async short-write/backpressure semantics via `io::asyncWriteAll`. A later transport, framing, cancellation or sink failure can occur after the sink has received a valid prefix; there is no rollback. For an atomic file download, stage bytes in temporary storage and publish only after the exchange succeeds and application-level checks pass. ## Stream a request body `sendFrom` accepts a mutable `AsyncReader` and one exact `Content-Length`. `ClientRequest.body` must remain empty, because buffered plus streamed payloads would create two authorities for framing. The complete head plus declared body length is checked against `maxRequestBytes` before connect. A fixed 16 KiB buffer carries natural source and socket backpressure; every read and write uses the caller's `Context`. ```vex let request = ClientRequest.new("PUT", "assets.example", "/upload.bin"); let! source = UploadReader.open(); // implements AsyncReader let response = await client.sendFrom( &request, endpoint, &source!, sourceLength, &context, )?; ``` `sendFromInto` additionally accepts an `AsyncWriter` for the decoded response. Premature source EOF returns `IoErrorKind.UnexpectedEof`; cancellation, source failure and socket failure close the transport. An exclusive `HttpSession` becomes reusable only after the declared request bytes and canonical response framing have both reached their terminal boundaries. ## Reuse one exclusive connection `HttpSession` is the zero-lock, caller-owned foundation for connection reuse. It is intentionally sequential rather than a shared pool: one session accepts one request at a time, so HTTP/1.1 response association cannot drift across tasks. It emits `Connection: keep-alive` and remains reusable only after an exact HTTP/1.1 boundary with no unread bytes. ```vex let client = HttpClient.new(); let! session = await client.connect(endpoint, &context)?; let first = ClientRequest.new("GET", "service.example", "/one"); let one = await session.send(&first, &context)?; let second = ClientRequest.new("GET", "service.example", "/two"); let two = await session.send(&second, &context)?; ``` The session closes and becomes non-reusable on I/O or protocol failure, cancellation, `Connection: close`, HTTP/1.0, `101`, or a close-delimited body. Calling it while an exchange is in flight returns `IoErrorKind.ResourceBusy`. It is not a shared connection pool and it does not pipeline requests. Its bounded request encoder and response decoder workspace are reused after a successful exchange; returned `ClientResponse` values retain independent owned headers and body data. A one-off large decoded body is not retained by the idle session after that response has been materialized. ## Framing and safety The client and HTTP parser share one framing classifier. It accepts exactly one of: - a single decimal `Content-Length`; - one exact `Transfer-Encoding: chunked`; or - no explicit framing (a response body is then delimited by connection close). Duplicate `Content-Length`, duplicate `Transfer-Encoding`, `Content-Length` combined with `Transfer-Encoding`, transfer-coding substring matches such as `notchunked`, malformed values, and bodies beyond configured limits are errors. This avoids a client/proxy boundary disagreement. `Connection` is interpreted as an RFC comma-token list across every such header field: `Connection: keep-alive, close` retires a session, while an `upgrade` token is detected even when it shares a field with other tokens. Interim `1xx` responses are consumed before the final response under `maxInformationalResponses`; an endless `100`/`103` chain therefore cannot pin the exchange. `101 Switching Protocols` returns `IoErrorKind.Unsupported`. A successful `CONNECT` response is rejected for the same ownership reason: the current surface cannot safely pretend to hand over a live WebSocket or tunnel. Interim headers may arrive together with a larger final header or across arbitrary read boundaries. Buffered and streaming clients consume their prefix using `StringBuilder.discardPrefix`, an overlap-safe in-place move without a temporary allocation. Final parsed header views retain their backing buffer until body processing finishes; that buffer cannot re-enter the header append loop. A partial status-line remains incomplete until its delimiter arrives, including a split CRLF. An empty, CRLF-terminated reason phrase is complete. Method comparison is ASCII-case-insensitive for response semantics. `HEAD`, `204`, and `304` consume no body bytes. Informational responses and `204` must not contain message framing. A `205 Reset Content` accepts no framing, `Content-Length: 0`, or a proven empty chunked stream; a non-zero length or non-empty chunk fails closed. These rules preserve the exact boundary required for safe `HttpSession` reuse. ## Lifecycle and present boundary Stateless exchange primitives each open one TCP stream, perform one complete exchange, and close it. `sendFollowing*` composes those exact exchanges under its explicit hop policy. `HttpSession` is the explicit sequential reuse surface; it proves the response boundary before retaining a connection and retires it on any unsafe boundary. There is no implicit/shared pooling, implicit redirect following, TLS, streamed decompression, or upgraded-stream handoff yet. Streaming APIs never transfer ownership of the TCP stream. Internally, request writes use `io::asyncWriteAll` and response reads use the generic `io::AsyncReader` contract. The contract carries the caller's `Context` on every operation and is the future adapter seam for TLS and streaming bodies; it does not yet imply TLS, shared pooling or an exposed stream handoff API. Those features will be added behind explicit ownership and cancellation contracts; they are not emulated by a convenience wrapper. For HTTP server and Fiber application APIs, see [HTTP overview](docs/std/http/index.md) and [Fiber](docs/std/http/fiber.md). --- Source: https://vex-lang.org/docs/std/http/fiber.md # Fiber Framework (`http/fiber`) `http/fiber` combines an event-loop server with routed handlers, path parameters, middleware, and explicit streaming/async lanes. Applications register their routes before serving; the framework owns connection lifetime and response framing. The framework exposes HTTP/1 routing and cleartext prior-knowledge HTTP/2 paths for synchronous buffered routes, async buffered routes and bounded response streams. HTTP/2 request-body streaming, TLS ALPN activation and WebSocket-over-H2 are not part of those serving lanes. Register capabilities explicitly and follow the [serving map](docs/std/http/index.md#development-capability-map) when choosing handlers and transports. ## Building Applications Apps are created, routes are mapped, and middlewares are configured dynamically onto memory tables during setup. ```vex import { App, AppConfig, Ctx } from "http/fiber"; import { logger, cors } from "http/middleware"; fn main(): i32 { let! config = AppConfig.defaults(); // Deadline values are milliseconds; size/count fields are explicit budgets. config.readTimeout = 5000; // absolute HTTP/1 header/body deadline config.writeTimeout = 5000; // complete response-drain deadline config.idleTimeout = 60000; // connection inactivity deadline config.maxConnections = 65536; // process-wide accepted-connection budget config.maxHeaderBytes = 32768 as usize; config.maxHeaders = 64 as usize; config.responseBatchBytes = 256 * 1024; // pipelined response high-water mark let! app = App.new(config); // Attach middlewares app.use(logger); app.use(cors); // Register Routes app.get("/", fn(c: &Ctx!) { c.sendString("Go Vex!"); }); app.post("/users", fn(c: &Ctx!) { let body = c.body(); // Validation / Storage c.status(201).sendString("Created: " + body); }); // Start app.listen("0.0.0.0", 3000); return 0; } ``` ## Compile-time HTTP/1 profile When a service needs synchronous HTTP/1 routing but not HTTP/2, WebSocket, async routes or request/response streaming, construct the sealed profile: ```vex import { App, Ctx, HTTP_V1 } from "http/fiber"; fn health(ctx: &Ctx!) { ctx.status(200).sendString("ok".toString()); } fn main() { let! app = App<{HTTP_V1}>.new(); app.get("/health", health); app.listen("0.0.0.0".toString(), 3000); } ``` The ordinary `App` and every derived `Group` retain the same const-generic mask. Synchronous methods, middleware, static routes, custom 404/error handlers and `listenWithContext` remain available. Calling a registration method without its capability is a compile-time error, not a runtime fallback. Profiles compose directly, such as `App<{HTTP_V1 | WEBSOCKET}>`, without a second facade or duplicated framework API. The current zero-residue serving specialization is the exact `HTTP_V1` profile. Other valid composed masks enforce registration at compile time but still select the full multi-protocol worker kernel; per-bit binary/IR pruning for those non-minimal masks is planned and must not be inferred from the API composition alone. The distinction is compile-time, not a runtime flag. The feature value is propagated through the exact listen, connection, parser and dispatch monomorphs; eliminated branches do not enter the semantic call graph. On the 2026-08-27 no-cache snapshot, the minimal hello emitted 4,862,955 bytes / 714 LLVM definitions, compared with 20,069,805 bytes / 1,919 for `App.new()` plus the full listener. The minimal IR audit rejects H2 transport, WebSocket engine, async-route and response-stream launchers, Hpack ownership, WebSocket session ownership and full-profile lane selection. This specialization includes data ownership, not only control flow. `Router<{HTTP_V1}>` does not allocate the async/stream/WebSocket route sidecar; H2 field backing, response-stream writers, WebSocket handshake scratch and session identity belong to their selected protocol worker/task rather than to every `App` or `Ctx`. The handler ABI and frozen radix source of truth remain shared, and no per-request feature boolean or indirect dispatch was added. Plain `App.new()` selects `HTTP_FULL`. It remains the compatibility default and does not add runtime dispatch to request handling. ## Routing Engine Fiber matches path segments with a radix router. Static segments, named parameters and wildcard tails do not require a regular-expression engine. Routes and middleware are frozen before workers start. Concurrent workers read the immutable radix trees while request parameters and middleware cursors stay inside each worker's reusable `Ctx`. ### URL Parameters `:param` Dynamic parts of the URL are easily accessible via the `Ctx: params` API. ```vex app.get("/users/:id", fn(c: &Ctx!) { let id = c.params("id"); // Given /users/142 -> 142 c.sendString(id.toString()); }); ``` ### Wildcards `*wildcard` Match all subsequent path requests. Highly useful for catching static directory matches. ```vex app.get("/files/*filepath", fn(c: &Ctx!) { let path = c.params("filepath"); c.sendString("Serving file: " + path); }); ``` ## Context (`Ctx`) Methods `Ctx` provides request views and accumulates the response for the framework. Request views and the context itself are scoped to the current handler. Copy values that must outlive that request. ### Request Properties - `c.method()`: Request HTTP method (`GET`, `POST`) - `c.path()`: URL path. - `c.params(key)`: Path router variable - `c.query(key)`: URL Query mapping (`?search=foo`) - `c.header(key)`: Reads header case-insensitively - `c.body()`: The request payload string - `c.isJSON()` / `c.contentType()` ### Response Modifiers - `c.status(200)`: Set status and return the same mutable context reference - `c.set("X-Request-ID", "req-001")`: Set or replace a response header - `c.setType("application/json")`: Override Content-Type - **Sending Output**: - `c.sendString("Text")` - `c.sendJSON("{\"success\":true}")` - `c.sendHTML("

Welcome

")` - `c.send()`: Submit the current response body/status. - `c.sendStatus(400)`: Set status and send its status-text body - `c.redirect("/login")`: HTTP 302 Redirection `sendJSON` accepts an already-serialized JSON string; it does not escape concatenated values or serialize a struct. Use [`serde/json`](docs/std/serde/json.md) when building JSON from application data. ## Bounded dynamic responses For generated output whose final size is unknown, use a route-level stream handler rather than a raw socket or `Ctx.send*` loop: ```vex import { App, Ctx, ResponseStreamWriter } from "http/fiber"; fn events(c: &Ctx!, out: &ResponseStreamWriter!) { c.status(200).set("Content-Type", "text/event-stream"); let _ = out.write("event: ready\ndata: vex\n\n"); let _ = out.write("event: tick\ndata: 1\n\n"); } let! app = App.new(); app.getStream("/events", events); ``` `App.getStream`, `postStream`, `getStreamWith`, `postStreamWith`, plus Group `getStream`/`postStream`, use the same frozen radix tree and `c.next()` middleware chain as ordinary routes. A stream handler sets status and headers before its first `out.write`; that first write emits the canonical HTTP/1 header block. `ResponseStreamWriter` then owns lowercase-hex chunk framing, the terminal chunk, a reusable 64 KiB buffer, and the complete response write deadline. It never exposes a file descriptor. If an earlier pipelined request already has a completed response, Fiber drains it before reaching the stream producer. A failed stream write makes the connection non-reusable; a partial response is never followed by another HTTP/1 reply. `HEAD` uses GET fallback metadata but emits no chunk framing or payload. This response-stream API is deliberately synchronous. Request-body streaming uses the separate task-owned lane below and is not implied by `getStream`. Fiber already exposes the safe first async lane for complete HTTP/1 requests: `getAsync`, `postAsync`, `putAsync`, `deleteAsync`, `patchAsync`, `headAsync`, `optionsAsync`, plus a `*AsyncWith` form for every method. After frozen route selection, Fiber unregisters the descriptor, moves its admission lease and task-owned request state into one boxed task owner, then adopts the sole owning `Socket` as a `TcpStream`. The response uses the normal context-aware async write contract and the connection closes after that response; there is no handback for this complete-body lane yet. Route-local awaitable middleware preserves `before → await next() → after` exactly once. Ordinary `Handler` routes remain synchronous and allocation-free; they are never silently reinterpreted as coroutines. Connection admission remains correct across this transfer: each tracked HTTP/1 connection owns a shared Vex `Box` lease for the admission budget, and the task moves that lease with the socket rather than retaining a borrowed worker-local counter pointer. ```vex import { App, AsyncHandler, AsyncPipelineNext, Ctx } from "http/fiber"; import { Context } from "context"; async fn auth(ctx: &Ctx!, next: &AsyncPipelineNext!, cx: &Context) { // validate auth await next.run(ctx, cx); } async fn createJob(ctx: &Ctx!, _: &AsyncPipelineNext!, _: &Context) { ctx.status(201).sendString(ctx.params("id") + ":" + ctx.body()); } let! app = App.new(); let! middleware = Vec.new(); middleware.push(auth); app.postAsyncWith("/jobs/:id", middleware, createJob); ``` This lane receives the already-bounded complete request body. Incremental body delivery is intentionally not implied by `AsyncHandler`. ## Bounded request-body streams Large or incrementally processed uploads use an explicit body-stream route. Fiber selects the frozen route after the complete validated header but before ordinary body accumulation. It unregisters the descriptor, then transfers the sole socket owner, admission lease, framing state, request context and already-read body/pipeline suffix to one scheduler task. ```vex import { App, AsyncBodyPipelineNext, AsyncRequestBody, Ctx, } from "http/fiber"; import { BodyConsumerStart, RequestBodyConsumer } from "http"; import { Context } from "context"; struct ByteCounter: RequestBodyConsumer { total: usize } fn (self: &ByteCounter!) begin(_info: BodyConsumerStart): bool { self.total = 0 as usize; return true; } fn (self: &ByteCounter!) acceptChunk(bytes: str): bool { self.total = self.total + bytes.len(); return true; } fn (self: &ByteCounter!) finish(_totalBytes: usize): bool { return true; } fn (self: &ByteCounter!) cancel() { self.total = 0 as usize; } async fn upload( ctx: &Ctx!, body: &AsyncRequestBody!, _next: &AsyncBodyPipelineNext!, cx: &Context, ) { let! counter = ByteCounter { total: 0 as usize }; match await body.consume(&counter!, cx) { Ok(total) => { ctx.status(201).sendString(total.toString()); } Err(_) => { ctx.status(400).sendString("invalid request body"); } } } let! app = App.new(); app.postBodyStream("/upload", upload); ``` `bodyStream(method, path, handler)`, `bodyStreamWith(...)`, and `getBodyStream` / `postBodyStream` / `putBodyStream` / `deleteBodyStream` / `patchBodyStream` / `headBodyStream` / `optionsBodyStream` share the immutable router. Groups provide matching body stream methods; `Group.useBodyAsync` composes awaitable middleware and is inherited by nested Groups. Ordinary synchronous `Group.use` middleware does not cross the descriptor handoff, so its stack frame and `after next()` logic cannot accidentally outlive the worker event. `AsyncRequestBody.consume` may run once. It drives the canonical fixed-length/chunked decoder and exact `begin` -> chunks -> `finish|cancel` lifecycle through four fixed 16 KiB pages and a reused 64 KiB transport workspace. Chunks are synchronous borrowed views of task-owned page storage: consumers must copy data they retain. Context deadline/cancellation, consumer rejection, malformed framing, premature EOF and I/O failure all fail closed. No raw fd or borrowed transport read crosses an `await`. After a positive body lifecycle completion, Fiber writes the complete response through the same task-owned socket. If both request and response permit reuse, the task then moves the sole socket owner, admission lease, and exact preserved pipeline suffix into a fixed-capacity non-blocking worker handback inbox. A native wake pipe notifies the pollers, but only the adopting worker mutates its event loop and connection map. Already-read suffix bytes are parsed immediately; they cannot be stranded waiting for a socket edge. Failed body or response completion, a full/closed inbox, poller registration failure, cancellation, and shutdown all close and release exactly once. Descriptor reattachment is an internal integration boundary, not a developer escape hatch: the ownership-transfer functions are free functions omitted from the public `net` and `http/fiber` facades, and neither `TcpStream` nor `AsyncRequestBody` exposes a method which relinquishes its transport. This path is covered by a live one-write `POST body + pipelined GET` regression: the first response completes before the second request is dispatched, the first response advertises keep-alive, the second suffix is preserved, and server cancellation joins every worker. The test has explicit 1.2-second client and 500-ms worker-join fail-fast bounds rather than an unbounded channel wait. Complete-body `*Async` routes remain a separate close-after-response lane; the proof above applies specifically to `*BodyStream` routes. Multipart is provided as a bounded consumer over the same lane: ```vex import { MultipartLimits, MultipartSink, multipartBoundary, multipartConsumer, } from "http"; // UploadSink implements beginPart/partHeader/acceptPartChunk/endPart, // finishMultipart and cancelMultipart. It copies only metadata it retains. let boundary = multipartBoundary(ctx.contentType())?; let! sink = UploadSink.new(); let! form = multipartConsumer( boundary.asStr(), MultipartLimits.defaults(), &sink!, )?; let result = await body.consume(&form!, cx); ``` `MultipartConsumer` does not read a socket and does not decode HTTP framing. It recognizes arbitrarily fragmented MIME delimiters over the canonical decoded body, forwards binary part bytes synchronously, and retains only a fixed header workspace plus a delimiter tail. Defaults bound parts, bytes and header count per part, field-name bytes and filename bytes; applications may lower those limits per route. Duplicate/empty/overlong boundaries, truncated bodies, illegal part headers, false delimiter suffixes and sink rejection fail closed through the one-shot cancellation lifecycle. ## WebSocket routes Fiber WebSocket routes use the same frozen radix tree and middleware ordering: The tree owns structural match metadata, not a second copy of route handlers. After matching, the route index restores the exact middleware range from the router's single startup-owned flat pool. This keeps ordinary, streamed and WebSocket routes on one ordering contract, makes repeated freeze idempotent, and removes per-route middleware Vec allocation/copy during startup. ```vex import { App } from "http/fiber"; import { WsMessage, WsSession } from "http/ws"; fn echo(peer: &WsSession!, message: WsMessage) { if message.isText() { let _ = peer.sendText(message.data); } } let! app = App.new(); app.ws("/ws/:room", echo); ``` `App.ws` and `Group.ws` accept only a valid bodyless RFC 6455 opening request. After global and route middleware finish, Fiber drains earlier pipelined HTTP output, queues `101 Switching Protocols`, and transfers the same worker-local connection state to a bounded non-blocking `WsSession`. The callback receives complete text/binary messages plus received close/pong events; ping replies, frame fragmentation and partial writes remain in the worker state. See [WebSocket](docs/std/http/ws.md) for queue limits and current scope. `App.wsWithLifecycle(path, onOpen, handler, onClose)` and the corresponding `Group` method preserve the same route/middleware boundary. `onOpen` receives the event-scoped session after `101` has been queued; `onClose` receives an opaque session id (not an fd) exactly once on the owner worker while the connection retires. `App.wsWithOptions` / `Group.wsWithOptions` accept a `WsRouteOptions` policy whose protocol insertion order is server preference order. The corresponding `wsWithLifecycleOptions` methods combine that policy with lifecycle hooks. Selection is bounded, case-sensitive, and stored on `WsSession.protocol()`; each configured token is capped at 255 bytes and `requireSubprotocol()` rejects a no-overlap offer before handoff. The validated key/protocol cross Fiber's request-arena rewind only through fixed inline storage; no borrowed header view enters the persistent session. ## HTTP/1 framing and connection lifetime The live server uses one bounded incremental framing state per active connection. The state survives socket fragmentation without retaining bytes that have already been decoded. - `Content-Length` and exact `Transfer-Encoding: chunked` request bodies are supported. - Fragmented fixed-length and chunked bodies reuse the same incremental decoder state. Fiber retains a parsed header once and appends only newly decoded body bytes, avoiding repeated `header + body-so-far` copies during a slow upload. Common body-buffer capacity is reused on keep-alive; an exceptional body larger than 64 KiB is released immediately after dispatch instead of becoming permanent per-connection RSS. - `Content-Length` plus `Transfer-Encoding`, conflicting lengths, unsupported transfer codings, obs-fold, malformed field syntax, and invalid HTTP/1.1 `Host` rules are rejected before handler dispatch. Only exact `HTTP/1.0` and `HTTP/1.1` spellings are accepted; request-target control bytes are rejected. `Host` must be an authority shape—userinfo, path/query/fragment, ambiguous unbracketed IPv6, and invalid ports are rejected before routing. - Normal host names use RFC `reg-name` grammar; malformed percent escapes and non-authority punctuation are rejected, while valid IPv6/IPvFuture literals remain bracketed URI authorities. - Chunk sizes, data, CRLF boundaries, trailers, and a following pipelined request may arrive in arbitrary socket fragments. - Decoded body limits are checked before every append; trailers have separate bounded validation. - Keep-alive and pipelined suffixes stay attached to the same descriptor generation. A stale event from an earlier generation cannot close a newly reused OS descriptor. - `Connection` is parsed as a comma-token list across all field lines; `close` wins over `keep-alive`, so an ambiguous list never keeps a peer reusable. - Outbound `ClientRequest.host` uses that same authority grammar before a socket is opened. A resolved `SocketAddr` may deliberately differ for virtual hosting, but userinfo, paths, malformed literal addresses, and invalid ports are never serialized as `Host`. - `readTimeout` starts with the first byte of an HTTP/1 request and is absolute; sending occasional bytes does not extend it. `idleTimeout` starts at accept and refreshes after successful IO. Worker polls wake at least once per second to retire expired connections even when no socket event arrives. - `writeTimeout` bounds the complete response drain across partial writes, `EINTR`, and `EAGAIN`. Timeout closes keep-alive rather than pinning the event-loop worker indefinitely. Multi-chunk static drains share that one absolute deadline rather than restarting it per 64 KiB copy. - Response headers and bodies are serialized into response-owned reusable `StringBuilder` storage. Numeric fields are formatted in place and direct sends borrow the initialized prefix, avoiding concatenation temporaries and steady-state allocations. - The response serializer is the final header safety boundary. It owns framing fields and silently excludes malformed names or CR/LF-bearing values from generic application `Headers`, preventing wire-level header injection. - Parser delimiter scans use complete fixed `[u8; 16]` blocks and `Mask<16>` reductions. This keeps the native SIMD path allocation-free; dynamic-size slice comparisons are intentionally not used because they materialize a dynamic mask. - A Fiber handler never writes the final HTTP/1 response directly while the connection owns the output buffer. The response is appended exactly once and drained in ordered batches, preserving one-request/one-response semantics while allowing safe pipelined coalescing. `responseBatchBytes` is a high-water mark: after a complete response reaches it, Fiber drains before dispatching further pipelined work. An individual larger response remains intact, then forces the following batch boundary. Fiber reuses ordinary batch capacity, but drops an exceptional buffer larger than two batches after it drains, so a one-off large response cannot become permanent RSS on an otherwise idle keep-alive connection. - `sendFile`, `App.static`, and `Group.static` do not load an asset into `Response.body`. Fiber writes the exact `Content-Length` header in sequence, drains preceding pipelined output, and copies the opened descriptor through its reusable 64 KiB worker scratch buffer. A short read or bounded-write failure closes that connection, preventing a false-length keep-alive reply. - Response framing is centralized: Fiber suppresses all `HEAD` payload bytes while retaining the corresponding `GET` length, and statuses that cannot carry content (`1xx`, `204`, `205`, `304`) are serialized with a zero length. User headers cannot override `Content-Length`, `Transfer-Encoding`, or `Connection`, avoiding ambiguous HTTP/1 framing. - Dynamic producers use the route-level `ResponseStreamWriter` API above; handlers do not receive arbitrary direct-write access. This keeps response ordering, canonical framing and bounded socket writes intact. - `AppConfig.maxConnections` bounds accepted connections across the whole process, not per worker. Excess peers are closed before HTTP parser/state allocation and capacity is returned exactly once when the owning descriptor generation closes. Non-positive values select the safe 65,536 default. - `AppConfig.maxHeaderBytes` and `maxHeaders` independently bound HTTP/1 header storage and field cardinality before handler dispatch. Body or pipelined bytes coalesced into the same socket read do not consume the header byte budget. HTTP/2 uses the same configured read/idle/write deadline budgets. A stalled active connection emits CANCEL GOAWAY; an idle connection emits NO_ERROR GOAWAY. Both become write-only and close only after the complete terminal frame drains or the write deadline expires. Per-stream async task deadlines remain a later lane-specific requirement. On macOS, the default multi-worker topology uses one dedicated acceptor plus the configured number of client workers. Accepted handles are transferred explicitly through worker pipes; `Socket` temporaries do not retain ownership after transfer. Set `VEX_HTTP_MACOS_SINGLE_WORKER=1` only for diagnostics and comparative measurements. ## Graceful lifecycle `listenWithContext` is the canonical cancelable server lifecycle. It reuses Vex's shared `Context` cancellation state, completes the handler/pipeline currently executing on each worker, stops new accepts, closes worker-owned connections, and waits for all HTTP workers before returning. ```vex import { Context } from "context"; import { App } from "http/fiber"; let (lifetime, stop) = Context.background().withCancel(); let app = App.new(); go { app.listenWithContext(lifetime, "0.0.0.0", 3000); } // A signal handler or application coordinator owns this capability. let first = stop.cancel(); ``` `listen()` remains the forever-serving convenience form and internally uses `Context.background()`. Cancellation is cooperative and checked between event batches; it never tears down a handler halfway through its synchronous execution. Response draining remains bounded by `writeTimeout`. --- Source: https://vex-lang.org/docs/std/http/h2.md # HTTP/2 protocol foundations (`http/parser`) `http/parser` provides Vex-native HTTP/2 protocol ownership: frame ingress, SETTINGS/GOAWAY, HPACK, flow control, extensible priority, stream state and a typed application boundary. Fiber uses this owner for cleartext prior-knowledge HTTP/2 synchronous buffered routes, async buffered routes and bounded response streams. There is no HTTP/2 client facade, TLS ALPN activation or gRPC facade in this interface. Application serving coordinates flow control, HPACK table lifetime, header-list limits, backpressure, cancellation, deadlines and GOAWAY draining through one bounded connection/stream state machine. Exact fragmented-preface promotion installs the connection-local transport; frame helpers cannot bypass the worker queue. Standalone frame parsing remains useful for protocol tools and deterministic tests without constructing an application server. ## Present use The module remains useful for parser tests and protocol tooling. The following is an illustrative fragment inside a unit-returning function, not a complete standalone program. Its public frame-level API is not a substitute for Fiber's application transport: ```vex import { DynamicTable, H2EndpointRole, H2EncodeResult, H2FlowResult, H2FieldSectionKind, H2FieldSectionResult, H2InboundFrameResult, H2IngressResult, H2ReceivePriorityResult, HpackDecodeLimits, H2ProtocolConfig, H2ProtocolState, H2ScheduleResult, H2ParseResult, H2ProtocolFrameResult, H2SendHeaderResult, HpackBlockResult, H2StreamAdmissionResult, decodeHeaderBlockLimited, encodePing, parseH2FrameLimited, validateH2FieldSection, } from "http/parser"; // Role and all bounded capacities belong to one owner. let config = H2ProtocolConfig { maxConcurrentStreams: 128, maximumChunkBytes: 16384, starvationTurns: 64, maxHeaderBlockBytes: 65536, hpackLimits: HpackDecodeLimits.defaults(), maxOutstandingSettings: 16, maxOutstandingPings: 16, }; let! h2 = match H2ProtocolState.new(H2EndpointRole.Client, config) { Some(state) => state, None => { return; }, // exit the enclosing function on invalid configuration }; match h2.openLocalStream() { H2StreamAdmissionResult.Opened(streamId, index) => { /* odd client ID */ } H2StreamAdmissionResult.Blocked(reason) => { /* capacity, drain or exhaustion */ } _ => { /* internal/protocol error */ } } // Validate metadata against the negotiated peer frame limit without guessing // error scope from a diagnostic string. match parseH2FrameLimited(bytes, peerSettings.maxFrameSize) { H2ParseResult.Ok(frame) => { // `exactPayload` is the complete frame payload retained by transport. let result = h2.recvFrame(&frame, exactPayload); } H2ParseResult.NeedMore(bytesNeeded) => { /* retain partial header */ } H2ParseResult.StreamError(rejectedFrame, code, message) => { // Retain/discard rejectedFrame.length payload bytes, then RST_STREAM. } H2ParseResult.ConnectionError(code, message) => { /* GOAWAY + close */ } H2ParseResult.Invalid(message) => { /* invalid local configuration */ } } // Recommended incremental boundary. The caller retains unconsumed bytes. match h2.recvBytes(bufferedInput) { H2IngressResult.Dispatched(consumed, result) => { // Handle borrowed result views before dropping `consumed` bytes. } H2IngressResult.NeedMore(consumed, additional) => { // Drop only `consumed`; retain the rest and read `additional` bytes. } H2IngressResult.Invalid(reason) => { /* local configuration/contract bug */ } } // A complete HPACK block is either wholly decoded or a terminal error. let! table = DynamicTable.new(peerSettings.headerTableSize as usize); let limits = HpackDecodeLimits.defaults(); match decodeHeaderBlockLimited(block, &table, &limits) { HpackBlockResult.Ok(headers) => { // Low-level users must apply the message-context gate themselves. let semantic = validateH2FieldSection(&headers, H2FieldSectionKind.Request); } HpackBlockResult.Error(message) => { /* COMPRESSION_ERROR */ } } // Control encoders are capacity-aware and atomic on failure. match encodePing(&output, "12345678", false) { H2EncodeResult.Ok(bytesWritten) => { /* exactly 17 */ } H2EncodeResult.Error(message) => { /* output is unchanged */ } } // PRIORITY_UPDATE parsing, connection sequencing and scheduler mutation share // one owner. `priorityFrame` is the already validated frame header. match h2.recvPriorityUpdateFrame(&priorityFrame, priorityPayload) { H2ReceivePriorityResult.Applied(streamId, priority) => { /* committed */ } H2ReceivePriorityResult.ConnectionError(code, message) => { /* fail closed */ } H2ReceivePriorityResult.Invalid(message) => { /* wrong local API route */ } } ``` ## Typed application boundary After `H2ProtocolState` has decoded and validated an initial request field section, `h2ApplicationRequest` moves the existing HPACK-owned strings into the shared Fiber `Ctx`. It does not synthesize or reparse an HTTP/1 request. Method, scheme, authority, path, query and ordinary header views remain backed by one stable owner in the context. The returned `H2ApplicationBody` connects DATA to the same `RequestBodyConsumer` contract used by HTTP/1 streaming routes: ```vex import { H2ApplicationBodyResult, H2ApplicationRequestResult, h2ApplicationRequest, } from "http/fiber"; match h2ApplicationRequest( fd, streamId, endStream, kind, info, &fields!, config.bodyLimit, ) { H2ApplicationRequestResult.Ready(request) => { let! request = request; let! body = request.body; match body.begin(&consumer!) { H2ApplicationBodyResult.Complete(0) => { /* header-only request */ } H2ApplicationBodyResult.NeedMore(_) => { /* wait for DATA */ } H2ApplicationBodyResult.Error(reason) => { /* reset/fail closed */ } } // `payload` is the padding-free borrowed view returned by // H2ProtocolState.recvDataFrame / recvFrame. let result = body.feedData(streamId, payload, endStream, &consumer!); } H2ApplicationRequestResult.Invalid(reason) => { /* local bridge contract */ } } ``` The shared `DecodedBodyLifecycle` owns admission, byte-limit enforcement, declared content-length equality, synchronous borrowed-chunk delivery and the exactly-once finish/cancel transition. HTTP/1 feeds it after transfer decoding; HTTP/2 feeds it after padding and flow-control validation. A DATA stream-ID mismatch, body-limit overflow, early END_STREAM or consumer rejection cancels the lifecycle atomically. Once a buffered request is complete, `app.dispatchBuffered(&request.ctx!)` uses the exact frozen radix lookup, route parameters, global middleware and route middleware used by HTTP/1. It performs no wire I/O. Ordinary buffered routes complete synchronously. Dynamic lanes return `ApplicationDispatchResult.TransportRequired` with one exact `ApplicationTransportRequirement`: `AsyncRequest`, `StreamingRequestBody`, `StreamingResponse` or `WebSocket`. Impossible combinations such as `TransportRequired(Complete)` are not representable. Those lanes cannot accidentally execute without a transport owner, and HTTP/2 does not maintain a second router or middleware implementation. The live H2 transport installs `AsyncRequest` as a scheduler task without lending it the multiplexed descriptor. Each worker owns one bounded MPSC result lane and non-blocking wake pipe; workers without async routes allocate neither. Cancellation is registered before spawn. A token containing exact boxed connection identity is authoritative, while its fd is only a lookup hint, so a late completion cannot target a reused descriptor or stream. Peer reset, deadline, connection abort and shutdown cancel the exact task owner; late results are dropped, and invalid handler results commit a stream-scoped reset. Streaming responses use a second bounded task-to-worker lane. One exact connection-generation token, cooperative cancellation handle and one-slot acknowledgement channel couple every producer chunk to actual HEADERS/DATA wire progress. Peer reset, deadline and connection abort cancel the producer, close backpressure and reject stale events. Request-body streaming and WebSocket lanes remain refused without leaking capacity: the transport removes the buffered application owner, returns accepted connection credit and commits one RST_STREAM without entering user code. The full frozen match plus capability classification measured 51.10 ns with zero allocations in the 2026-08-26 short M2 Max O3 regression run. This seam is the static `BufferedApplicationDispatcher` contract rather than a dependency on Fiber's concrete `App` type. `App` implements it with no virtual dispatch or allocation; HTTP/2 transport code therefore remains reusable by a future HTTP/3 owner without creating an application/transport import cycle. The live prior-knowledge integration uses a connection-local `H2BufferedStreamSet` for ordinary synchronous routes. Its capacity mirrors the negotiated concurrent-stream limit; duplicate/full admission changes no state, fragmented bodies remain bounded by the shared lifecycle, completed responses release their slot, and RST_STREAM/GOAWAY teardown cancels each remaining consumer once. Header-only requests allocate no body buffer. Small declared bodies reserve exactly their size, while large declarations start at 4 KiB and grow only after validated DATA arrives, avoiding eager per-stream RSS. `H2ApplicationSession` now connects typed protocol results to that registry. It moves initial request HEADERS into the shared `App`, completes DATA or terminal trailers through the same body lifecycle, and cancels the exact owner on RST_STREAM or connection failure. Accepted DATA records both connection and stream receive credit; neither ledger entry is cleared until `flushConnectionCredit` / `flushStreamCredit` successfully encode a complete WINDOW_UPDATE. Callers must flush stream credit before committing an END_STREAM response which closes that stream. Receive validation may correctly retire a malformed stream before transport has written its required reset. `H2ProtocolState.sendStreamErrorFrame` owns that separate obligation: failed output capacity leaves it pending and the first successful 13-byte RST_STREAM commit makes later attempts inert. The transport never selects reset scope by matching diagnostic strings. Late DATA on a closed stream is reported as typed `DiscardedData` with the exact flow-controlled payload size. It is not delivered to the application, but `H2ApplicationSession` retains the connection-level credit for a later atomic WINDOW_UPDATE. Stream credit is intentionally absent after retirement, so one bad stream cannot leak or inflate another stream's window. `H2ResponseEgress` is the bounded outbound counterpart. It serializes one HPACK field block at a time, copies each complete HEADERS/CONTINUATION frame into a caller-reserved queue region, and retains response bodies until scheduled DATA has also been copied. DATA chunk size is the minimum of queue capacity, the peer's max-frame-size, the RFC 9218 scheduler turn and connection/stream send windows. HPACK reports an exact `OutputTooSmall(required)` result without changing compression state, allowing the connection scratch to begin at 512 bytes and grow only when a real response needs more. The 2026-08-25 M2 Max O3 gate measures one 64 KiB borrowed DATA admission, accounting callback and END_STREAM transition at **1.86 ns / 536.8 M transitions/s**. Its 32.0 TB/s logical byte rate is not a memory-bandwidth claim: this boundary intentionally performs no payload copy. Fiber's cleartext prior-knowledge server now drains these typed session, task-completion, response-stream and egress actions through its existing socket event loop. Mandatory control bytes are reserved ahead of DATA, buffered work is deferred fairly, accepted credit returns before terminal responses, and connection deadlines retain GOAWAY until write completion. Async/stream task cancellation and late-result rejection are complete; TLS ALPN and two-stage active-stream shutdown remain open. Request ownership, flow-credit accounting, receive-error reset mapping and bounded response scheduling are complete. After dispatch, `h2ApplicationResponse(&ctx!)` moves the buffered response body into one HTTP/2 egress owner. It emits `:status`, canonical content-length and lowercase validated application fields, filters HTTP/1-only framing fields and preserves HEAD representation length while suppressing payload DATA. The returned fields are passed directly to `H2ProtocolState.sendHeaderBlock`; the HTTP/1 response encoder is never involved. The codec boundary is fail-closed: - frame parsing enforces the negotiated frame size and type-specific stream/length rules before a caller accepts metadata. Peer failures carry typed `StreamError` or `ConnectionError` scope and HTTP/2 error codes; local negotiated-limit misuse is a separate `Invalid` result. The transport never has to inspect diagnostic text to choose RST_STREAM versus GOAWAY. Unknown extension frames are discarded without stream admission or mutation in every state, but still pass through connection sequencing and cannot interleave a fragmented field block; - SETTINGS validation is transactional and rejects invalid push, window and frame-size values without partially mutating state. Omitted values retain their effective value, duplicate known fields apply in wire order, and unknown identifiers are ignored. Typed parse errors preserve RFC scope: an oversized initial window is `FLOW_CONTROL_ERROR`, while malformed frame size/push values retain their specified connection error; - complete SETTINGS, SETTINGS ACK, PING, WINDOW_UPDATE, RST_STREAM and GOAWAY encoders validate buffer capacity and wire metadata before writing; failures leave the destination unchanged. GOAWAY encoding also preserves optional opaque debug bytes under the 24-bit payload bound; - GOAWAY parsing is typed and rejects every payload shorter than eight bytes. `recvGoAwayFrame` / `sendGoAwayFrame` own exact payload/debug data, connection sequencing, the non-increasing boundary, retry-safe stream retirement and complete wire encoding. Generic connection/frame APIs cannot bypass the owner, and undersized output changes no drain state; - PING uses exact eight-byte opaque payloads. `sendPingFrame` registers a token only after the complete 17-byte frame encodes; the preallocated `maxOutstandingPings` set rejects duplicates and overflow without mutation. `recvPingFrame` releases only an exact matching ACK, classifies unmatched acknowledgements without consuming another probe, and exposes non-ACK bytes as a borrowed `AckRequired` payload for `sendPingAckFrame`. Generic frame methods cannot bypass this correlation owner; - HPACK integers distinguish truncation from overflow; - Huffman literals use the complete RFC 7541 octet table, validate EOS/padding and never write beyond caller capacity; - complete block decoding returns `HpackBlockResult`, never a silent partial header list, and applies explicit field-count, decoded-byte, per-string and dynamic-table limits; - table-size updates are accepted only at the beginning of a block and cannot exceed the configured SETTINGS maximum. After an acknowledged reduction, the peer's next block must begin with a conforming size update; a rejected block cannot mutate shared table state; - outbound `HpackEncoder` state is connection-owned and transactional. Fields select `Auto`, `Incremental`, `Without` or `Never` indexing; authorization and cookie fields default to never-indexed, and Huffman is emitted only when it is shorter. Preflight checks field count/list/string/block/output bounds before the first byte, so a rejected block changes neither output nor the dynamic table; - stream windows reject zero/negative consumption and update increments, check overflow before arithmetic, represent the full 1–256 priority range, and enforce the map's concurrent-stream cap. DATA arriving after the peer-facing side closes is discarded with `STREAM_CLOSED` but remains charged to connection flow control; non-zero WINDOW_UPDATE racing a closed stream is accepted without reviving it; - `H2ConnectionState` independently sequences received and emitted header blocks, rejects orphan/wrong-stream/interleaved CONTINUATION frames, accounts both local SETTINGS awaiting peer ACKs and peer SETTINGS awaiting local ACKs, and enforces non-increasing GOAWAY last-stream identifiers; - the live prior-knowledge transport requires the first post-preface peer frame to be non-ACK SETTINGS. A request or other frame cannot reach user dispatch before this RFC 9113 connection gate succeeds; - the same connection owner assigns local IDs and admits peer streams under an explicit client/server role. It enforces odd/even ownership, monotonic peer IDs, concurrent capacity and non-wrapping 31-bit exhaustion before materialization. PUSH_PROMISE reserves only its payload's promised ID, never its carrier, and peer HEADERS cannot open a locally owned idle stream. Valid refused/ignored peer IDs are consumed, while failed local admission leaves the next ID unchanged; - graceful GOAWAY supports the initial maximum boundary followed by a lower final boundary. New local work stops after peer GOAWAY, streams above its boundary are classified retry-safe, and peer streams above the locally sent boundary are ignored without entering the stream map. A steady-state exact GOAWAY receive turn with three debug bytes measures **13.20 ns / 75.74 M/s** on the 2026-08-25 M2 Max O3 gate; - `recvDataFrame` validates exact payload length and padding, returns only a borrowed application-byte slice, and commits connection/stream receive credit with END_STREAM state. `sendDataFrame` symmetrically commits the selected scheduler budget, both send windows, frame metadata and stream transition. Generic stream methods reject DATA, so flow accounting cannot be split from protocol state; local exhaustion reports `Blocked`, while peer violations distinguish connection and stream error scope; - `recvWindowUpdateFrame` / `sendWindowUpdateFrame` own payload parsing or encoding, connection sequencing, zero/31-bit validation, scoped overflow, credit mutation and scheduler wakeup as one transaction. Generic stream and connection methods reject WINDOW_UPDATE. `StreamMap` applies peer and local SETTINGS_INITIAL_WINDOW_SIZE deltas to all existing streams transactionally, preserves legal negative windows, and gives future streams the correct direction-specific defaults; - WINDOW_UPDATE payload parsing is typed, exact-width and rejects the reserved zero increment before arithmetic; - RST_STREAM payload parsing preserves the complete open 32-bit error-code space. `recvRstStreamFrame` / `sendRstStreamFrame` own sequencing, idle-stream classification, stream/scheduler retirement and encoding as one transaction; generic frame methods reject resets, and a failed 13-byte encode changes no active state; - RFC 9218 dictionaries accept `u=0..7` and boolean `i`, ignore valid unknown or unsupported members, and reject malformed RFC 8941 syntax or over-limit fields before registration; - `recvPriorityUpdateFrame` and `sendPriorityUpdateFrame` own complete PRIORITY_UPDATE turns: exact bounded Structured Fields parsing or canonical encoding, client-only connection sequencing and scheduler mutation commit together. Generic connection/stream APIs reject the frame. Request priority may arrive before HEADERS, push targets must already be materialized, closed targets are discarded, and active plus idle priority state belongs to one bounded scheduler registry; - `H2PriorityScheduler` pre-reserves its registry and performs selection and completion without allocation. Lower urgency numbers win, non-incremental peers run serially by stream ID, incremental peers rotate, byte chunks are capped, and a configurable turn bound prevents starvation. One outstanding lease makes structural mutation and completion ordering explicit; - `H2ProtocolState` is the production-facing composition used by Fiber's live prior-knowledge transport. It uses one capacity for active streams and early idle priorities, pre-reserves and recycles stream slots, and retires stream plus scheduler state atomically on reset, natural close, GOAWAY or abort. Stream memory is therefore bounded by concurrency rather than total IDs observed over a long-lived connection; - `H2ProtocolState.recvFrame` is the single transport-facing receive switch for a complete parsed frame. It routes DATA, headers, SETTINGS, WINDOW_UPDATE, reset, GOAWAY, PING and both priority formats to their dedicated owner and returns one `H2InboundFrameResult`. Unknown extensions are sequenced then ignored, so transport needs no competing frame-type switch; - `recvBytes` connects fragmented caller-owned buffers to that switch through connection-owned discard state. Incomplete valid frames report zero consumed bytes and retain a zero-copy payload. Stream-invalid or oversized payloads are safely discarded across read boundaries before the next pipelined frame is parsed, avoiding attacker-selected frame-sized allocations; - SETTINGS is not accepted through generic frame methods. Peer deltas become effective before `SettingsAckRequired` is returned. Locally sent deltas are merged onto the newest pending snapshot and commit from a pre-bounded FIFO only when the corresponding ACK arrives. This keeps ordered ACK semantics, concurrent-stream admission, directional frame/window limits, header-list policy and HPACK table lifetime under one owner; - `recvHeaderFrame` owns the exact received payload path behind that dispatcher. HEADERS admits a new peer stream inside the same transaction; capacity- refused and post-GOAWAY ignored blocks are nevertheless decoded fully before the typed result is exposed, preserving the connection HPACK table. It validates frame length, strips HEADERS/PUSH_PROMISE padding and metadata, reassembles only compressed bytes under `maxHeaderBlockBytes`, and decodes at END_HEADERS using one connection-lifetime dynamic table. The generic stream-frame method rejects header-bearing frames, so HPACK lifetime cannot be bypassed; - `sendHeaderBlock` owns the symmetric outbound path. Request/response/trailer semantics, per-stream message phase, stream transition, connection sequencing, peer limits, encoder table and caller bytes commit as one unit. `sendStreamFrame` rejects HEADERS, PUSH_PROMISE and CONTINUATION. The result carries an allocation-free cursor that maps the contiguous HPACK payload to one HEADERS and any required CONTINUATION frames under the effective peer frame size. `remainingWireBytes` supports exact all-or-nothing queue reservation before cursor drain, preventing frame interleaving; - `sendPushPromise` owns outbound server push under the same transaction. It reserves an even local ID as `ReservedLocal`, scheduler capacity and the carrier transition together with HPACK/output commit. Failure restores the ID, slot, scheduler, compression table and caller bytes. The returned cursor counts the four-byte promised-ID prefix inside the first frame and uses CONTINUATION for the remainder without copying; - a stream transition error is retained until the complete compressed block has advanced HPACK state. This keeps later streams synchronized. A malformed compressed block returns `COMPRESSION_ERROR` and makes the owner terminal; - after successful HPACK decode, fields cross an RFC 9113 semantic gate before application delivery. It enforces lowercase token names, rejects CR/LF/NUL, invalid control bytes and edge whitespace, forbids connection-specific fields, limits `te` to request `trailers`, and validates pseudo-header context/order/uniqueness plus request, response, CONNECT and trailer shape; - message-phase state distinguishes initial requests, informational responses, final responses and terminal trailers. Malformed messages retire their stream with `PROTOCOL_ERROR` after HPACK synchronization; they do not become connection-level compression failures; - valid server PUSH_PROMISE received by a client atomically reserves the promised peer ID as `ReservedRemote` under the same parity, monotonicity and active-capacity checks. Its field section must be a complete GET/HEAD request; unsafe/non-cacheable methods retire the consumed promised stream. Forbidden client push and zero/reused IDs fail closed; - writable selection is a byte lease capped by scheduler policy, connection credit and stream credit. Flow-blocked work stays pending; WINDOW_UPDATE makes it schedulable again without requiring the application to republish readiness. Connection-only entry points reject stream frames, preventing callers from bypassing the unified stream state machine; - RFC 7540 dependency/weight fields are deprecated by RFC 9113 and retained as explicitly named `legacy*` metadata for old wire compatibility only. `recvLegacyPriorityFrame` owns the exact five-byte payload, accepts idle and closed IDs without materializing them, preserves stream-scoped size and self-dependency errors, and still enforces the connection CONTINUATION lock. `sendLegacyPriorityFrame` is the symmetric explicit compatibility encoder. Neither path affects the RFC 9218 scheduler. A legacy priority prefix inside HEADERS uses the same codec; self-dependency becomes a delayed stream error only after the HPACK block has advanced; Example transport-owner scheduling (an integration fragment). Here `data` is this selected stream's pending byte view, `bytesToWrite: u32` describes its available prefix, and `peerMaxFrameSize` is the current negotiated frame limit. The transport must reserve queue capacity before committing protocol state: ```vex // Admission has already registered the stream in the bounded priority domain. h2.markReady(streamId); match h2.nextWritable(Math.min(maximumWriteBytes, peerMaxFrameSize)) { H2ScheduleResult.Selected(id, budget) => { let payloadBytes = Math.min(budget, bytesToWrite); let finalChunk = endStream && payloadBytes == bytesToWrite; // The transport reserves exactly 9 + payloadBytes writable queue bytes // here. If reservation fails, release the lease while keeping work ready. // This example sends unpadded DATA, so payloadBytes == flowBytes. let! stillReady = true; match h2.sendDataFrame(id, payloadBytes, 0 as u8, finalChunk) { H2SendDataResult.Ready(frame, dataBytes, trailingPadding) => { emitData(frame, data, dataBytes, trailingPadding); // Advance the application's pending prefix by dataBytes. stillReady = hasMoreData || dataBytes < bytesToWrite; } H2SendDataResult.Blocked => { /* retain all pending application data */ } _ => { /* handle the local/protocol error; do not emit a frame */ } } let _ = h2.completeWritable(id, stillReady); } H2ScheduleResult.FlowBlocked => { /* wait for connection/stream credit */ } _ => { /* empty, busy, or invalid budget */ } } ``` `emitData` is transport pseudocode, not an exported helper. Select `data` and its completion flags for the returned `id`, not for an unrelated ready stream. When adding padding, the charged payload is `dataBytes + 1 + paddingBytes` (the extra byte is absent when padding is zero). That whole amount must fit both the selected remaining budget and the peer frame limit. Reserve `9 + flowBytes` queue bytes before `sendDataFrame`; the returned `Ready` commits windows, scheduler budget and stream state, so a subsequent queue-capacity failure cannot be treated as a harmless retry. Inbound DATA uses the symmetric exact-payload boundary: ```vex match h2.recvDataFrame(&frame, exactPayload) { H2ReceiveDataResult.Data(id, applicationBytes, endStream, flowBytes) => { consumeBorrowed(id, applicationBytes, endStream); // Replenish credit only after the consumer releases flowBytes. } H2ReceiveDataResult.Discarded(id, code, reason, flowBytes) => { // Do not deliver these bytes to the application. // Retain flowBytes as CONNECTION-only pending receive credit; // replenish it through stream-0 WINDOW_UPDATE after discarding input. // Queue the stream-scoped error/reset; never replenish this stream. } H2ReceiveDataResult.StreamError(id, code, reason) => { /* scoped error/reset */ } H2ReceiveDataResult.ConnectionError(code, reason) => { /* GOAWAY */ } H2ReceiveDataResult.Invalid(reason) => { /* local API contract violation */ } } ``` `Discarded` is distinct from an uncharged rejection: the connection receive window has already consumed `flowBytes`, even though the stream is rejected. Dropping that credit stalls unrelated streams; returning stream credit would revive accounting for a retired stream. `H2ApplicationSession` retains the connection-only obligation for its atomic credit flush. Application cancellation uses the complete wire-owned reset API: ```vex match h2.sendRstStreamFrame(streamId, ERR_CANCEL, &reservedOutput!) { H2SendResetResult.Encoded(id, code, 13) => { // Frame bytes, stream retirement and scheduler revocation committed. } H2SendResetResult.Closed(id) => { // Locally reserved idle stream: no wire stream, no reset frame. } H2SendResetResult.IdlePriorityRemoved(id) => { // Early priority state retired without inventing a stream. } H2SendResetResult.Invalid(reason) => { // State is unchanged; reserve output capacity and retry if appropriate. } _ => { /* already closed, not found, or sequencing error */ } } ``` Inbound reset payloads cross the symmetric `recvRstStreamFrame` boundary. A valid reset exposes its exact peer error code after retiring stream and scheduler state; RST_STREAM on an idle stream is connection-terminal. PING liveness uses the same transaction boundary: ```vex match h2.sendPingFrame("12345678", &reservedOutput!) { H2SendPingResult.Encoded(17) => { /* one bounded token is outstanding */ } H2SendPingResult.Duplicate => { /* choose a distinct probe token */ } H2SendPingResult.Full => { /* wait for an ACK or timeout policy */ } _ => { /* no token was consumed */ } } match h2.recvPingFrame(&frame, exactPayload) { H2ReceivePingResult.AckRequired(payload) => { let _ = h2.sendPingAckFrame(payload, &reservedOutput!); } H2ReceivePingResult.Acknowledged(payload) => { /* liveness confirmed */ } H2ReceivePingResult.UnmatchedAcknowledgement(_) => { /* ignore/report */ } _ => { /* malformed or sequencing failure */ } } ``` Received frames use the unified owner rather than transport-side routing or an independent HPACK decoder: ```vex match h2.recvFrame(&frame, exactPayload) { H2InboundFrameResult.HeaderBlockPending(streamId) => { // Only CONTINUATION for this stream may follow. } H2InboundFrameResult.Headers(streamId, promisedId, endStream, kind, info, headers) => { // promisedId is zero for HEADERS and non-zero for PUSH_PROMISE. // Admission, HPACK and HTTP/2 message semantics are validated here. // kind distinguishes request/response/trailers/push without a second // stream-state interpretation; info retains pseudo-header positions. // endStream tells the application whether a DATA body can follow. dispatch(headers); } H2InboundFrameResult.StreamError(id, code, reason) => { // Emit RST_STREAM; HPACK state is already synchronized. } H2InboundFrameResult.ConnectionError(code, reason) => { // Emit GOAWAY and close; the owner is terminal for compression errors. } H2InboundFrameResult.SettingsAckRequired => { /* emit SETTINGS ACK */ } H2InboundFrameResult.PingAckRequired(payload) => { /* echo ACK */ } H2InboundFrameResult.Ignored(_, _) => { /* compatible extension/ignored block */ } _ => { /* deliver other typed control/data results */ } } ``` The validated `info` also carries the canonical `contentLength` (`-1` when absent) and exact pseudo-header indexes. The connection owner compares that declaration with application DATA bytes in both directions. Frame padding is charged to flow-control windows but excluded from message content. Conflicting or overflowing declarations, trailer redefinition, early END_STREAM and excess DATA are stream-scoped protocol failures; a rejected local send changes no window, scheduler lease, HPACK state or stream phase. SETTINGS transport integration uses the dedicated owner methods: ```vex match h2.recvSettingsFrame(&frame, exactPayload) { H2ProtocolFrameResult.SettingsAckRequired => { // Peer values are already effective; emit one SETTINGS ACK. } H2ProtocolFrameResult.ConnectionError(code, reason) => { // Emit GOAWAY and close. } _ => { /* ACK committed, or caller contract violation */ } } // Record a locally emitted SETTINGS frame before handing bytes to transport. // Its snapshot becomes effective only after the matching peer ACK. let result = h2.sendSettingsFrame(&outboundFrame, outboundPayload); ``` Outbound application fields must also enter through the owner: ```vex let! output = VexStr.fromRaw(storage.asPtr() as Ptr, storage.len()); match h2.sendHeaderBlock(streamId, endStream, &headers, &output!) { H2SendHeaderResult.Encoded(id, payloadBytes, frames) => { let! cursor = frames; // Each fragment slices output without copying the HPACK block. while let Some(fragment) = cursor.next() { emitFrame(fragment.frame, output[fragment.payloadOffset .. fragment.payloadOffset + fragment.payloadBytes]); } } H2SendHeaderResult.StreamError(id, code, reason) => { /* reset stream */ } H2SendHeaderResult.ConnectionError(code, reason) => { /* close */ } H2SendHeaderResult.Invalid(reason) => { /* caller/policy failure */ } } match h2.sendPushPromise(carrierStreamId, &promisedRequest, &output!) { H2SendPushResult.Promised(carrier, promised, payloadBytes, frames) => { let! cursor = frames; // Reserve cursor.remainingWireBytes() atomically before this loop. while let Some(fragment) = cursor.next() { if fragment.promisedStreamId != 0 { emitPushFrame(fragment.frame, fragment.promisedStreamId, output[fragment.payloadOffset .. fragment.payloadOffset + fragment.payloadBytes]); } else { emitFrame(fragment.frame, output[fragment.payloadOffset .. fragment.payloadOffset + fragment.payloadBytes]); } } } _ => { /* no promised ID, slot, HPACK, or bytes leaked on failure */ } } ``` RFC 9113 defaults `MAX_CONCURRENT_STREAMS` and `MAX_HEADER_LIST_SIZE` to no wire-level limit. That does not make the implementation unbounded: `H2ProtocolConfig.maxConcurrentStreams`, `maxHeaderBlockBytes`, `hpackLimits` and `maxOutstandingSettings` are independent local resource ceilings. The connection configuration requires `hpackLimits.maxDynamicTableSize >= 4096` so the decoder can safely honor the pre-ACK RFC default before any advertised reduction becomes effective. The following are historical component measurements reported for an M2 Max with `-O3` in August 2026. They have not been revalidated for this page's current checkout or compiler and do not establish live-server throughput or production readiness. Reproduce them with recorded fixtures and a pinned build before using them for comparison. The 2026-08-24 M2 Max O3 component baseline measured priority-field parsing at 30.64 ns (32.6 M/s) and a select+complete turn across 32 ready streams at 72.77 ns (13.7 M/s). The unified owner performed the same turn, including stream lookup and connection/stream flow checks, in 77.71 ns (12.87 M/s), only about 4.94 ns above the raw policy primitive. These figures are not live HTTP throughput measurements. After the semantic gate, the 2026-08-24 M2 Max O3 baseline measures HPACK decode plus validation of a canonical three-field request at 126.19 ns (7.92 M/s). A complete connection-owner lifecycle turn—monotonic admission, request decode and validation, response-side close, scheduler retirement and slot reuse—takes 171.54 ns (5.83 M streams/s). The earlier 51.64 ns single-field probe was retired because it was not a complete valid HTTP/2 request and omitted stream retirement. Steady-state encoding of a canonical four-field request into four indexed bytes measures 40.06 ns (24.97 M blocks/s). The common all-indexed path performs a stack preflight and direct RFC static-table dispatch; literal and table-update blocks keep the full virtual-table transaction. A full reusable server-push ownership cycle—promise reservation and encoding, terminal response, scheduler release and slot recycle—measures 172.94 ns (5.78 M cycles/s). The complete received-reset lifecycle—monotonic admission, HPACK/field validation, exact RST_STREAM decode, stream/scheduler retirement and bounded slot reuse—measures **175.27 ns / 5.71 M streams/s**. A complete reusable PING send/ACK correlation turn measures **14.45 ns / 69.20 M round trips/s**; it includes frame encoding, bounded token registration, exact ACK matching and token release. The 2026-08-25 complete transport-facing PRIORITY_UPDATE receive turn—unified dispatch, bounded Structured Fields parse, direction/connection sequencing, registry lookup and in-place scheduler update—measures **29.43 ns / 33.97 M updates/s**. The corresponding production-shaped `recvBytes` turn—including the nine-byte frame-header parse and exact payload slice—measures **42.55 ns / 23.50 M frames/s**. The 2026-08-25 exact DATA-owner baseline measures a complete scheduled outbound turn—including two parsed WINDOW_UPDATE frames, flow/state commit, scheduler rotation and wakeup—at 32.99 ns / 30.31 M turns/s. Inbound exact-payload validation, state/flow commit and two atomically encoded credit updates measure 22.53 ns / 44.38 M turns/s. These use a 16-byte payload to emphasize control-plane cost, not bandwidth throughput. ## Remaining integration and qualification The cleartext prior-knowledge path is present in the development event loop; TLS ALPN integration remains open. Before relying on it, investigate the failed local async loopback run and validate reset, cancellation and write completion on the target. Cross-implementation interoperability, adversarial conformance and sustained backpressure tests also remain qualification gates. HTTP/3/QUIC follows only after these contracts exist; it will use the same application/router/middleware interface rather than a parallel framework. ## Detailed implementation notes from the overview The development implementation includes exact fragmented-preface selection, non-blocking worker queues, negotiated and type-specific frame checks with typed RFC stream/connection error scope, separate local-configuration failures, and extension-safe unknown-frame discard that still enforces field-block exclusivity. Transactional SETTINGS, typed whole-block HPACK, complete Huffman decoding, explicit header/table limits, checked stream windows, atomic capacity-aware control encoders and connection-owned CONTINUATION/SETTINGS-ACK/GOAWAY sequencing. DATA ownership is transactional across exact payload shape, checked padding, borrowed application bytes, scheduler budget, connection/stream windows and END_STREAM state. Late DATA is discarded without losing connection credit, while closed-stream WINDOW_UPDATE races are accepted without reviving state; generic frame APIs cannot bypass it. WINDOW_UPDATE has the same exact-frame ownership across parsing/encoding, sequencing, scoped overflow, credit and scheduler wakeup. RST_STREAM likewise owns exact payload/error decoding, idle-stream scope, sequencing, retirement and complete encoding; failed output commits nothing. SETTINGS window deltas are overflow-safe and directional. Explicit endpoint roles enforce local/peer stream parity, monotonic peer IDs, capacity, non-wrapping ID exhaustion and graceful GOAWAY drain/retry boundaries before materialization. Dedicated GOAWAY receive/send methods bind exact payload/debug bytes, sequencing, the non-increasing boundary, retry-safe retirement and complete encoding; failed output cannot begin draining. PING uses exact opaque payloads and a preallocated bounded correlation set; duplicate/full/failed sends consume no token, matched ACKs release one, and unmatched ACKs cannot corrupt another liveness probe. RFC 9218 priority fields and PRIORITY_UPDATE are bounded and typed. Dedicated receive/send methods atomically bind exact parsing or encoding, client-only sequencing and scheduler mutation; generic frame APIs cannot bypass them. A pre-reserved urgency/incremental scheduler providing serial/round-robin service, bounded starvation and no allocation during selection/completion. Deprecated RFC 7540 PRIORITY is isolated behind compatibility-only exact-frame methods: it accepts any stream state without materializing unknown IDs, preserves error scope and never enters the RFC 9218 scheduler. `H2ProtocolState` is the recommended integration boundary: it atomically owns admission, recyclable stream slots, active plus idle priority capacity, flow-aware writable leases, reset, GOAWAY retirement and abort. It also owns bounded fragmented header reassembly and the connection-lifetime HPACK table; stream errors do not desynchronize later streams, while compression errors fail the connection closed. Successfully decompressed fields then cross a strict request/response/CONNECT/push/trailer semantic gate; invalid names/values, connection fields and pseudo-header/message-phase violations retire only the malformed stream before application delivery. It also owns SETTINGS lifecycle: peer changes apply immediately, local snapshots commit in FIFO ACK order, initial-window deltas are transactional, and acknowledged HPACK table reductions are enforced at the next field-block boundary. Wire-level unlimited defaults remain separate from configured local memory/concurrency ceilings. `H2ProtocolState.recvFrame` is the single complete-frame receive boundary: known types reach their dedicated transaction, unknown extensions remain connection-sequenced, and HEADERS performs peer admission internally. Refused/GOAWAY-ignored field blocks still advance HPACK before their typed result is returned, so transport cannot split admission from compression. Completed field results retain validated message kind, pseudo-header positions and END_STREAM. Content-Length lists and DATA content totals are owned per stream in both directions; padding consumes flow credit but never content length, while mismatches fail without contaminating the connection. connection-owned `recvBytes` handles fragmented caller-owned input with exact consumed-prefix reporting. Valid payloads remain zero-copy; rejected stream payloads are discarded incrementally without frame-sized allocation before parsing resumes at the next pipelined frame. Outbound field sections use the same owner: semantic phase, stream/connection transition, negotiated limits, HPACK table and output commit atomically. Indexing policy is explicit, credentials/cookies default to never-indexed, Huffman is used only when smaller, and generic frame APIs reject header-bearing sends. Successful blocks return an allocation-free cursor that maps the contiguous payload to negotiated-size HEADERS and CONTINUATION frames without copying. Server `sendPushPromise` uses the same transaction for the carrier, even promised ID, `ReservedLocal` slot, scheduler capacity and HPACK bytes; its cursor includes the four-byte promised-ID prefix in exact frame/queue accounting. Fiber contains no dormant H2 side transport; prior knowledge installs the same cancellable non-blocking owner used by the protocol/application tests. Async request handlers publish through a bounded worker-local completion lane while the event loop retains the socket. Exact connection-generation identity rejects late results after reset, deadline, shutdown or fd reuse. --- Source: https://vex-lang.org/docs/std/http/index.md # HTTP & Client Overview For routed synchronous HTTP/1-only services, `App<{HTTP_V1}>.new()` selects a compile-time capability profile. `App` and its `Group` values retain one exact const-generic mask while H2, WebSocket, async-route and streaming execution engines are excluded from the emitted program. Capabilities can be composed, for example `App<{HTTP_V1 | WEBSOCKET}>`; unsupported registrations fail at compile time. The specialized listener applies to `HTTP_V1`; other valid masks use the full worker kernel. Plain `App.new()` remains the `HTTP_FULL` compatibility default. The choice adds no per-request runtime feature branch. See [Fiber Framework](docs/std/http/fiber.md#compile-time-http-1-profile). The `http` package provides Vex-native HTTP parsers, client/server foundations, and the `http/fiber` application framework. Its API direction takes inspiration from modern Go/Rust libraries and Fiber v3, while ownership, arenas, scheduling, and hardware acceleration remain native Vex mechanisms. Fiber serves HTTP/1 routes and WebSocket upgrades with bounded connection queues and explicit lifecycle hooks. Its HTTP/2 transport uses cleartext prior knowledge for synchronous buffered routes, async buffered routes and bounded response streams. TLS ALPN, HTTP/2 request-body streaming and WebSocket-over-H2 are separate capabilities and are not exposed by those lanes. HTTP/3/QUIC is outside this package's serving surface. ## Serving capability map | Feature | HTTP/1 | Cleartext prior-knowledge HTTP/2 | | --- | --- | --- | | Synchronous buffered route | Routed application handlers | Routed application handlers | | Async buffered request route | Async route lane | Async route lane | | Bounded streaming response | Response-stream lane | Response-stream lane | | Streaming request body | Separate body-stream lane | Not exposed through the live route lane | | Static files / `sendFile` | Descriptor-based bounded streaming | No dedicated file-send contract in this overview; use the documented response lane | | WebSocket | HTTP/1 upgrade path | WebSocket-over-H2 is not exposed | Use [Fiber](docs/std/http/fiber.md) for application registration, [HTTP/2](docs/std/http/h2.md) for connection/stream ownership, and [Middleware](docs/std/http/middleware.md) for request composition. ## Key Capabilities 1. **Fiber Framework Layer**: `App`, `Ctx`, and `Router` provide routing, including `:param` and `*wildcard` patterns. 2. **Borrowed parser fields**: Request paths, queries and header fields use `str` views into retained input bytes. The input owner must remain live while those views are used; they are not direct socket-backed spans. Fragmented input and owning application state can require retained storage or copies. 3. **WebSockets (`http/ws`)**: Fiber-integrated HTTP/1 RFC 6455 upgrade with worker-owned bounded queues, strict framing, lifecycle hooks, non-blocking partial I/O, bounded route-level subprotocol selection and idle timeout ownership. Upgrade/frame handoff preserves the connection's input and request-arena lifetime through protocol callbacks and close drain. 4. **HTTP/2 (`http/parser`, `http/fiber`)**: Cleartext prior-knowledge serving has synchronous buffered, async buffered and bounded response-stream paths through the shared application boundary. See [HTTP/2](docs/std/http/h2.md) for the protocol owner, flow control and limits. 5. **Middlewares**: Composable request handlers for logging and CORS. Static serving is a first-class `App.static` / `Group.static` route, not a duplicate middleware path. ## HTTP/1 framing and resource ownership The server coordinates parser, connection and worker state through these boundaries: - strict request framing rejects ambiguous length/transfer-encoding forms; - bounded incremental fixed-length and chunked bodies; - fragmented chunks and trailers with exact consumed/decoded progress; - preserved HTTP/1 pipelining suffixes and keep-alive ordering; - frozen immutable routing with worker-local request scratch; - route-local middleware is held once in a startup-owned flat router pool; frozen radix nodes retain route identity only, avoiding per-route middleware allocation/copy and duplicate handler ownership; - explicit native-handle ownership transfer in multi-worker servers; - request arenas reset handler temporaries without owning persistent connection state; - monotonic absolute HTTP/1 read deadlines resist slowloris drip-feeding; - idle peers are retired by bounded worker maintenance ticks; - response drains are bounded across partial writes and socket backpressure; - one shared `AppConfig.maxConnections` budget sheds excess accepted peers before parser/state allocation and reclaims capacity on exact descriptor ownership; - response serialization uses reusable one-pass storage with zero allocations after warmup on the verified common path. - fixed-width `Mask<16>` SIMD delimiter scans avoid dynamic-mask allocation in the HTTP/1 parser hot path; request/response correctness does not depend on a C or Rust parser implementation. - the live Fiber and canonical request parsers agree on exact HTTP version, request-target, framing, and `Connection` token rules; those shared security boundaries are regression-tested rather than inferred from one parser alone. - Fragmented `Content-Length` and chunked request bodies share one incremental body state, so slow uploads retain their header once rather than repeatedly copying the complete partial request. - Fiber appends responses directly into connection-owned reusable storage; `Response.appendEncodedTo(out)` exposes the same caller-owned batching contract for advanced servers without raw socket manipulation. Its `AppConfig.responseBatchBytes` high-water mark drains long pipelined bursts before aggregate response storage can grow with the peer's request queue; exceptional response buffers are released after drain rather than retained for the entire keep-alive connection. - `App.listenWithContext` provides context-native cancellation, descriptor cleanup, worker joining, and same-port restart safety. - `App.static` and `Group.static` check traversal and canonicalize the root and candidate before a separate open. Candidates outside the root are rejected at check time; concurrent path changes can invalidate that check. Keep the served tree writable only by trusted actors. - Known-length static and `Ctx.sendFile` responses are framed in order and streamed from their opened descriptor through Fiber's reusable 64 KiB worker scratch buffer, rather than being materialized as response-sized strings. - Dynamic HTTP/1 responses use `App.getStream` / `postStream` and a bounded `ResponseStreamWriter`: canonical chunk framing, terminal signaling and a single full-response deadline remain Fiber-owned. Stream routes preserve the normal frozen router and middleware chain, while prior pipelined replies drain before a producer starts. - Response framing has one authority: `HEAD` reports the equivalent `GET` length without sending bytes, while `1xx`, `204`, `205`, and `304` never carry content. Application headers cannot inject a competing `Content-Length`, `Transfer-Encoding`, or `Connection` field. See [Fiber Framework](docs/std/http/fiber.md) for route registration, application configuration and the live server model. --- ## HTTP Client The outbound HTTP/1 client is a bounded async exchange over an already-resolved `SocketAddr`. A request carries its HTTP authority; the endpoint carries its TCP peer. This prevents a blocking DNS operation from being accidentally hidden inside a scheduler task. ```vex import { ClientRequest } from "http"; import { Context } from "context"; import { IpAddr, Ipv4Addr, SocketAddr } from "net"; import { Duration } from "time"; let endpoint = SocketAddr(IpAddr.V4(Ipv4Addr.loopback()), 8080); let context = Context.background().withTimeout(Duration.seconds(2)); let request = ClientRequest.new("GET", "service.example", "/health"); let response = await request.send(endpoint, &context)?; ``` The encoder owns `Host`, `Content-Length`, and `Connection`. Stateless client calls use `Connection: close`; an explicit caller-owned `HttpSession` uses `keep-alive` only after a proven response boundary. The client uses one canonical framing decision shared with the parser: a single `Content-Length`, exact `Transfer-Encoding: chunked`, or close-delimited body. Ambiguous framing and configured-size violations are errors. There is no implicit shared pool. Redirects are equally explicit. `sendFollowing` accepts a finite `HttpRedirectPolicy` and reuses the caller-resolved endpoint only for same-origin hops. `sendFollowingResolved` requires an async `HttpRedirectResolver` before any cross-origin connection and strips authorization/cookie credentials at that boundary. RFC 3986 relative resolution, method/body replay rules, unsupported schemes and limit failures are documented and tested; ordinary `send` still means exactly one exchange. Owning responses can opt into pure-Vex `br`, `zstd`, `gzip`, and `deflate` decoding with `acceptCompressed` plus `decodeContent`. Transferred and decoded byte ceilings are independent, coding chains are bounded and reversed strictly, and failure leaves the raw response unchanged. Streamed decoding is not emulated with hidden whole-body buffering. Interim responses have an explicit count bound. Upgrade and successful `CONNECT` responses are rejected until a public API can transfer sole stream ownership. `HEAD`, `204`, `205`, and `304` follow their bodyless response semantics; `205` may consume only a provably empty framed body. Chunked responses are safe across arbitrary TCP read boundaries: an incomplete chunk-size line, data CRLF, or trailer is retained in a small bounded framing buffer, while already-decoded payload goes directly to the selected response destination. This applies equally to buffered `send` and `sendInto`. The client already routes its request/response I/O through the shared, context-required `io::AsyncReader` / `AsyncWriter` boundary. This preserves cancellation and backpressure semantics today while reserving one adapter seam for TLS and streaming bodies; it is not a claim of pooling or upgrade support. See [HTTP Client](docs/std/http/client.md) for limits, cancellation behavior, supported surface, and deliberate current boundaries. --- Source: https://vex-lang.org/docs/std/http/middleware.md # Middleware (`http/middleware`) Fiber supports synchronous middleware handlers and separate async middleware lanes for the routes that expose them. Middleware registration occurs during application setup; consult [Fiber](docs/std/http/fiber.md) for the lane-specific rules. This modular architecture allows you to easily inject utilities right into the HTTP lifecycle: The examples require the `http` standard-library modules to be resolvable by your compiler. In a source checkout, setting `VEX_STDLIB_PATH` to the checkout's `lib/std` directory is one way to select them. Availability and resolution in a downloadable release must be checked separately. ```vex import { logger, cors, CorsConfig } from "http/middleware"; ``` ## Logger When installed first, `logger` wraps subsequent handlers and logs method, path, response status and elapsed time. The implementation does not add a timestamp. ```vex app.use(logger); // Output: // Example shape: [GET] /api/users → 200 (1ms) ``` ## CORS (Cross-Origin Resource Sharing) `cors` adds allow-origin, methods, headers and max-age response headers. It answers `OPTIONS` with status 204. CORS is a browser policy and does not replace authentication or authorization. ```vex app.use(cors); // Allows any origin // Or instead, configure a specific origin: app.use(CorsConfig.new("https://example.com").build()); ``` ## Static files Static serving is deliberately a route API, so it shares Fiber's frozen router and request lifecycle rather than adding a second middleware path. ```vex app.static("/static", "./public"); ``` The implementation checks parent traversal, canonicalizes the configured root and candidate, and rejects candidates outside the root at check time. It then opens the canonical path in a separate operation, so this check does not prove confinement if an attacker can change path components concurrently. Keep the served tree writable only by trusted actors and validate the threat model for your deployment. The HTTP/1 implementation queues an opened file for bounded descriptor-based streaming; it is not a general asset-pipeline replacement. HTTP/2 static-route behavior requires separate validation on the target. --- Source: https://vex-lang.org/docs/std/http/reference.md # std::http API Reference Public declarations reachable through the documented package entry points. Signatures follow the source snapshot; consult the module guide for support and qualification boundaries. ## Application entry points Choose [client exchanges](docs/std/http/client.md), [direct Server callbacks](docs/std/http/server.md), or [Fiber routing](docs/std/http/fiber.md) before consulting signatures. [HTTP/2](docs/std/http/h2.md) and [WebSocket](docs/std/http/ws.md) have separate protocol and qualification boundaries. Names declared `export` in an internal module are not necessarily re-exported from `"http"` or `"http/fiber"`. ## Re-exports from other packages - [`WsFrame`](docs/std/net_reference.md#WsFrame) from `"http/ws"`. ### HTTP_V1 Import: `"http/fiber"`. ```vex export const HTTP_V1: u32=1 as u32; ``` ### HTTP_V2 Import: `"http/fiber"`. ```vex export const HTTP_V2: u32=1 as u32 << 1; ``` ### WEBSOCKET Import: `"http/fiber"`. ```vex export const WEBSOCKET: u32=1 as u32 << 2; ``` ### ASYNC_ROUTES Import: `"http/fiber"`. ```vex export const ASYNC_ROUTES: u32=1 as u32 << 3; ``` ### REQUEST_STREAMING Import: `"http/fiber"`. ```vex export const REQUEST_STREAMING: u32=1 as u32 << 4; ``` ### RESPONSE_STREAMING Import: `"http/fiber"`. ```vex export const RESPONSE_STREAMING: u32=1 as u32 << 5; ``` ### HTTP_FULL Import: `"http/fiber"`. ```vex export const HTTP_FULL: u32=HTTP_V1 | HTTP_V2 | WEBSOCKET | ASYNC_ROUTES | REQUEST_STREAMING | RESPONSE_STREAMING; ``` ### FRAME_DATA Import: `"http/parser"`. ```vex export const FRAME_DATA: u8=0x0; ``` ### FRAME_HEADERS Import: `"http/parser"`. ```vex export const FRAME_HEADERS: u8=0x1; ``` ### FRAME_PRIORITY Import: `"http/parser"`. ```vex export const FRAME_PRIORITY: u8=0x2; ``` ### FRAME_RST_STREAM Import: `"http/parser"`. ```vex export const FRAME_RST_STREAM: u8=0x3; ``` ### FRAME_SETTINGS Import: `"http/parser"`. ```vex export const FRAME_SETTINGS: u8=0x4; ``` ### FRAME_PUSH_PROMISE Import: `"http/parser"`. ```vex export const FRAME_PUSH_PROMISE: u8=0x5; ``` ### FRAME_PING Import: `"http/parser"`. ```vex export const FRAME_PING: u8=0x6; ``` ### FRAME_GOAWAY Import: `"http/parser"`. ```vex export const FRAME_GOAWAY: u8=0x7; ``` ### FRAME_WINDOW_UPDATE Import: `"http/parser"`. ```vex export const FRAME_WINDOW_UPDATE: u8=0x8; ``` ### FRAME_CONTINUATION Import: `"http/parser"`. ```vex export const FRAME_CONTINUATION: u8=0x9; ``` ### FRAME_PRIORITY_UPDATE Import: `"http/parser"`. ```vex export const FRAME_PRIORITY_UPDATE: u8=0x10; ``` RFC 9218 extensible HTTP priority signal. ### FLAG_END_STREAM Import: `"http/parser"`. ```vex export const FLAG_END_STREAM: u8=0x1; ``` ### FLAG_ACK Import: `"http/parser"`. ```vex export const FLAG_ACK: u8=0x1; ``` ### FLAG_END_HEADERS Import: `"http/parser"`. ```vex export const FLAG_END_HEADERS: u8=0x4; ``` ### FLAG_PADDED Import: `"http/parser"`. ```vex export const FLAG_PADDED: u8=0x8; ``` ### FLAG_PRIORITY_F Import: `"http/parser"`. ```vex export const FLAG_PRIORITY_F: u8=0x20; ``` ### H2_SETTINGS_HEADER_TABLE_SIZE Import: `"http/parser"`. ```vex export const H2_SETTINGS_HEADER_TABLE_SIZE: u8=1; ``` ### H2_SETTINGS_ENABLE_PUSH Import: `"http/parser"`. ```vex export const H2_SETTINGS_ENABLE_PUSH: u8=2; ``` ### H2_SETTINGS_MAX_CONCURRENT_STREAMS Import: `"http/parser"`. ```vex export const H2_SETTINGS_MAX_CONCURRENT_STREAMS: u8=4; ``` ### H2_SETTINGS_INITIAL_WINDOW_SIZE Import: `"http/parser"`. ```vex export const H2_SETTINGS_INITIAL_WINDOW_SIZE: u8=8; ``` ### H2_SETTINGS_MAX_FRAME_SIZE Import: `"http/parser"`. ```vex export const H2_SETTINGS_MAX_FRAME_SIZE: u8=16; ``` ### H2_SETTINGS_MAX_HEADER_LIST_SIZE Import: `"http/parser"`. ```vex export const H2_SETTINGS_MAX_HEADER_LIST_SIZE: u8=32; ``` ### H2_DEFAULT_URGENCY Import: `"http/parser"`. ```vex export const H2_DEFAULT_URGENCY: u8=3; ``` ### H2_MAX_PRIORITY_FIELD_BYTES Import: `"http/parser"`. ```vex export const H2_MAX_PRIORITY_FIELD_BYTES: usize=1024; ``` ### OP_CONTINUATION Import: `"http/parser"`. ```vex export const OP_CONTINUATION: u8=0x0; ``` ### OP_TEXT Import: `"http/parser"`. ```vex export const OP_TEXT: u8=0x1; ``` ### OP_BINARY Import: `"http/parser"`. ```vex export const OP_BINARY: u8=0x2; ``` ### OP_CLOSE Import: `"http/parser"`. ```vex export const OP_CLOSE: u8=0x8; ``` ### OP_PING Import: `"http/parser"`. ```vex export const OP_PING: u8=0x9; ``` ### OP_PONG Import: `"http/parser"`. ```vex export const OP_PONG: u8=0xA; ``` ### CLOSE_NORMAL Import: `"http/parser"`. ```vex export const CLOSE_NORMAL: u16=1000; ``` ### CLOSE_GOING_AWAY Import: `"http/parser"`. ```vex export const CLOSE_GOING_AWAY: u16=1001; ``` ### CLOSE_PROTOCOL_ERROR Import: `"http/parser"`. ```vex export const CLOSE_PROTOCOL_ERROR: u16=1002; ``` ### STATUS_OK Import: `"http"`. ```vex export const STATUS_OK: i32=200; ``` ### STATUS_CREATED Import: `"http"`. ```vex export const STATUS_CREATED: i32=201; ``` ### STATUS_ACCEPTED Import: `"http"`. ```vex export const STATUS_ACCEPTED: i32=202; ``` ### STATUS_NO_CONTENT Import: `"http"`. ```vex export const STATUS_NO_CONTENT: i32=204; ``` ### STATUS_RESET_CONTENT Import: `"http"`. ```vex export const STATUS_RESET_CONTENT: i32=205; ``` ### STATUS_PARTIAL_CONTENT Import: `"http"`. ```vex export const STATUS_PARTIAL_CONTENT: i32=206; ``` ### STATUS_MOVED_PERMANENTLY Import: `"http"`. ```vex export const STATUS_MOVED_PERMANENTLY: i32=301; ``` ### STATUS_FOUND Import: `"http"`. ```vex export const STATUS_FOUND: i32=302; ``` ### STATUS_NOT_MODIFIED Import: `"http"`. ```vex export const STATUS_NOT_MODIFIED: i32=304; ``` ### STATUS_TEMPORARY_REDIRECT Import: `"http"`. ```vex export const STATUS_TEMPORARY_REDIRECT: i32=307; ``` ### STATUS_PERMANENT_REDIRECT Import: `"http"`. ```vex export const STATUS_PERMANENT_REDIRECT: i32=308; ``` ### STATUS_BAD_REQUEST Import: `"http"`. ```vex export const STATUS_BAD_REQUEST: i32=400; ``` ### STATUS_UNAUTHORIZED Import: `"http"`. ```vex export const STATUS_UNAUTHORIZED: i32=401; ``` ### STATUS_FORBIDDEN Import: `"http"`. ```vex export const STATUS_FORBIDDEN: i32=403; ``` ### STATUS_NOT_FOUND Import: `"http"`. ```vex export const STATUS_NOT_FOUND: i32=404; ``` ### STATUS_METHOD_NOT_ALLOWED Import: `"http"`. ```vex export const STATUS_METHOD_NOT_ALLOWED: i32=405; ``` ### STATUS_CONFLICT Import: `"http"`. ```vex export const STATUS_CONFLICT: i32=409; ``` ### STATUS_GONE Import: `"http"`. ```vex export const STATUS_GONE: i32=410; ``` ### STATUS_CONTENT_TOO_LARGE Import: `"http"`. ```vex export const STATUS_CONTENT_TOO_LARGE: i32=413; ``` ### STATUS_UNPROCESSABLE_ENTITY Import: `"http"`. ```vex export const STATUS_UNPROCESSABLE_ENTITY: i32=422; ``` ### STATUS_TOO_MANY_REQUESTS Import: `"http"`. ```vex export const STATUS_TOO_MANY_REQUESTS: i32=429; ``` ### STATUS_INTERNAL_SERVER_ERROR Import: `"http"`. ```vex export const STATUS_INTERNAL_SERVER_ERROR: i32=500; ``` ### STATUS_NOT_IMPLEMENTED Import: `"http"`. ```vex export const STATUS_NOT_IMPLEMENTED: i32=501; ``` ### STATUS_BAD_GATEWAY Import: `"http"`. ```vex export const STATUS_BAD_GATEWAY: i32=502; ``` ### STATUS_SERVICE_UNAVAILABLE Import: `"http"`. ```vex export const STATUS_SERVICE_UNAVAILABLE: i32=503; ``` ### STATUS_GATEWAY_TIMEOUT Import: `"http"`. ```vex export const STATUS_GATEWAY_TIMEOUT: i32=504; ``` ### WS_MAX_QUEUED_BYTES Import: `"http/ws"`. ```vex export const WS_MAX_QUEUED_BYTES: usize=WS_MAX_BUFFER_BYTES; ``` The output limit is intentionally equal to the accepted input/message limit. It makes a slow peer a bounded backpressure condition instead of an unbounded worker-memory commitment. ### WS_TEXT Import: `"http/ws"`. ```vex export const WS_TEXT: u8=1; ``` ### WS_BINARY Import: `"http/ws"`. ```vex export const WS_BINARY: u8=2; ``` ### WS_CLOSE Import: `"http/ws"`. ```vex export const WS_CLOSE: u8=8; ``` ### WS_PING Import: `"http/ws"`. ```vex export const WS_PING: u8=9; ``` ### WS_PONG Import: `"http/ws"`. ```vex export const WS_PONG: u8=10; ``` ### WS_MAX_SUBPROTOCOLS Import: `"http/ws"`. ```vex export const WS_MAX_SUBPROTOCOLS: usize=32 as usize; ``` A handshake may advertise several subprotocols, but an attacker-controlled comma list must not turn route selection into unbounded quadratic work. ### AsyncBodyHandler Import: `"http/fiber"`. ```vex type AsyncBodyHandler = async fn( &Ctx!, &AsyncRequestBody!, &AsyncBodyPipelineNext!, &Context ) ``` One explicit awaitable body-route step. All middleware in this lane sees the same task-owned request body and continuation; ordinary synchronous Fiber middleware is never allowed to retain either value. ### AsyncHandler Import: `"http/fiber"`. ```vex type AsyncHandler = async fn(&Ctx!, &AsyncPipelineNext!, &Context) ``` A task-owned, awaitable Fiber handler. This is an explicit async lane; ordinary `Handler` remains synchronous by design. ### Handler Import: `"http/fiber"`. ```vex type Handler = fn ( &Ctx!) ``` ### StreamHandler Import: `"http/fiber"`. ```vex type StreamHandler = fn ( &Ctx!, &ResponseStreamWriter!) ``` A bounded HTTP response producer. The route owns response metadata through `Ctx` until its first `out.write`; afterwards `ResponseStreamWriter` is the only path which can produce body bytes and HTTP/1 framing. ### WsHandler Import: `"http/fiber"`. ```vex type WsHandler = fn ( &WsSession!, WsMessage) ``` Runs on the owning Fiber worker for each complete WebSocket message. The `WsSession` borrow is event-scoped: applications can queue replies but do not receive descriptor ownership or a blocking read primitive. ### WsOpenHandler Import: `"http/fiber"`. ```vex type WsOpenHandler = fn ( &WsSession!) ``` Runs after Fiber has accepted a valid upgrade and queued its `101` reply. The borrow is worker-scoped, so opening work can queue a welcome frame but cannot take ownership of the descriptor. ### WsCloseHandler Import: `"http/fiber"`. ```vex type WsCloseHandler = fn (u64) ``` Runs exactly once when Fiber retires a WebSocket connection. The supplied identity is stable for the session but is never an OS descriptor. Close hooks are observational: transport ownership has ended, so no session handle is exposed for further I/O. ### RequestHandler Import: `"http"`. ```vex type RequestHandler = fn (req: &Request, res: &Response!) ``` Direct request/response callback for `Server` and `App.serveDirect`. The request is valid only for the callback. Responses are buffered into the worker-owned connection output and drained after the callback returns. ### HttpRedirectResolver Import: `"http"`. ```vex export contract HttpRedirectResolver { async fn resolve( host: str, port: u16, context: &Context, ): Result; } ``` Async authority-to-endpoint boundary used only by cross-origin redirects. Implementations receive an HTTP host and effective port. They may consult an application-owned pre-resolved map or an async resolver, but must not perform blocking DNS on a scheduler worker. Same-origin redirects never invoke this contract and keep using the caller's original endpoint. ### RequestBodyConsumer Import: `"http"`, `"http/parser"`. ```vex export contract RequestBodyConsumer: ChunkSink { begin(info: BodyConsumerStart)!: bool; acceptChunk(bytes: str)!: bool; finish(totalBytes: usize)!: bool; cancel()!; } ``` Stateful destination for one bounded decoded HTTP body. The lifecycle is deliberately synchronous at the byte-delivery seam: `acceptChunk` receives a borrowed transport view, so acknowledging it after an `await` would be an ownership violation. Async Fiber routes will place owned fixed-capacity pages *before* this contract, not turn this contract into a raw descriptor callback. ### ChunkSink Import: `"http/parser"`. ```vex export contract ChunkSink { acceptChunk(bytes: str)!: bool; } ``` Destination for decoded transfer-coding payload bytes. The view is borrowed from the current transport fragment and is valid only for this call. Returning `false` aborts decoding without accepting later transport bytes. This is a statically-dispatched contract: a streaming consumer does not pay for a closure, allocation, or virtual call. ### MultipartSink Import: `"http"`, `"http/parser"`. ```vex export contract MultipartSink { beginPart(info: MultipartPartInfo)!: bool; partHeader(name: str, value: str)!: bool; acceptPartChunk(bytes: str)!: bool; endPart()!: bool; finishMultipart(partCount: usize)!: bool; cancelMultipart()!; } ``` Synchronous destination for one decoded multipart stream. The contract is deliberately allocation-free and non-awaitable at the byte seam: Fiber's task-owned page ring has already established ownership before invoking it. ### HttpClientConfig Import: `"http"`. ```vex export struct HttpClientConfig ``` Resource limits for one HTTP/1.1 request/response exchange. Zero limits are never treated as "unbounded": use `defaults()` and modify an explicit field instead. The parser itself has a structural 64-header ceiling, therefore `maxResponseHeaders` may not exceed 64. **Implements:** `Copy` **Public fields:** - `maxRequestBytes`: `usize` - `maxResponseHeaderBytes`: `usize` - `maxResponseBodyBytes`: `usize` - `maxResponseHeaders`: `usize` - `maxInformationalResponses`: `usize` ### HttpClient Import: `"http"`. ```vex export struct HttpClient ``` Stateless HTTP/1.1 transport configuration. The type intentionally owns no socket pool yet: closing every exchange makes response framing exact and is safer than pretending that partially supported keep-alive is reusable. ### HttpRedirectPolicy Import: `"http"`. ```vex export struct HttpRedirectPolicy ``` Explicit policy for buffered redirect following. Zero is deliberately invalid: callers that do not want redirects use `send`, while redirect-enabled code always has a finite, visible bound. **Public fields:** - `maxRedirects`: `usize` ### HttpContentDecoding Import: `"http"`. ```vex export struct HttpContentDecoding ``` Explicit decoded-response resource policy. Encoded transfer bytes remain bounded by `HttpClientConfig`; this second ceiling applies after every Content-Encoding layer and prevents compressed payloads from turning a small wire response into an allocation bomb. **Public fields:** - `maxDecodedBodyBytes`: `usize` - `maxEncodingLayers`: `usize` ### ClientResponse Import: `"http"`. ```vex export struct ClientResponse ``` Fully decoded and owning HTTP response. A transport/protocol failure is represented by `Result.Err(IoError)`, never by a magic invalid response. **Public fields:** - `status`: `i32` - `statusText`: `string` - `version`: `string` - `headers`: `Headers` - `body`: `string` - `connectionWillClose`: `bool` ### ClientResponseHead Import: `"http"`. ```vex export struct ClientResponseHead ``` Final response metadata for `HttpClient.sendInto`. The body has already been decoded into the caller-provided async writer, so this value never owns an unbounded payload. **Public fields:** - `status`: `i32` - `statusText`: `string` - `version`: `string` - `headers`: `Headers` - `connectionWillClose`: `bool` ### HttpSession Import: `"http"`. ```vex export struct HttpSession ``` One caller-owned, sequential HTTP/1.1 keep-alive connection. This is deliberately not a shared pool. It has no lock, queue, background reaper, or cross-task ownership ambiguity: one task owns one session and performs one request at a time. The session closes itself on every framing, I/O, cancellation, upgrade, HTTP/1.0, close-delimited, or `Connection: close` boundary. A future pool can therefore contain only already-proven reusable sessions rather than duplicating HTTP parsing policy. **Implements:** `Drop` ### ClientRequest Import: `"http"`. ```vex export struct ClientRequest ``` Request builder. `host` is the HTTP authority sent in `Host`; `endpoint` is deliberately supplied separately to `HttpClient.send`, allowing a resolved address and a virtual-host authority to differ safely. **Public fields:** - `method`: `string` - `host`: `string` - `path`: `string` - `headers`: `Headers` - `body`: `string` ### AppConfig Import: `"http/fiber"`. ```vex export struct AppConfig { public: bodyLimit: usize, maxHeaderBytes: usize, maxHeaders: usize, responseBatchBytes: usize, readTimeout: i32, writeTimeout: i32, idleTimeout: i32, maxConnections: i32, } ``` ### App Import: `"http/fiber"`. ```vex export struct App: BufferedApplicationDispatcher { public: config: AppConfig, router: Router<{FEATURES}>, middlewares: Vec, frozenMiddlewares: Vec, notFoundHandler: Option, errorHandler: Option, directHandler: Option, frozen: bool, } ``` **Implements:** `BufferedApplicationDispatcher` ### AsyncBodyPipelineNext Import: `"http/fiber"`. ```vex export struct AsyncBodyPipelineNext ``` ### AsyncRequestBody Import: `"http/fiber"`. ```vex export struct AsyncRequestBody ``` Sole owner of one streamed HTTP/1 request after Fiber unregisters the descriptor. `consume` may be called once; completion, rejection, EOF and Context cancellation all terminate the same RequestBodyLifecycle. ### AsyncPipelineNext Import: `"http/fiber"`. ```vex export struct AsyncPipelineNext ``` Monotonic continuation state for one task-owned request. The continuation owns its handler vector. That makes its lifetime and storage independent of its caller and prevents a suspended request from observing a reallocated external Vec. ### ConnBuf Import: `"http/fiber"`. ```vex export struct ConnBuf ``` **Public fields:** - `data`: `Vec` - `readPos`: `usize` - `writePos`: `usize` ### Connection Import: `"http/fiber"`. ```vex export struct Connection ``` **Public fields:** - `fd`: `i32` - `buf`: `ConnBuf` - `keepAlive`: `bool` - `headerLen`: `i32` ### ResponseStreamWriter Import: `"http/fiber"`. ```vex export struct ResponseStreamWriter ``` Connection-bound dynamic response writer used only by Fiber stream routes. It never exposes an fd to application code, retains a fixed-size buffer and shares one absolute deadline across headers, every chunk and the terminator. ### Ctx Import: `"http/fiber"`. ```vex export struct Ctx ``` **Public fields:** - `req`: `Request` - `res`: `Response` - `ownedRequestParts`: `Vec` - `routeId`: `i32` - `routePath`: `str` - `staticRoot`: `str` - `routeParams`: `Vec` - `queryParams`: `Vec` - `locals`: `Vec` - `handlers`: `Vec` - `routeMiddlewares`: `Vec` - `handlerIdx`: `usize` - `cookieParsed`: `bool` - `parsedCookies`: `Vec` - `streamFileLength`: `u64` - `streamFilePending`: `bool` - `streamFile`: `Option` - `streamHandler`: `Option` - `streamWriter`: `Ptr` - `wsUpgrade`: `Ptr` ### RouteParam Import: `"http/fiber"`. ```vex export struct RouteParam ``` Key-value pair for route parameters. `routeParams[i]` is read out of a shared `&Ctx` by value, so the pair must own copy semantics: four scalars/raw descriptors, no destructor. Without the declaration every read out of a `&Ctx` is a move out of borrowed storage and the borrow checker has to reject it. **Implements:** `Copy` **Public fields:** - `keyPtr`: `Ptr` - `keyLength`: `usize` - `valueStart`: `usize` - `valueLength`: `usize` ### QueryParam Import: `"http/fiber"`. ```vex export struct QueryParam ``` Query parameter represented entirely by offsets into Request.query. **Public fields:** - `keyStart`: `usize` - `keyLength`: `usize` - `valueStart`: `usize` - `valueLength`: `usize` ### LocalEntry Import: `"http/fiber"`. ```vex export struct LocalEntry ``` Key-value pair for user-defined locals (middleware data passing). **Public fields:** - `key`: `string` - `value`: `string` ### Group Import: `"http/fiber"`. ```vex export struct Group { public: prefix: string, router: &Router<{FEATURES}>!, middlewares: Vec, bodyMiddlewares: Vec, } ``` ### RadixTree Import: `"http/fiber"`. ```vex export struct RadixTree ``` **Public fields:** - `parents`: `Vec` - `firstChild`: `Vec` - `nextSibling`: `Vec` - `prefixes`: `Vec` - `kinds`: `Vec` - `paramNames`: `Vec` - `handlerIdx`: `Vec` - `handlerPool`: `Vec` - `hasHandlers`: `Vec` - `mwStart`: `Vec` - `mwLen`: `Vec` - `mwPool`: `Vec` - `routeIdx`: `Vec` ### MatchResult Import: `"http/fiber"`. ```vex export struct MatchResult ``` **Public fields:** - `found`: `bool` - `handler`: `Option` - `params`: `Vec` - `middlewares`: `Vec` ### ParamPair Import: `"http/fiber"`. ```vex export struct ParamPair ``` **Public fields:** - `key`: `string` - `value`: `string` ### WsRouteOptions Import: `"http/fiber"`. ```vex export struct WsRouteOptions ``` Immutable WebSocket handshake policy compiled into route metadata. Protocol insertion order is server preference order; no per-request protocol vector is constructed on the hot path. ### Router Import: `"http/fiber"`. ```vex export struct Router { public: routeMethodIds: Vec, routePatterns: Vec, routeStaticRoots: Vec, routeParamNameStart: Vec, routeParamNameLen: Vec, routeParamNamePool: Vec, routeHandlers: Vec, routeIsStatic: Vec, routeMwStart: Vec, routeMwLen: Vec, routeMwPool: Vec, protocolRoutes: RouteCapabilityState<{FEATURES}>, trees: Vec, frozen: bool, cacheMid: i32, cachePath: string, cacheIdx: i32, } ``` ### HeaderEntry Import: `"http"`. ```vex export struct HeaderEntry ``` **Public fields:** - `name`: `string` - `value`: `string` ### RequestHeaders Import: `"http"`. ```vex export struct RequestHeaders ``` **Public fields:** - `names`: `Vec` - `values`: `Vec` ### Headers Import: `"http"`. ```vex export struct Headers ``` **Public fields:** - `names`: `Vec` - `values`: `Vec` ### CorsConfig Import: `"http"`, `"http/middleware"`. ```vex export struct CorsConfig ``` **Public fields:** - `origin`: `string` - `methods`: `string` - `headers`: `string` - `maxAge`: `string` - `credentials`: `bool` ### BodyProgress Import: `"http/parser"`. ```vex export struct BodyProgress ``` **Public fields:** - `consumed`: `usize` - `decoded`: `usize` ### BodyConsumerStart Import: `"http"`, `"http/parser"`. ```vex export struct BodyConsumerStart ``` Immutable metadata delivered exactly once before a streaming consumer sees decoded bytes. `declaredLength` is -1 when the framing has no fixed decoded length (`chunked` or `until-close`). A consumer must treat every chunk view as borrowed from the current transport read and may not retain it. **Public fields:** - `mode`: `BodyMode` - `declaredLength`: `i64` - `maxBodyBytes`: `usize` ### BodyReader Import: `"http/parser"`. ```vex export struct BodyReader ``` **Public fields:** - `mode`: `BodyMode` - `consumed`: `usize` - `expected`: `usize` - `chunked`: `ChunkedDecoder` - `done`: `bool` ### RequestBodyLifecycle Import: `"http"`, `"http/parser"`. ```vex export struct RequestBodyLifecycle ``` Owns exactly one `BodyReader` plus the begin/finish/cancel transition for a route-owned consumer. This is the only place a future Fiber body lane may translate parser completion or transport failure into consumer lifecycle calls; it prevents multipart/proxy helpers from inventing competing body decoders or success-on-error behavior. **Public fields:** - `reader`: `BodyReader` - `delivery`: `DecodedBodyLifecycle` ### DecodedBodyLifecycle Import: `"http"`, `"http/parser"`. ```vex export struct DecodedBodyLifecycle ``` Protocol-neutral owner of the application body-consumer contract. HTTP/1 feeds this owner after `BodyReader` removes transfer framing. HTTP/2 feeds it directly from validated DATA payloads. Keeping admission, byte limits, declared-length accounting and terminal callbacks here prevents each transport from inventing subtly different body semantics. **Public fields:** - `state`: `BodyConsumerState` - `mode`: `BodyMode` - `declaredLength`: `i64` - `maxBodyBytes`: `usize` - `totalBytes`: `usize` ### BodyPageRing Import: `"http"`, `"http/parser"`. ```vex export struct BodyPageRing ``` Fixed-capacity storage for Fiber's task-owned asynchronous request-body lane. `BodyReader` still presents decoded chunks as borrowed views; this ring is the ownership boundary used before forwarding decoded bytes to the route-owned consumer. Storage is allocated once at construction and never grows. Both readable and writable views stop at a logical page boundary, so a task can release one fixed page at a time without exposing an interior allocation or making a peer-controlled fragment size affect retained memory. This type itself is deliberately single-owner: the Fiber handoff transfers the descriptor and its ring together rather than sharing mutable pages between worker and task. ### ChunkProgress Import: `"http/parser"`. ```vex export struct ChunkProgress ``` Progress is relative to the input passed to the current `decodeInto` call. The caller must retain `input[consumed..]` when `NeedMore` is returned. **Public fields:** - `consumed`: `usize` - `decoded`: `usize` ### ChunkedDecoder Import: `"http/parser"`. ```vex export struct ChunkedDecoder ``` **Public fields:** - `state`: `ChunkState` - `dataRemaining`: `usize` - `totalDecoded`: `usize` - `trailerBytes`: `usize` ### FiberRequestLimits Import: `"http/parser"`. ```vex export struct FiberRequestLimits ``` **Public fields:** - `maxHeaderBytes`: `usize` - `maxHeaders`: `usize` ### FiberHeader Import: `"http/parser"`. ```vex export struct FiberHeader ``` **Implements:** `Copy` **Public fields:** - `name`: `str` - `value`: `str` ### FiberParsedRequest Import: `"http/parser"`. ```vex export struct FiberParsedRequest { public: _raw_owned: string, method: str, uri: str, path: str, query: str, version: str, headers: Vec, contentLength: i64, chunked: bool, keepAlive: bool, } ``` ### H2Frame Import: `"http/parser"`. ```vex export struct H2Frame ``` **Public fields:** - `length`: `u32` - `frameType`: `u8` - `flags`: `u8` - `streamId`: `u32` ### H2Settings Import: `"http/parser"`. ```vex export struct H2Settings ``` **Public fields:** - `headerTableSize`: `u32` - `enablePush`: `bool` - `maxConcurrentStreams`: `u32` - `initialWindowSize`: `u32` - `maxFrameSize`: `u32` - `maxHeaderListSize`: `u32` ### GoAway Import: `"http/parser"`. ```vex export struct GoAway ``` **Public fields:** - `lastStreamId`: `u32` - `errorCode`: `u32` - `debugData`: `str` ### H2LegacyPriority Import: `"http/parser"`. ```vex export struct H2LegacyPriority ``` Deprecated RFC 7540 dependency metadata retained only for HTTP/2 wire interoperability. Modern scheduling uses RFC 9218 `H2Priority` instead. **Public fields:** - `streamDependency`: `u32` - `weight`: `u16` - `exclusive`: `bool` ### H2ConnectionState Import: `"http/parser"`. ```vex export struct H2ConnectionState ``` **Public fields:** - `role`: `H2EndpointRole` - `recvContinuationStreamId`: `u32` - `sendContinuationStreamId`: `u32` - `outstandingLocalSettings`: `u32` - `pendingPeerSettingsAcks`: `u32` - `sendWindow`: `i32` - `recvWindow`: `i32` - `receivedGoAway`: `bool` - `sentGoAway`: `bool` - `receivedLastStreamId`: `u32` - `sentLastStreamId`: `u32` - `nextLocalStreamId`: `u32` - `highestRemoteStreamId`: `u32` ### H2FieldSectionInfo Import: `"http/parser"`. ```vex export struct H2FieldSectionInfo ``` Successful validation metadata. `statusCode` is zero for non-responses. **Implements:** `Copy` **Public fields:** - `statusCode`: `u16` - `methodIndex`: `usize` - `schemeIndex`: `usize` - `authorityIndex`: `usize` - `pathIndex`: `usize` - `statusIndex`: `usize` - `regularStart`: `usize` - `contentLength`: `i64` ### H2Priority Import: `"http/parser"`. ```vex export struct H2Priority ``` **Public fields:** - `urgency`: `u8` - `incremental`: `bool` ### H2PriorityUpdate Import: `"http/parser"`. ```vex export struct H2PriorityUpdate ``` **Public fields:** - `streamId`: `u32` - `priority`: `H2Priority` ### H2PriorityScheduler Import: `"http/parser"`. ```vex export struct H2PriorityScheduler ``` ### H2ProtocolConfig Import: `"http/parser"`. ```vex export struct H2ProtocolConfig ``` **Implements:** `Copy` **Public fields:** - `maxConcurrentStreams`: `u32` - `maximumChunkBytes`: `u32` - `starvationTurns`: `u64` - `maxHeaderBlockBytes`: `usize` - `hpackLimits`: `HpackDecodeLimits` - `maxOutstandingSettings`: `u32` - `maxOutstandingPings`: `u32` ### H2HeaderFragment Import: `"http/parser"`. ```vex export struct H2HeaderFragment ``` One wire fragment of a successfully committed outbound HPACK block. `payloadOffset` and `payloadBytes` slice the caller-owned contiguous block; transport prepends `frame` and never copies compression state. **Public fields:** - `frame`: `H2Frame` - `promisedStreamId`: `u32` - `payloadOffset`: `usize` - `payloadBytes`: `usize` ### H2HeaderFrameCursor Import: `"http/parser"`. ```vex export struct H2HeaderFrameCursor ``` Allocation-free HEADERS/CONTINUATION cursor bound to the peer's effective SETTINGS_MAX_FRAME_SIZE at the same transaction that encoded the block. ### H2ProtocolState Import: `"http/parser"`. ```vex export struct H2ProtocolState ``` ### HeaderEntry Import: `"http/parser"`. ```vex export struct HeaderEntry ``` **Implements:** `Copy` **Public fields:** - `name`: `str` - `value`: `str` ### ParserHeaders Import: `"http/parser"`. ```vex export struct ParserHeaders ``` **Public fields:** - `entries`: `[HeaderEntry; 64]` - `count`: `usize` ### DynamicTable Import: `"http/parser"`. ```vex export struct DynamicTable ``` **Public fields:** - `entries`: `Vec` - `size`: `usize` - `maxSize`: `usize` - `allowedMaxSize`: `usize` - `requiredSizeUpdate`: `bool` - `requiredSizeUpdateMaximum`: `usize` ### HpackHeader Import: `"http/parser"`. ```vex export struct HpackHeader ``` **Public fields:** - `name`: `string` - `value`: `string` - `indexing`: `HpackIndexing` ### HpackDecodeLimits Import: `"http/parser"`. ```vex export struct HpackDecodeLimits ``` Explicit resource policy for one complete HPACK header block. **Implements:** `Copy` **Public fields:** - `maxHeaderListBytes`: `usize` - `maxHeaderCount`: `usize` - `maxStringBytes`: `usize` - `maxDynamicTableSize`: `usize` ### HpackEncodeLimits Import: `"http/parser"`. ```vex export struct HpackEncodeLimits ``` **Implements:** `Copy` **Public fields:** - `maxHeaderListBytes`: `usize` - `maxHeaderCount`: `usize` - `maxStringBytes`: `usize` - `maxBlockBytes`: `usize` - `useHuffman`: `bool` ### HpackEncoder Import: `"http/parser"`. ```vex export struct HpackEncoder ``` Connection-lifetime encoder state. Peer SETTINGS changes are applied to table capacity immediately and emitted at the beginning of the next block. A reduction followed by an increase retains both the smallest observed value and the final value, as required by RFC 7541 §4.2. ### MultipartLimits Import: `"http"`, `"http/parser"`. ```vex export struct MultipartLimits ``` **Implements:** `Copy` **Public fields:** - `maxParts`: `usize` - `maxPartHeaderBytes`: `usize` - `maxHeadersPerPart`: `usize` - `maxNameBytes`: `usize` - `maxFileNameBytes`: `usize` ### MultipartPartInfo Import: `"http"`, `"http/parser"`. ```vex export struct MultipartPartInfo ``` Metadata views are valid only during `beginPart`. A sink which retains a name or filename must copy it into its own storage. **Public fields:** - `index`: `usize` - `name`: `str` - `fileName`: `str` - `hasFileName`: `bool` - `contentType`: `str` ### MultipartConsumer Import: `"http"`, `"http/parser"`. ```vex export struct MultipartConsumer: RequestBodyConsumer { sink: &S!, limits: MultipartLimits, startMarker: string, bodyMarker: string, workspace: Vec, buffered: usize, state: MultipartState, partCount: usize, activePart: bool, began: bool, terminal: bool, partHasFileName: bool, partName: StringBuilder, partFileName: StringBuilder, } ``` Fixed-budget incremental parser bound to one caller-owned sink. **Implements:** `RequestBodyConsumer` ### ParserRequest Import: `"http/parser"`. ```vex export struct ParserRequest ``` **Public fields:** - `method`: `Method` - `uri`: `str` - `version`: `HttpVersion` - `headers`: `ParserHeaders` ### Response Import: `"http/parser"`. ```vex export struct Response ``` **Public fields:** - `statusCode`: `i32` - `reasonPhrase`: `str` - `version`: `str` - `headers`: `ParserHeaders` ### Scanner Import: `"http/parser"`. ```vex export struct Scanner ``` **Public fields:** - `data`: `str` - `pos`: `usize` ### H2Stream Import: `"http/parser"`. ```vex export struct H2Stream ``` **Public fields:** - `id`: `u32` - `state`: `StreamState` - `sendWindow`: `i32` - `recvWindow`: `i32` - `legacyWeight`: `u16` - `legacyDependency`: `u32` - `legacyExclusive`: `bool` - `recvInitialHeaders`: `bool` - `recvFinalHeaders`: `bool` - `sendInitialHeaders`: `bool` - `sendFinalHeaders`: `bool` - `recvContentLength`: `i64` - `recvContentBytes`: `u64` - `recvContentForbidden`: `bool` - `sentRequestHead`: `bool` - `sentRequestConnect`: `bool` - `recvRequestHead`: `bool` - `recvRequestConnect`: `bool` - `sendContentLength`: `i64` - `sendContentBytes`: `u64` - `sendContentForbidden`: `bool` - `resetSent`: `bool` ### StreamMap Import: `"http/parser"`. ```vex export struct StreamMap ``` **Public fields:** - `streams`: `Vec` - `sendInitialWindow`: `i32` - `recvInitialWindow`: `i32` - `maxStreams`: `u32` ### WsFrame Import: `"http/parser"`. ```vex export struct WsFrame ``` **Public fields:** - `fin`: `bool` - `rsv1`: `bool` - `rsv2`: `bool` - `rsv3`: `bool` - `opcode`: `u8` - `masked`: `bool` - `payloadLen`: `u64` - `maskKey`: `u32` - `headerLen`: `usize` ### WsMessage Import: `"http/parser"`. ```vex export struct WsMessage ``` **Public fields:** - `opcode`: `u8` - `data`: `string` - `complete`: `bool` - `active`: `bool` ### Request Import: `"http"`. ```vex export struct Request ``` **Public fields:** - `method`: `str` - `path`: `str` - `query`: `str` - `version`: `str` - `scheme`: `str` - `authority`: `str` - `headers`: `RequestHeaders` - `body`: `str` - `_raw`: `str` - `_raw_owned`: `Vec` - `fd`: `i64` - `streamId`: `i32` - `valid`: `bool` - `contentLength`: `i64` - `keepAlive`: `bool` ### Response Import: `"http"`. ```vex export struct Response ``` **Public fields:** - `statusCode`: `i32` - `headers`: `Headers` - `body`: `string` - `sent`: `bool` - `keepAlive`: `bool` - `buffered`: `bool` - `bodySuppressed`: `bool` - `bufferedContentType`: `str` - `buffered_output`: `StringBuilder` ### Server Import: `"http"`. ```vex export struct Server ``` **Public fields:** - `host`: `string` - `port`: `i32` - `app`: `App<{HTTP_FULL}>` ### WsSession Import: `"http/ws"`. ```vex export struct WsSession ``` A persistent non-blocking WebSocket endpoint. It borrows the descriptor: the enclosing Fiber worker remains the only authority that closes it. ### WsMessage Import: `"http/ws"`. ```vex export struct WsMessage ``` A complete WebSocket message (possibly assembled from fragments). **Public fields:** - `opcode`: `u8` - `data`: `string` ### WsConn Import: `"http/ws"`. ```vex export struct WsConn ``` **Public fields:** - `fd`: `i64` - `open`: `bool` - `recvBuffer`: `WsFrameStream` - `fragmentOpcode`: `u8` - `fragmentData`: `StringBuilder` ### BodyMode Import: `"http"`, `"http/parser"`. ```vex export enum BodyMode ``` **Variants:** - `NoBody` - `ContentLength` - `Chunked` - `UntilClose` - `EndStream` — Decoded bytes are terminated by an explicit protocol stream boundary ### BodyResult Import: `"http/parser"`. ```vex export enum BodyResult ``` **Variants:** - `NeedMore` - `Complete` - `Error` ### BodyConsumerState Import: `"http"`, `"http/parser"`. ```vex export enum BodyConsumerState ``` The terminal state is explicit because a transport error after `begin` must never look like a successful empty body to a route-level consumer. **Variants:** - `Idle` - `Reading` - `Finished` - `Cancelled` ### ChunkState Import: `"http/parser"`. ```vex export enum ChunkState ``` **Variants:** - `Size` - `Data` - `DataCRLF` - `Trailer` - `Done` - `Error` ### ChunkResult Import: `"http/parser"`. ```vex export enum ChunkResult ``` **Variants:** - `NeedMore` - `Complete` - `Error` ### FiberRequestResult Import: `"http/parser"`. ```vex export enum FiberRequestResult ``` **Variants:** - `Complete` - `Incomplete` - `Error` ### H2ParseResult Import: `"http/parser"`. ```vex export enum H2ParseResult ``` **Variants:** - `Ok` — Frame header parsed successfully. - `NeedMore` — Need more data (at least N bytes). - `StreamError` — Stream-scoped metadata rejection. Frame metadata is retained so a - `ConnectionError` — Peer violation that terminates the HTTP/2 connection. - `Invalid` — Invalid local parser configuration rather than peer input. ### H2SettingsUpdateResult Import: `"http/parser"`. ```vex export enum H2SettingsUpdateResult ``` **Variants:** - `Ok` - `Error` ### H2GoAwayResult Import: `"http/parser"`. ```vex export enum H2GoAwayResult ``` **Variants:** - `Ok` - `Error` ### H2WindowUpdateResult Import: `"http/parser"`. ```vex export enum H2WindowUpdateResult ``` **Variants:** - `Ok` - `Error` ### H2RstStreamResult Import: `"http/parser"`. ```vex export enum H2RstStreamResult ``` **Variants:** - `Ok` - `Error` ### H2LegacyPriorityResult Import: `"http/parser"`. ```vex export enum H2LegacyPriorityResult ``` **Variants:** - `Ok` - `Error` ### H2EncodeResult Import: `"http/parser"`. ```vex export enum H2EncodeResult ``` **Variants:** - `Ok` - `Error` ### H2EndpointRole Import: `"http/parser"`. ```vex export enum H2EndpointRole ``` **Variants:** - `Client` - `Server` ### H2ConnectionResult Import: `"http/parser"`. ```vex export enum H2ConnectionResult ``` **Variants:** - `Ok` - `HeaderBlockOpen` — A fragmented header block now owns this direction of the connection. - `HeaderBlockComplete` — A complete header block is ready for HPACK decoding. - `SettingsAckRequired` — Peer SETTINGS were accepted and require an acknowledgement. - `Error` — Connection-level HTTP/2 error code and stable diagnostic. ### H2FlowResult Import: `"http/parser"`. ```vex export enum H2FlowResult ``` **Variants:** - `Ok` - `Blocked` — Local send capacity is exhausted; wait for WINDOW_UPDATE. - `Invalid` — Invalid local API request; no flow-control state changed. - `ConnectionError` — Peer violated the connection flow-control window. - `StreamError` — Peer violated one stream's flow-control window. ### H2StreamAdmissionResult Import: `"http/parser"`. ```vex export enum H2StreamAdmissionResult ``` **Variants:** - `Opened` — A stream was materialized. Contains its stream identifier and map index. - `Existing` — The stream was already materialized. Contains its identifier and index. - `Blocked` — Local admission cannot proceed (draining, concurrency limit, exhaustion). - `Ignored` — A peer stream above the locally sent GOAWAY boundary was consumed but ignored. - `StreamError` — Peer admission failed at stream scope. - `ConnectionError` — Peer admission violated a connection-wide stream-ID invariant. ### H2FieldSectionKind Import: `"http/parser"`. ```vex export enum H2FieldSectionKind ``` The semantic context of one fully decompressed HTTP/2 field section. **Variants:** - `Request` - `Response` - `Trailers` - `PushRequest` ### H2FieldSectionResult Import: `"http/parser"`. ```vex export enum H2FieldSectionResult ``` **Variants:** - `Ok` - `Malformed` ### H2PriorityFieldResult Import: `"http/parser"`. ```vex export enum H2PriorityFieldResult ``` **Variants:** - `Ok` - `Error` ### H2PriorityUpdateResult Import: `"http/parser"`. ```vex export enum H2PriorityUpdateResult ``` **Variants:** - `Ok` - `Error` ### H2PriorityRegistrationResult Import: `"http/parser"`. ```vex export enum H2PriorityRegistrationResult ``` **Variants:** - `Added` - `Updated` - `Full` - `Invalid` ### H2ScheduleResult Import: `"http/parser"`. ```vex export enum H2ScheduleResult ``` **Variants:** - `Selected` - `Empty` - `FlowBlocked` - `Busy` - `Invalid` ### H2ProtocolFrameResult Import: `"http/parser"`. ```vex export enum H2ProtocolFrameResult ``` **Variants:** - `Ok` - `HeaderBlockOpen` - `HeaderBlockComplete` - `SettingsAckRequired` - `StreamError` - `ConnectionError` - `Invalid` ### H2ReceiveGoAwayResult Import: `"http/parser"`. ```vex export enum H2ReceiveGoAwayResult ``` **Variants:** - `Applied` - `ConnectionError` - `Invalid` ### H2SendGoAwayResult Import: `"http/parser"`. ```vex export enum H2SendGoAwayResult ``` **Variants:** - `Encoded` - `ConnectionError` - `Invalid` ### H2ReceivePingResult Import: `"http/parser"`. ```vex export enum H2ReceivePingResult ``` Exact received PING ownership. Non-ACK payloads must be echoed by `sendPingAckFrame`; ACK payloads are correlated against the bounded local outstanding set. Unmatched ACKs are observable but not connection errors. **Variants:** - `AckRequired` - `Acknowledged` - `UnmatchedAcknowledgement` - `ConnectionError` - `Invalid` ### H2SendPingResult Import: `"http/parser"`. ```vex export enum H2SendPingResult ``` **Variants:** - `Encoded` - `Duplicate` - `Full` - `ConnectionError` - `Invalid` ### H2ReceivePriorityResult Import: `"http/parser"`. ```vex export enum H2ReceivePriorityResult ``` Exact RFC 9218 PRIORITY_UPDATE receive ownership. Wire parsing, directional connection sequencing and bounded scheduler mutation commit as one turn. **Variants:** - `Applied` - `ConnectionError` - `Invalid` ### H2SendPriorityResult Import: `"http/parser"`. ```vex export enum H2SendPriorityResult ``` **Variants:** - `Encoded` - `ConnectionError` - `Invalid` ### H2ReceiveLegacyPriorityResult Import: `"http/parser"`. ```vex export enum H2ReceiveLegacyPriorityResult ``` **Variants:** - `Applied` - `Ignored` - `StreamError` - `ConnectionError` - `Invalid` ### H2ProtocolAbortResult Import: `"http/parser"`. ```vex export enum H2ProtocolAbortResult ``` **Variants:** - `Closed` - `AlreadyClosed` ### H2HeaderFrameResult Import: `"http/parser"`. ```vex export enum H2HeaderFrameResult ``` Result of connection-owned received header-block processing. A stream error is intentionally delayed until END_HEADERS so HPACK state still advances exactly as it did on the wire. **Variants:** - `Pending` - `Decoded` - `Ignored` - `StreamError` - `ConnectionError` - `Invalid` ### H2ReceiveDataResult Import: `"http/parser"`. ```vex export enum H2ReceiveDataResult ``` Result of exact-payload DATA ingestion. `Data` borrows only the application bytes after the optional pad-length field and trailing padding; `flowBytes` is the complete frame payload charged to both receive windows. **Variants:** - `Data` - `Discarded` - `StreamError` - `ConnectionError` - `Invalid` ### H2SendDataResult Import: `"http/parser"`. ```vex export enum H2SendDataResult ``` A DATA frame whose scheduler lease, stream/connection windows and stream transition committed together. Transport writes one optional pad-length byte, `dataBytes` application bytes, then `paddingBytes` zero bytes. **Variants:** - `Ready` - `Blocked` - `StreamError` - `ConnectionError` - `Invalid` ### H2SendControlResult Import: `"http/parser"`. ```vex export enum H2SendControlResult ``` Shared result for atomically encoded payload-bearing control frames. **Variants:** - `Encoded` - `StreamError` - `ConnectionError` - `Invalid` ### H2ReceiveResetResult Import: `"http/parser"`. ```vex export enum H2ReceiveResetResult ``` A peer reset whose payload, connection sequencing, stream retirement and scheduler revocation committed together. **Variants:** - `Reset` - `ConnectionError` - `Invalid` ### H2InboundFrameResult Import: `"http/parser"`. ```vex export enum H2InboundFrameResult ``` One transport-facing receive result for every HTTP/2 frame class. The dispatcher preserves borrowed payload views, moves decoded header ownership once, and retains exact stream-vs-connection error scope. **Variants:** - `Data` - `DiscardedData` - `HeaderBlockPending` - `Headers` - `SettingsAckRequired` - `SettingsAcknowledged` - `WindowUpdated` - `Reset` - `GoAway` - `PingAckRequired` - `PingAcknowledged` - `PingUnmatched` - `PriorityUpdated` - `LegacyPriorityApplied` - `LegacyPriorityIgnored` - `Ignored` - `StreamError` - `ConnectionError` - `Invalid` ### H2IngressResult Import: `"http/parser"`. ```vex export enum H2IngressResult ``` One incremental transport step over caller-retained bytes. `Dispatched` reports the exact prefix safe to consume after the result is handled; borrowed DATA/PING/GOAWAY views remain valid until then. **Variants:** - `Dispatched` - `NeedMore` - `Invalid` ### H2SendResetResult Import: `"http/parser"`. ```vex export enum H2SendResetResult ``` Result of an application cancellation/reset. Idle identifiers have no wire representation and are retired without encoding; active streams commit only after the complete 13-byte RST_STREAM has been encoded successfully. **Variants:** - `Encoded` - `Closed` - `IdlePriorityRemoved` - `AlreadyClosed` - `NotFound` - `StreamError` - `ConnectionError` - `Invalid` ### H2SendHeaderResult Import: `"http/parser"`. ```vex export enum H2SendHeaderResult ``` Result of a semantically validated, connection-owned outbound field block. `Encoded` returns the HPACK payload length; transport owns the nine-byte frame header and writes it only after this transaction succeeds. **Variants:** - `Encoded` - `OutputTooSmall` - `StreamError` - `ConnectionError` - `Invalid` ### H2SendPushResult Import: `"http/parser"`. ```vex export enum H2SendPushResult ``` **Variants:** - `Promised` - `OutputTooSmall` - `StreamError` - `ConnectionError` - `Invalid` ### MessageFraming Import: `"http/parser"`. ```vex export enum MessageFraming ``` The sole framing decision derived from HTTP message headers. Callers must not independently inspect `Content-Length` and `Transfer-Encoding`: doing so is how request/response parsers disagree about message boundaries. `Invalid` is deliberately a borrowed static diagnostic, so the zero-copy parser stays allocation-free. **Variants:** - `NoFraming` - `ContentLength` - `Chunked` - `Invalid` ### HeaderParseResult Import: `"http/parser"`. ```vex export enum HeaderParseResult ``` Parse result for headers. **Variants:** - `Complete` — ParserHeaders fully parsed. Value = position after \r\n\r\n. - `Incomplete` — Need more data (incomplete header block). - `Error` — Malformed header line. - `TooManyHeaders` — Too many headers. ### HpackIntegerResult Import: `"http/parser"`. ```vex export enum HpackIntegerResult ``` **Variants:** - `Ok` - `NeedMore` - `Error` ### HpackIndexing Import: `"http/parser"`. ```vex export enum HpackIndexing ``` Encoding policy for one HPACK field. Decoded literals preserve their wire policy; indexed fields decode as `Auto` because they carry no literal flag. **Variants:** - `Auto` - `Incremental` - `Without` - `Never` ### HpackResult Import: `"http/parser"`. ```vex export enum HpackResult ``` **Variants:** - `Ok` — Decoded one header. - `TableUpdate` — Dynamic table size update (not a header). - `NeedMore` — Need more data. - `Error` — Decode error. ### HpackBlockResult Import: `"http/parser"`. ```vex export enum HpackBlockResult ``` **Variants:** - `Ok` - `Error` ### HpackEncodeResult Import: `"http/parser"`. ```vex export enum HpackEncodeResult ``` **Variants:** - `Ok` - `OutputTooSmall` - `Error` ### HuffDecodeResult Import: `"http/parser"`. ```vex export enum HuffDecodeResult ``` Decode result. **Variants:** - `Ok` — Successfully decoded. usize = bytes written to output. - `Error` — Invalid Huffman sequence. ### MultipartState Import: `"http"`, `"http/parser"`. ```vex export enum MultipartState ``` **Variants:** - `Start` - `Headers` - `Body` - `BoundarySuffix` - `Done` - `Failed` ### Method Import: `"http/parser"`. ```vex export enum Method ``` **Variants:** - `GET` - `POST` - `PUT` - `DELETE` - `PATCH` - `HEAD` - `OPTIONS` - `CONNECT` - `TRACE` - `Unknown` ### HttpVersion Import: `"http/parser"`. ```vex export enum HttpVersion ``` **Variants:** - `Http10` - `Http11` - `Unknown` ### RequestResult Import: `"http/parser"`. ```vex export enum RequestResult ``` **Variants:** - `Complete` — Fully parsed. usize = byte offset where body starts. - `Incomplete` — Need more data (headers not complete). - `Error` — Protocol error. ### ResponseResult Import: `"http/parser"`. ```vex export enum ResponseResult ``` **Variants:** - `Complete` — Fully parsed. usize = byte offset where body starts. - `Incomplete` — Need more data. - `Error` — Protocol error. ### StreamState Import: `"http/parser"`. ```vex export enum StreamState ``` **Variants:** - `Idle` - `ReservedLocal` - `ReservedRemote` - `Open` - `HalfClosedLocal` - `HalfClosedRemote` - `Closed` ### StreamError Import: `"http/parser"`. ```vex export enum StreamError ``` **Variants:** - `Ok` — No error, transition successful. - `InvalidTransition` — Frame type not valid in current state. - `StreamError` — Stream-level protocol error (RST_STREAM). - `ConnectionError` — Connection-level error (GOAWAY). ### WsParseResult Import: `"http/parser"`. ```vex export enum WsParseResult ``` **Variants:** - `Ok` — Frame header parsed. WsFrame contains metadata. - `NeedMore` — Need more data (at least needBytes more). - `Error` — Protocol error. ### asyncBodyPipelineNext Import: `"http/fiber"`. ```vex export fn asyncBodyPipelineNext(steps: Vec): AsyncBodyPipelineNext ``` **Returns:** `AsyncBodyPipelineNext` ### asyncPipelineNext Import: `"http/fiber"`. ```vex export fn asyncPipelineNext(steps: Vec): AsyncPipelineNext ``` Move a finalized handler sequence into a task-owned continuation. **Returns:** `AsyncPipelineNext` ### cors Import: `"http"`, `"http/middleware"`. ```vex export fn cors(c: &Ctx!) ``` Default CORS middleware — allows all origins. ### logger Import: `"http"`, `"http/middleware"`. ```vex export fn logger(c: &Ctx!) ``` Logger middleware — prints method, path, status, and latency. ### detectBodyMode Import: `"http/parser"`. ```vex export fn detectBodyMode(hdrs: &ParserHeaders, isRequest: bool): BodyMode ``` **Returns:** `BodyMode` ### parseFiberRequestInto Import: `"http/parser"`. ```vex export fn parseFiberRequestInto(buf: str, out: &FiberParsedRequest!): FiberRequestResult ``` **Returns:** `FiberRequestResult` ### parseFiberRequestIntoWithLimits Import: `"http/parser"`. ```vex export fn parseFiberRequestIntoWithLimits(buf: str, out: &FiberParsedRequest!, limits: FiberRequestLimits): FiberRequestResult ``` **Returns:** `FiberRequestResult` ### parseFiberRequest Import: `"http/parser"`. ```vex export fn parseFiberRequest(buf: str): (FiberParsedRequest, FiberRequestResult) ``` **Returns:** `(FiberParsedRequest, FiberRequestResult)` ### isKnownH2FrameType Import: `"http/parser"`. ```vex export fn isKnownH2FrameType(frameType: u8): bool ``` Whether this package assigns semantics to a frame type. Unknown extension frames must be discarded without consulting the stream state machine. **Returns:** `bool` ### parseH2Frame Import: `"http/parser"`. ```vex export fn parseH2Frame(data: str): H2ParseResult ``` Parse an HTTP/2 frame header (9 bytes). Caller must then read frame.length bytes of payload. **Returns:** `H2ParseResult` ### parseH2FrameLimited Import: `"http/parser"`. ```vex export fn parseH2FrameLimited(data: str, maxFrameSize: u32): H2ParseResult ``` Parse a frame header under the peer's negotiated maximum frame size. **Returns:** `H2ParseResult` ### parseSettingsUpdate Import: `"http/parser"`. ```vex export fn parseSettingsUpdate(payload: str, current: &H2Settings): H2SettingsUpdateResult ``` Parse one SETTINGS delta against the currently effective values. Unknown identifiers are ignored, duplicate identifiers are applied in wire order, and omitted settings retain their previous values. **Returns:** `H2SettingsUpdateResult` ### parseSettings Import: `"http/parser"`. ```vex export fn parseSettings(payload: str, settings: &H2Settings!): bool ``` Parse SETTINGS payload. Each setting is 6 bytes: id(16) + value(32). **Returns:** `bool` ### parseLegacyPriority Import: `"http/parser"`. ```vex export fn parseLegacyPriority(payload: str): H2LegacyPriorityResult ``` Parse the exact five-byte deprecated PRIORITY payload. Stream self-dependency is validated by the protocol owner because it needs the frame's stream identifier. **Returns:** `H2LegacyPriorityResult` ### parseRstStream Import: `"http/parser"`. ```vex export fn parseRstStream(payload: str): H2RstStreamResult ``` Parse the exact four-byte RST_STREAM error code. Error codes are an open 32-bit space, so every value (including extension codes) is preserved. **Returns:** `H2RstStreamResult` ### parseWindowUpdate Import: `"http/parser"`. ```vex export fn parseWindowUpdate(payload: str): H2WindowUpdateResult ``` Parse a complete WINDOW_UPDATE payload and reject the reserved zero increment before it can reach flow-control arithmetic. **Returns:** `H2WindowUpdateResult` ### parseGoAway Import: `"http/parser"`. ```vex export fn parseGoAway(payload: str): H2GoAwayResult ``` Parse a complete GOAWAY payload. Truncated control frames fail closed. **Returns:** `H2GoAwayResult` ### encodeH2FrameHeader Import: `"http/parser"`. ```vex export fn encodeH2FrameHeader(out: &str!, length: u32, frameType: u8, flags: u8, streamId: u32): H2EncodeResult ``` Encode an HTTP/2 frame header into `out` after validating the complete metadata and destination capacity. Failed writes leave `out` unchanged. **Returns:** `H2EncodeResult` ### encodeSettingsPayload Import: `"http/parser"`. ```vex export fn encodeSettingsPayload(out: &str!, settings: &H2Settings): H2EncodeResult ``` Encode the six standard SETTINGS entries as a 36-byte payload. **Returns:** `H2EncodeResult` ### encodeSettingsFrame Import: `"http/parser"`. ```vex export fn encodeSettingsFrame(out: &str!, settings: &H2Settings): H2EncodeResult ``` Build a complete SETTINGS frame (9-byte header + 36-byte payload). **Returns:** `H2EncodeResult` ### encodeSettingsFrameSelected Import: `"http/parser"`. ```vex export fn encodeSettingsFrameSelected(out: &str!, settings: &H2Settings, present: u8): H2EncodeResult ``` Encode only the selected standard SETTINGS entries. This is the canonical transport API: roles can omit forbidden fields (servers must not emit SETTINGS_ENABLE_PUSH), and unchanged defaults do not waste wire bytes. Selection uses the `H2_SETTINGS_*` presence mask returned by `parseSettingsUpdate`; unknown mask bits fail before output mutation. **Returns:** `H2EncodeResult` ### encodeSettingsAck Import: `"http/parser"`. ```vex export fn encodeSettingsAck(out: &str!): H2EncodeResult ``` Build an empty SETTINGS acknowledgement frame. **Returns:** `H2EncodeResult` ### encodePing Import: `"http/parser"`. ```vex export fn encodePing(out: &str!, opaqueData: str, isAck: bool): H2EncodeResult ``` Build a PING frame. `opaqueData` must contain exactly eight bytes. **Returns:** `H2EncodeResult` ### encodeLegacyPriority Import: `"http/parser"`. ```vex export fn encodeLegacyPriority(out: &str!, streamId: u32, priority: &H2LegacyPriority): H2EncodeResult ``` Build one deprecated RFC 7540 PRIORITY compatibility frame. Vex-native scheduling should emit RFC 9218 PRIORITY_UPDATE instead. **Returns:** `H2EncodeResult` ### encodeWindowUpdate Import: `"http/parser"`. ```vex export fn encodeWindowUpdate(out: &str!, streamId: u32, increment: u32): H2EncodeResult ``` Build a WINDOW_UPDATE frame. **Returns:** `H2EncodeResult` ### encodeRstStream Import: `"http/parser"`. ```vex export fn encodeRstStream(out: &str!, streamId: u32, errorCode: u32): H2EncodeResult ``` Build a RST_STREAM frame. **Returns:** `H2EncodeResult` ### encodeGoAway Import: `"http/parser"`. ```vex export fn encodeGoAway(out: &str!, lastStreamId: u32, errorCode: u32): H2EncodeResult ``` Build a GOAWAY frame. **Returns:** `H2EncodeResult` ### encodeGoAwayWithDebug Import: `"http/parser"`. ```vex export fn encodeGoAwayWithDebug(out: &str!, lastStreamId: u32, errorCode: u32, debugData: str): H2EncodeResult ``` Build a complete GOAWAY frame including optional opaque diagnostic bytes. Capacity and the 24-bit frame-length bound are validated before any write. **Returns:** `H2EncodeResult` ### validateH2FieldSection Import: `"http/parser"`. ```vex export fn validateH2FieldSection(headers: &Vec, kind: H2FieldSectionKind): H2FieldSectionResult ``` Validate a complete decompressed field section according to RFC 9113's generic field, pseudo-header, request, response and trailer rules. **Returns:** `H2FieldSectionResult` ### parseH2PriorityFieldWithLimit Import: `"http/parser"`. ```vex export fn parseH2PriorityFieldWithLimit(fieldValue: str, maximumBytes: usize): H2PriorityFieldResult ``` Parse the RFC 9218 Priority Dictionary without allocation. Unknown members and known members with unsupported/out-of-range types are ignored exactly as required; malformed Structured Fields syntax fails closed. **Returns:** `H2PriorityFieldResult` ### parseH2PriorityField Import: `"http/parser"`. ```vex export fn parseH2PriorityField(fieldValue: str): H2PriorityFieldResult ``` **Returns:** `H2PriorityFieldResult` ### parseH2PriorityUpdateWithLimit Import: `"http/parser"`. ```vex export fn parseH2PriorityUpdateWithLimit(payload: str, maximumFieldBytes: usize): H2PriorityUpdateResult ``` Parse a complete HTTP/2 PRIORITY_UPDATE payload: 31-bit target stream ID followed by one ASCII Structured Fields Dictionary. **Returns:** `H2PriorityUpdateResult` ### parseH2PriorityUpdate Import: `"http/parser"`. ```vex export fn parseH2PriorityUpdate(payload: str): H2PriorityUpdateResult ``` **Returns:** `H2PriorityUpdateResult` ### encodeH2PriorityUpdate Import: `"http/parser"`. ```vex export fn encodeH2PriorityUpdate(out: &str!, streamId: u32, priority: &H2Priority): H2EncodeResult ``` Encode a canonical complete PRIORITY_UPDATE frame. False incremental uses its RFC default by omission; urgency is always explicit. **Returns:** `H2EncodeResult` ### advanceMessageFraming Import: `"http/parser"`. ```vex export fn advanceMessageFraming(current: MessageFraming, name: str, value: str): MessageFraming ``` Apply one field to an in-progress framing decision. The incremental Fiber parser and the fixed `ParserHeaders` parser both use this transition, so an attacker cannot get a different body boundary by choosing the server's fast parser instead of the canonical parser. **Returns:** `MessageFraming` ### isValidHostAuthority Import: `"http/parser"`. ```vex export fn isValidHostAuthority(value: str): bool ``` Validate the HTTP `Host` field's authority *shape* without allocation. This deliberately validates the interpretation boundary needed by an origin server: no user-info, path, query, fragment, unbracketed IPv6 ambiguity, or invalid decimal port can reach host-based middleware. Bracketed literals use the URI `IPv6address` / `IPvFuture` grammar, while socket address-family resolution remains the networking layer's responsibility. Both HTTP/1 parser front doors call this helper. **Returns:** `bool` ### parseHeaders Import: `"http/parser"`. ```vex export fn parseHeaders(sc: &Scanner!, hdrs: &ParserHeaders!): HeaderParseResult ``` Parse HTTP/1.1 headers from a scanner. Expects scanner positioned at start of first header line. Parses until \r\n\r\n (empty line). Returns HeaderParseResult indicating outcome. Format per RFC 7230: field-name ":" OWS field-value OWS CRLF **Returns:** `HeaderParseResult` ### decodeIntegerChecked Import: `"http/parser"`. ```vex export fn decodeIntegerChecked(data: str, prefixBits: u8): HpackIntegerResult ``` Decode an HPACK integer while preserving truncation and overflow. **Returns:** `HpackIntegerResult` ### decodeInteger Import: `"http/parser"`. ```vex export fn decodeInteger(data: str, prefixBits: u8): (u64, usize) ``` Compatibility helper. Prefer `decodeIntegerChecked` in protocol code. **Returns:** `(u64, usize)` ### encodeInteger Import: `"http/parser"`. ```vex export fn encodeInteger(out: &str!, value: u64, prefixBits: u8, prefixByte: u8): usize ``` Encode an HPACK integer. Returns bytes written to `out`. **Returns:** `usize` ### decodeHeader Import: `"http/parser"`. ```vex export fn decodeHeader(data: str, table: &DynamicTable!): (HpackResult, usize) ``` Decode the next HPACK header representation from data. Returns (HpackResult, bytesConsumed). **Returns:** `(HpackResult, usize)` ### decodeHeaderLimited Import: `"http/parser"`. ```vex export fn decodeHeaderLimited(data: str, table: &DynamicTable!, maxStringBytes: usize, maxDynamicTableSize: usize): (HpackResult, usize) ``` Decode one representation under explicit string and table bounds. **Returns:** `(HpackResult, usize)` ### decodeHeaderBlock Import: `"http/parser"`. ```vex export fn decodeHeaderBlock(data: str, table: &DynamicTable!): HpackBlockResult ``` Decode a complete HPACK header block. Returns list of decoded headers. **Returns:** `HpackBlockResult` ### decodeHeaderBlockLimited Import: `"http/parser"`. ```vex export fn decodeHeaderBlockLimited(data: str, table: &DynamicTable!, limits: &HpackDecodeLimits): HpackBlockResult ``` Decode a complete block or return a typed terminal error. Partial header lists are never reported as success. **Returns:** `HpackBlockResult` ### encodeHeaderBlockLimited Import: `"http/parser"`. ```vex export fn encodeHeaderBlockLimited(headers: &Vec, encoder: &HpackEncoder!, out: &str!, limits: &HpackEncodeLimits): HpackEncodeResult ``` Encode one complete HPACK field block transactionally. Every semantic and capacity check runs before the first output write. The dynamic table and pending SETTINGS update are committed only after encoding succeeds. **Returns:** `HpackEncodeResult` ### encodeHeaderBlock Import: `"http/parser"`. ```vex export fn encodeHeaderBlock(headers: &Vec, encoder: &HpackEncoder!, out: &str!): HpackEncodeResult ``` **Returns:** `HpackEncodeResult` ### huffmanCode Import: `"http/parser"`. ```vex export fn huffmanCode(sym: u8): (u32, u8) ``` Get the HPACK Huffman code and bit length for a byte value (0..255). O(1), branch-free table lookup. **Returns:** `(u32, u8)` ### huffmanEncodedLength Import: `"http/parser"`. ```vex export fn huffmanEncodedLength(input: str): usize ``` Calculate the encoded byte length of a string under HPACK Huffman. Used to decide whether Huffman encoding saves space. **Returns:** `usize` ### huffmanEncode Import: `"http/parser"`. ```vex export fn huffmanEncode(input: str, out: &str!): usize ``` Encode a string using HPACK Huffman coding. Writes to `out` and returns the number of bytes written. Output is padded with the EOS prefix (all 1-bits) to the next byte boundary, as required by RFC 7541 section 5.2. **Returns:** `usize` ### huffmanDecode Import: `"http/parser"`. ```vex export fn huffmanDecode(input: str, inputLen: usize, out: &str!, outputCapacity: usize): HuffDecodeResult ``` Decode HPACK Huffman-encoded bytes. The decoder walks a compact canonical binary trie. Every input bit performs exactly one transition-table lookup; terminal transitions emit one symbol and reset to the root state. Validation: - EOS cannot occur in the encoded payload - caller output capacity is enforced before every write - terminal padding is at most 7 bits - terminal padding must be an all-1 prefix of EOS **Returns:** `HuffDecodeResult` ### multipartBoundary Import: `"http"`, `"http/parser"`. ```vex export fn multipartBoundary(contentType: str): Option ``` Extract and own the boundary parameter from a multipart/form-data content type. Quoted values support backslash escaping; duplicate or trailing junk is rejected instead of selecting one ambiguous boundary. **Returns:** `Option` ### multipartConsumer Import: `"http"`, `"http/parser"`. ```vex export fn multipartConsumer( boundary: str, limits: MultipartLimits, sink: &S!, ): Option> where S: MultipartSink ``` **Type Parameters:** - `S` **Where:** - `MultipartSink`: `MultipartSink` **Returns:** `Option>where S: MultipartSink` ### parseRequest Import: `"http/parser"`. ```vex export fn parseRequest(buf: str): (ParserRequest, RequestResult) ``` Parse an HTTP/1.1 request from buffer. Returns (Request, RequestResult). On Complete, the usize is the byte index where the body starts. On Incomplete/Error, the Request may be partially filled. Zero-copy: all str fields reference the input buffer. **Returns:** `(ParserRequest, RequestResult)` ### parseRequestBuffer Import: `"http/parser"`. ```vex export fn parseRequestBuffer(buf: str): (ParserRequest, RequestResult) ``` Alias entrypoint to avoid name collision with `http/src/request.vx` parseRequest(fd). **Returns:** `(ParserRequest, RequestResult)` ### parseResponse Import: `"http/parser"`. ```vex export fn parseResponse(buf: str): (Response, ResponseResult) ``` Parse an HTTP/1.1 response from buffer. RFC 7230 status-line: HTTP-version SP status-code SP reason-phrase CRLF Returns (Response, ResponseResult). **Returns:** `(Response, ResponseResult)` ### eqCaseInsensitive Import: `"http/parser"`. ```vex export fn eqCaseInsensitive(a: str, target: str): bool ``` Case-insensitive ASCII comparison. Both inputs must have the same length; neither side carries a hidden pre-normalization requirement. **Returns:** `bool` ### parseDecimal Import: `"http/parser"`. ```vex export fn parseDecimal(s: str): Option ``` Parse a decimal integer from a str view. Returns Some(value) only when the entire view is decimal digits. Overflow-safe for values ≤ i64.MAX. **Returns:** `Option` ### parseHex Import: `"http/parser"`. ```vex export fn parseHex(s: str): Option ``` Parse a hexadecimal integer from a str view (for chunked encoding). Returns Some(value) only when the complete view is hexadecimal digits. Case-insensitive A-F. Overflow-safe. **Returns:** `Option` ### parseFrame Import: `"http/parser"`. ```vex export fn parseFrame(data: str): WsParseResult ``` Parse a WebSocket frame header from raw bytes. Returns WsParseResult with frame info. On Ok, frame.headerLen indicates where payload starts. Caller must then read frame.payloadLen bytes of payload. **Returns:** `WsParseResult` ### applyMask Import: `"http/parser"`. ```vex export fn applyMask(payload: &str!, maskKey: u32, len: usize) ``` Apply/remove WebSocket mask to payload buffer (in-place). XOR with 4-byte rotating mask key. Uses RawBuf for safe byte-level access. ### encodedFrameSize Import: `"http/parser"`. ```vex export fn encodedFrameSize(payloadLen: usize, masked: bool): usize ``` Calculate encoded frame size (header + payload). **Returns:** `usize` ### encodeFrameHeader Import: `"http/parser"`. ```vex export fn encodeFrameHeader(out: &str!, fin: bool, opcode: u8, payloadLen: usize, masked: bool, maskKey: u32): usize ``` Encode a WebSocket frame header into `out` buffer. Returns number of header bytes written. Caller must write payload immediately after. **Returns:** `usize` ### parseRequest Import: `"http"`. ```vex export fn parseRequest(fd: i64): Request ``` Read and parse an HTTP request from a TCP socket fd. **Returns:** `Request` ### respondText Import: `"http"`. ```vex export fn respondText(fd: i64, text: string) ``` ### respondJSON Import: `"http"`. ```vex export fn respondJSON(fd: i64, json: string) ``` ### respondError Import: `"http"`. ```vex export fn respondError(fd: i64, code: i32, message: string) ``` ### respondRedirect Import: `"http"`. ```vex export fn respondRedirect(fd: i64, location: string) ``` ### writeDeadlineNs Import: `"http"`. ```vex export fn writeDeadlineNs(timeoutMs: i32): u64 ``` Compute one saturating monotonic deadline for a complete response drain. Internal streaming paths call this once and reuse it for every chunk; a slow peer therefore cannot reset the timeout by accepting one chunk at a time. **Returns:** `u64` ### sendAllUntil Import: `"http"`. ```vex export fn sendAllUntil(fd: i64, buf: Ptr, len: u64, deadlineNs: u64): i64 ``` Drain bytes against a caller-owned absolute monotonic deadline. This is the streaming primitive used by Fiber's multi-chunk paths. The deadline applies to the entire response, not merely one `send()` retry. **Returns:** `i64` ### sendAllWithTimeout Import: `"http"`. ```vex export fn sendAllWithTimeout(fd: i64, buf: Ptr, len: u64, timeoutMs: i32): i64 ``` Drain a socket without allowing a permanently backpressured peer to pin the worker forever. Non-positive timeouts use the production default rather than disabling the safety bound. Returns -110 when the monotonic deadline expires. **Returns:** `i64` ### sendAll Import: `"http"`. ```vex export fn sendAll(fd: i64, buf: Ptr, len: u64): i64 ``` Drain using HTTP's production default write deadline. **Returns:** `i64` ### statusText Import: `"http"`. ```vex export fn statusText(code: i32): string ``` **Returns:** `string` ### statusAllowsContent Import: `"http"`. ```vex export fn statusAllowsContent(code: i32): bool ``` Whether an HTTP response status permits a payload body on the wire. `HEAD` is intentionally not handled here: it has the status semantics of its corresponding `GET` response and therefore preserves the prospective payload length while suppressing only the payload bytes. The response serializer carries that request-specific distinction separately. **Returns:** `bool` ### webSocketUpgradeResponse Import: `"http/ws"`. ```vex export fn webSocketUpgradeResponse(req: &Request): Option ``` Build the exact RFC 6455 `101 Switching Protocols` bytes after validation. This is transport-neutral: blocking `WsConn` may write it immediately, whereas Fiber queues it in its worker-owned non-blocking session. **Returns:** `Option` ### webSocketUpgradeResponseWithProtocol Import: `"http/ws"`. ```vex export fn webSocketUpgradeResponseWithProtocol(req: &Request, protocol: str): Option ``` Build a validated RFC 6455 upgrade response selecting one client-offered subprotocol. An empty selection preserves the ordinary extension-free handshake. A non-empty value must be one exact, case-sensitive HTTP token from the request; a server cannot invent or rewrite a protocol name. **Returns:** `Option` ### isWebSocketUpgrade Import: `"http/ws"`. ```vex export fn isWebSocketUpgrade(req: &Request): bool ``` Check if a request is a WebSocket upgrade request. **Returns:** `bool` ### webSocketProtocolOffered Import: `"http/ws"`. ```vex export fn webSocketProtocolOffered(req: &Request, protocol: str): bool ``` Test whether the validated opening request offered one exact subprotocol. RFC 6455 subprotocol identifiers are case-sensitive; HTTP header-name matching remains case-insensitive. **Returns:** `bool` ### HttpClientConfig.defaults ```vex export fn HttpClientConfig.defaults(): HttpClientConfig ``` **Returns:** `HttpClientConfig` ### HttpClient.new ```vex export fn HttpClient.new(): HttpClient ``` **Returns:** `HttpClient` ### HttpClient.new ```vex export fn HttpClient.new(config: HttpClientConfig): HttpClient ``` **Returns:** `HttpClient` ### HttpClient.config ```vex export fn (self: &HttpClient) config(): HttpClientConfig ``` **Returns:** `HttpClientConfig` ### HttpRedirectPolicy.defaults ```vex export fn HttpRedirectPolicy.defaults(): HttpRedirectPolicy ``` **Returns:** `HttpRedirectPolicy` ### HttpContentDecoding.defaults ```vex export fn HttpContentDecoding.defaults(): HttpContentDecoding ``` **Returns:** `HttpContentDecoding` ### HttpRedirectResolver.resolve ```vex async fn resolve( host: str, port: u16, context: &Context, ): Result; ``` This is the `resolve` requirement of `HttpRedirectResolver`, not a free function. **Returns:** `Result;` ### ClientResponseHead.header ```vex export fn (self: &ClientResponseHead) header(name: str): string ``` Get a streamed response header (case-insensitive). **Returns:** `string` ### ClientResponseHead.ok ```vex export fn (self: &ClientResponseHead) ok(): bool ``` Check whether a streamed response has a 2xx status. **Returns:** `bool` ### ClientResponse.header ```vex export fn (self: &ClientResponse) header(name: str): string ``` Get a response header (case-insensitive). **Returns:** `string` ### ClientResponse.ok ```vex export fn (self: &ClientResponse) ok(): bool ``` Check if response status is successful (2xx). **Returns:** `bool` ### ClientResponse.isRedirect ```vex export fn (self: &ClientResponse) isRedirect(): bool ``` Check if response status is a redirect (3xx). **Returns:** `bool` ### ClientResponse.decodeContent ```vex export fn (self: &ClientResponse!) decodeContent(decoding: &HttpContentDecoding): Result<(), IoError> ``` Decode the complete owning response body according to Content-Encoding. Mutation is atomic: malformed/unsupported/oversized content leaves the original response body and headers unchanged. **Returns:** `Result<(), IoError>` ### HttpSession.isReusable ```vex export fn (self: &HttpSession) isReusable(): bool ``` True only while the exact connection is open and has completed a reusable HTTP/1.1 response boundary. **Returns:** `bool` ### HttpSession.close ```vex export fn (self: &HttpSession!) close(): Result<(), IoError> ``` Explicitly close the session. Closing an already invalidated session is a successful no-op. **Returns:** `Result<(), IoError>` ### HttpSession.drop ```vex export fn (self: &HttpSession!) drop() ``` **Receiver:** `self: &HttpSession!` *(mutable reference)* ### ClientRequest.new ```vex export fn ClientRequest.new(method: str, host: str, path: str): ClientRequest ``` **Usage contract:** Construction does not connect or resolve DNS. Send-time validation rejects invalid authority, target and framing before opening a socket. See [client request construction](docs/std/http/client.md#request-construction). Creates a request for an HTTP authority. Direct-origin requests use `/path?query`; `OPTIONS` may use `*`, while `CONNECT` uses authority-form. The endpoint is supplied to `HttpClient.send` so the async request path never performs hidden DNS. **Returns:** `ClientRequest` ### ClientRequest.setHeader ```vex export fn (self: &ClientRequest!) setHeader(name: str, value: str): &ClientRequest! ``` Set a request header. Authority/framing fields remain transport-owned and are rejected at send time before a socket is opened. **Returns:** `&ClientRequest!` ### ClientRequest.setBody ```vex export fn (self: &ClientRequest!) setBody(body: str): &ClientRequest! ``` Set a complete buffered request body. **Returns:** `&ClientRequest!` ### ClientRequest.setContentType ```vex export fn (self: &ClientRequest!) setContentType(contentType: str): &ClientRequest! ``` Set Content-Type for a buffered request body. **Returns:** `&ClientRequest!` ### ClientRequest.acceptCompressed ```vex export fn (self: &ClientRequest!) acceptCompressed(): &ClientRequest! ``` Advertise exactly the pure-Vex content codings understood by `ClientResponse.decodeContent`. **Returns:** `&ClientRequest!` ### HttpClient.connect ```vex export async fn (self: &HttpClient) connect( endpoint: SocketAddr, context: &Context, ): Result ``` Establish one exclusive reusable HTTP/1.1 session with this client's configured resource policy. The endpoint is resolved by the caller; no DNS work is hidden in this async path. **Returns:** `Result` ### HttpSession.connect ```vex export async fn HttpSession.connect( endpoint: SocketAddr, context: &Context, ): Result ``` Establish one exclusive session using the default bounded client policy. **Returns:** `Result` ### HttpSession.send ```vex export async fn (self: &HttpSession!) send( request: &ClientRequest, context: &Context, ): Result ``` Send one complete request over this session. A session is intentionally sequential: calling `send` while another exchange is in flight fails with `ResourceBusy` rather than allowing HTTP/1.1 response association to drift. **Returns:** `Result` ### HttpSession.sendInto ```vex export async fn (self: &HttpSession!) sendInto( request: &ClientRequest, destination: &W, context: &Context, ): Result where W: AsyncWriter ``` Session equivalent of `HttpClient.sendInto`. Decoded body bytes are streamed into `destination`; the connection remains reusable only after a fully framed HTTP/1.1 response reaches its terminal boundary. **Type Parameters:** - `W` **Where:** - `AsyncWriter`: `AsyncWriter` **Returns:** `Resultwhere W: AsyncWriter` ### HttpSession.sendFrom ```vex export async fn (self: &HttpSession!) sendFrom( request: &ClientRequest, source: &R!, contentLength: usize, context: &Context, ): Result where R: AsyncReader ``` Stream an exact-length request body over this exclusive keep-alive session, then materialize the bounded response. The request's buffered body must be empty; short source EOF, cancellation, source failure and socket failure invalidate the session before it can re-enter a pool or caller loop. **Type Parameters:** - `R` **Where:** - `AsyncReader`: `AsyncReader` **Returns:** `Resultwhere R: AsyncReader` ### HttpSession.sendFromInto ```vex export async fn (self: &HttpSession!) sendFromInto( request: &ClientRequest, source: &R!, contentLength: usize, destination: &W, context: &Context, ): Result where R: AsyncReader, W: AsyncWriter ``` Stream an exact-length request body and stream the decoded response body into `destination` on the same exclusive session. **Type Parameters:** - `R` - `W` **Where:** - `AsyncReader`: `AsyncReader` - `AsyncWriter`: `AsyncWriter` **Returns:** `Resultwhere R: AsyncReader, W: AsyncWriter` ### HttpClient.send ```vex export async fn (self: &HttpClient) send( request: &ClientRequest, endpoint: SocketAddr, context: &Context, ): Result ``` **Usage contract:** Performs one plaintext HTTP/1 exchange and returns independently owned headers/body. It does not follow redirects or decompress Content-Encoding automatically. HTTP error statuses can still be a successful transport result; inspect response.status or response.ok(). Sends one bounded HTTP/1.1 request to an already-resolved endpoint. Cancellation and deadlines are forwarded through connect, complete write, and every read; a canceled request never collapses into an invalid response sentinel. The implementation closes its stream after one exchange until connection-pool ownership and reuse proofs are available. **Returns:** `Result` ### HttpClient.sendFollowing ```vex export async fn (self: &HttpClient) sendFollowing( request: &ClientRequest, endpoint: SocketAddr, redirectPolicy: &HttpRedirectPolicy, context: &Context, ): Result ``` Follow a finite chain of same-origin redirects for an owning buffered request. Relative references are resolved with RFC 3986 semantics and the original already-resolved endpoint is reused. A cross-origin Location fails closed before opening another connection. **Returns:** `Result` ### HttpClient.sendFollowingResolved ```vex export async fn (self: &HttpClient) sendFollowingResolved( request: &ClientRequest, endpoint: SocketAddr, redirectPolicy: &HttpRedirectPolicy, resolver: &R, context: &Context, ): Result where R: HttpRedirectResolver ``` Follow same- and cross-origin redirects through an explicit async endpoint resolver. No DNS is hidden by the HTTP client. Cross-origin hops remove Authorization, Proxy-Authorization and Cookie credentials before connect. **Type Parameters:** - `R` **Where:** - `HttpRedirectResolver`: `HttpRedirectResolver` **Returns:** `Resultwhere R: HttpRedirectResolver` ### HttpClient.sendInto ```vex export async fn (self: &HttpClient) sendInto( request: &ClientRequest, endpoint: SocketAddr, destination: &W, context: &Context, ): Result where W: AsyncWriter ``` **Usage contract:** Removes HTTP transfer framing and writes each accepted prefix to the sink; Content-Encoding is not decompressed. Later failure does not roll back bytes already delivered. A successful head is returned only after the final body boundary; stage output when atomic publication is required. Sends one bounded HTTP/1.1 request and streams its decoded final body into `destination`. This is the allocation-bounded alternative to `send` for downloads, proxying and protocol adapters: no response-sized `string` is materialized. The TCP stream is intentionally closed after this exchange; pooling and upgraded-connection ownership remain separate future APIs. **Type Parameters:** - `W` **Where:** - `AsyncWriter`: `AsyncWriter` **Returns:** `Resultwhere W: AsyncWriter` ### HttpClient.sendFrom ```vex export async fn (self: &HttpClient) sendFrom( request: &ClientRequest, endpoint: SocketAddr, source: &R!, contentLength: usize, context: &Context, ): Result where R: AsyncReader ``` Send one exact-length streaming request body and materialize the bounded response. The stateless transport advertises `Connection: close`; callers wanting proven sequential reuse should use `HttpSession.sendFrom`. **Type Parameters:** - `R` **Where:** - `AsyncReader`: `AsyncReader` **Returns:** `Resultwhere R: AsyncReader` ### HttpClient.sendFromInto ```vex export async fn (self: &HttpClient) sendFromInto( request: &ClientRequest, endpoint: SocketAddr, source: &R!, contentLength: usize, destination: &W, context: &Context, ): Result where R: AsyncReader, W: AsyncWriter ``` Send one exact-length streaming request body and stream the decoded response into `destination` without materializing either payload. **Type Parameters:** - `R` - `W` **Where:** - `AsyncReader`: `AsyncReader` - `AsyncWriter`: `AsyncWriter` **Returns:** `Resultwhere R: AsyncReader, W: AsyncWriter` ### ClientRequest.send ```vex export async fn (self: &ClientRequest) send( endpoint: SocketAddr, context: &Context, ): Result ``` Convenience overload for the default bounded client policy. **Returns:** `Result` ### ClientRequest.sendInto ```vex export async fn (self: &ClientRequest) sendInto( endpoint: SocketAddr, destination: &W, context: &Context, ): Result where W: AsyncWriter ``` Convenience overload for a streamed response with default bounded policy. **Type Parameters:** - `W` **Where:** - `AsyncWriter`: `AsyncWriter` **Returns:** `Resultwhere W: AsyncWriter` ### AppConfig.defaults ```vex export fn AppConfig.defaults(): AppConfig ``` **Returns:** `AppConfig` ### App.new ```vex export fn App.new(): App<{HTTP_FULL}> ``` Create a new application with default config. **Returns:** `App<{HTTP_FULL}>` ### App.new ```vex export fn App.new(config: AppConfig): App<{HTTP_FULL}> ``` Create an application with one coherent resource/deadline policy. **Returns:** `App<{HTTP_FULL}>` ### App.new ```vex export fn App.new(): App<{FEATURES}> ``` Create an exactly specialized application. Unknown bits and profiles without HTTP/1 are rejected at compile time; no runtime configuration branch is introduced. **Type Parameters:** - `const FEATURES: u32` **Returns:** `App<{FEATURES}>` ### App.new ```vex export fn App.new(config: AppConfig): App<{FEATURES}> ``` **Type Parameters:** - `const FEATURES: u32` **Returns:** `App<{FEATURES}>` ### App.get ```vex export fn (self: &App!) get(path: string, handler: Handler) ``` ### App.getAsync ```vex export fn (self: &App!) getAsync(path: string, handler: AsyncHandler) ``` Register an explicit task-owned async route. It is a separate middleware lane: synchronous `App.use` callbacks never cross an await boundary. The initial transport policy closes after the response while descriptor reattachment and pipelined-response ordering are still being proven. ### App.postAsync ```vex export fn (self: &App!) postAsync(path: string, handler: AsyncHandler) ``` ### App.putAsync ```vex export fn (self: &App!) putAsync(path: string, handler: AsyncHandler) ``` ### App.deleteAsync ```vex export fn (self: &App!) deleteAsync(path: string, handler: AsyncHandler) ``` ### App.patchAsync ```vex export fn (self: &App!) patchAsync(path: string, handler: AsyncHandler) ``` ### App.headAsync ```vex export fn (self: &App!) headAsync(path: string, handler: AsyncHandler) ``` ### App.optionsAsync ```vex export fn (self: &App!) optionsAsync(path: string, handler: AsyncHandler) ``` ### App.getAsyncWith ```vex export fn (self: &App!) getAsyncWith(path: string, middlewares: Vec, handler: AsyncHandler) ``` Route-local awaitable middleware. The final endpoint is appended exactly once, preserving `before → await next() → after` in `AsyncPipelineNext`. ### App.postAsyncWith ```vex export fn (self: &App!) postAsyncWith(path: string, middlewares: Vec, handler: AsyncHandler) ``` ### App.putAsyncWith ```vex export fn (self: &App!) putAsyncWith(path: string, middlewares: Vec, handler: AsyncHandler) ``` ### App.deleteAsyncWith ```vex export fn (self: &App!) deleteAsyncWith(path: string, middlewares: Vec, handler: AsyncHandler) ``` ### App.patchAsyncWith ```vex export fn (self: &App!) patchAsyncWith(path: string, middlewares: Vec, handler: AsyncHandler) ``` ### App.headAsyncWith ```vex export fn (self: &App!) headAsyncWith(path: string, middlewares: Vec, handler: AsyncHandler) ``` ### App.optionsAsyncWith ```vex export fn (self: &App!) optionsAsyncWith(path: string, middlewares: Vec, handler: AsyncHandler) ``` ### App.bodyStream ```vex export fn (self: &App!) bodyStream(method: str, path: string, handler: AsyncBodyHandler) ``` Register a task-owned, backpressured request-body stream. The handler calls `await body.consume(consumer, context)`; decoded chunks never cross an await as borrowed transport views and the connection closes after the response until keep-alive reattachment is proven independently. ### App.bodyStreamWith ```vex export fn (self: &App!) bodyStreamWith(method: str, path: string, middlewares: Vec, handler: AsyncBodyHandler) ``` ### App.getBodyStream ```vex export fn (self: &App!) getBodyStream(path: string, handler: AsyncBodyHandler) ``` ### App.postBodyStream ```vex export fn (self: &App!) postBodyStream(path: string, handler: AsyncBodyHandler) ``` ### App.putBodyStream ```vex export fn (self: &App!) putBodyStream(path: string, handler: AsyncBodyHandler) ``` ### App.deleteBodyStream ```vex export fn (self: &App!) deleteBodyStream(path: string, handler: AsyncBodyHandler) ``` ### App.patchBodyStream ```vex export fn (self: &App!) patchBodyStream(path: string, handler: AsyncBodyHandler) ``` ### App.headBodyStream ```vex export fn (self: &App!) headBodyStream(path: string, handler: AsyncBodyHandler) ``` ### App.optionsBodyStream ```vex export fn (self: &App!) optionsBodyStream(path: string, handler: AsyncBodyHandler) ``` ### App.ws ```vex export fn (self: &App!) ws(path: string, handler: WsHandler) ``` Register a bounded, worker-owned WebSocket endpoint. The callback runs for complete protocol messages only; `WsSession` queues outbound frames and is drained through Fiber's non-blocking writable-interest path. ### App.wsWithOptions ```vex export fn (self: &App!) wsWithOptions(path: string, options: WsRouteOptions, handler: WsHandler) ``` Register a WebSocket endpoint with a startup-compiled subprotocol policy. Server preference order is the order added to `WsRouteOptions`. ### App.wsWithLifecycle ```vex export fn (self: &App!) wsWithLifecycle(path: string, onOpen: Option, handler: WsHandler, onClose: Option) ``` Register a WebSocket route with worker-owned lifecycle hooks. `onOpen` runs only after the validated `101` is queued; `onClose` receives an opaque session id when Fiber retires that connection for any terminal reason. ### App.wsWithLifecycleOptions ```vex export fn (self: &App!) wsWithLifecycleOptions(path: string, options: WsRouteOptions, onOpen: Option, handler: WsHandler, onClose: Option) ``` ### App.getStream ```vex export fn (self: &App!) getStream(path: string, handler: StreamHandler) ``` Register a bounded dynamic HTTP/1 producer. Status and headers belong to `Ctx` until `out.write` begins; body bytes then flow only through the response-owned chunk framing writer. ### App.postStream ```vex export fn (self: &App!) postStream(path: string, handler: StreamHandler) ``` ### App.getStreamWith ```vex export fn (self: &App!) getStreamWith(path: string, middlewares: Vec, handler: StreamHandler) ``` ### App.postStreamWith ```vex export fn (self: &App!) postStreamWith(path: string, middlewares: Vec, handler: StreamHandler) ``` ### App.post ```vex export fn (self: &App!) post(path: string, handler: Handler) ``` ### App.put ```vex export fn (self: &App!) put(path: string, handler: Handler) ``` ### App.delete ```vex export fn (self: &App!) delete(path: string, handler: Handler) ``` ### App.patch ```vex export fn (self: &App!) patch(path: string, handler: Handler) ``` ### App.head ```vex export fn (self: &App!) head(path: string, handler: Handler) ``` ### App.options ```vex export fn (self: &App!) options(path: string, handler: Handler) ``` ### App.static ```vex export fn (self: &App!) static(prefix: string, root: string) ``` Serve static files from a directory. Registers a GET route on `prefix + "/*filepath"`; Router's standard HEAD fallback selects the same representation without sending file bytes. ### App.getWith ```vex export fn (self: &App!) getWith(path: string, middlewares: Vec, handler: Handler) ``` Register GET route with route-level middleware. Middleware runs after global middleware, before the handler. Example: app.getWith("/admin", myVec, adminHandler); ### App.postWith ```vex export fn (self: &App!) postWith(path: string, middlewares: Vec, handler: Handler) ``` ### App.putWith ```vex export fn (self: &App!) putWith(path: string, middlewares: Vec, handler: Handler) ``` ### App.deleteWith ```vex export fn (self: &App!) deleteWith(path: string, middlewares: Vec, handler: Handler) ``` ### App.patchWith ```vex export fn (self: &App!) patchWith(path: string, middlewares: Vec, handler: Handler) ``` ### App.all ```vex export fn (self: &App!) all(path: string, handler: Handler) ``` ### App.group ```vex export fn (self: &App!) group(prefix: string): Group<{FEATURES}> ``` Create a route group with a shared prefix. Example: let! api = app.group("/api"); api.get("/users", handler); // → GET /api/users **Returns:** `Group<{FEATURES}>` ### App.use ```vex export fn (self: &App!) use(handler: Handler) ``` ### App.setNotFound ```vex export fn (self: &App!) setNotFound(handler: Handler) ``` ### App.setErrorHandler ```vex export fn (self: &App!) setErrorHandler(handler: Handler) ``` ### App.serveDirect ```vex export fn (self: App) serveDirect(host: string, port: i32, handler: RequestHandler) ``` Serve one direct request callback through Fiber's production HTTP/1 path. This is the canonical replacement for a separate low-level accept loop. Use routes and middleware when an application needs routing semantics; direct callbacks deliberately receive only the parsed request and response. ### App.serveDirectWithContext ```vex export fn (self: App) serveDirectWithContext(lifetime: Context, host: string, port: i32, handler: RequestHandler) ``` Context-cancellable direct callback variant. It has the same framing, deadline, admission and lifecycle behavior as `listenWithContext`. ### App.freeze ```vex export fn (self: &App!) freeze() ``` Freeze the application: compile radix tree and snapshot middleware list. Called automatically by listen(). After freeze(), no new routes or middlewares can be added (they would be ignored at runtime). **Receiver:** `self: &App!` *(mutable reference)* ### App.listen ```vex export fn (self: App) listen(host: string, port: i32) ``` Start the server. Blocks forever. Linux: N listen sockets with SO_REUSEPORT (kernel-level LB). macOS: Single acceptor thread + N workers via pipe-based FD distribution. Eliminates kqueue thundering herd — guarantees even load spread. Each worker owns its own event loop for independent I/O processing. ### App.listenWithContext ```vex export fn (self: App) listenWithContext(lifetime: Context, host: string, port: i32) ``` Serve until `lifetime` is canceled or its deadline expires. Cancellation is observed between event batches: an executing handler/pipeline completes, new accepts stop, worker-owned connections close, and this call waits for every spawned HTTP worker before returning. ### App.dispatchBuffered ```vex export fn (self: &App) dispatchBuffered(ctx: &Ctx!): ApplicationDispatchResult ``` Dispatch a fully validated, buffered request without assuming a wire protocol. `Ctx.res.buffered` is mandatory: handlers may call the ordinary Fiber response API, but no socket write or protocol framing occurs here. Dynamic transport lanes are returned before middleware or terminal user code runs, allowing the owning event loop to install the correct stream. **Returns:** `ApplicationDispatchResult` ### AsyncBodyPipelineNext.run ```vex export async fn (self: &AsyncBodyPipelineNext!) run( ctx: &Ctx!, body: &AsyncRequestBody!, context: &Context, ) ``` Monotonic body-route continuation. Advancing before awaiting prevents a buggy middleware from replaying the endpoint with a second `next.run`. ### AsyncRequestBody.new ```vex export fn AsyncRequestBody.new(stream: TcpStream, mode: BodyMode, initialBytes: str, maxBodyBytes: usize): Option ``` Construct the task-owned body after Socket -> TcpStream adoption. Initial bytes are the exact suffix following the complete HTTP/1 header block and may contain body framing plus a later pipelined request. The canonical body reader preserves that suffix; the initial safe transport policy closes the connection instead of attempting unproven worker reattachment. **Returns:** `Option` ### AsyncRequestBody.consume ```vex export async fn (self: &AsyncRequestBody!) consume( consumer: &C!, context: &Context, ): Result where C: RequestBodyConsumer ``` Decode the complete bounded body into one route-owned consumer. Socket reads park only this coroutine and use the supplied Context for cancellation and deadlines. `Ok(total)` means `finish(total)` ran exactly once. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` **Returns:** `Resultwhere C: RequestBodyConsumer` ### AsyncRequestBody.writeResponse ```vex export async fn (self: &AsyncRequestBody!) writeResponse( encoded: str, context: &Context, ): Result<(), IoError> ``` Fiber transport finalization. Kept on the body owner so the descriptor can never be wrapped by a second writer after handoff. **Returns:** `Result<(), IoError>` ### AsyncRequestBody.close ```vex export fn (self: &AsyncRequestBody!) close(): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### AsyncRequestBody.isReusable ```vex export fn (self: &AsyncRequestBody) isReusable(): bool ``` A streamed connection is reusable only after the canonical lifecycle has positively completed. `NoBody` may remain idle because its boundary is already known at header completion; cancelled/rejected consumers never become reusable even when their reader happened to reach `done` first. **Returns:** `bool` ### AsyncPipelineNext.run ```vex export async fn (self: &AsyncPipelineNext!) run(ctx: &Ctx!, context: &Context) ``` Resume the next handler in order. The cursor is advanced before the await, so a handler cannot invoke the same successor twice. Calling `run` after the terminal handler is a harmless no-op. ### ConnBuf.new ```vex export fn ConnBuf.new(): ConnBuf ``` Create a new connection buffer with default capacity. reserve() + push loop — no reallocation during init. **Returns:** `ConnBuf` ### ConnBuf.pending ```vex export fn (self: &ConnBuf) pending(): usize ``` Number of unprocessed bytes available. **Returns:** `usize` ### ConnBuf.writePtr ```vex export fn (self: &ConnBuf!) writePtr(): Ptr ``` Pointer to the start of free space (where recv should write). **Returns:** `Ptr` ### ConnBuf.freeSpace ```vex export fn (self: &ConnBuf) freeSpace(): usize ``` Amount of free space available for recv(). **Returns:** `usize` ### ConnBuf.advance ```vex export fn (self: &ConnBuf!) advance(n: usize) ``` Advance write position after a successful recv(). ### ConnBuf.readPtr ```vex export fn (self: &ConnBuf) readPtr(): Ptr ``` Pointer to start of unprocessed data. **Returns:** `Ptr` ### ConnBuf.consume ```vex export fn (self: &ConnBuf!) consume(n: usize) ``` Consume `n` bytes from the front (after processing). ### ConnBuf.compact ```vex export fn (self: &ConnBuf!) compact() ``` Move unprocessed data to front of buffer to free space at the end. Uses RawBuf.copyTo (memmove) instead of byte-by-byte loop — ~10x faster. **Receiver:** `self: &ConnBuf!` *(mutable reference)* ### ConnBuf.grow ```vex export fn (self: &ConnBuf!) grow(): bool ``` Grow buffer capacity (doubles up to MAX_BUF). Returns false if at limit. reserve() + push(0) loop — at most O(log N) reallocations total. **Returns:** `bool` ### ConnBuf.reset ```vex export fn (self: &ConnBuf!) reset() ``` Reset for keep-alive reuse (zero alloc — just resets cursors). **Receiver:** `self: &ConnBuf!` *(mutable reference)* ### Connection.new ```vex export fn Connection.new(fd: i32): Connection ``` **Returns:** `Connection` ### Connection.recv ```vex export fn (self: &Connection!) recv(): i64 ``` Read from socket into buffer. Returns bytes read (0=EOF, <0=error/EAGAIN). **Returns:** `i64` ### Connection.findHeaderEnd ```vex export fn (self: &Connection!) findHeaderEnd(): i32 ``` Check if a complete HTTP header block is available. Scans for \r\n\r\n in the unprocessed region using SIMD acceleration. Returns the offset (relative to readPos) of the first byte after \r\n\r\n, or -1 if not yet complete. **Returns:** `i32` ### Connection.reset ```vex export fn (self: &Connection!) reset() ``` Reset connection for keep-alive reuse. **Receiver:** `self: &Connection!` *(mutable reference)* ### Connection.consumeRequest ```vex export fn (self: &Connection!) consumeRequest(total_len: usize) ``` Consume processed bytes (header + body). ### ResponseStreamWriter.new ```vex export fn ResponseStreamWriter.new(): ResponseStreamWriter ``` **Returns:** `ResponseStreamWriter` ### ResponseStreamWriter.write ```vex export fn (self: &ResponseStreamWriter!) write(data: str): bool ``` Write a bounded sequence of HTTP/1 chunks. Large producer strings are segmented without a temporary copy; a zero-length write is intentionally a no-op because only `finish` may send the terminal zero chunk. **Returns:** `bool` ### Ctx.new ```vex export fn Ctx.new(req: Request): Ctx ``` Create a new Ctx from a parsed request. req.query is str (Copy) — .clone() is a no-op, removed for perf. **Returns:** `Ctx` ### Ctx.empty ```vex export fn Ctx.empty(): Ctx ``` Create an empty Ctx for pre-allocation (zero alloc reuse pattern). Fields are populated by handleRequest via reset() + direct assignment. **Returns:** `Ctx` ### Ctx.emptyHttp1Sync ```vex export fn Ctx.emptyHttp1Sync(): Ctx ``` Zero-capacity dynamic transport storage for the capability-sealed H1 profile. The public `Ctx` handler ABI stays stable, but construction does not make response-stream machinery reachable or reserve its write buffer. **Returns:** `Ctx` ### Ctx.reset ```vex export fn (self: &Ctx!) reset() ``` Reset Ctx for reuse — clears all Vecs keeping capacity (zero alloc after warmup). **Receiver:** `self: &Ctx!` *(mutable reference)* ### Ctx.resetHttp1Sync ```vex export fn (self: &Ctx!) resetHttp1Sync() ``` Reset only state reachable from the H1-sync capability surface. Dynamic transport fields remain permanently disabled and therefore require no per-request work or codegen closure. **Receiver:** `self: &Ctx!` *(mutable reference)* ### Ctx.method ```vex export fn (self: &Ctx) method(): str ``` HTTP method (GET, POST, PUT, DELETE, etc.) **Returns:** `str` ### Ctx.path ```vex export fn (self: &Ctx) path(): str ``` Request path (without query string). **Returns:** `str` ### Ctx.params ```vex export fn (self: &Ctx) params(key: str): string ``` Get route parameter by name (from :param patterns). **Returns:** `string` ### Ctx.param ```vex export fn (self: &Ctx) param(key: str): str ``` Borrowed route parameter view. The result is valid for this request. Prefer this on hot paths when ownership is not required. **Returns:** `str` ### Ctx.query ```vex export fn (self: &Ctx) query(key: str): string ``` Get query parameter by name. **Returns:** `string` ### Ctx.queryView ```vex export fn (self: &Ctx) queryView(key: str): str ``` Borrowed raw query parameter view. Percent/form decoding is intentionally separate because decoded bytes may require owned storage. **Returns:** `str` ### Ctx.indexQuery ```vex export fn (self: &Ctx!) indexQuery() ``` Re-index the raw query after assigning Request.query. Reuses the Vec capacity retained by reset(), so steady-state requests do not allocate for ordinary query pairs. **Receiver:** `self: &Ctx!` *(mutable reference)* ### Ctx.header ```vex export fn (self: &Ctx) header(name: str): str ``` Get request header by name (case-insensitive). **Returns:** `str` ### Ctx.body ```vex export fn (self: &Ctx) body(): str ``` Raw request body. **Returns:** `str` ### Ctx.contentType ```vex export fn (self: &Ctx) contentType(): str ``` Request Content-Type. **Returns:** `str` ### Ctx.isJSON ```vex export fn (self: &Ctx) isJSON(): bool ``` Check if request is JSON. **Returns:** `bool` ### Ctx.contentLength ```vex export fn (self: &Ctx) contentLength(): i64 ``` Content-Length value (-1 if not present). **Returns:** `i64` ### Ctx.protocol ```vex export fn (self: &Ctx) protocol(): str ``` HTTP version string (e.g. "HTTP/1.1", "HTTP/2"). **Returns:** `str` ### Ctx.scheme ```vex export fn (self: &Ctx) scheme(): str ``` URI scheme supplied by the transport protocol. **Returns:** `str` ### Ctx.authority ```vex export fn (self: &Ctx) authority(): str ``` Canonical request authority. HTTP/2 uses `:authority`; HTTP/1 falls back to the validated Host field. **Returns:** `str` ### Ctx.originalURL ```vex export fn (self: &Ctx) originalURL(): string ``` Full original URL (path + query string). Returns owned string. **Returns:** `string` ### Ctx.baseURL ```vex export fn (self: &Ctx) baseURL(): string ``` Base URL (scheme + host). Derives from Host header. **Returns:** `string` ### Ctx.hostname ```vex export fn (self: &Ctx) hostname(): str ``` Hostname from Host header (without port). **Returns:** `str` ### Ctx.ip ```vex export fn (self: &Ctx) ip(): str ``` Client IP address from X-Forwarded-For or X-Real-IP headers. Falls back to empty str if neither header is set. **Returns:** `str` ### Ctx.userAgent ```vex export fn (self: &Ctx) userAgent(): str ``` User-Agent header. **Returns:** `str` ### Ctx.get ```vex export fn (self: &Ctx) get(name: str): str ``` Get request header by name (alias for header(), Fiber v3 compat). **Returns:** `str` ### Ctx.xhr ```vex export fn (self: &Ctx) xhr(): bool ``` Check if request is XMLHttpRequest (AJAX). **Returns:** `bool` ### Ctx.accepts ```vex export fn (self: &Ctx) accepts(contentType: str): bool ``` Check if the request accepts a given content type. **Returns:** `bool` ### Ctx.cookies ```vex export fn (self: &Ctx!) cookies(name: string): string ``` Get a cookie value by name from the request. Parses the Cookie header lazily on first call; subsequent calls use the cache. **Returns:** `string` ### Ctx.setCookie ```vex export fn (self: &Ctx!) setCookie(cookie: Cookie) ``` Set a cookie on the response (adds Set-Cookie header). ### Ctx.setSimpleCookie ```vex export fn (self: &Ctx!) setSimpleCookie(name: string, value: string, maxAge: i32) ``` Set a simple cookie by name, value, and max-age in seconds (HttpOnly). ### Ctx.clearCookie ```vex export fn (self: &Ctx!) clearCookie(name: string) ``` Delete a cookie by name (Max-Age=0). ### Ctx.status ```vex export fn (self: &Ctx!) status(code: i32): &Ctx! ``` Set response status code (chainable). **Returns:** `&Ctx!` ### Ctx.setType ```vex export fn (self: &Ctx!) setType(ct: string): &Ctx! ``` Set response Content-Type (chainable). **Returns:** `&Ctx!` ### Ctx.set ```vex export fn (self: &Ctx!) set(name: string, value: string): &Ctx! ``` Set a response header (chainable). **Returns:** `&Ctx!` ### Ctx.sendString ```vex export fn (self: &Ctx!) sendString(text: string) ``` Send a plain text response. ### Ctx.sendJSON ```vex export fn (self: &Ctx!) sendJSON(json: string) ``` **Usage contract:** Sets the JSON response body through the context-owned response. Use serde/json to serialize application data; concatenating arbitrary text here does not create valid JSON. Fiber owns the eventual wire flush. Send a JSON string response. ### Ctx.sendHTML ```vex export fn (self: &Ctx!) sendHTML(html: string) ``` Send an HTML response. ### Ctx.send ```vex export fn (self: &Ctx!) send() ``` Send the response with current body/status. **Receiver:** `self: &Ctx!` *(mutable reference)* ### Ctx.sendStatus ```vex export fn (self: &Ctx!) sendStatus(code: i32) ``` Send an empty response (status + headers only). ### Ctx.redirect ```vex export fn (self: &Ctx!) redirect(url: string) ``` Redirect to a URL (302 by default). ### Ctx.redirectWithStatus ```vex export fn (self: &Ctx!) redirectWithStatus(url: string, code: i32) ``` Redirect with a specific status code (301, 302, 307, 308). ### Ctx.location ```vex export fn (self: &Ctx!) location(path: string): &Ctx! ``` Set Location header only (no redirect status). **Returns:** `&Ctx!` ### Ctx.download ```vex export fn (self: &Ctx!) download(body: string, filename: string) ``` Set Content-Disposition for file download. Sends the body with attachment headers so the browser triggers a download. ### Ctx.setContentType ```vex export fn (self: &Ctx!) setContentType(ext: string): &Ctx! ``` Set Content-Type based on file extension. **Returns:** `&Ctx!` ### Ctx.sendFile ```vex export fn (self: &Ctx!) sendFile(filePath: string) ``` Serve a file from the filesystem. Automatically detects Content-Type and handles error codes. ### Ctx.sendStaticFile ```vex export fn (self: &Ctx!) sendStaticFile(root: str, relative: str) ``` Serve one file that must remain below a configured static root. Both the configured root and resolved candidate are canonicalized before the file is opened. This rejects `..`, absolute-path tricks and symlinks that point outside the published tree; checking the lexical request path alone cannot provide that guarantee. This is deliberately the only path used by `App.static` and `Group.static`. The opened descriptor is retained until Fiber drains the response. This preserves canonical-path security across the open/send boundary and streams through the worker's bounded scratch buffer instead of materializing the whole asset as a string. ### Ctx.next ```vex export fn (self: &Ctx!) next() ``` Continue to the next handler in the middleware chain. This is the core of Fiber v3's middleware model. **Receiver:** `self: &Ctx!` *(mutable reference)* ### Ctx.runHandlerChain ```vex export fn (self: &Ctx!) runHandlerChain() ``` Start the prepared middleware/handler chain at its first entry. Middleware controls continuation exclusively through `next()`. **Receiver:** `self: &Ctx!` *(mutable reference)* ### Ctx.setLocal ```vex export fn (self: &Ctx!) setLocal(key: string, value: string) ``` Set a local value (for passing data between middlewares). ### Ctx.getLocal ```vex export fn (self: &Ctx) getLocal(key: string): string ``` Get a local value set by a previous middleware. **Returns:** `string` ### Ctx.bodyJSON ```vex export fn (self: &Ctx) bodyJSON(key: string): string ``` Get a value from a JSON body by key (simple top-level string extraction). Returns the string value for the key, or empty string if not found. Note: This is a lightweight parser for {"key":"value"} patterns. For nested JSON, use a dedicated JSON library. **Returns:** `string` ### Ctx.formValue ```vex export fn (self: &Ctx) formValue(key: str): string ``` Get a form value from application/x-www-form-urlencoded body. **Returns:** `string` ### Group.get ```vex export fn (self: &Group!) get(path: string, handler: Handler) ``` ### Group.post ```vex export fn (self: &Group!) post(path: string, handler: Handler) ``` ### Group.getStream ```vex export fn (self: &Group!) getStream(path: string, handler: StreamHandler) ``` ### Group.postStream ```vex export fn (self: &Group!) postStream(path: string, handler: StreamHandler) ``` ### Group.bodyStream ```vex export fn (self: &Group!) bodyStream(method: str, path: string, handler: AsyncBodyHandler) ``` ### Group.getBodyStream ```vex export fn (self: &Group!) getBodyStream(path: string, handler: AsyncBodyHandler) ``` ### Group.postBodyStream ```vex export fn (self: &Group!) postBodyStream(path: string, handler: AsyncBodyHandler) ``` ### Group.putBodyStream ```vex export fn (self: &Group!) putBodyStream(path: string, handler: AsyncBodyHandler) ``` ### Group.deleteBodyStream ```vex export fn (self: &Group!) deleteBodyStream(path: string, handler: AsyncBodyHandler) ``` ### Group.patchBodyStream ```vex export fn (self: &Group!) patchBodyStream(path: string, handler: AsyncBodyHandler) ``` ### Group.ws ```vex export fn (self: &Group!) ws(path: string, handler: WsHandler) ``` Register a WebSocket endpoint under this group's path and middleware boundary. Its callback is invoked only after the worker has completed the non-blocking HTTP upgrade handoff. ### Group.wsWithOptions ```vex export fn (self: &Group!) wsWithOptions(path: string, options: WsRouteOptions, handler: WsHandler) ``` ### Group.wsWithLifecycle ```vex export fn (self: &Group!) wsWithLifecycle(path: string, onOpen: Option, handler: WsHandler, onClose: Option) ``` Register WebSocket callbacks for open/message/close while preserving this group's middleware boundary and prefix. ### Group.wsWithLifecycleOptions ```vex export fn (self: &Group!) wsWithLifecycleOptions(path: string, options: WsRouteOptions, onOpen: Option, handler: WsHandler, onClose: Option) ``` ### Group.put ```vex export fn (self: &Group!) put(path: string, handler: Handler) ``` ### Group.delete ```vex export fn (self: &Group!) delete(path: string, handler: Handler) ``` ### Group.patch ```vex export fn (self: &Group!) patch(path: string, handler: Handler) ``` ### Group.head ```vex export fn (self: &Group!) head(path: string, handler: Handler) ``` ### Group.options ```vex export fn (self: &Group!) options(path: string, handler: Handler) ``` ### Group.static ```vex export fn (self: &Group!) static(prefix: string, root: string) ``` Serve static files from a directory under this group. Registers a GET route on `groupPrefix + prefix + "/*filepath"`; Router's standard HEAD fallback selects the same representation without file bytes. ### Group.all ```vex export fn (self: &Group!) all(path: string, handler: Handler) ``` ### Group.use ```vex export fn (self: &Group!) use(handler: Handler) ``` ### Group.useBodyAsync ```vex export fn (self: &Group!) useBodyAsync(handler: AsyncBodyHandler) ``` Add middleware to this group's explicit request-body coroutine lane. Synchronous `use` middleware deliberately remains worker-local and is not smuggled across the descriptor handoff. ### Group.group ```vex export fn (self: &Group!) group(subPrefix: string): Group<{FEATURES}> ``` Create a sub-group with an additional prefix. **Returns:** `Group<{FEATURES}>` ### RadixTree.empty ```vex export fn RadixTree.empty(): RadixTree ``` Construct storage without allocating a root node. Router freeze uses this for method slots which have no registered routes; the first insertion materializes the root. Ordinary callers receive an initialized tree from `new()`. **Returns:** `RadixTree` ### RadixTree.new ```vex export fn RadixTree.new(): RadixTree ``` **Returns:** `RadixTree` ### RadixTree.insert ```vex export fn (self: &RadixTree!) insert(pattern: string, handler: Handler) ``` ### RadixTree.insertWithMiddleware ```vex export fn (self: &RadixTree!) insertWithMiddleware(pattern: string, handler: Handler, middlewares: Vec) ``` ### RadixTree.insertRoute ```vex export fn (self: &RadixTree!) insertRoute(pattern: string, handler: Handler, routeIndex: i32) ``` Insert a route while retaining the Router table index used to restore route metadata after a hot-path match. ### RadixTree.insertRouteWithMiddleware ```vex export fn (self: &RadixTree!) insertRouteWithMiddleware(pattern: string, handler: Handler, middlewares: Vec, routeIndex: i32) ``` ### RadixTree.findInto ```vex export fn (self: &RadixTree) findInto(path: str, ctx: &Ctx!): RadixMatch ``` Match directly into reusable request context buffers. No MatchResult, parameter strings, or middleware Vec is allocated on the request path. **Returns:** `RadixMatch` ### RadixTree.find ```vex export fn (self: &RadixTree) find(path: str): MatchResult ``` **Returns:** `MatchResult` ### WsRouteOptions.new ```vex export fn WsRouteOptions.new(): WsRouteOptions ``` **Returns:** `WsRouteOptions` ### WsRouteOptions.protocol ```vex export fn (self: &WsRouteOptions!) protocol(value: string): &WsRouteOptions! ``` Add one case-sensitive RFC 6455 subprotocol in server preference order. Invalid or duplicate startup configuration is a programmer error rather than a silently unreachable production route. **Returns:** `&WsRouteOptions!` ### WsRouteOptions.requireSubprotocol ```vex export fn (self: &WsRouteOptions!) requireSubprotocol(): &WsRouteOptions! ``` Reject an opening handshake when it offers none of this route's supported protocols. Without this flag, a valid no-overlap request upgrades without a `Sec-WebSocket-Protocol` response, as RFC 6455 permits. **Returns:** `&WsRouteOptions!` ### Router.new ```vex export fn Router.new(): Router<{HTTP_FULL}> ``` Create an empty router. **Returns:** `Router<{HTTP_FULL}>` ### Router.new ```vex export fn Router.new(): Router<{FEATURES}> ``` **Type Parameters:** - `const FEATURES: u32` **Returns:** `Router<{FEATURES}>` ### Router.selectWsProtocol ```vex export fn (self: &Router) selectWsProtocol(routeId: i32, request: &Request): WsProtocolSelection ``` Select at most one client-offered protocol using immutable server preference order. The compact pool keeps ordinary HTTP and WebSocket route matching allocation-free after startup. **Returns:** `WsProtocolSelection` ### Router.addAsync ```vex export fn (self: &Router!) addAsync(method: str, pattern: string, handlers: Vec) ``` Register an explicit awaitable route. `handlers` is moved into immutable router metadata at startup; the serving path copies only function values into the task-owned `AsyncPipelineNext` chain. ### Router.addBodyAsync ```vex export fn (self: &Router!) addBodyAsync(method: str, pattern: string, handlers: Vec) ``` Register an explicit task-owned request-body stream. Route selection occurs after the complete header block but before body accumulation, allowing the descriptor, admission lease and framing state to move as one unit. ### Router.asyncHandlersFor ```vex export fn (self: &Router) asyncHandlersFor(routeId: i32): Vec ``` Copy a selected route's function values into fresh task-owned storage. Returning an empty vector is distinct from a valid route and keeps the synchronous hot path branchless apart from its one route-id lookup. **Returns:** `Vec` ### Router.hasAsyncRoute ```vex export fn (self: &Router) hasAsyncRoute(routeId: i32): bool ``` Test async-route membership without allocating task handler storage. This is used on every routed request, so the synchronous hot path must not build and immediately discard a handler vector just to make a branch. **Returns:** `bool` ### Router.hasAnyAsyncRoutes ```vex export fn (self: &Router) hasAnyAsyncRoutes(): bool ``` Zero-cost startup guard for workers which do not serve complete-body async routes. H2 completion channels and wake descriptors are created only when the frozen application can actually launch one of these tasks. **Returns:** `bool` ### Router.hasAnyResponseStreamRoutes ```vex export fn (self: &Router) hasAnyResponseStreamRoutes(): bool ``` Startup-only capability guard for protocol stream completion lanes. **Returns:** `bool` ### Router.asyncBodyHandlersFor ```vex export fn (self: &Router) asyncBodyHandlersFor(routeId: i32): Vec ``` **Returns:** `Vec` ### Router.hasAsyncBodyRoute ```vex export fn (self: &Router) hasAsyncBodyRoute(routeId: i32): bool ``` **Returns:** `bool` ### Router.hasAnyAsyncBodyRoutes ```vex export fn (self: &Router) hasAnyAsyncBodyRoutes(): bool ``` Zero-cost global guard for applications which never register request-body streams. Ordinary Fiber deployments avoid an early route lookup entirely. **Returns:** `bool` ### Router.add ```vex export fn (self: &Router!) add(method: str, pattern: str, handler: Handler) ``` Register a route with a method, pattern, and handler. ### Router.addWs ```vex export fn (self: &Router!) addWs(pattern: str, handler: WsHandler) ``` Register a GET endpoint whose HTTP request is later promoted to a worker-owned WebSocket session. The radix tree stores the ordinary marker handler, while the endpoint callback remains route metadata until handoff. ### Router.addWsWithLifecycle ```vex export fn (self: &Router!) addWsWithLifecycle(pattern: str, onOpen: Option, handler: WsHandler, onClose: Option) ``` Register a WebSocket endpoint with worker-owned lifecycle hooks. The hooks are route metadata, not ordinary HTTP handlers: middleware still decides whether an upgrade is allowed before `onOpen` can observe the session. ### Router.addWsWithOptions ```vex export fn (self: &Router!) addWsWithOptions(pattern: str, options: WsRouteOptions, handler: WsHandler) ``` Register a WebSocket endpoint with immutable subprotocol policy. Existing `addWs` routes remain protocol-agnostic and pay no per-request allocation. ### Router.addWsWithLifecycleOptions ```vex export fn (self: &Router!) addWsWithLifecycleOptions(pattern: str, options: WsRouteOptions, onOpen: Option, handler: WsHandler, onClose: Option) ``` ### Router.addWsWithMiddleware ```vex export fn (self: &Router!) addWsWithMiddleware(pattern: str, middlewares: Vec, handler: WsHandler) ``` WebSocket equivalent of `addWithMiddleware`. The same terminal marker is used, so authorization middleware runs before the HTTP→stream transfer and may reject without ever handing the descriptor to a WebSocket callback. ### Router.addWsWithMiddlewareLifecycle ```vex export fn (self: &Router!) addWsWithMiddlewareLifecycle(pattern: str, middlewares: Vec, onOpen: Option, handler: WsHandler, onClose: Option) ``` Lifecycle variant of `addWsWithMiddleware`; route middleware remains outside the session and can reject without producing an open callback. ### Router.addWsWithMiddlewareOptions ```vex export fn (self: &Router!) addWsWithMiddlewareOptions(pattern: str, middlewares: Vec, options: WsRouteOptions, handler: WsHandler) ``` ### Router.addWsWithMiddlewareLifecycleOptions ```vex export fn (self: &Router!) addWsWithMiddlewareLifecycleOptions(pattern: str, middlewares: Vec, options: WsRouteOptions, onOpen: Option, handler: WsHandler, onClose: Option) ``` ### Router.addStream ```vex export fn (self: &Router!) addStream(method: str, pattern: str, handler: StreamHandler) ``` Register a dynamic producer endpoint. It uses the same route metadata and freeze-time radix tree as ordinary handlers; the terminal marker resolves the producer from `routeStreamHandlers` after routing has completed. ### Router.addStreamWithMiddleware ```vex export fn (self: &Router!) addStreamWithMiddleware(method: str, pattern: str, middlewares: Vec, handler: StreamHandler) ``` Stream equivalent of `addWithMiddleware`. The producer still occupies only the terminal chain slot; middleware remains ordinary `Handler` code and retains before/after `next()` behavior. ### Router.addStaticRoute ```vex export fn (self: &Router!) addStaticRoute(method: str, pattern: str, handler: Handler, root: string) ``` Register a static route with a method, pattern, handler, and root directory. ### Router.addStaticRouteWithMiddleware ```vex export fn (self: &Router!) addStaticRouteWithMiddleware(method: str, pattern: str, handler: Handler, root: string, middlewares: Vec) ``` Register a static route with route-level middleware. This mirrors addStaticRoute while preserving the same flat startup-only middleware pool used by ordinary routes. ### Router.addWithMiddleware ```vex export fn (self: &Router!) addWithMiddleware(method: str, pattern: str, middlewares: Vec, handler: Handler) ``` Register a route with route-level middleware. Middleware runs in order before the handler (after global middleware). Example: router.addWithMiddleware("GET", "/admin", authMW, handler) ### Router.freeze ```vex export fn (self: &Router!) freeze() ``` Compile all routes into per-method radix trees. Called once at startup. After this, find() uses O(L) tree lookup. **Receiver:** `self: &Router!` *(mutable reference)* ### Router.find ```vex export fn (self: &Router!) find(method: str, path: str, ctx: &Ctx!): Option ``` Find a matching route and extract parameters into ctx. Frozen routers use O(L) radix lookup; mutable routers use the linear builder path. **Returns:** `Option` ### Router.findFrozen ```vex export fn (self: &Router) findFrozen(method: str, path: str, ctx: &Ctx!): Option ``` Match against a frozen router without mutating shared application state. Server workers must use this entry point: the compiled radix trees are immutable after `freeze()` and are therefore safe to share across tasks. **Returns:** `Option` ### RequestHeaders.new ```vex export fn RequestHeaders.new(): RequestHeaders ``` **Returns:** `RequestHeaders` ### RequestHeaders.get ```vex export fn (self: &RequestHeaders) get(name: str): str ``` Get header value by name (case-insensitive). Returns empty str if not found. **Returns:** `str` ### RequestHeaders.has ```vex export fn (self: &RequestHeaders) has(name: str): bool ``` Check if a header exists (case-insensitive). **Returns:** `bool` ### RequestHeaders.add ```vex export fn (self: &RequestHeaders!) add(name: str, value: str) ``` Add a header — zero-copy, stores str views directly. ### RequestHeaders.clear ```vex export fn (self: &RequestHeaders!) clear() ``` Clear all headers (no allocations — str is Copy). **Receiver:** `self: &RequestHeaders!` *(mutable reference)* ### RequestHeaders.len ```vex export fn (self: &RequestHeaders) len(): usize ``` Number of headers. **Returns:** `usize` ### Headers.new ```vex export fn Headers.new(): Headers ``` Create an empty Headers collection. **Returns:** `Headers` ### Headers.get ```vex export fn (self: &Headers) get(name: str): string ``` Get header value by name (case-insensitive). Returns empty string if not found. Uses .asStr() for zero-copy comparison — avoids heap alloc per iteration. **Returns:** `string` ### Headers.has ```vex export fn (self: &Headers) has(name: str): bool ``` Check if a header exists (case-insensitive). Uses .asStr() for zero-copy comparison. **Returns:** `bool` ### Headers.set ```vex export fn (self: &Headers!) set(name: str, value: str) ``` Set a header. Replaces existing (case-insensitive) or appends. ### Headers.add ```vex export fn (self: &Headers!) add(name: str, value: str) ``` Add a header (allows duplicate names, e.g. Set-Cookie). ### Headers.del ```vex export fn (self: &Headers!) del(name: str) ``` Remove all headers with the given name (case-insensitive). In-place removal — no allocation. ### Headers.clear ```vex export fn (self: &Headers!) clear() ``` Clear all headers. **Receiver:** `self: &Headers!` *(mutable reference)* ### Headers.shrinkToFit ```vex export fn (self: &Headers!) shrinkToFit() ``` Shrink underlying storage to match actual header count. **Receiver:** `self: &Headers!` *(mutable reference)* ### Headers.len ```vex export fn (self: &Headers) len(): usize ``` Number of headers. **Returns:** `usize` ### CorsConfig.new ```vex export fn CorsConfig.new(origin: string): CorsConfig ``` Create a CORS config with a specific origin. **Returns:** `CorsConfig` ### CorsConfig.setMethods ```vex export fn (self: &CorsConfig!) setMethods(m: string): &CorsConfig! ``` Set allowed methods (chainable). **Returns:** `&CorsConfig!` ### CorsConfig.setHeaders ```vex export fn (self: &CorsConfig!) setHeaders(h: string): &CorsConfig! ``` Set allowed headers (chainable). **Returns:** `&CorsConfig!` ### CorsConfig.setMaxAge ```vex export fn (self: &CorsConfig!) setMaxAge(age: string): &CorsConfig! ``` Set max age for preflight cache (chainable). **Returns:** `&CorsConfig!` ### CorsConfig.allowCredentials ```vex export fn (self: &CorsConfig!) allowCredentials(): &CorsConfig! ``` Enable credentials (chainable). **Returns:** `&CorsConfig!` ### CorsConfig.build ```vex export fn (self: &CorsConfig) build(): Handler ``` Build a Handler from this config. **Returns:** `Handler` ### BodyPageRing.new ```vex export fn BodyPageRing.new(pageCount: usize, pageBytes: usize): Option ``` Create a bounded owned page ring. Zero dimensions and overflowing total capacity are rejected before allocation; callers choose the explicit page budget as part of route admission rather than accepting an implicit unbounded upload buffer. **Returns:** `Option` ### BodyPageRing.capacity ```vex export fn (self: &BodyPageRing) capacity(): usize ``` Total fixed storage reserved by this ring. **Returns:** `usize` ### BodyPageRing.len ```vex export fn (self: &BodyPageRing) len(): usize ``` Number of decoded bytes currently owned by the ring. **Returns:** `usize` ### BodyPageRing.isEmpty ```vex export fn (self: &BodyPageRing) isEmpty(): bool ``` **Returns:** `bool` ### BodyPageRing.free ```vex export fn (self: &BodyPageRing) free(): usize ``` Remaining bounded storage. A zero result is the backpressure signal: the producer must not read another socket fragment until the route task drains at least one current readable segment. **Returns:** `usize` ### BodyPageRing.writable ```vex export fn (self: &BodyPageRing) writable(): usize ``` Bytes that may be committed through `writePtr` without crossing one page. The value is always bounded by `free()` and is zero when the ring is full. **Returns:** `usize` ### BodyPageRing.writePtr ```vex export fn (self: &BodyPageRing!) writePtr(): Ptr ``` Writable tail storage for one bounded producer operation. It is valid only up to `writable()` bytes, and the producer must call `commitWrite` exactly once after populating it. A full ring returns a null pointer instead of exposing a stale page. **Returns:** `Ptr` ### BodyPageRing.commitWrite ```vex export fn (self: &BodyPageRing!) commitWrite(count: usize): bool ``` Commit bytes written through the current writable page. Invalid counts do not alter any cursor, so a faulty transport adapter cannot corrupt queued body ownership. **Returns:** `bool` ### BodyPageRing.write ```vex export fn (self: &BodyPageRing!) write(data: str): bool ``` Copy a complete caller-owned fragment into the bounded pages. This is the convenience path for parser adapters; unlike a partial append it either accepts the full fragment or leaves the ring untouched, preserving an exact backpressure boundary. **Returns:** `bool` ### BodyPageRing.readable ```vex export fn (self: &BodyPageRing) readable(): usize ``` Bytes available to one consumer callback without crossing a page. The resulting view is borrowed from the ring and becomes invalid after its corresponding `consume` or any subsequent mutable ring operation. **Returns:** `usize` ### BodyPageRing.readChunk ```vex export fn (self: &BodyPageRing) readChunk(): str ``` Borrow the current readable page fragment. Empty rings return an empty view; they never manufacture a pointer into uninitialized storage. **Returns:** `str` ### BodyPageRing.consume ```vex export fn (self: &BodyPageRing!) consume(count: usize): bool ``` Release exactly a prefix of the current readable page. Crossing a page in one call is intentionally rejected: that keeps every route callback's borrowed view and the following cursor transition unambiguous. **Returns:** `bool` ### BodyPageRing.reset ```vex export fn (self: &BodyPageRing!) reset() ``` Clear queued ownership after a terminal request transition. Pages remain allocated for the next route/task, while every borrowed payload view has to be discarded by the caller before reset. **Receiver:** `self: &BodyPageRing!` *(mutable reference)* ### BodyReader.new ```vex export fn BodyReader.new(mode: BodyMode): BodyReader ``` **Returns:** `BodyReader` ### RequestBodyLifecycle.new ```vex export fn RequestBodyLifecycle.new(mode: BodyMode): RequestBodyLifecycle ``` **Returns:** `RequestBodyLifecycle` ### DecodedBodyLifecycle.new ```vex export fn DecodedBodyLifecycle.new(mode: BodyMode, declaredLength: i64, maxBodyBytes: usize): DecodedBodyLifecycle ``` **Returns:** `DecodedBodyLifecycle` ### DecodedBodyLifecycle.begin ```vex export fn (self: &DecodedBodyLifecycle!) begin(consumer: &C!): bool where C: RequestBodyConsumer ``` Admit exactly one consumer. Invalid or oversized declared lengths are rejected before application code observes a partial lifecycle. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` **Returns:** `boolwhere C: RequestBodyConsumer` ### DecodedBodyLifecycle.accept ```vex export fn (self: &DecodedBodyLifecycle!) accept( bytes: str, consumer: &C!, ): BodyResult where C: RequestBodyConsumer ``` Deliver one already-decoded protocol payload synchronously. Accounting is committed only after the consumer accepts the borrowed view. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` **Returns:** `BodyResultwhere C: RequestBodyConsumer` ### DecodedBodyLifecycle.finish ```vex export fn (self: &DecodedBodyLifecycle!) finish( consumer: &C!, ): BodyResult where C: RequestBodyConsumer ``` Complete the protocol-neutral stream boundary exactly once. A declared content length is an equality constraint at END_STREAM, not only a cap. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` **Returns:** `BodyResultwhere C: RequestBodyConsumer` ### DecodedBodyLifecycle.cancel ```vex export fn (self: &DecodedBodyLifecycle!) cancel(consumer: &C!) where C: RequestBodyConsumer ``` Idempotently cancel an admitted consumer without publishing completion. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` ### DecodedBodyLifecycle.rearm ```vex export fn (self: &DecodedBodyLifecycle!) rearm(mode: BodyMode, declaredLength: i64, maxBodyBytes: usize): bool ``` Re-arm only after a terminal transition; active borrowed callbacks can therefore never race with storage reuse. **Returns:** `bool` ### RequestBodyLifecycle.begin ```vex export fn (self: &RequestBodyLifecycle!) begin( consumer: &C!, maxBodyBytes: usize, ): bool where C: RequestBodyConsumer ``` Begin one consumer exactly once. A consumer that rejects admission is cancelled immediately and this lifecycle cannot be reused without `reset`. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` **Returns:** `boolwhere C: RequestBodyConsumer` ### RequestBodyLifecycle.feed ```vex export fn (self: &RequestBodyLifecycle!) feed( data: str, consumer: &C!, maxBodyBytes: usize, ): BodyResult where C: RequestBodyConsumer ``` Decode one transport fragment into an admitted consumer. Calls after a terminal transition fail closed; successful completion invokes `finish` once and only once. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` **Returns:** `BodyResultwhere C: RequestBodyConsumer` ### RequestBodyLifecycle.connectionClosed ```vex export fn (self: &RequestBodyLifecycle!) connectionClosed( consumer: &C!, ): bool where C: RequestBodyConsumer ``` Terminal peer-close handling. Only close-delimited bodies may finish at EOF; every framed body is cancelled because its declared boundary was not reached. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` **Returns:** `boolwhere C: RequestBodyConsumer` ### RequestBodyLifecycle.cancel ```vex export fn (self: &RequestBodyLifecycle!) cancel(consumer: &C!) where C: RequestBodyConsumer ``` Cancel an admitted consumer due to deadline, routing failure, or explicit shutdown. It is idempotent and never calls `finish`. **Type Parameters:** - `C` **Where:** - `RequestBodyConsumer`: `RequestBodyConsumer` ### RequestBodyLifecycle.reset ```vex export fn (self: &RequestBodyLifecycle!) reset(mode: BodyMode): bool ``` Reset only after a terminal transition. This makes accidental reuse while a borrowed chunk callback is active impossible by construction. **Returns:** `bool` ### BodyReader.feedInto ```vex export fn (self: &BodyReader!) feedInto(data: str, output: &StringBuilder!, maxBodyBytes: usize): BodyResult ``` Consume one transport fragment and append decoded bytes to `output`. `progress.consumed` always refers to this call's `data` view, so a caller can retain the exact suffix for pipelined messages without guessing. **Returns:** `BodyResult` ### BodyReader.feedTo ```vex export fn (self: &BodyReader!) feedTo( data: str, sink: &S!, maxBodyBytes: usize, ): BodyResult where S: ChunkSink ``` Consume one transport fragment through a caller-owned decoded-byte sink. This is the zero-copy parser seam used by the HTTP/1 request lifecycle: data reaches `sink` as borrowed `str` views into the current transport fragment, with no response-sized intermediate allocation. The sink must consume each view synchronously and must return `false` to fail closed. `progress.consumed` remains relative to this call's `data` view. **Type Parameters:** - `S` **Where:** - `ChunkSink`: `ChunkSink` **Returns:** `BodyResultwhere S: ChunkSink` ### BodyReader.connectionClosed ```vex export fn (self: &BodyReader!) connectionClosed() ``` **Receiver:** `self: &BodyReader!` *(mutable reference)* ### BodyReader.isDone ```vex export fn (self: &BodyReader) isDone(): bool ``` **Returns:** `bool` ### BodyReader.totalBytes ```vex export fn (self: &BodyReader) totalBytes(): usize ``` **Returns:** `usize` ### BodyReader.reset ```vex export fn (self: &BodyReader!) reset(mode: BodyMode) ``` ### ChunkedDecoder.new ```vex export fn ChunkedDecoder.new(): ChunkedDecoder ``` **Returns:** `ChunkedDecoder` ### ChunkedDecoder.decodeTo ```vex export fn (self: &ChunkedDecoder!) decodeTo( input: str, sink: &S!, maxBodyBytes: usize, ): ChunkResult where S: ChunkSink ``` Incrementally decode one input fragment into a caller-owned sink. `maxBodyBytes` is checked before every append. On `NeedMore`, bytes before `progress.consumed` are permanently consumed; the unconsumed suffix must be prepended to the next fragment. On `Complete`, the suffix after `consumed` is the next pipelined message and is never swallowed by this decoder. **Type Parameters:** - `S` **Where:** - `ChunkSink`: `ChunkSink` **Returns:** `ChunkResultwhere S: ChunkSink` ### ChunkedDecoder.decodeInto ```vex export fn (self: &ChunkedDecoder!) decodeInto(input: str, output: &StringBuilder!, maxBodyBytes: usize): ChunkResult ``` Buffered convenience form of `decodeTo`. Kept for source compatibility and small callers; applications which already own a stateful destination can call `decodeTo` and avoid the response-sized accumulation entirely. **Returns:** `ChunkResult` ### ChunkedDecoder.reset ```vex export fn (self: &ChunkedDecoder!) reset() ``` **Receiver:** `self: &ChunkedDecoder!` *(mutable reference)* ### ChunkedDecoder.isDone ```vex export fn (self: &ChunkedDecoder) isDone(): bool ``` **Returns:** `bool` ### ChunkedDecoder.isError ```vex export fn (self: &ChunkedDecoder) isError(): bool ``` **Returns:** `bool` ### FiberRequestLimits.defaults ```vex export fn FiberRequestLimits.defaults(): FiberRequestLimits ``` **Returns:** `FiberRequestLimits` ### FiberParsedRequest.empty ```vex export fn FiberParsedRequest.empty(): FiberParsedRequest ``` **Returns:** `FiberParsedRequest` ### FiberParsedRequest.clearBorrowedViews ```vex export fn (self: &FiberParsedRequest!) clearBorrowedViews() ``` End every view currently published by this reusable parse scratch. **Receiver:** `self: &FiberParsedRequest!` *(mutable reference)* ### H2Frame.isEndStream ```vex export fn (self: &H2Frame) isEndStream(): bool ``` Has END_STREAM flag? **Returns:** `bool` ### H2Frame.isEndHeaders ```vex export fn (self: &H2Frame) isEndHeaders(): bool ``` Has END_HEADERS flag? **Returns:** `bool` ### H2Frame.isPadded ```vex export fn (self: &H2Frame) isPadded(): bool ``` Has PADDED flag? **Returns:** `bool` ### H2Frame.hasPriority ```vex export fn (self: &H2Frame) hasPriority(): bool ``` Has PRIORITY flag? **Returns:** `bool` ### H2Frame.isAck ```vex export fn (self: &H2Frame) isAck(): bool ``` Has ACK flag? **Returns:** `bool` ### H2Settings.defaults ```vex export fn H2Settings.defaults(): H2Settings ``` Default HTTP/2 settings. **Returns:** `H2Settings` ### H2ConnectionState.new ```vex export fn H2ConnectionState.new(role: H2EndpointRole): H2ConnectionState ``` Create connection state with explicit endpoint ownership. Clients initiate odd streams; servers initiate even streams (including pushed streams). **Returns:** `H2ConnectionState` ### H2ConnectionState.openLocalStream ```vex export fn (self: &H2ConnectionState!) openLocalStream(streams: &StreamMap!): H2StreamAdmissionResult ``` Open the next locally owned stream and materialize it atomically. Once a peer GOAWAY is received, no new local stream is admitted; callers may retry work whose prior stream ID is above the peer's last-stream boundary. **Returns:** `H2StreamAdmissionResult` ### H2ConnectionState.acceptRemoteStream ```vex export fn (self: &H2ConnectionState!) acceptRemoteStream(streams: &StreamMap!, id: u32): H2StreamAdmissionResult ``` Admit a peer-owned stream under parity, monotonic-ID, GOAWAY and concurrent stream rules. Valid refused/ignored IDs are consumed so they cannot later be reused as if they were new. **Returns:** `H2StreamAdmissionResult` ### H2ConnectionState.localStreamMayHaveBeenProcessed ```vex export fn (self: &H2ConnectionState) localStreamMayHaveBeenProcessed(id: u32): bool ``` Whether the peer's GOAWAY confirms that a locally initiated stream may have been processed. False means the operation is safe to consider for retry. **Returns:** `bool` ### H2ConnectionState.applyReceivedPriorityUpdate ```vex export fn (self: &H2ConnectionState!) applyReceivedPriorityUpdate(update: &H2PriorityUpdate, streams: &StreamMap, scheduler: &H2PriorityScheduler!): H2ConnectionResult ``` Apply a client PRIORITY_UPDATE to the bounded scheduler. Request priorities may arrive before their stream opens. Push priorities must reference an already reserved/open local push stream; closed targets are discarded. **Returns:** `H2ConnectionResult` ### H2ConnectionState.reserveSendData ```vex export fn (self: &H2ConnectionState!) reserveSendData(stream: &H2Stream!, flowBytes: u32): H2FlowResult ``` Atomically reserve connection and stream credit for outgoing DATA. `flowBytes` is the complete DATA payload length, including padding fields. **Returns:** `H2FlowResult` ### H2ConnectionState.acceptReceivedData ```vex export fn (self: &H2ConnectionState!) acceptReceivedData(stream: &H2Stream!, flowBytes: u32): H2FlowResult ``` Atomically account peer DATA against connection and stream receive credit. **Returns:** `H2FlowResult` ### H2ConnectionState.acceptReceivedDiscardedData ```vex export fn (self: &H2ConnectionState!) acceptReceivedDiscardedData(flowBytes: u32): H2FlowResult ``` Account DATA that arrived after the peer-facing side of a stream closed. RFC 9113 section 5.1 requires discarding those stream bytes while still charging the connection receive window, unless the connection itself fails. **Returns:** `H2FlowResult` ### H2ConnectionState.recvConnectionWindowUpdate ```vex export fn (self: &H2ConnectionState!) recvConnectionWindowUpdate(increment: u32): H2FlowResult ``` Apply a peer connection-level WINDOW_UPDATE to local send credit. **Returns:** `H2FlowResult` ### H2ConnectionState.sendConnectionWindowUpdate ```vex export fn (self: &H2ConnectionState!) sendConnectionWindowUpdate(increment: u32): H2FlowResult ``` Record a locally emitted connection WINDOW_UPDATE in receive credit. **Returns:** `H2FlowResult` ### H2ConnectionState.recvStreamWindowUpdate ```vex export fn (self: &H2ConnectionState!) recvStreamWindowUpdate(stream: &H2Stream!, increment: u32): H2FlowResult ``` Apply a peer stream-level WINDOW_UPDATE to local send credit. **Returns:** `H2FlowResult` ### H2ConnectionState.sendStreamWindowUpdate ```vex export fn (self: &H2ConnectionState!) sendStreamWindowUpdate(stream: &H2Stream!, increment: u32): H2FlowResult ``` Record a locally emitted stream WINDOW_UPDATE in receive credit. **Returns:** `H2FlowResult` ### H2ConnectionState.recvFrame ```vex export fn (self: &H2ConnectionState!) recvFrame(frame: &H2Frame): H2ConnectionResult ``` Apply a peer frame to connection-owned receive sequencing. **Returns:** `H2ConnectionResult` ### H2ConnectionState.sendFrame ```vex export fn (self: &H2ConnectionState!) sendFrame(frame: &H2Frame): H2ConnectionResult ``` Apply a local frame to connection-owned send sequencing. **Returns:** `H2ConnectionResult` ### H2ConnectionState.recordReceivedGoAway ```vex export fn (self: &H2ConnectionState!) recordReceivedGoAway(goAway: &GoAway): H2ConnectionResult ``` Record an accepted peer GOAWAY payload. Later GOAWAY frames may reduce, but never increase, the last processed stream identifier. **Returns:** `H2ConnectionResult` ### H2ConnectionState.recordSentGoAway ```vex export fn (self: &H2ConnectionState!) recordSentGoAway(goAway: &GoAway): H2ConnectionResult ``` Record a locally emitted GOAWAY payload under the same non-increasing rule. **Returns:** `H2ConnectionResult` ### H2Priority.defaults ```vex export fn H2Priority.defaults(): H2Priority ``` **Returns:** `H2Priority` ### H2Priority.new ```vex export fn H2Priority.new(urgency: u8, incremental: bool): Option ``` **Returns:** `Option` ### H2PriorityScheduler.new ```vex export fn H2PriorityScheduler.new(capacity: u32, maximumChunkBytes: u32, starvationTurns: u64): Option ``` Create a bounded scheduler. `starvationTurns` is the maximum normal-priority selections before an older ready entry becomes eligible for forced service. **Returns:** `Option` ### H2PriorityScheduler.defaults ```vex export fn H2PriorityScheduler.defaults(capacity: u32): Option ``` **Returns:** `Option` ### H2PriorityScheduler.len ```vex export fn (self: &H2PriorityScheduler) len(): usize ``` **Returns:** `usize` ### H2PriorityScheduler.isRegistered ```vex export fn (self: &H2PriorityScheduler) isRegistered(streamId: u32): bool ``` **Returns:** `bool` ### H2PriorityScheduler.isFull ```vex export fn (self: &H2PriorityScheduler) isFull(): bool ``` **Returns:** `bool` ### H2PriorityScheduler.remainingCapacity ```vex export fn (self: &H2PriorityScheduler) remainingCapacity(): u32 ``` **Returns:** `u32` ### H2PriorityScheduler.hasPendingWork ```vex export fn (self: &H2PriorityScheduler) hasPendingWork(): bool ``` **Returns:** `bool` ### H2PriorityScheduler.hasFlowBlockedWork ```vex export fn (self: &H2PriorityScheduler) hasFlowBlockedWork(): bool ``` **Returns:** `bool` ### H2PriorityScheduler.priorityFor ```vex export fn (self: &H2PriorityScheduler) priorityFor(streamId: u32): Option ``` **Returns:** `Option` ### H2PriorityScheduler.streamIdAt ```vex export fn (self: &H2PriorityScheduler) streamIdAt(index: usize): Option ``` Inspect bounded registry identity without exposing mutable entries. Protocol owners use this to retire priorities for stream IDs implicitly closed by a newer peer stream. **Returns:** `Option` ### H2PriorityScheduler.register ```vex export fn (self: &H2PriorityScheduler!) register(streamId: u32, priority: H2Priority): H2PriorityRegistrationResult ``` Register an active or idle stream. Re-registration is a reprioritization and never grows the bounded registry. **Returns:** `H2PriorityRegistrationResult` ### H2PriorityScheduler.markReady ```vex export fn (self: &H2PriorityScheduler!) markReady(streamId: u32): bool ``` **Returns:** `bool` ### H2PriorityScheduler.markBlocked ```vex export fn (self: &H2PriorityScheduler!) markBlocked(streamId: u32): bool ``` **Returns:** `bool` ### H2PriorityScheduler.markFlowBlocked ```vex export fn (self: &H2PriorityScheduler!) markFlowBlocked(streamId: u32): bool ``` Park application-ready work behind stream flow control without forgetting that bytes remain pending. **Returns:** `bool` ### H2PriorityScheduler.markFlowWritable ```vex export fn (self: &H2PriorityScheduler!) markFlowWritable(streamId: u32): bool ``` Publish new stream credit. Pending work becomes selectable again without a second application wakeup. **Returns:** `bool` ### H2PriorityScheduler.remove ```vex export fn (self: &H2PriorityScheduler!) remove(streamId: u32): bool ``` **Returns:** `bool` ### H2PriorityScheduler.cancel ```vex export fn (self: &H2PriorityScheduler!) cancel(streamId: u32): bool ``` Cancel a registered stream even when another selection lease is active. The selected index is repaired when removal shifts it; cancelling the selected stream also revokes that lease. Capacity is retained for reuse. **Returns:** `bool` ### H2PriorityScheduler.clear ```vex export fn (self: &H2PriorityScheduler!) clear() ``` Drop all active and idle priority state while retaining pre-reserved storage. Any outstanding selection lease is revoked. **Receiver:** `self: &H2PriorityScheduler!` *(mutable reference)* ### H2PriorityScheduler.next ```vex export fn (self: &H2PriorityScheduler!) next(maximumBytes: u32): H2ScheduleResult ``` Reserve one bounded scheduling turn. Exactly one selection may be in flight; `complete` publishes whether the stream remains ready. **Returns:** `H2ScheduleResult` ### H2PriorityScheduler.selectedStreamId ```vex export fn (self: &H2PriorityScheduler) selectedStreamId(): Option ``` **Returns:** `Option` ### H2PriorityScheduler.selectedRemainingBytes ```vex export fn (self: &H2PriorityScheduler) selectedRemainingBytes(): u32 ``` **Returns:** `u32` ### H2PriorityScheduler.capSelectedBudget ```vex export fn (self: &H2PriorityScheduler!) capSelectedBudget(streamId: u32, maximumBytes: u32): bool ``` Narrow a selected turn after connection/stream flow windows are applied. **Returns:** `bool` ### H2PriorityScheduler.consumeSelectedBudget ```vex export fn (self: &H2PriorityScheduler!) consumeSelectedBudget(streamId: u32, byteCount: u32): bool ``` Consume bytes from the current selection lease. This enforces the scheduler chunk contract even when a transport performs more than one partial write. **Returns:** `bool` ### H2PriorityScheduler.restoreSelectedBudget ```vex export fn (self: &H2PriorityScheduler!) restoreSelectedBudget(streamId: u32, byteCount: u32): bool ``` Restore a provisional budget reservation when flow-control mutation fails. **Returns:** `bool` ### H2PriorityScheduler.complete ```vex export fn (self: &H2PriorityScheduler!) complete(streamId: u32, stillReady: bool): bool ``` Complete the outstanding selection. `stillReady=true` requeues it without allocation; false leaves it registered but dormant for flow-control wakeup. **Returns:** `bool` ### H2PriorityScheduler.completeFlowBlocked ```vex export fn (self: &H2PriorityScheduler!) completeFlowBlocked(streamId: u32): bool ``` Complete a selected turn that discovered exhausted stream credit. Pending application work is retained and automatically wakes on markFlowWritable. **Returns:** `bool` ### H2ProtocolConfig.defaults ```vex export fn H2ProtocolConfig.defaults(): H2ProtocolConfig ``` **Returns:** `H2ProtocolConfig` ### H2ProtocolConfig.isValid ```vex export fn (self: &H2ProtocolConfig) isValid(): bool ``` **Returns:** `bool` ### H2HeaderFrameCursor.remainingPayloadBytes ```vex export fn (self: &H2HeaderFrameCursor) remainingPayloadBytes(): usize ``` **Returns:** `usize` ### H2HeaderFrameCursor.remainingFragmentCount ```vex export fn (self: &H2HeaderFrameCursor) remainingFragmentCount(): usize ``` **Returns:** `usize` ### H2HeaderFrameCursor.remainingWireBytes ```vex export fn (self: &H2HeaderFrameCursor) remainingWireBytes(): usize ``` Remaining payload plus the nine-byte header for every remaining frame. A transport can reserve this exact queue capacity before draining the cursor, preventing partial enqueue/interleaving of a compressed block. **Returns:** `usize` ### H2HeaderFrameCursor.nextWireBytes ```vex export fn (self: &H2HeaderFrameCursor) nextWireBytes(): usize ``` Exact destination capacity required by the next cursor turn without advancing it. Egress can reserve/copy atomically and never consume a fragment merely to discover that its socket queue is too small. **Returns:** `usize` ### H2HeaderFrameCursor.next ```vex export fn (self: &H2HeaderFrameCursor!) next(): Option ``` **Returns:** `Option` ### H2ProtocolState.new ```vex export fn H2ProtocolState.new(role: H2EndpointRole, config: H2ProtocolConfig): Option ``` Create one bounded owner for connection sequencing, live stream slots and active/idle priority state. The scheduler and stream map use the same concurrent capacity by construction. **Returns:** `Option` ### H2ProtocolState.role ```vex export fn (self: &H2ProtocolState) role(): H2EndpointRole ``` **Returns:** `H2EndpointRole` ### H2ProtocolState.activeStreamCount ```vex export fn (self: &H2ProtocolState) activeStreamCount(): u32 ``` **Returns:** `u32` ### H2ProtocolState.residentStreamCount ```vex export fn (self: &H2ProtocolState) residentStreamCount(): usize ``` **Returns:** `usize` ### H2ProtocolState.priorityStateCount ```vex export fn (self: &H2ProtocolState) priorityStateCount(): usize ``` **Returns:** `usize` ### H2ProtocolState.bufferedHeaderBytes ```vex export fn (self: &H2ProtocolState) bufferedHeaderBytes(): usize ``` **Returns:** `usize` ### H2ProtocolState.remainingIngressDiscardBytes ```vex export fn (self: &H2ProtocolState) remainingIngressDiscardBytes(): usize ``` **Returns:** `usize` ### H2ProtocolState.receiveDynamicTableBytes ```vex export fn (self: &H2ProtocolState) receiveDynamicTableBytes(): usize ``` **Returns:** `usize` ### H2ProtocolState.sendDynamicTableBytes ```vex export fn (self: &H2ProtocolState) sendDynamicTableBytes(): usize ``` **Returns:** `usize` ### H2ProtocolState.sendMaximumDynamicTableBytes ```vex export fn (self: &H2ProtocolState) sendMaximumDynamicTableBytes(): usize ``` **Returns:** `usize` ### H2ProtocolState.hasPendingSendTableSizeUpdate ```vex export fn (self: &H2ProtocolState) hasPendingSendTableSizeUpdate(): bool ``` **Returns:** `bool` ### H2ProtocolState.effectiveLocalSettings ```vex export fn (self: &H2ProtocolState) effectiveLocalSettings(): H2Settings ``` **Returns:** `H2Settings` ### H2ProtocolState.effectivePeerSettings ```vex export fn (self: &H2ProtocolState) effectivePeerSettings(): H2Settings ``` **Returns:** `H2Settings` ### H2ProtocolState.pendingLocalSettingsCount ```vex export fn (self: &H2ProtocolState) pendingLocalSettingsCount(): usize ``` **Returns:** `usize` ### H2ProtocolState.pendingLocalPingCount ```vex export fn (self: &H2ProtocolState) pendingLocalPingCount(): usize ``` **Returns:** `usize` ### H2ProtocolState.receiveMaximumFrameSize ```vex export fn (self: &H2ProtocolState) receiveMaximumFrameSize(): u32 ``` **Returns:** `u32` ### H2ProtocolState.sendMaximumFrameSize ```vex export fn (self: &H2ProtocolState) sendMaximumFrameSize(): u32 ``` **Returns:** `u32` ### H2ProtocolState.isClosed ```vex export fn (self: &H2ProtocolState) isClosed(): bool ``` **Returns:** `bool` ### H2ProtocolState.lastRemoteStreamId ```vex export fn (self: &H2ProtocolState) lastRemoteStreamId(): u32 ``` Highest peer-owned stream identifier admitted or refused by this connection. Transport uses this structural boundary for GOAWAY; it never reconstructs lifecycle state from response names or resident slots. **Returns:** `u32` ### H2ProtocolState.isDraining ```vex export fn (self: &H2ProtocolState) isDraining(): bool ``` **Returns:** `bool` ### H2ProtocolState.streamState ```vex export fn (self: &H2ProtocolState) streamState(streamId: u32): Option ``` **Returns:** `Option` ### H2ProtocolState.streamPriority ```vex export fn (self: &H2ProtocolState) streamPriority(streamId: u32): Option ``` **Returns:** `Option` ### H2ProtocolState.openLocalStream ```vex export fn (self: &H2ProtocolState!) openLocalStream(): H2StreamAdmissionResult ``` Open a locally owned stream only when its scheduler slot is also available. No stream ID or map slot is consumed on capacity failure. **Returns:** `H2StreamAdmissionResult` ### H2ProtocolState.acceptRemoteStream ```vex export fn (self: &H2ProtocolState!) acceptRemoteStream(streamId: u32): H2StreamAdmissionResult ``` Admit a peer stream and preserve any PRIORITY_UPDATE that raced ahead of HEADERS. Active streams and prioritized idle streams consume the same bounded registry. A capacity refusal consumes the valid peer ID but exposes no partially active stream. **Returns:** `H2StreamAdmissionResult` ### H2ProtocolState.sendRstStreamFrame ```vex export fn (self: &H2ProtocolState!) sendRstStreamFrame(streamId: u32, errorCode: u32, out: &str!): H2SendResetResult ``` Cancel/reset a locally owned stream under one wire transaction. Active streams are retired only after the complete RST_STREAM is encoded; an undersized output therefore cannot lose a required reset. Idle stream IDs and early priority records never existed on the wire and need no frame. **Returns:** `H2SendResetResult` ### H2ProtocolState.sendStreamErrorFrame ```vex export fn (self: &H2ProtocolState!) sendStreamErrorFrame(streamId: u32, errorCode: u32, out: &str!): H2SendResetResult ``` Encode the RST_STREAM required by a locally detected receive-side stream error. Receive validation deliberately retires the stream before exposing its typed error, so this transaction cannot use the ordinary active-stream cancellation path. `resetSent` keeps the wire obligation exact: a failed encode changes nothing and a repeated call cannot emit a duplicate reset. **Returns:** `H2SendResetResult` ### H2ProtocolState.sendCancelFrame ```vex export fn (self: &H2ProtocolState!) sendCancelFrame(streamId: u32, out: &str!): H2SendResetResult ``` **Returns:** `H2SendResetResult` ### H2ProtocolState.recvRstStreamFrame ```vex export fn (self: &H2ProtocolState!) recvRstStreamFrame(frame: &H2Frame, payload: str): H2ReceiveResetResult ``` Consume a peer RST_STREAM payload exactly once. Idle-stream violations, connection sequencing and the four-byte payload are validated before the stream state and scheduler capacity are published. **Returns:** `H2ReceiveResetResult` ### H2ProtocolState.markReady ```vex export fn (self: &H2ProtocolState!) markReady(streamId: u32): bool ``` **Returns:** `bool` ### H2ProtocolState.markBlocked ```vex export fn (self: &H2ProtocolState!) markBlocked(streamId: u32): bool ``` **Returns:** `bool` ### H2ProtocolState.completeWritable ```vex export fn (self: &H2ProtocolState!) completeWritable(streamId: u32, stillReady: bool): bool ``` **Returns:** `bool` ### H2ProtocolState.nextWritable ```vex export fn (self: &H2ProtocolState!) nextWritable(maximumBytes: u32): H2ScheduleResult ``` Select only work that has both application bytes and connection/stream flow credit. The returned budget is capped by scheduler chunk policy and both windows. Flow-blocked work remains pending and is skipped without allocation until WINDOW_UPDATE wakes it. **Returns:** `H2ScheduleResult` ### H2ProtocolState.sendHeaderBlock ```vex export fn (self: &H2ProtocolState!) sendHeaderBlock(streamId: u32, endStream: bool, headers: &Vec, out: &str!): H2SendHeaderResult ``` Encode one complete HEADERS field block. Semantic phase, stream transition, connection sequencing, HPACK state and caller output form one transaction. The returned allocation-free cursor fragments the contiguous payload according to the peer's effective frame-size setting. **Returns:** `H2SendHeaderResult` ### H2ProtocolState.sendPushPromise ```vex export fn (self: &H2ProtocolState!) sendPushPromise(carrierStreamId: u32, headers: &Vec, out: &str!): H2SendPushResult ``` Reserve and encode one server PUSH_PROMISE transactionally. Carrier state, promised stream ID/slot, priority capacity, connection sequencing, HPACK table and output either commit together or are all restored. The returned cursor emits the four-byte promised ID before the first HPACK slice and then uses CONTINUATION as required by the peer frame-size setting. **Returns:** `H2SendPushResult` ### H2ProtocolState.recvDataFrame ```vex export fn (self: &H2ProtocolState!) recvDataFrame(frame: &H2Frame, payload: str): H2ReceiveDataResult ``` Consume one complete DATA payload under a single protocol owner. Payload shape, connection sequencing, both flow-control windows and the stream transition are staged before publication. Application bytes remain a borrowed slice of `payload`; padding is never copied or exposed. **Returns:** `H2ReceiveDataResult` ### H2ProtocolState.sendDataFrame ```vex export fn (self: &H2ProtocolState!) sendDataFrame(streamId: u32, dataBytes: u32, paddingBytes: u8, endStream: bool): H2SendDataResult ``` Commit one outbound DATA frame from the current scheduler lease. Caller must reserve `9 + frame.length` transport bytes before invoking this method; after `Ready`, the returned metadata and payload layout are infallible. **Returns:** `H2SendDataResult` ### H2ProtocolState.recvWindowUpdateFrame ```vex export fn (self: &H2ProtocolState!) recvWindowUpdateFrame(frame: &H2Frame, payload: str): H2ProtocolFrameResult ``` Apply a complete peer WINDOW_UPDATE transaction. Frame sequencing, increment parsing, scoped overflow checks, stream state and scheduler wakeup commit together; malformed connection updates make the owner terminal, while stream-scoped failures retire only that stream. **Returns:** `H2ProtocolFrameResult` ### H2ProtocolState.sendWindowUpdateFrame ```vex export fn (self: &H2ProtocolState!) sendWindowUpdateFrame(streamId: u32, increment: u32, out: &str!): H2SendControlResult ``` Encode and record one locally emitted WINDOW_UPDATE atomically. `out` must provide thirteen bytes; failed capacity, sequencing or window arithmetic leaves protocol state and destination bytes unchanged. **Returns:** `H2SendControlResult` ### H2ProtocolState.recvPingFrame ```vex export fn (self: &H2ProtocolState!) recvPingFrame(frame: &H2Frame, payload: str): H2ReceivePingResult ``` Consume one exact peer PING payload. ACKs remove only the matching bounded local token; unmatched ACKs remain observable without killing a healthy connection. Non-ACK payloads borrow the caller's bytes for zero-copy echo. **Returns:** `H2ReceivePingResult` ### H2ProtocolState.sendPingFrame ```vex export fn (self: &H2ProtocolState!) sendPingFrame(opaqueData: str, out: &str!): H2SendPingResult ``` Emit a locally initiated PING and retain its opaque token until the peer's exact ACK arrives. Duplicate tokens and bounded-capacity overflow fail before output or connection state changes. **Returns:** `H2SendPingResult` ### H2ProtocolState.sendPingAckFrame ```vex export fn (self: &H2ProtocolState!) sendPingAckFrame(opaqueData: str, out: &str!): H2SendPingResult ``` Echo a peer PING payload as ACK without consuming local outstanding-PING capacity. `opaqueData` should be the borrowed `AckRequired` payload. **Returns:** `H2SendPingResult` ### H2ProtocolState.recvPriorityUpdateFrame ```vex export fn (self: &H2ProtocolState!) recvPriorityUpdateFrame(frame: &H2Frame, payload: str): H2ReceivePriorityResult ``` Consume one complete peer PRIORITY_UPDATE. The raw Structured Fields value never escapes this boundary: payload shape and RFC 9218 syntax are checked before direction/CONTINUATION sequencing and scheduler state can commit. **Returns:** `H2ReceivePriorityResult` ### H2ProtocolState.sendPriorityUpdateFrame ```vex export fn (self: &H2ProtocolState!) sendPriorityUpdateFrame(streamId: u32, priority: &H2Priority, out: &str!): H2SendPriorityResult ``` Encode one client PRIORITY_UPDATE and publish local connection sequencing only after the complete frame fits. This signal changes the peer scheduler; it deliberately does not mutate the local scheduler. **Returns:** `H2SendPriorityResult` ### H2ProtocolState.recvLegacyPriorityFrame ```vex export fn (self: &H2ProtocolState!) recvLegacyPriorityFrame(frame: &H2Frame, payload: str): H2ReceiveLegacyPriorityResult ``` Consume one deprecated RFC 7540 PRIORITY frame for interoperability. It never creates a stream and never feeds the RFC 9218 scheduler. Known live streams retain the metadata as a fallback; idle/closed unknown IDs are validated then ignored exactly without affecting stream state. **Returns:** `H2ReceiveLegacyPriorityResult` ### H2ProtocolState.sendLegacyPriorityFrame ```vex export fn (self: &H2ProtocolState!) sendLegacyPriorityFrame(streamId: u32, priority: &H2LegacyPriority, out: &str!): H2SendControlResult ``` Emit deprecated PRIORITY only for explicit compatibility. The frame may name an idle or closed stream, so local stream state is intentionally not consulted or mutated. **Returns:** `H2SendControlResult` ### H2ProtocolState.recvStreamFrame ```vex export fn (self: &H2ProtocolState!) recvStreamFrame(frame: &H2Frame): H2ProtocolFrameResult ``` Apply a non-header stream frame. Header-bearing frames must use `recvHeaderFrame`, which owns payload reassembly and HPACK lifetime. **Returns:** `H2ProtocolFrameResult` ### H2ProtocolState.sendStreamFrame ```vex export fn (self: &H2ProtocolState!) sendStreamFrame(frame: &H2Frame): H2ProtocolFrameResult ``` Apply a locally emitted frame transactionally. Invalid stream transitions and connection sequencing errors commit neither side of the state machine. **Returns:** `H2ProtocolFrameResult` ### H2ProtocolState.recvConnectionFrame ```vex export fn (self: &H2ProtocolState!) recvConnectionFrame(frame: &H2Frame): H2ConnectionResult ``` **Returns:** `H2ConnectionResult` ### H2ProtocolState.sendConnectionFrame ```vex export fn (self: &H2ProtocolState!) sendConnectionFrame(frame: &H2Frame): H2ConnectionResult ``` **Returns:** `H2ConnectionResult` ### H2ProtocolState.recvSettingsFrame ```vex export fn (self: &H2ProtocolState!) recvSettingsFrame(frame: &H2Frame, payload: str): H2ProtocolFrameResult ``` Receive and apply a peer SETTINGS frame. Non-ACK values become effective before `SettingsAckRequired` is returned. ACK frames commit the oldest queued local SETTINGS snapshot in FIFO order. **Returns:** `H2ProtocolFrameResult` ### H2ProtocolState.sendSettingsFrame ```vex export fn (self: &H2ProtocolState!) sendSettingsFrame(frame: &H2Frame, payload: str): H2ProtocolFrameResult ``` Record a locally emitted SETTINGS frame. A non-ACK payload is merged onto the newest queued snapshot and retained until the corresponding peer ACK; local decoder/receive policy never changes early. **Returns:** `H2ProtocolFrameResult` ### H2ProtocolState.recvHeaderFrame ```vex export fn (self: &H2ProtocolState!) recvHeaderFrame(frame: &H2Frame, payload: str): H2HeaderFrameResult ``` Process one received HEADERS/PUSH_PROMISE/CONTINUATION frame and its exact payload under connection-owned HPACK lifetime. Fragment memory is bounded; decoding happens only after END_HEADERS. Stream errors are reported only after the complete block has advanced compression state. **Returns:** `H2HeaderFrameResult` ### H2ProtocolState.applyPeerInitialWindowSize ```vex export fn (self: &H2ProtocolState!) applyPeerInitialWindowSize(newSize: u32): bool ``` **Returns:** `bool` ### H2ProtocolState.applyLocalInitialWindowSize ```vex export fn (self: &H2ProtocolState!) applyLocalInitialWindowSize(newSize: u32): bool ``` **Returns:** `bool` ### H2ProtocolState.recvGoAwayFrame ```vex export fn (self: &H2ProtocolState!) recvGoAwayFrame(frame: &H2Frame, payload: str): H2ReceiveGoAwayResult ``` Consume one complete peer GOAWAY transaction. Payload/debug bytes remain borrowed from the exact frame payload; sequencing, non-increasing boundary and retry-safe local stream retirement commit together. **Returns:** `H2ReceiveGoAwayResult` ### H2ProtocolState.recvFrame ```vex export fn (self: &H2ProtocolState!) recvFrame(frame: &H2Frame, payload: str): H2InboundFrameResult ``` Consume one complete frame returned by `parseH2FrameLimited`. This is the transport-facing receive boundary: every known frame class reaches its dedicated transactional owner, while unknown extensions are sequenced and ignored without accidentally admitting or retiring a stream. **Returns:** `H2InboundFrameResult` ### H2ProtocolState.recvBytes ```vex export fn (self: &H2ProtocolState!) recvBytes(input: str): H2IngressResult ``` Parse and dispatch at most one frame from caller-retained transport bytes. Valid frames remain zero-copy: `NeedMore(0, n)` asks the caller to retain the prefix, and `Dispatched(consumed, result)` permits compaction only after borrowed result views have been handled. Stream-invalid frame payloads are discarded incrementally through `ingress`, bounding hostile-frame memory. **Returns:** `H2IngressResult` ### H2ProtocolState.sendGoAwayFrame ```vex export fn (self: &H2ProtocolState!) sendGoAwayFrame(lastStreamId: u32, errorCode: u32, debugData: str, out: &str!): H2SendGoAwayResult ``` Encode and publish one local GOAWAY transaction. The output must reserve `17 + debugData.len()` bytes first; failed capacity/sequencing/boundary validation leaves connection, streams and scheduler unchanged. **Returns:** `H2SendGoAwayResult` ### H2ProtocolState.localStreamMayHaveBeenProcessed ```vex export fn (self: &H2ProtocolState) localStreamMayHaveBeenProcessed(streamId: u32): bool ``` **Returns:** `bool` ### H2ProtocolState.abort ```vex export fn (self: &H2ProtocolState!) abort(errorCode: u32): H2ProtocolAbortResult ``` Terminate the entire protocol owner without freeing its reusable storage. Every scheduler lease and active/idle priority record is revoked exactly once; transport/task owners can then propagate `errorCode` to their waiters. **Returns:** `H2ProtocolAbortResult` ### HeaderEntry.empty ```vex export fn HeaderEntry.empty(): HeaderEntry ``` **Returns:** `HeaderEntry` ### ParserHeaders.new ```vex export fn ParserHeaders.new(): ParserHeaders ``` Create an empty header collection. **Returns:** `ParserHeaders` ### ParserHeaders.add ```vex export fn (self: &ParserHeaders!) add(name: str, value: str): bool ``` Add a header entry. Returns false if at capacity. **Returns:** `bool` ### ParserHeaders.get ```vex export fn (self: &ParserHeaders) get(name: str): str ``` Get header value by name (case-insensitive). Returns first matching value, or empty str if not found. **Returns:** `str` ### ParserHeaders.has ```vex export fn (self: &ParserHeaders) has(name: str): bool ``` Check if a header exists (case-insensitive). **Returns:** `bool` ### ParserHeaders.messageFraming ```vex export fn (self: &ParserHeaders) messageFraming(): MessageFraming ``` Derive the unique HTTP body framing from the complete header collection. This HTTP/1 layer accepts only the transfer coding it can decode itself: one `chunked` field. Multiple Content-Length or Transfer-Encoding fields, a comma-list, unsupported transfer coding, or both framing mechanisms are rejected rather than silently choosing a different boundary than a proxy. **Returns:** `MessageFraming` ### ParserHeaders.contentLength ```vex export fn (self: &ParserHeaders) contentLength(): i64 ``` Get Content-Length value, or -1 when no unambiguous content length exists. New framing-sensitive code should use `messageFraming()` directly. **Returns:** `i64` ### ParserHeaders.isChunked ```vex export fn (self: &ParserHeaders) isChunked(): bool ``` True only when the complete message framing is exactly chunked. **Returns:** `bool` ### ParserHeaders.isConnectionClose ```vex export fn (self: &ParserHeaders) isConnectionClose(): bool ``` Check whether any Connection token says `close`. **Returns:** `bool` ### ParserHeaders.isUpgrade ```vex export fn (self: &ParserHeaders) isUpgrade(): bool ``` Check whether any Connection token says `upgrade`. **Returns:** `bool` ### ParserHeaders.len ```vex export fn (self: &ParserHeaders) len(): usize ``` Get number of stored headers. **Returns:** `usize` ### ParserHeaders.clear ```vex export fn (self: &ParserHeaders!) clear() ``` Reset the header collection for reuse. **Receiver:** `self: &ParserHeaders!` *(mutable reference)* ### ParserHeaders.at ```vex export fn (self: &ParserHeaders) at(index: usize): HeaderEntry ``` Get header entry by index. **Returns:** `HeaderEntry` ### DynamicTable.new ```vex export fn DynamicTable.new(maxSize: usize): DynamicTable ``` **Returns:** `DynamicTable` ### DynamicTable.add ```vex export fn (self: &DynamicTable!) add(name: string, value: string) ``` Add entry to dynamic table (front = newest). ### DynamicTable.lookup ```vex export fn (self: &DynamicTable) lookup(index: usize): (string, string) ``` Look up by absolute index (1-based, 1..61 = static, 62+ = dynamic). **Returns:** `(string, string)` ### DynamicTable.setMaxSize ```vex export fn (self: &DynamicTable!) setMaxSize(newMax: usize): bool ``` Update max size (from SETTINGS_HEADER_TABLE_SIZE). **Returns:** `bool` ### DynamicTable.setAllowedMaxSize ```vex export fn (self: &DynamicTable!) setAllowedMaxSize(newMaximum: usize) ``` Apply an acknowledged SETTINGS_HEADER_TABLE_SIZE to the decoder. A reduction below the encoder's currently declared table size does not evict immediately: the peer must begin its next field block with the HPACK size update that performs the synchronized eviction. ### DynamicTable.requiresSizeUpdate ```vex export fn (self: &DynamicTable) requiresSizeUpdate(): bool ``` **Returns:** `bool` ### HpackHeader.new ```vex export fn HpackHeader.new(name: str, value: str): HpackHeader ``` **Returns:** `HpackHeader` ### HpackHeader.withIndexing ```vex export fn HpackHeader.withIndexing(name: str, value: str, indexing: HpackIndexing): HpackHeader ``` **Returns:** `HpackHeader` ### HpackHeader.sensitive ```vex export fn HpackHeader.sensitive(name: str, value: str): HpackHeader ``` **Returns:** `HpackHeader` ### HpackDecodeLimits.defaults ```vex export fn HpackDecodeLimits.defaults(): HpackDecodeLimits ``` **Returns:** `HpackDecodeLimits` ### HpackDecodeLimits.isValid ```vex export fn (self: &HpackDecodeLimits) isValid(): bool ``` **Returns:** `bool` ### HpackEncodeLimits.defaults ```vex export fn HpackEncodeLimits.defaults(): HpackEncodeLimits ``` **Returns:** `HpackEncodeLimits` ### HpackEncodeLimits.isValid ```vex export fn (self: &HpackEncodeLimits) isValid(): bool ``` **Returns:** `bool` ### HpackEncoder.new ```vex export fn HpackEncoder.new(maximumTableBytes: usize): HpackEncoder ``` **Returns:** `HpackEncoder` ### HpackEncoder.dynamicTableBytes ```vex export fn (self: &HpackEncoder) dynamicTableBytes(): usize ``` **Returns:** `usize` ### HpackEncoder.maximumTableBytes ```vex export fn (self: &HpackEncoder) maximumTableBytes(): usize ``` **Returns:** `usize` ### HpackEncoder.hasPendingSizeUpdate ```vex export fn (self: &HpackEncoder) hasPendingSizeUpdate(): bool ``` **Returns:** `bool` ### HpackEncoder.setMaximumTableBytes ```vex export fn (self: &HpackEncoder!) setMaximumTableBytes(maximum: usize) ``` Apply the peer's effective SETTINGS_HEADER_TABLE_SIZE. No wire state is consumed until a field block is successfully encoded. ### MultipartLimits.defaults ```vex export fn MultipartLimits.defaults(): MultipartLimits ``` **Returns:** `MultipartLimits` ### Method.asStr ```vex export fn (self: &Method) asStr(): str ``` Method to string. **Returns:** `str` ### HttpVersion.asStr ```vex export fn (self: &HttpVersion) asStr(): str ``` **Returns:** `str` ### ParserRequest.empty ```vex export fn ParserRequest.empty(): ParserRequest ``` Create an empty request. **Returns:** `ParserRequest` ### ParserRequest.path ```vex export fn (self: &ParserRequest) path(): str ``` Get the URI path component (before '?'). **Returns:** `str` ### ParserRequest.query ```vex export fn (self: &ParserRequest) query(): str ``` Get query string (after '?'), or empty. **Returns:** `str` ### ParserRequest.host ```vex export fn (self: &ParserRequest) host(): str ``` Get Host header value. **Returns:** `str` ### ParserRequest.contentLength ```vex export fn (self: &ParserRequest) contentLength(): i64 ``` Get Content-Length or -1. **Returns:** `i64` ### ParserRequest.isChunked ```vex export fn (self: &ParserRequest) isChunked(): bool ``` Is this a chunked transfer? **Returns:** `bool` ### ParserRequest.isWebSocketUpgrade ```vex export fn (self: &ParserRequest) isWebSocketUpgrade(): bool ``` Is this a WebSocket upgrade? **Returns:** `bool` ### ParserRequest.hasBody ```vex export fn (self: &ParserRequest) hasBody(): bool ``` Does the request expect a body? **Returns:** `bool` ### Response.empty ```vex export fn Response.empty(): Response ``` Create an empty response. **Returns:** `Response` ### Response.isInformational ```vex export fn (self: &Response) isInformational(): bool ``` True if status is 1xx (informational). **Returns:** `bool` ### Response.isSuccess ```vex export fn (self: &Response) isSuccess(): bool ``` True if status is 2xx (success). **Returns:** `bool` ### Response.isRedirect ```vex export fn (self: &Response) isRedirect(): bool ``` True if status is 3xx (redirect). **Returns:** `bool` ### Response.isClientError ```vex export fn (self: &Response) isClientError(): bool ``` True if status is 4xx (client error). **Returns:** `bool` ### Response.isServerError ```vex export fn (self: &Response) isServerError(): bool ``` True if status is 5xx (server error). **Returns:** `bool` ### Response.contentLength ```vex export fn (self: &Response) contentLength(): i64 ``` Get Content-Length or -1. **Returns:** `i64` ### Response.isChunked ```vex export fn (self: &Response) isChunked(): bool ``` Is chunked transfer? **Returns:** `bool` ### Response.isConnectionClose ```vex export fn (self: &Response) isConnectionClose(): bool ``` Is Connection: close? **Returns:** `bool` ### Response.location ```vex export fn (self: &Response) location(): str ``` Get Location header (for redirects). **Returns:** `str` ### Response.contentType ```vex export fn (self: &Response) contentType(): str ``` Get Content-Type header. **Returns:** `str` ### Scanner.new ```vex export fn Scanner.new(input: str): Scanner ``` Create a scanner over the given input. **Returns:** `Scanner` ### Scanner.at ```vex export fn Scanner.at(input: str, offset: usize): Scanner ``` Create a scanner starting at a given offset. **Returns:** `Scanner` ### Scanner.remaining ```vex export fn (self: &Scanner) remaining(): usize ``` Bytes remaining from current position. **Returns:** `usize` ### Scanner.isEof ```vex export fn (self: &Scanner) isEof(): bool ``` True if no bytes remain. **Returns:** `bool` ### Scanner.position ```vex export fn (self: &Scanner) position(): usize ``` Current absolute cursor position. **Returns:** `usize` ### Scanner.setPosition ```vex export fn (self: &Scanner!) setPosition(newPos: usize) ``` Set absolute cursor position (clamped to input length). ### Scanner.peek ```vex export fn (self: &Scanner) peek(): u8 ``` Peek at byte at current position (0 if EOF). **Returns:** `u8` ### Scanner.peekAt ```vex export fn (self: &Scanner) peekAt(offset: usize): u8 ``` Peek at byte at offset from current position. **Returns:** `u8` ### Scanner.advance ```vex export fn (self: &Scanner!) advance(n: usize) ``` Advance position by n bytes. ### Scanner.rest ```vex export fn (self: &Scanner) rest(): str ``` Get a str slice from current position to end. **Returns:** `str` ### Scanner.slice ```vex export fn (self: &Scanner) slice(start: usize, end: usize): str ``` Get a str slice [start..end) relative to buffer start. **Returns:** `str` ### Scanner.findByte ```vex export fn (self: &Scanner) findByte(byt: u8): usize ``` Find first occurrence of `byte` from current position. Returns absolute index into buffer, or `Limits.usizeMax` if not found. Uses SIMD comparison for buffers >= 16 bytes, scalar for short. **Returns:** `usize` ### Scanner.findCRLF ```vex export fn (self: &Scanner) findCRLF(): usize ``` Find \r\n (CRLF) from current position. Returns absolute index of \r, or `Limits.usizeMax` if not found. SIMD: scan for \r, then verify \n follows. **Returns:** `usize` ### Scanner.findDoubleCRLF ```vex export fn (self: &Scanner) findDoubleCRLF(): usize ``` Find \r\n\r\n (double CRLF — end of headers). Returns absolute index of first \r, or `Limits.usizeMax` if not found. Strategy: SIMD scan for \r, then verify \n\r\n pattern. **Returns:** `usize` ### Scanner.readUntil ```vex export fn (self: &Scanner!) readUntil(delim: u8): str ``` Read bytes until `delim` is found. Returns slice [pos..delim_pos). Advances past the delimiter. Returns empty str and does NOT advance if delimiter not found. **Returns:** `str` ### Scanner.readLine ```vex export fn (self: &Scanner!) readLine(): str ``` Read bytes until CRLF. Returns slice [pos..cr_pos). Advances past the \r\n. Returns empty str if CRLF not found (incomplete). **Returns:** `str` ### Scanner.expect ```vex export fn (self: &Scanner!) expect(byt: u8): bool ``` Expect and consume a specific byte. Returns true if matched. **Returns:** `bool` ### Scanner.skipOWS ```vex export fn (self: &Scanner!) skipOWS() ``` Skip optional whitespace (SP and HTAB). **Receiver:** `self: &Scanner!` *(mutable reference)* ### Scanner.skipSP ```vex export fn (self: &Scanner!) skipSP(): bool ``` Skip exactly one SP (space). Returns true if consumed. **Returns:** `bool` ### Scanner.readN ```vex export fn (self: &Scanner!) readN(n: usize): str ``` Read a fixed number of bytes as a str slice. **Returns:** `str` ### Scanner.startsWith ```vex export fn (self: &Scanner) startsWith(pattern: str): bool ``` Check if the next bytes match a pattern (case-sensitive). Does NOT advance the position. **Returns:** `bool` ### StreamState.name ```vex export fn (self: &StreamState) name(): str ``` Human-readable state name. **Returns:** `str` ### H2Stream.new ```vex export fn H2Stream.new(id: u32, initialWindow: i32): H2Stream ``` Create a new stream in idle state. **Returns:** `H2Stream` ### H2Stream.recvFrame ```vex export fn (self: &H2Stream!) recvFrame(frame: &H2Frame): StreamError ``` Process a received frame and transition state. Returns StreamError indicating if the transition is valid. **Returns:** `StreamError` ### H2Stream.sendFrame ```vex export fn (self: &H2Stream!) sendFrame(frame: &H2Frame): StreamError ``` Process a sent frame and transition state. **Returns:** `StreamError` ### H2Stream.setLegacyPriority ```vex export fn (self: &H2Stream!) setLegacyPriority(dep: u32, weight: u16, exclusive: bool): bool ``` Retain deprecated RFC 7540 dependency metadata for interoperability fallback. New scheduling uses RFC 9218 `H2PriorityScheduler`. **Returns:** `bool` ### H2Stream.isClosed ```vex export fn (self: &H2Stream) isClosed(): bool ``` Is the stream in a terminal state? **Returns:** `bool` ### H2Stream.canSend ```vex export fn (self: &H2Stream) canSend(): bool ``` Can this stream send DATA/HEADERS? **Returns:** `bool` ### H2Stream.canRecv ```vex export fn (self: &H2Stream) canRecv(): bool ``` Can this stream receive DATA/HEADERS? **Returns:** `bool` ### StreamMap.new ```vex export fn StreamMap.new(maxStreams: u32): StreamMap ``` Create a stream map with RFC default send/receive windows. Negotiated SETTINGS are applied transactionally through the directional methods below. **Returns:** `StreamMap` ### StreamMap.find ```vex export fn (self: &StreamMap) find(id: u32): i32 ``` Find a materialized stream without changing connection state. **Returns:** `i32` ### StreamMap.getOrCreate ```vex export fn (self: &StreamMap!) getOrCreate(id: u32): i32 ``` Get or create a stream by ID. **Returns:** `i32` ### StreamMap.residentCount ```vex export fn (self: &StreamMap) residentCount(): usize ``` Number of resident slots. This never exceeds the configured concurrent bound even after arbitrarily many sequential streams. **Returns:** `usize` ### StreamMap.applyPeerInitialWindowSize ```vex export fn (self: &StreamMap!) applyPeerInitialWindowSize(newSize: u32): bool ``` Apply peer SETTINGS_INITIAL_WINDOW_SIZE to every local send window. A decrease may legally make an existing stream window negative. **Returns:** `bool` ### StreamMap.applyLocalInitialWindowSize ```vex export fn (self: &StreamMap!) applyLocalInitialWindowSize(newSize: u32): bool ``` Apply a locally advertised SETTINGS_INITIAL_WINDOW_SIZE to receive windows. **Returns:** `bool` ### StreamMap.get ```vex export fn (self: &StreamMap) get(index: usize): Option ``` Get stream by index. **Returns:** `Option` ### StreamMap.activeCount ```vex export fn (self: &StreamMap) activeCount(): u32 ``` Count active (non-closed) streams. **Returns:** `u32` ### WsFrame.isControl ```vex export fn (self: &WsFrame) isControl(): bool ``` Is this a control frame? (opcodes 0x8-0xF) **Returns:** `bool` ### WsFrame.isText ```vex export fn (self: &WsFrame) isText(): bool ``` Is this a text frame? **Returns:** `bool` ### WsFrame.isBinary ```vex export fn (self: &WsFrame) isBinary(): bool ``` Is this a binary frame? **Returns:** `bool` ### WsFrame.isClose ```vex export fn (self: &WsFrame) isClose(): bool ``` Is this a close frame? **Returns:** `bool` ### WsFrame.isPing ```vex export fn (self: &WsFrame) isPing(): bool ``` Is this a ping frame? **Returns:** `bool` ### WsFrame.isPong ```vex export fn (self: &WsFrame) isPong(): bool ``` Is this a pong frame? **Returns:** `bool` ### WsMessage.new ```vex export fn WsMessage.new(): WsMessage ``` **Returns:** `WsMessage` ### WsMessage.feedFrame ```vex export fn (self: &WsMessage!) feedFrame(frame: &WsFrame, payload: str): bool ``` Feed a parsed frame into the message assembler. For single-frame messages, returns immediately. For fragmented messages, accumulates until FIN. **Returns:** `bool` ### WsMessage.reset ```vex export fn (self: &WsMessage!) reset() ``` Reset for next message. **Receiver:** `self: &WsMessage!` *(mutable reference)* ### Request.invalid ```vex export fn Request.invalid(): Request ``` Empty/invalid request sentinel. **Returns:** `Request` ### Request.header ```vex export fn (self: &Request) header(name: str): str ``` Get a header value by name (case-insensitive). Returns empty str if absent. **Returns:** `str` ### Request.hasHeader ```vex export fn (self: &Request) hasHeader(name: str): bool ``` Check if a header exists. **Returns:** `bool` ### Request.isMethod ```vex export fn (self: &Request) isMethod(m: str): bool ``` Check if the request method matches (case-sensitive). **Returns:** `bool` ### Request.hasBody ```vex export fn (self: &Request) hasBody(): bool ``` Check if the request has a body. **Returns:** `bool` ### Request.contentType ```vex export fn (self: &Request) contentType(): str ``` Get Content-Type header. **Returns:** `str` ### Request.isJSON ```vex export fn (self: &Request) isJSON(): bool ``` Check if request is JSON. **Returns:** `bool` ### Response.new ```vex export fn Response.new(): Response ``` Create a new response with default 200 OK and keep-alive. **Returns:** `Response` ### Response.takeStreamHead ```vex export fn! (self: &Response!) takeStreamHead(): ResponseStreamHead ``` Move streaming response metadata exactly once. Header vectors retain their allocations and are not cloned across the task/transport boundary. **Returns:** `ResponseStreamHead` ### Response.reset ```vex export fn (self: &Response!) reset() ``` Reset response for reuse (clears headers, keeps capacity). **Receiver:** `self: &Response!` *(mutable reference)* ### Response.status ```vex export fn (self: &Response!) status(code: i32): &Response! ``` **Returns:** `&Response!` ### Response.header ```vex export fn (self: &Response!) header(name: string, value: string): &Response! ``` **Returns:** `&Response!` ### Response.contentType ```vex export fn (self: &Response!) contentType(ct: string): &Response! ``` **Returns:** `&Response!` ### Response.setBody ```vex export fn (self: &Response!) setBody(b: string): &Response! ``` **Returns:** `&Response!` ### Response.sendString ```vex export fn (self: &Response!) sendString(fd: i64, text: string) ``` ### Response.sendJSON ```vex export fn (self: &Response!) sendJSON(fd: i64, json: string) ``` ### Response.sendHTML ```vex export fn (self: &Response!) sendHTML(fd: i64, html: string) ``` ### Response.send ```vex export fn (self: &Response!) send(fd: i64) ``` ### Response.sendEmpty ```vex export fn (self: &Response!) sendEmpty(fd: i64) ``` ### Response.appendEncodedTo ```vex export fn (self: &Response) appendEncodedTo(out: &StringBuilder!) ``` Append the buffered Fiber response into caller-owned reusable storage. `sendString`/`sendJSON`/`sendHTML` preserve their implicit content type; a plain `send` uses only explicitly set headers. The method does not reset `out`, so a server can coalesce complete HTTP responses before one socket write. ### Response.appendStreamHeadersTo ```vex export fn (self: &Response) appendStreamHeadersTo(out: &StringBuilder!, bodyLength: u64): bool ``` Append only the HTTP/1 headers for a body that Fiber will stream directly after its ordered response queue drains. The body length is mandatory: HTTP/1 keep-alive cannot safely infer a streamed body boundary. **Returns:** `bool` ### Response.appendChunkedHeadersTo ```vex export fn (self: &Response) appendChunkedHeadersTo(out: &StringBuilder!): bool ``` Append headers for an unknown-length HTTP/1 response body. A writable dynamic body uses chunked transfer coding. For HEAD, the representation length is unknown and must not be invented as zero, so the response deliberately omits both framing fields and returns false. For a status that forbids content, the ordinary zero-length framing is retained. **Returns:** `bool` ### Response.appendChunkTo ```vex export fn (self: &Response) appendChunkTo(out: &StringBuilder!, data: str) ``` ### Response.appendChunkTerminatorTo ```vex export fn (self: &Response) appendChunkTerminatorTo(out: &StringBuilder!) ``` ### Response.encode ```vex export fn (self: &Response!) encode(): str ``` Serialize into response-owned reusable storage and borrow the encoded bytes. The returned view remains valid until this Response is mutated or reset. **Returns:** `str` ### Server.new ```vex export fn Server.new(host: string, port: i32): Server ``` Create a direct callback server with Fiber's production defaults. Binding, worker creation and socket ownership begin in `serve`. **Returns:** `Server` ### Server.withConfig ```vex export fn Server.withConfig(host: string, port: i32, config: AppConfig): Server ``` Create a direct callback server with one coherent Fiber resource policy. **Returns:** `Server` ### Server.serve ```vex export fn (self: Server) serve(handler: RequestHandler) ``` Serve requests through the canonical Fiber HTTP/1 state machine. Use `App` directly when routes or middleware are required. This callback form remains useful for compact protocol endpoints without maintaining a separate server implementation. ### Server.serveWithContext ```vex export fn (self: Server) serveWithContext(lifetime: Context, handler: RequestHandler) ``` Context-cancellable direct callback server. Cancellation has the same descriptor cleanup and worker-join semantics as `App.listenWithContext`. ### WsSession.new ```vex export fn WsSession.new(fd: i64): WsSession ``` Create a session for an already non-blocking, already-upgraded socket. `fd < 0` produces a fail-closed inert session useful for tests/adapters. **Returns:** `WsSession` ### WsSession.withId ```vex export fn WsSession.withId(fd: i64, id: u64): WsSession ``` Create a session with a stable application-visible identity. Low-level adapters use zero; Fiber assigns a nonzero process-local id at handoff. **Returns:** `WsSession` ### WsSession.withIdAndProtocol ```vex export fn WsSession.withIdAndProtocol(fd: i64, id: u64, protocol: string): WsSession ``` Create an upgraded session with the one route-selected subprotocol. The value is immutable after construction and is exposed to lifecycle/message callbacks without consulting HTTP headers again. **Returns:** `WsSession` ### WsSession.isOpen ```vex export fn (self: &WsSession) isOpen(): bool ``` **Returns:** `bool` ### WsSession.id ```vex export fn (self: &WsSession) id(): u64 ``` **Returns:** `u64` ### WsSession.protocol ```vex export fn (self: &WsSession) protocol(): str ``` The negotiated RFC 6455 subprotocol, or empty when none was selected. **Returns:** `str` ### WsSession.pendingInput ```vex export fn (self: &WsSession) pendingInput(): usize ``` **Returns:** `usize` ### WsSession.pendingOutput ```vex export fn (self: &WsSession) pendingOutput(): usize ``` **Returns:** `usize` ### WsSession.wantsWrite ```vex export fn (self: &WsSession) wantsWrite(): bool ``` **Returns:** `bool` ### WsSession.shouldCloseAfterFlush ```vex export fn (self: &WsSession) shouldCloseAfterFlush(): bool ``` A close response may be queued behind earlier application output. The worker must keep writable interest until it drains, then retire the fd. **Returns:** `bool` ### WsSession.stageInitialInput ```vex export fn (self: &WsSession!) stageInitialInput(data: Ptr, len: usize): bool ``` Copy HTTP's already-received post-upgrade suffix into the session. This is the handoff seam that preserves a WebSocket frame coalesced with the HTTP request; it is all-or-nothing under the same input bound as socket reads. **Returns:** `bool` ### WsSession.readFromTransport ```vex export fn (self: &WsSession!) readFromTransport(): i64 ``` Fill the common bounded input queue after an EVT_READ notification. Positive = bytes read, zero = peer EOF, negative = native error/EAGAIN. **Returns:** `i64` ### WsSession.flushTransport ```vex export fn (self: &WsSession!) flushTransport(): i64 ``` Drain queued output after an EVT_WRITE notification. A negative EAGAIN is intentionally propagated so the worker can retain writable interest; non-retryable errors are owned by the worker's close policy. **Returns:** `i64` ### WsSession.sendText ```vex export fn (self: &WsSession!) sendText(text: str): bool ``` **Returns:** `bool` ### WsSession.sendBinary ```vex export fn (self: &WsSession!) sendBinary(data: Ptr, len: usize): bool ``` **Returns:** `bool` ### WsSession.sendPing ```vex export fn (self: &WsSession!) sendPing(data: str): bool ``` **Returns:** `bool` ### WsSession.sendPong ```vex export fn (self: &WsSession!) sendPong(data: Ptr, len: usize): bool ``` **Returns:** `bool` ### WsSession.closeWith ```vex export fn (self: &WsSession!) closeWith(data: Ptr, len: usize): bool ``` Queue a close payload once. The session remains drainable so a valid close reply can reach the peer before the Fiber worker retires the descriptor. **Returns:** `bool` ### WsSession.close ```vex export fn (self: &WsSession!) close(): bool ``` **Returns:** `bool` ### WsSession.advanceFrame ```vex export fn (self: &WsSession!) advanceFrame(message: &WsMessage!): i32 ``` **Returns:** `i32` ### WsSession.nextMessage ```vex export fn (self: &WsSession!) nextMessage(): Option ``` Consume buffered frames until an application-visible message is available. This compatibility helper intentionally preserves the simple polling API; Fiber itself uses `advanceFrame` so its worker turn has a finite budget. **Returns:** `Option` ### WsMessage.isText ```vex export fn (self: &WsMessage) isText(): bool ``` Check if this is a text message. **Returns:** `bool` ### WsMessage.isBinary ```vex export fn (self: &WsMessage) isBinary(): bool ``` Check if this is a binary message. **Returns:** `bool` ### WsMessage.isClose ```vex export fn (self: &WsMessage) isClose(): bool ``` Check if this is a close frame. **Returns:** `bool` ### WsMessage.isPing ```vex export fn (self: &WsMessage) isPing(): bool ``` Check if this is a ping frame. **Returns:** `bool` ### WsMessage.text ```vex export fn (self: &WsMessage) text(): string ``` Return an independent owned copy of the text content (for text messages). Use `message.data.asStr()` for a borrowed, allocation-free view. **Returns:** `string` ### WsConn.new ```vex export fn WsConn.new(fd: i64): WsConn ``` Create a WebSocket connection from an already-upgraded socket fd. **Returns:** `WsConn` ### WsConn.upgrade ```vex export fn WsConn.upgrade(fd: i64, req: &Request): WsConn ``` Perform the WebSocket upgrade handshake. Sends the HTTP 101 Switching Protocols response. The request must have the WebSocket upgrade headers. **Returns:** `WsConn` ### WsConn.sendText ```vex export fn (self: &WsConn!) sendText(text: string) ``` Send a text message. ### WsConn.sendBinary ```vex export fn (self: &WsConn!) sendBinary(data: Ptr, len: u64) ``` Send a binary message. ### WsConn.sendPing ```vex export fn (self: &WsConn!) sendPing() ``` Send a ping frame. **Receiver:** `self: &WsConn!` *(mutable reference)* ### WsConn.sendPong ```vex export fn (self: &WsConn!) sendPong() ``` Send a pong frame (response to ping). **Receiver:** `self: &WsConn!` *(mutable reference)* ### WsConn.close ```vex export fn (self: &WsConn!) close() ``` Send a close frame and mark connection as closed. **Receiver:** `self: &WsConn!` *(mutable reference)* ### WsConn.readMessage ```vex export fn (self: &WsConn!) readMessage(): Option ``` Read the next complete logical WebSocket message. TCP read boundaries are unrelated to RFC 6455 frame boundaries: this method retains suffix bytes, waits for a complete frame, unmasks client payloads, responds to pings with the same payload, and joins continuation frames. `None` means EOF, transport failure, malformed client input, or the bounded message limit; each of those permanently closes this descriptor helper. **Returns:** `Option` ### WsConn.messageLoop ```vex export fn (self: &WsConn!) messageLoop(handler: fn (msg: WsMessage)) ``` Run a message loop. Calls the handler for each received message. Blocks until the connection closes. --- Source: https://vex-lang.org/docs/std/http/server.md # Core Server (`http/server`) `http/server` is the compact direct-callback entry point. It delegates to the same `http/fiber::App` HTTP/1 state machine used by routed services, so there is no second parser, accept loop, or deadline policy to drift from production. Use `Server` for a single direct request/response callback. Use `App` directly when a service needs routes or middleware. Both paths have bounded incremental bodies, pipelined suffixes, deadlines, connection admission, worker lifecycle and response coalescing. ## Minimal Hello World ```vex import { Server, Request, Response } from "http"; fn main(): i32 { let! srv = Server.new("0.0.0.0", 8080); srv.serve(handler); return 0; } fn handler(req: &Request, res: &Response!) { res.sendString(req.fd, "Hello, Vex!"); } ``` --- ## Direct callback contract The request is valid for the callback only. `Response` is encoded into connection-owned reusable storage and drained after the callback returns. A handler may still use the familiar `res.sendString(req.fd, ...)` form; in this mode it is buffered rather than performing an independent socket write. For cancellation-aware serving, use `server.serveWithContext(context, handler)`. For direct raw-socket parsing experiments, `parseRequest(fd)` remains an explicit low-level function, not a competing server runtime. ### `Request` Struct | Field | Type | Description | |-------|------|-------------| | `method` | `str` | `"GET"`, `"POST"`, `"PUT"`, `"DELETE"`, `"PATCH"`, `"HEAD"`, `"OPTIONS"` | | `path` | `str` | URL path without query string (e.g. `/api/users`) | | `query` | `str` | Raw query string (e.g. `page=1&sort=name`) | | `version` | `str` | `"HTTP/1.1"` or `"HTTP/1.0"` | | `headers` | `Headers` | Parsed header collection (case-insensitive) | | `body` | `str` | Request body (for `POST`/`PUT`/`PATCH`) | | `fd` | `i64` | Native-width socket handle | | `streamId` | `i32` | Reserved stream identifier; the direct HTTP/1 `Server` facade uses `0` (Fiber HTTP/2 routes use `Ctx`) | | `valid` | `bool` | `true` if parsing succeeded | | `contentLength` | `i64` | Parsed `Content-Length` value (-1 if absent) | | `keepAlive` | `bool` | Parser-selected reuse policy from HTTP version and all `Connection` tokens; `close` wins | ### Request Accessor Methods ```vex req.header("Authorization") // Get header value (case-insensitive) req.hasHeader("X-Custom") // Check if header exists req.isMethod("POST") // Match method (case-sensitive) req.hasBody() // true if body.len() > 0 req.contentType() // Get Content-Type header value req.isJSON() // true if Content-Type == "application/json" ``` ## Headers (`Headers` Collection) Headers are stored as parallel `Vec<string>` arrays (names + values) with byte-level case-insensitive comparison. No `Map` overhead, no hash computation—just linear scan optimized for the typical 5–15 header count. | Method | Description | |--------|-------------| | `Headers.new()` | Create empty collection | | `hdrs.get(name): string` | Get value (case-insensitive), returns `""` if not found | | `hdrs.has(name): bool` | Check existence | | `hdrs.set(name, value)` | Set/replace (removes existing, then appends) | | `hdrs.add(name, value)` | Append (allows duplicates, e.g. `Set-Cookie`) | | `hdrs.del(name)` | Remove all matching (in-place, zero-alloc) | | `hdrs.clear()` | Remove all headers | | `hdrs.shrinkToFit()` | Release excess capacity | | `hdrs.len(): i32` | Count of headers | --- ## Cookies The `cookie.vx` module parses request-cookie pairs and serializes configured `Set-Cookie` attributes. It is not a browser cookie jar or a session store. Cookie values are application data; the serializer does not create, encrypt or sign an authentication token. ### Building Cookies ```vex import { Cookie } from "http"; // Simple session cookie let session = Cookie.new("session_id", "abc123"); // → "session_id=abc123; Path=/; HttpOnly; SameSite=Lax" // Persistent cookie (expires in 1 hour) let remember = Cookie.persistent("remember", "yes", 3600); // → "remember=yes; Max-Age=3600; Path=/; HttpOnly; SameSite=Lax" // Deletion cookie let logout = Cookie.delete("session_id"); // → "session_id=; Max-Age=0; Path=/" // Set on response res.header("Set-Cookie", session.toString()); ``` Use an application-generated opaque session value, not the literal `abc123`. For an HTTPS deployment, set `secure = true` explicitly; its default is false. The cookie settings do not enable TLS in the server. Deletion must use the same path/domain scope as the original cookie. Keep cookie names and attributes under application control; the serializer does not escape arbitrary values. ### Parsing Incoming Cookies ```vex import { parseCookies } from "http"; let pairs = parseCookies(req.header("Cookie")); // "session_id=abc123; theme=dark" // → [CookiePair{name:"session_id", value:"abc123"}, CookiePair{name:"theme", value:"dark"}] ``` ### Cookie Fields | Field | Type | Description | |-------|------|-------------| | `name` | `string` | Cookie name | | `value` | `string` | Cookie value | | `path` | `string` | Path attribute (default `"/"`) | | `domain` | `string` | Domain attribute (empty = current) | | `maxAge` | `i32` | Max-Age in seconds (-1 = session, 0 = delete) | | `secure` | `bool` | HTTPS only flag | | `httpOnly` | `bool` | No JS access flag | | `sameSite` | `string` | `"Strict"`, `"Lax"`, `"None"`, or `""` | --- ## Response Builder ```vex import { Response, respondText, respondJSON, respondError, respondRedirect } from "http"; // Builder pattern let! res = Response.new(); res.status(201) .header("X-Request-ID", "req-001") .contentType("application/json"); res.sendJSON(req.fd, "{\"created\": true}"); // One-liner convenience functions respondText(fd, "Hello!"); // 200 text/plain respondJSON(fd, "{\"ok\":true}"); // 200 application/json respondError(fd, 404, "Not Found"); // 404 with message respondRedirect(fd, "/login"); // 302 redirect ``` --- ## Internal Parser Architecture Underneath, request parsing is handled by a dedicated `parser/` subsystem: | File | Purpose | |------|---------| | `parser/scanner.vx` | Low-level byte scanner with position tracking | | `parser/request.vx` | HTTP/1.1 request line + header parser | | `parser/fiber_request.vx` | Optimized Fiber-compatible incremental parser | | `parser/headers.vx` | Header-specific parsing logic | | `parser/body.vx` | Body extraction with Content-Length validation | | `parser/chunked.vx` | Transfer-Encoding: chunked decoder | | `parser/response.vx` | Client-side response parser | | `parser/h2.vx` | HTTP/2 frame parser | | `parser/hpack.vx` | HPACK header compression (RFC 7541) | | `parser/huffman.vx` | Huffman coding tables for HPACK | | `parser/ws.vx` | WebSocket frame parser | | `parser/stream.vx` | Streaming parser for large payloads | --- Source: https://vex-lang.org/docs/std/http/ws.md # WebSocket (`http/ws`) Fiber exposes a bounded RFC 6455 server endpoint through `App.ws` and `Group.ws`; `App.wsWithLifecycle` and `Group.wsWithLifecycle` add optional open/close hooks. Every callback runs on the same worker that owns the connection. Message and open callbacks receive a temporary `&WsSession!`, not a raw descriptor or blocking socket API. ```vex import { App } from "http/fiber"; import { WsMessage, WsSession } from "http/ws"; fn echo(peer: &WsSession!, message: WsMessage) { if message.isText() { let _ = peer.sendText(message.data); } } let! app = App.new(); app.ws("/chat/:room", echo); app.listen("127.0.0.1", 3000); ``` `Group.ws` preserves its prefix and route middleware in the same way as ordinary Fiber routes. Middleware runs before the upgrade marker, so an auth middleware can reject the HTTP request normally; no WebSocket state is created in that case. Use lifecycle hooks when a route needs to initialize or release application state around a validated handoff: ```vex fn opened(peer: &WsSession!) { let _ = peer.sendText("ready"); } fn closed(sessionId: u64) { // The transport has been retired; release this connection's app state. let _ = sessionId; } app.wsWithLifecycle("/chat/:room", Some(opened), echo, Some(closed)); ``` `opened` runs after Fiber has accepted the request and queued `101 Switching Protocols`, before any complete WebSocket message is delivered. `closed` runs exactly once on the owner worker when Fiber retires the connection (peer close, protocol failure, I/O failure, deadline, or shutdown). It receives a unique opaque `u64`, never a recycled OS descriptor or session handle, so it remains observational after transport ownership has ended. ## Subprotocol selection `WsRouteOptions` compiles supported protocol tokens into frozen route metadata. Insertion order is server preference order; selection allocates only the one owned protocol string for an accepted connection, never a request-time vector. ```vex import { App, WsRouteOptions } from "http/fiber"; let! protocols = WsRouteOptions.new(); protocols .protocol("vex.chat.v2") .protocol("vex.chat.v1") .requireSubprotocol(); app.wsWithOptions("/chat/:room", protocols, echo); ``` Use `wsWithLifecycleOptions` when the same route also needs open/close hooks. `peer.protocol()` returns the selected token to both open and message callbacks, or an empty `str` when an optional policy selected none. Client and server lists are each limited to 32 tokens. Client tokens are case-sensitive and may span repeated `Sec-WebSocket-Protocol` fields, but empty elements, invalid HTTP tokens, duplicates, and trailing commas reject the handshake. Server-configured tokens are additionally limited to 255 bytes. The server emits exactly one client-offered token. By default a valid no-overlap request may upgrade without a protocol; `requireSubprotocol` instead rejects it before connection ownership changes. ## Ownership and backpressure `WsMessage.text()` returns an independent owned `string` without consuming the message. It copies the payload, so use `message.data.asStr()` when a borrowed, allocation-free view is sufficient. That view must not outlive its backing message data; the owned `text()` result may outlive the message. After a valid `101` handoff, the original HTTP/1 connection state changes in place to a worker-owned `WsSession`. The worker remains the sole fd owner: - prior pipelined HTTP responses drain before `101` is queued; - a frame coalesced with the upgrade request is retained as initial WebSocket input, never dropped or reparsed as HTTP; - reads and writes use the same bounded `net::Conn` input/output queues; - write readiness is armed only while queued output exists, so regular HTTP connections do not pay an `EVT_WRITE` wake-up cost; - at most 256 received frames are delivered from one connection in one worker turn; remaining already-buffered frames enter a worker-local FIFO, so a ping or tiny-message flood cannot monopolize a worker and Linux `EPOLLET` bytes are still drained into the bounded input queue; - text/binary replies use `sendText` / `sendBinary`; ping replies and close echoes are queued by the transport state rather than synchronously written; - each input and output queue is capped at 16 MiB. A slow peer becomes a visible `false` return from a send method, not unbounded worker RSS. Fiber reclaims its request-local arena before constructing the long-lived session. Only a fixed inline capability containing the validated 24-byte key and selected bounded protocol crosses that boundary; the `Request` and its borrowed header views never escape. The automated 2026-08-24 loopback test coalesces the opening request and first masked frame in one TCP write and verifies `101`, protocol visibility in both callbacks, ordered replies, close drain and bounded server join (7 ms O3 runtime on M2 Max). `WsSession.close()` queues one close frame and becomes drain-only. The worker retires the descriptor once that queue drains, or under Fiber's normal idle / read deadline and shutdown ownership rules. `sendText` rejects invalid UTF-8; `closeWith` rejects reserved/invalid close codes and malformed UTF-8 reasons. Malformed peer framing queues the RFC 6455 `1002` protocol-error close when the bounded outbound queue still has capacity, then becomes drain-only. ## RFC 6455 boundary The opening request requires HTTP/1.1 `GET`, exactly one `Sec-WebSocket-Key`, exactly one `Sec-WebSocket-Version: 13`, list-aware `Upgrade: websocket` and `Connection: upgrade` tokens, and a canonical Base64 key decoding to exactly 16 bytes. HTTP request bodies and `Transfer-Encoding` are refused before handoff so body bytes cannot be smuggled into frame input. Frames are strict and extension-free: reserved RSV bits/opcodes, non-canonical extended lengths, unmasked client frames, fragmented control frames, invalid close payloads, malformed UTF-8 text/close reasons and invalid continuation order fail closed. Fragmented messages, ping/pong and close echo are handled by the session state with a 16 MiB message ceiling. ## Current scope This is a plaintext HTTP/1 WebSocket server path. TLS termination, negotiated extensions (including permessage-deflate), outbound cross-worker broadcast ownership and HTTP/2 extended CONNECT are intentionally not implied by `App.ws`. `WsConn` remains available only as the lower-level blocking helper for callers that already own their descriptor; do not use it inside a live Fiber route. --- Source: https://vex-lang.org/docs/std/index.md # Vex Standard Library The standard library supplies reusable building blocks for Vex applications. Most algorithms are written in Vex; platform services and selected providers use native boundaries. Each module documents its imports, ownership, error behavior and supported surface. Consult the module's layout and integration requirements when connecting packages. New to the library? Follow [your first standard-library workflow](docs/guide/stdlib-start.md) to parse an input, transform it and add a test. For coding assistants, use [the documentation exports and Vex skill](docs/guide/ai-tools.md). Formatting is deliberately not a separate `std/fmt` package. Use [`$format`, `$print`, and `$println`](docs/guide/advanced/builtins.md#i-o-formatting-and-debugging), the built-in `Display`/`Debug` contracts, or [`strings.StringBuilder`](docs/std/strings.md) for reusable caller-owned construction. This keeps format parsing, diagnostics, and allocation policy in one canonical stack. ## Core Modules | Module | Purpose | | --- | --- | | [CLI](docs/std/cli.md) | Commands, arguments and flags | | [Collections](docs/std/collections.md) | Deques, stacks, priority heaps and indexed lists | | [Compression](docs/std/compress/index.md) | Bounded LZ4, Zstandard, Gzip, Zlib and Brotli codecs | | [Context](docs/std/context.md) | Cooperative cancellation, deadlines and metadata | | [Contracts](docs/std/contracts.md) | Conversion, collection and packed-data protocols | | [Crypto](docs/std/crypto/index.md) | Hashing, authenticated encryption, signatures and key derivation | | [Database](docs/std/db/index.md) | Owning synchronous SQLite access and optional native providers | | [Encoding](docs/std/encoding.md) | Checked text/binary encoding and reusable output | | [Errors](docs/std/errors.md) | Typed errors, causal chains and aggregation | | [Filter](docs/std/filter.md) | Predicate filtering and mask-based compaction | | [File system](docs/std/fs/index.md) | Files, paths, metadata, mappings and directory traversal | | [Geographic coordinates](docs/std/geo.md) | Geographic distances, bearings, routes, bounds and polygon operations | | [Hash](docs/std/hash.md) | Non-cryptographic hashing and explicit hash builders | | [HTTP](docs/std/http/index.md) | Client, parser and Fiber server APIs with explicit protocol boundaries | | [I/O](docs/std/io.md) | Readers, writers, buffering and stream adapters | | [Logging](docs/std/log.md) | Structured fields, loggers and sinks | | [Networking](docs/std/net.md) | TCP/UDP sockets and typed address/resolver APIs | | [Randomness](docs/std/rand.md) | Explicit reproducible streams and unbiased distributions | | [Regex](docs/std/regex/index.md) | Pattern compilation, matching and borrowed match ranges | | [Semver](docs/std/semver.md) | Semantic versions and version requirements | | [Serde](docs/std/serde/index.md) | Structured codecs and owning dynamic trees for six formats | | [Sort](docs/std/sort.md) | Ordering with explicit comparator and stability choices | | [String conversion](docs/std/strconv.md) | Checked parsing and numeric formatting | | [Strings](docs/std/strings.md) | Reusable string construction and string utilities | | [System](docs/std/sys.md) | Processes, environment and platform services | | [Testing](docs/std/testing.md) | Assertions, test context and benchmark context | | [Time](docs/std/time/index.md) | Monotonic elapsed time, wall time, durations and calendars | | [TLS](docs/std/tls.md) | TLS primitives and the documented transport/verification surface | | [Unicode](docs/std/unicode.md) | Character properties, casing, normalization and segmentation | | [URL](docs/std/url.md) | URI parsing/resolution and strict percent/form codecs | ## Builtin numeric namespaces [Math](docs/std/math.md), [Bit](docs/std/bit.md), and [Crypto](docs/guide/crypto.md) are compiler namespaces rather than packages. They require no import. The `Crypto` namespace contains low-level primitives; the `crypto` package supplies complete algorithms. ## Images, media, compute and language tools | Family | Guide | | --- | --- | | Image processing | [Vips](docs/std/vips.md): owning pixels, transforms, filters, rows and codec providers | | Video and audio | [Media](docs/std/media.md): frame layouts, PCM/WAV, containers and codec components | | Real-time protocols | [WebRTC](docs/std/webrtc.md): SDP, ICE, RTP/RTCP, media queues and protection boundaries | | Numeric kernels | [ML](docs/std/ml.md): normalization, activations, linear algebra and attention | | Model execution | [Inference](docs/std/inference.md): model loading, generation and backend selection | | Developer tooling | [Language tools](docs/guide/tooling/language-tools.md): the `ide/*` package family | These guides distinguish complete entry points from lower-level components, document required native providers, and show how to connect ownership and buffer layouts across package boundaries. ## Choosing an API Prefer owning values when data must outlive its input, borrowed views while an owner remains live, and reusable-output APIs for repeated work. A pointer, `Span`, or `RawBuf` parameter carries additional lifetime and capacity obligations; it is not an automatic zero-allocation or safety guarantee. Use checked parse/decode entry points for external data and set resource limits where the API provides them. Preserve typed errors until the application boundary so callers can distinguish malformed input, exhaustion, cancellation and I/O failure. The [standard-library guide](docs/guide/stdlib.md) explains the prelude/package boundary and routes common tasks to these references. --- Source: https://vex-lang.org/docs/std/inference.md # Inference `inference` is an experimental model-execution package built on [`ml`](docs/std/ml.md) and Vex SIR. Its current implementation centers on memory-mapped GGUF weights, tokenization, sampling, and F16/F32 inference plans. It is separate from the core standard-library release scope. ## Public API and current behavior The following describes the inspected development source. It is a guide to choosing an entry point, not a model or hardware qualification report. | Entry point | Current behavior | | --- | --- | | `Model.load(path)` | Loads a GGUF model and tokenizer; returns `Model` and panics on a load failure. It does not return a `Result`. | | `generate(&model, prompt, options)` | Uses the supported-weight F16 SIR plan. Unsupported weight routes panic rather than selecting a legacy CPU fallback. | | `GenerateOptions.default()` / `.greedy()` | Construct explicit token-count, sampler and end-of-sequence options. | | `stream(&model, prompt, options, callback)` | Generates the complete text, then calls the callback once. It is not incremental token streaming. | | `generate_typed` / `stream_typed` | Exported but currently stop at an unimplemented-specialization diagnostic; do not use these as working alternatives. | | `InferencePlanF32` / `InferencePlanF16` | Lower-level plan construction, prefill, decode, and sampling surfaces for integration work. | The generation eligibility check recognizes F32, F16, Q4_0, Q8_0, Q4_K, and Q6_K projection/output weights. That check is only one prerequisite: a file's architecture, tensor shapes, tokenizer, context size, and backend operations must also match the implementation. The current loader is GGUF-specific; SafeTensors loading is not documented as an available path here. ## Generation sequence For a model and target already qualified by the package's tests, the API shape is: ```vex import { Model, GenerateOptions, generate } from "inference"; fn main() { let model = Model.load("models/qualified-model.gguf"); let! options = GenerateOptions.greedy(); options.max_tokens = 32; let text = generate(&model, "Hello", options); $println(text); } ``` This integration example requires an actual compatible model file; it is not a self-contained smoke test and no expected model output is promised. The current high-level path also prints loading/generation diagnostics, so an application that needs a machine-readable response must not treat all stdout as generated text. ## Model and cache ownership The model retains the weight store and tokenizer. The loader's mapped storage backs weight views and must remain alive while they are used. Generation constructs a plan, prefills prompt tokens, and advances its KV state during decode. A repeated `generate` call should not be treated as an implicit conversation session or an API for reusing a previous call's KV cache. The public surface also includes chat-template helpers, sampler utilities, quantized-row helpers, attention operations and LoRA structures. A declaration or export establishes availability in source; it does not establish complete model coverage or a completed application workflow. ## Direction: Graph-Based Inference SIR graphs expose compute to the compiler. They do not establish where weights are dequantized, how many device dispatches occur, or whether a workload stays on the GPU. Verify the complete loading → tokenization → prefill → decode → sampling sequence for the exact model, compiler binary and backend before depending on it. Record model identity, precision, context length and output checks alongside any throughput measurement. The package source contains targeted tests under `lib/std/inference/tests`; these are starting points for qualification. This page does not claim a fresh end-to-end inference or physical-GPU run. --- Source: https://vex-lang.org/docs/std/io.md # io — composable byte I/O The `io` package is the shared byte-I/O layer for files, streams, protocols, serializers and loggers. It provides separate synchronous and cancellation-aware async contracts, reusable buffering, bounded input APIs and a portable error model. ```vex import { Reader, Writer, ByteReader, ByteWriter, StringWriter, BufReader, BufWriter, bufReader, bufWriter, IoError, IoErrorKind } from "io"; ``` ## Contracts ```vex contract Reader { read(buf: Ptr, len: usize)!: Result; } contract Writer { write(data: Ptr, len: usize)!: Result; flush()!: Result<(), IoError>; } contract ReaderAt { // Never changes the source's sequential cursor. readAt(buf: Ptr, len: usize, offset: u64)!: Result; } contract WriterAt { // Never changes the sink's sequential cursor. writeAt(data: Ptr, len: usize, offset: u64)!: Result; } contract ByteReader { readByte()!: Result; } contract ByteWriter { writeByte(value: u8)!: Result<(), IoError>; } contract StringWriter { writeStr(value: str)!: Result; } contract AsyncReader { async fn read(buf: Ptr, len: usize, context: &Context): Result; } contract AsyncWriter { async fn write(data: Ptr, len: usize, context: &Context): Result; } ``` `Reader` writes into caller-owned mutable storage. `Writer` only borrows its input for the duration of the call. For a non-empty read request, a zero-byte result means EOF; a zero-length request can also return zero without testing EOF. A writer may accept a partial prefix. Use `writeAll` when the complete input must be written. The package also exports `Seeker`, `Closer` and composed contracts such as `ReadWriter`, `ReadReaderAt`, `WriteWriterAt`, `ReadSeeker`, `ReadWriteSeeker`, `ReadWriteRandom` and `ReadWriteCloser`. `ReaderAt` and `WriterAt` are not "seek, perform an operation, then seek back" wrappers. They are for sources that can honour an offset without changing their shared sequential cursor. `Cursor` and `fs.File` implement both. A provider must document whether concurrent operations on the same underlying resource are permitted. ## Async transports `AsyncReader`, `AsyncWriter` and `AsyncReadWriter` are deliberately not aliases for synchronous `Reader`/`Writer`. Their mandatory `Context` preserves cancellation and deadline propagation for every operation that can park a Vex task. Files, memory buffers and stdio remain free of scheduler overhead. `TcpStream` implements `AsyncReadWriter`. Generic protocol code can use the same surface today and later accept TLS or QUIC adapters without a second read/write loop: ```vex import { AsyncWriter, IoError, asyncWriteAll } from "io"; import { Context } from "context"; async fn sendFrame(out: &W, bytes: str, request: &Context): Result<(), IoError> where W: AsyncWriter { return await asyncWriteAll(out, bytes.asPtr() as Ptr, bytes.len(), request); } ``` `asyncWriteAll` is allocation-free, accepts legal short writes, forwards the same context on every retry, and turns a zero-byte successful write into `IoErrorKind.WriteZero` rather than spinning. This is the canonical complete write helper for HTTP/TLS-style transports. When an API accepts an async callback (for example, a future HTTP streaming body producer), use `async fn` in the function type instead of spelling a nominal `Future` return type: ```vex type ByteProducer = async fn(out: Ptr, cap: usize): usize ``` Calling `ByteProducer` yields the compiler-owned `Future` and therefore must be awaited. This keeps scheduler ownership structural and prevents a user-defined type named `Future` from accidentally gaining runtime semantics. ## Position-independent random access The following is a fragment inside a unit-returning function; handle the construction error according to your application. ```vex import { cursorFromString, readExactAt, sectionReader, SeekFrom } from "io"; let! source = cursorFromString("0123456789".toString()); let! header: [u8; 4] = [0; 4]; match readExactAt(&source!, &header[0] as Ptr, header.len(), 2) { Ok(_) => {}, Err(error) => { $println(error.message()); return; }, }; // source.position() is still 0. let! body = match sectionReader(&source!, 3, 4) { Ok(section) => section, // visible bytes: 3456 Err(error) => { $println(error.message()); return; }, }; let _ = body.seek(SeekFrom.End(-1)); ``` `readAt` may return a short count at the end of the visible range, just like `Reader.read`; use `readExactAt` for fixed binary records. `writeAllAt` retries partial random writes and rejects zero progress. `SectionReader` bounds every read and seek to `[start, start + length)`, checks range overflow at creation, and never mutates the inner reader's cursor. ## Files and streams ```vex import { openRead, openWrite, readToStringLimit, writeAll } from "io"; match openRead("config.txt".toString()) { Ok(stream) => { let! input = stream; match readToStringLimit(&input!, 1024 * 1024) { Ok(text) => { $println(text); }, Err(err) => { $panic(err.toString()); }, } let _ = input.close(); }, Err(err) => { $panic(err.toString()); }, } ``` `openRead`, `openWrite` and `openAppend` return `Stream`. Owned streams close on drop; `close()` is idempotent and should be used when flush/close errors matter. `stdin()`, `stdout()` and `stderr()` return runtime-owned stream wrappers and are not closed by their wrappers. ## Generic buffering `BufReader` and `BufWriter` hold a caller-owned reference to the underlying implementation and use a private 16 KiB buffer. Dispatch remains static—there is no trait object or per-operation heap allocation. Large reads and writes bypass the intermediate buffer. While an adapter is in use, access its underlying reader/writer through `getRef()` (read-only) or `getRefMut()` (mutable), not through the original binding. Both methods reborrow the existing object; they do not clone it or allocate. A returned reference follows the adapter's normal borrow rules. Direct underlying operations do not synchronize the private buffer: - After seeking or reading through `BufReader.getRefMut()`, call `discardBuffered()` if the old read-ahead bytes are no longer wanted. - Flush `BufWriter` successfully before writing directly to its underlying writer when byte ordering matters. `getRefMut()` does not flush implicitly; it can also be used to repair a provider after a failed flush, then retry the preserved buffered suffix. The following fragment also assumes a surrounding unit-returning function: ```vex let! source = match openRead("records.txt".toString()) { Ok(stream) => stream, Err(error) => { $println(error.message()); return; }, }; let! reader = bufReader(&source!); let! lineBytes = Vec.withCapacity(4096); loop { match reader.readLineInto(&lineBytes!, 1024 * 1024) { Ok(None) => { break; }, Ok(Some(length)) => { // `lineBytes` is reused; LF and an optional CR were removed. consumeRecord(lineBytes.asSpan()); }, Err(err) => { $panic(err.toString()); }, } } ``` `readLineInto` distinguishes EOF (`None`) from an empty line (`Some(0)`). If a line exceeds the supplied payload limit, it returns `InvalidData` and drains the rest of that record so the next call starts at the following line. For binary records or non-newline text framing, use the same reusable SIMD scan directly: ```vex let! bytes = Vec.withCapacity(4096); match reader.readUntilInto(&bytes!, 124 as u8, 64 * 1024) { Ok(Some(count)) => { // A found delimiter is included: `bytes[count - 1] == '|'`. consumeFrame(bytes.asSpan()); }, Ok(None) => { /* EOF before another record */ }, Err(err) => { /* limit exceeded; reader already resynchronized */ }, } ``` `skipUntil(delimiter)` performs the matching zero-allocation recovery/skip operation and returns the consumed byte count, including the delimiter when found. `readUntilInto` uses the same 64-byte VexArch byte-search primitive as line scanning; no target-specific path is embedded in the package source. Use `readLineLimit` when an owned UTF-8 string is desired: ```vex match reader.readLineLimit(64 * 1024) { Ok(Some(line)) => { useLine(line); }, Ok(None) => { /* EOF */ }, Err(err) => { /* invalid UTF-8, limit or provider failure */ }, } ``` `BufWriter.flush()` is explicit. It retries partial writes, reports `WriteZero`, and preserves unwritten buffered bytes after an error. No destructor silently discards a flush failure. ## In-memory cursor ```vex import { newCursor, SeekFrom } from "io"; let! cursor = newCursor(); let _ = cursor.writeStr("header"); let _ = cursor.seek(SeekFrom.Start(0)); let first = cursor.readByte(); ``` `Cursor` implements sequential read, write, byte, string and seek contracts plus cursor-independent `ReaderAt`/`WriterAt`. It supports reuse, zero-fills sparse writes and safely handles input/output views that alias its own backing storage. ## Transfer and bounded reads ```vex copy(src, dst) // 16 KiB convenience scratch copyBuffer(src, dst, scratch, length) // caller-owned, allocation-free core copyN(src, dst, maximum) writeAll(dst, data, length) readAll(src) readAllLimit(src, maximum) readAtLeast(src, buffer, length, minimum) readExact(src, buffer, length) readExactAt(src, buffer, length, offset) writeAllAt(dst, data, length, offset) readToStringLimit(src, maximum) ``` Prefer bounded variants for files supplied by users, network input and parser front ends. `copyBuffer` lets large applications use stack, arena or pooled scratch storage without a hidden allocation. ## Adapters - `emptyReader()` is permanently at EOF. - `sinkWriter()` accepts and discards bytes without allocation. - `chainReader(a, b)` reads `a` to EOF and then `b`. - `teeReader(reader, writer)` mirrors every returned byte. - `countingReader` and `countingWriter` expose checked `u64` totals. - `limitReader(reader, maximum)` exposes at most the configured byte count. All adapters are generic and statically dispatched. ## Errors `IoError.kind()` returns a portable `IoErrorKind`; `osCode()` preserves the VexArch-normalized native code and `messageView()` returns diagnostic text without allocating. Common kinds include: - `NotFound`, `PermissionDenied`, `AlreadyExists`; - `WouldBlock`, `Interrupted`, `TimedOut`; - `UnexpectedEof`, `WriteZero`, `InvalidInput`, `InvalidData`; - connection, address, filesystem-capacity and resource-limit failures. Only `Interrupted` and `WouldBlock` are reported by `isRetryable()`. ## Standard I/O helpers ```vex printStr("without newline") eprint("diagnostic") eprintln("diagnostic with newline") match readLineLimit(64 * 1024) { Ok(line) => { useLine(line); }, Err(err) => { $panic(err.toString()); }, } ``` The simple stdin `readLine()` returns an owned `string`, so EOF and an empty line are both represented by `""`. Use `BufReader.readLineInto` or `BufReader.readLineLimit` when a protocol needs to distinguish them. ## Performance and safety notes - `copyBuffer` supplies its scratch explicitly. Cursor and buffered adapters reuse established capacity; creating an adapter, copying string input into a Cursor, or growing output can allocate. Provider operations may also allocate independently. - ASCII UTF-8 validation and byte scanning use target-independent Vex fixed-array/Mask operations; the backend selects CPU SIMD or GPU/SIMT lowering. - Non-empty null buffers, oversized provider counts, counter overflows and zero-progress writes are rejected. - `std/io` does not import libc directly. Native behavior enters through the selected VexArch provider, preserving Vex's freestanding core. --- Source: https://vex-lang.org/docs/std/log.md # `log` — typed structured logging `std/log` provides immutable contextual loggers, typed fields, dynamic level control and synchronized persistent destinations. A rejected record returns before reading the clock or allocating its formatting buffer. ## Quick start ```vex import { Format, Level, Logger, field } from "log"; let logger = Logger.stderr(Level.Info) .withFormat(Format.Json) .withService("checkout".toString()); let fields = [ field("order_id".toString(), 42 as u64), field("cached".toString(), false), ]; match logger.info("order accepted", &fields[0..2]) { Ok(_) => { /* complete record written */ } Err(err) => { /* apply the application's I/O failure policy */ } } ``` JSON output is one complete object per line: ```json {"time":"2026-08-17T12:34:56.789Z","level":"INFO","msg":"order accepted","service":"checkout","order_id":42,"cached":false} ``` ## Levels and destinations Levels are ordered `Level.Trace`, `Debug`, `Info`, `Warn`, `Error`, and `Off`. `Off` rejects every record. | Constructor | Destination | |---|---| | `Logger.new(level)` | stderr | | `Logger.stderr(level)` | stderr | | `Logger.stdout(level)` | stdout | | `Logger.file(path, level)` | one persistent append descriptor | | `Logger.discard()` | disabled sink | `Logger.file` returns `Result`. It opens the destination once; clones share that descriptor and serialize complete records through one lock. ```vex let logger = match Logger.file("service.log".toString(), Level.Debug) { Ok(value) => value.withFormat(Format.Json), Err(err) => $panic("could not open log file"), }; ``` ## Typed fields `field` overloads accept `bool`, `i64`, `u64`, `f64`, and owned `string`. `nullField` emits null. `group` creates a nested structured object rather than flattening keys into text. ```vex import { field, group, nullField } from "log"; let requestFields = [ field("method".toString(), "GET".toString()), field("status".toString(), 200 as i64), nullField("error".toString()), ]; let fields = [group("request".toString(), &requestFields[0..3])]; let result = logger.info("request complete", &fields[0..1]); ``` Retained string fields are owned. A derived logger never keeps a borrow into a request buffer after that buffer's lifetime. ## Immutable context and groups Builder methods consume and return a logger. Clone a base logger when deriving independent contextual children: ```vex let common = [field("region".toString(), "eu-west".toString())]; let base = Logger.stderr(Level.Info).withFields(&common[0..1]); let requestLogger = base.clone() .withGroup("request".toString()) .withTraceparent( "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", ); ``` Available derivations: - `withFormat(Format.Text | Format.Json)`; - `withTimestamp(bool)`; - `withFields(&[Field])` and `withGroup(string)`; - `withService(string)`; - `withTrace(traceId, spanId)`; - `withTraceparent(str)` for canonical W3C trace context; - `withLevelSwitch(LevelSwitch)`. Invalid, uppercase, future-version or all-zero traceparent identifiers leave the logger unchanged. ## Dynamic filtering `LevelSwitch` is shared across all loggers derived from it. Updates use acquire/release atomics and do not rebuild logger context. ```vex import { LevelSwitch } from "log"; let levels = LevelSwitch.new(Level.Info); let logger = Logger.stderr(Level.Info) .withLevelSwitch(levels.clone()); levels.set(Level.Debug); ``` Use `logger.enabled(level)` before constructing application-level expensive fields. The logger performs its own second check before clock/format work. ## Emission API Convenience methods `trace`, `debug`, `info`, `warn`, and `err` have message-only and message-plus-fields overloads. Every method returns `Result<(), IoError>`. `log(level, message, fields)` selects a level explicitly. `logAt` also accepts a supplied `Time`, which is useful for replay and imported events. Source metadata is explicit and compile-time discoverable: ```vex import { Field, Source } from "log"; let source = Source.new( #Source.fileName().toString(), #Source.module().toString(), #Source.line(), #Source.column(), ); let fields: [Field; 0] = []; let result = logger.log(Level.Error, "request failed", &fields[0..0], &source); ``` This avoids an opaque runtime stack walk. `formatRecordAt` is available for deterministic custom formatting and tests. ## Flush and close `flush()` forwards to the destination. `close()` closes a file destination at most once across all clones; stdout, stderr, and discard remain process-owned. Later writes through a closed file logger return the canonical `IoError`. The package is intentionally synchronous. Async batching, sampling, rotation, and telemetry export require explicit loss/backpressure and lifecycle policies; they are not hidden behind a process-global logger. ## Performance baseline M2 Max, O3, 200 ms: | Operation | Result | |---|---:| | disabled level check | 1.62 ns | | disabled record | 2.10 ns | | empty JSON record | 275.60 ns | | JSON record with six fields | 408.85 ns | | text record with six fields | 414.88 ns | Formatting measurements include the returned owned string allocation; they do not include destination I/O. --- Source: https://vex-lang.org/docs/std/math.md # Mathematics `Math` is a builtin namespace, available without an import. There is no separate `math` package to add to a project. The [Math namespace reference](docs/guide/math.md) contains function names, numeric widths, constants, and examples. ## Choose the numeric operation first For scalar floating-point work, select the required precision explicitly: ```vex let root: f64 = Math.sqrt(144.0); // 12.0 let root32: f32 = Math.sqrtf(144.0 as f32); let angle: f64 = Math.PI / 4.0; let sine: f64 = Math.sin(angle); ``` The unsuffixed transcendental operations use the `f64` family; explicitly supported `f` spellings, such as `sqrtf`, select `f32`. Not every function has an `f` spelling. Constants include `Math.PI`, `Math.E`, `Math.TAU` and `Math.SQRT2`. Float classification uses `Math.isNaN`, `Math.isInf`, and `Math.isFinite` with that capitalization. ## GPU and SIMD Acceleration Supported array and Tensor calls express elementwise work. The operation, number type, shape, compiler path, and target determine whether it lowers to vector instructions, scalar operations, library calls, or an accelerator kernel. For example, a semantic sine operation does not imply a CPU instruction that calculates every lane's sine in one cycle. ## Graph Functions Inside a `graph fn`, supported math operations participate in SIR composition. The graph must still satisfy the selected backend's operation and precision rules. A graph declaration alone does not establish GPU dispatch, transfer-free execution, or numerical equivalence across devices. See the [SIMD/SIMT contract](docs/guide/simd/simd-simt-contract.md). ## Exact float representation `Math.toBits` and `Math.fromBits` reinterpret scalar representations: ```vex let negativeZero: f64 = Math.fromBits(0x8000000000000000 as u64); let bits: u64 = Math.toBits(negativeZero); // 0x8000000000000000 ``` The accepted pairs are `f32`/`u32` and `f64`/`u64`. This is not a numeric cast; it preserves signed zero and NaN payload bits. Signed integers and mismatched widths are rejected. Subsequent floating-point arithmetic may have different NaN behavior, so preserve the integer bits when exact representation is the goal. ## Related operations - [Integer bit operations](docs/std/bit.md) - [Explicit random streams and unbiased ranges](docs/std/rand.md) - [Normalization, activations and attention](docs/std/ml.md) --- Source: https://vex-lang.org/docs/std/media.md # Video and audio components (`media`) `media` brings together frame storage, container and bitstream parsers, audio DSP, transforms, packet formats and codec components. Use `"media"` for the facade or component imports such as `"media/tensor_media"` and `"media/audio/wav_mux"` for a focused pipeline. A container parser, a packetizer and a complete codec are distinct pieces: choose the component that matches your input and required output. ## Frame storage `VexMediaTensor` owns a byte buffer with dimensions, a format, `ptsNs` and flags. Presentation timestamps are **nanoseconds**. The format determines how to interpret its dimensions: | Format | Layout | | --- | --- | | `MEDIA_FORMAT_RGB24` | Packed RGB; image consumers require three channels | | `MEDIA_FORMAT_YUV420P` | Planar Y, U, V; use `channels = 1` | | `MEDIA_FORMAT_NV12` | Y plane plus interleaved UV; use `channels = 1` | | `MEDIA_FORMAT_AUDIO_PCM_F32` | Interleaved float samples; width is sample-frame count, height is 1, channels is audio channel count | `newMediaTensor` checks dimensions and allocation arithmetic, returning an empty tensor on invalid layout or allocation failure. Check `bufferLen` and the buffer before processing. The allocation is **not initialized**: fill its samples before encoding, filtering or exposing it to another consumer. Chroma planes round width and height independently for odd 4:2:0 dimensions. The tensor releases its buffer on drop. `freeMediaTensor` releases it early and resets the descriptor; borrowed buffers cannot survive either release. `MEDIA_FLAG_KEYFRAME`, `MEDIA_FLAG_INTERFRAME`, `MEDIA_FLAG_AUDIO` and `MEDIA_FLAG_HARDWARE` describe payloads. An empty error/EOS product can carry `MEDIA_FLAG_ERROR`; it is not a decoded frame. ## Create PCM and a WAV header This complete program produces a short stereo sine wave in a caller-owned 300-byte WAV buffer. It performs no file I/O. ```vex [media-wav.vx] import { newMediaTensor, MEDIA_FORMAT_AUDIO_PCM_F32 } from "media/tensor_media"; import { generateSineWaveFloat, encodeFloatToPcm16, createWavHeader } from "media/audio/wav_mux"; fn main() { let! samples = newMediaTensor(64, 1, 2, MEDIA_FORMAT_AUDIO_PCM_F32); if samples.bufferLen != 512 { $panic("audio allocation failed"); } generateSineWaveFloat(&samples!, 48000.0 as f32, 440.0 as f32); let! bytes: [u8; 300] = [0; 300]; let header = RawBuf.of(&bytes[0] as Ptr); let payload = RawBuf.of(&bytes[44] as Ptr); let written = encodeFloatToPcm16(&samples, payload, 256); if written != 256 { $panic("PCM encoding failed"); } if createWavHeader(header, 44, 48000, 2, 16, 256) != 44 { $panic("WAV header failed"); } if bytes[0] != 82 || bytes[8] != 87 { $panic("wrong WAV signature"); } $println("media WAV: PASS"); } ``` `createWavHeader` writes a 44-byte RIFF/PCM header and returns zero for invalid parameters or insufficient header capacity. It does not append samples. `dataSize` is the byte count of the following PCM payload and must contain whole interleaved frames. `encodeFloatToPcm16` clamps samples to `[-1, 1]`, maps NaN to zero and emits little-endian PCM16. Its output count excludes the header. The raw buffers above borrow the array only for the calls shown. ## Decode lifecycle `newMediaPipelineBuilder()` creates a configuration record. Set `maxBufferMb` before `openMedia(&builder, input, length)` to bound accepted encoded input. The `Media` value exposes `width`, `height`, `durationMs` and its `pipeline`. Inspect `pipeline.isOpen` before reading. The pipeline borrows the encoded input; retain those bytes until `closeMedia(&media!)` and the last read are complete. The integrated video path consumes the supported MP4/AVC sample-table subset with parsed SPS/PPS and H.264 samples. `decodeNextFrame(&media!)` returns an owning tensor. `pipeline.isEos`, empty storage and the error flag describe termination/error products; do not process them as full frames. This interface does not provide a distinct typed error for every open/decode failure. Hardware acceleration, HDR and audio-sync fields in `MediaPipelineBuilder` are configuration preferences; `openMedia` currently connects only the input budget to the decode pipeline. Use explicit transform/sync components where their contracts fit, rather than expecting those preferences to install a backend automatically. ## Compose lower-level components | Work | Component surface | | --- | --- | | Containers | MP4 sample tables, Matroska/WebM parsing, GIF/WebP/APNG metadata; MP4/MKV muxing components | | Bitstreams | Bounded readers/writers, H.264 NAL/SPS/PPS/slice helpers, entropy and prediction primitives | | Audio | ADTS/Opus header parsing, MP3 components, resampling, EBU R128 measurement, PCM/WAV output | | Image output | `encodeBmp` for three-channel packed RGB; returns a byte count or zero | | Pixel processing | Colour-space conversion, scaling, deinterlacing, frame-rate conversion, LUT3D and tone-mapping helpers | | Timing | A/V synchronization state, seek control, circular buffering and presentation timestamps | | Transport formats | RTP, RTSP, HLS/DASH, MPEG-TS and RTMP/FLV parsing/building components | | Image interoperation | `vipsToMediaTensor`, `mediaTensorToVips` copy packed RGB into independent storage | These components expose particular syntax/layout operations. An AAC ADTS or Opus header parser does not synthesize compliant PCM audio: the AAC raw-data block/codebook path and Opus packet synthesis are outside the complete decoder surface. Likewise, codec-specific H.265/VP9/AV1 primitives are not a declaration that the high-level `Media` reader decodes every such stream. The `transcodeMp4ToMkv`, `transcodeMkvToMp4`, `transcodeMp3ToAac` and `transcodeAacToOpus` entry points return zero output; there is no complete cross-format conversion route behind them. VideoToolbox, VA-API and NVDEC configuration records do not open or submit to a hardware decoder. Select a working external codec/backend when your application needs those end-to-end operations, and adapt its output to the explicit tensor layout. ## Buffer and pipeline boundaries Supply actual readable/writable extents with every `RawBuf` and length pair. A caller-provided output budget does not allocate storage. Do not overlap encoded input, decoded output and scratch storage unless the specific function documents in-place operation. Validate dimensions before allocating images derived from untrusted metadata and impose stream-level frame/byte budgets. Container timestamps, RTP timestamps and `ptsNs` have different units. Convert through the stream's time base instead of treating all integer timestamps as milliseconds. [WebRTC](docs/std/webrtc.md) covers RTP clocks and encoded media delivery; [image processing](docs/std/vips.md) covers packed image operations. --- Source: https://vex-lang.org/docs/std/ml.md # ml `ml` provides pure Vex building blocks for normalization, activations, linear algebra and attention. Compute kernels use Tensor operators and `graph fn` where supported; orchestration and borrowed-view helpers also use ordinary functions. A graph declaration is not a guarantee of GPU execution or a single fused dispatch. ## Integrated Operations - `norm`, `rms_norm`: RMS normalization. - `layernorm`, `layer_norm`: layer normalization. - `softmax`, `log_softmax`, `relu`, `silu`, `swiglu`, `gelu`: activations. Softmax subtracts the maximum before exponentiation; this does not define every empty-input, NaN or infinity case. `gelu` currently uses a sigmoid approximation, not the exact Gaussian-error-function formula. - `linear`, `dot`, `matvec`: linear algebra, with additional Span helpers. - `fused_attend`, `extract_k_head`, `extract_v_head_t`, `multi_head_attention`, `argmax`: attention and scoring helpers. ## Graph composition and ownership Import the actual lowercase API names. For example: ```vex import { norm, softmax } from "ml"; graph fn hidden_layer(t: Tensor, w: Tensor): Tensor { return softmax(norm(t, w)); } ``` Graph composition exposes operations to SIR. Backend support, shapes and dispatch decisions determine the actual execution plan. Inspect compiler diagnostics and retained IR before claiming fusion or transfer-free GPU work. Attention cache extraction accepts a borrowed `Span` over a row-major `[seq_len, kv_dim]` cache. K extraction returns `[seq_len, head_dim]`; V extraction returns its transposed `[head_dim, seq_len]` layout. Both return independent owned Tensors and preserve the cache. Negative dimensions, out-of-row heads and layouts larger than the supplied Span panic before generating indices. Empty rows/heads return empty Tensors. `span_view(&tensor)` and `tensor_ptr(&tensor)` borrow an existing Tensor; they do not consume it. The Span cannot outlive its owner. `tensor_view(span)` creates an independent owned Tensor in ordinary code. `copy_tensor` requires `Ptr`, `&Tensor` and `T: Copy`; it is unsafe because the caller must prove destination capacity and non-overlap. Its source count is checked. ## Shapes and execution Keep logical tensor dimensions explicit at package boundaries. A composed `graph fn` exposes a computation to the graph compiler; the selected backend and supported operations determine placement and dispatch. Use ordinary functions for application orchestration and inspect the emitted execution plan when transfer costs or dispatch count matter. The ML package supplies numeric operations. A complete model additionally needs weights, tokenizer/configuration handling and generation policy; see [inference](docs/std/inference.md) for that layer. Package tests and benchmark inputs live under `lib/std/ml/tests` in the source distribution. --- Source: https://vex-lang.org/docs/std/net.md # net — typed TCP/UDP, task-aware I/O and frame processing `net` provides two deliberate layers: - `TcpListener`, `TcpStream` and `UdpSocket` own platform-width socket handles and return `Result<_, IoError>`; - `Socket`, `EventLoop` and the raw `*Fd` helpers expose normalized negative status codes for runtimes and protocol engines that need direct control. Native providers normalize Darwin and WinSock errors to the common VexArch error domain. High-level code can therefore inspect `IoErrorKind` without OS branches or message matching. ## TCP ```vex import { Context } from "context"; import { TcpListener } from "net"; import { Duration } from "time"; let! listener = match TcpListener.bind("127.0.0.1", 8080) { Ok(value) => value, Err(failure) => { $panic(failure.toString()); }, }; let request = Context.background().withTimeout(Duration.seconds(5)); let stream = match await listener.accept(&request) { Ok(value) => value, Err(failure) => { $panic(failure.toString()); }, }; ``` Listeners are non-blocking. `accept`, stream reads and stream writes park the current Vex task instead of polling in user code. Accepted handles are made non-blocking explicitly and enable `TCP_NODELAY` before becoming observable. `TcpStream` is also the canonical `io::AsyncReadWriter`: generic transport code receives a mandatory `Context` on each read/write, preserving cancellation and deadlines without a protocol-specific socket loop. Context-free TCP overloads remain available only for deliberately uncancelable fast paths. `TcpStream.connect` is task-aware and asynchronous. It uses the same runtime poller contract as accept/read/write and never narrows Windows' platform-width `SOCKET`. Bootstrap code that deliberately wants a blocking establishment step must say so with `TcpStream.connectBlocking`; the returned stream is switched to non-blocking mode before it becomes observable. Useful stream operations: - `read(buffer, len) -> Result`; `Ok(0)` means orderly EOF; - `write(buffer, len) -> Result`; - `writeAll` and `writeAllStr` preserve the unwritten tail across partial I/O; - `close` is idempotent and invalidates the local handle before entering the OS; - `rawHandle` is available for poller integration without narrowing WinSock's 64-bit `SOCKET` carrier. ### Cancellation and deadlines TCP accept, connect, read, write and write-all have `&Context` overloads. A context is checked before native access and then bound to the exact in-flight runtime operation, so cancellation or deadline expiry actively wakes an already parked task. There is no user-space sleep/poll loop. ```vex let request = Context.background().withTimeout(Duration.milliseconds(250)); let stream = match await TcpStream.connect(endpoint, &request) { Ok(value) => value, Err(failure) => { $panic(failure.toString()); }, }; let count = await stream.read(buffer, capacity, &request); ``` Manual cancellation maps to `IoErrorKind.Canceled`; deadline expiry maps to `IoErrorKind.TimedOut`. The runtime stores cancellation identity and absolute monotonic deadline in the same generation-owned operation slot as provider completion. Exactly one of completion, cancellation or timeout retires the provider resource and wakes the task. Context-free overloads remain a separate hot path with null identity and no deadline work. ## UDP ```vex import { Context } from "context"; import { UdpSocket } from "net"; import { Duration } from "time"; let! socket = match UdpSocket.bind("0.0.0.0", 9000) { Ok(value) => value, Err(failure) => { $panic(failure.toString()); }, }; let request = Context.background().withTimeout(Duration.milliseconds(250)); let received = await socket.recvDatagram(buffer, capacity, &request); ``` UDP sockets are readiness-safe and non-blocking after `bind`. `sendTo`, `recvFrom`, `recvDatagram` and `recvFromWithSource` provide `&Context` overloads that park the current task and participate in the same cancellation, deadline and generation-owned retirement contract as TCP. A datagram is never split across resumptions. On Windows, the IOCP operation owns its destination or source address storage until the completion packet retires it. Context-free overloads perform one immediate operation and report the normalized would-block error when no datagram is ready. A caller that deliberately requires an operating-system-thread-blocking receive must opt in with `socket.setNonBlock(false)`. All overloads validate buffer bounds and never report more bytes than the caller supplied. `UdpRecvFromResult` preserves the source port and a bounded, zero-terminated address buffer. ## Typed address boundary `Ipv4Addr`, `Ipv6Addr`, `IpAddr` and `SocketAddr` are canonical value types. IPv4 text is parsed once in portable Vex code. The parser is length-bounded, requires exactly four decimal octets and rejects values above 255, empty segments, extra segments and non-decimal input. IPv6 accepts canonical compressed forms and embedded IPv4, and formats according to RFC 5952. Native providers receive validated address bytes; they do not scan C strings or duplicate address parsing. `bind` and `connect` accept either text plus port or a typed `SocketAddr`. `localAddr` and `peerAddr` return typed endpoints. Numeric-address APIs never pretend that name resolution happened. ### Allocation-free address formatting Every address value exposes exact planning, a safe reusable-`Vec` append API, and a transactional advanced caller-buffer writer: ```vex import { SocketAddr } from "net"; let endpoint = match SocketAddr.tryParse("[2001:db8::5]:443") { Ok(value) => value, Err(failure) => { $panic(failure.message()); }, }; let! bytes = Vec.withCapacity(47); let written = endpoint.appendTo(&bytes!); ``` `appendTo` preserves existing bytes, reserves when necessary and becomes allocation-free after capacity is established. `textLength()` returns the exact RFC 5952 byte length without allocating. Advanced serializers may use `tryWriteTo(RawBuf, capacity)`: it validates capacity before its first store and reports both `required()` and `capacity()` through `AddressFormatError`. Supplying the public maximum widths—15 bytes for IPv4, 39 for IPv6, 21 for an IPv4 endpoint or 47 for an IPv6 endpoint—selects the one-pass path. `toString()` remains the owned convenience API. On the 2026-08-21 M2 Max O3 five-round gate, caller-buffer formatting measured 6.88 ns for IPv4, 17.20 ns for IPv6 and 20.88 ns for an IPv6 `SocketAddr`, all at zero allocation. Safe reused-`Vec` endpoint append measured 26.18 ns. The same run measured 18.50 ns IPv4 parse, 56.80 ns compressed IPv6 parse and 69.90 ns bracketed IPv6 endpoint parse. ## DNS resolution The system resolver is explicit and typed: ```vex import { ResolveFamily, ResolveOptions, resolveSocketAddrsBlocking, } from "net"; let endpoints = match resolveSocketAddrsBlocking( "example.com", 443, ResolveOptions.new(ResolveFamily.Any, 16), ) { Ok(value) => value, Err(failure) => { $panic(failure.toString()); }, }; ``` `resolveHostBlocking` returns ordered, duplicate-free `Vec` values; `resolveSocketAddrsBlocking` attaches the requested port. Numeric IPv4/IPv6 input uses the portable parser and does not enter the OS resolver. Hostname results are bounded (maximum 64), family-filterable and converted immediately from native `addrinfo` storage into Vex value types. The `Blocking` suffix is a semantic guarantee: the platform resolver may use files, NSS, mDNS or network I/O and can block the operating-system thread. Do not call it on a latency-sensitive scheduler worker. Hostnames must be ASCII or caller-supplied IDNA punycode; embedded NUL and locale-dependent Unicode input are rejected before native access. Unknown targets return typed `Unsupported` instead of inheriting a hosted resolver ABI. ## Raw socket and event-loop layer ```vex import { Socket } from "net"; let! socket = Socket.tcpBlocking(); if !socket.isValid() { $panic("TCP socket creation failed"); } ``` The raw layer is intentionally status-oriented. Check every fallible return. Socket handles are `i64` throughout the std boundary; descriptor-only Unix fallbacks reject values outside the i32 descriptor range instead of truncating. `EventLoop` routes to kqueue on macOS and epoll on Linux. Windows task-aware socket I/O uses VexArch's IOCP completion path; the separate readiness-style `EventLoop` reports `Unsupported` rather than faking successful registration. Unknown targets use a freestanding fail-closed provider with no borrowed libc ABI. Task-aware readiness never publishes a task pointer to the kernel. VexArch publishes a 64-bit generation-owned registration token only after the provider resource is prepared. A completion or cancellation must win the registration's single terminal transition before it may wake the task or retire the provider resource. Late, duplicate and recycled-generation events are therefore ignored without reading a stale task. On the Linux epoll fallback, read and write waits for the same socket own distinct provider registrations, so registering one direction cannot overwrite the other. ## Buffered connections `Conn.wrap(handle)` takes ownership; `Conn.wrapBorrowed(handle)` leaves ownership with the outer adapter. Its read/write queues start at 8 KiB/4 KiB, grow only to the 1 MiB bound, use bulk `Mem.copy`/`Mem.move`, and never report silently discarded bytes. ## WebSocket frames `parseFrame` validates canonical RFC 6455 lengths and returns a zero-copy payload pointer. Masking keys remain encapsulated in `WsFrame`; use `frame.unmaskPayload(ptr, len) -> bool` for in-place decoding. It validates the requested range against the parsed payload and target pointer width before its first store. `false` therefore means that no payload byte was changed. Mask XOR is implemented with Vex fixed-array SIMD, not C/Rust FFI or a source-level architecture branch. Four independent 16-byte vectors form the bulk loop and a bounded scalar tail handles the remainder. On the M2 Max O3 five-round gate, 125 bytes measured 10.87 ns / 10.7 GB/s and 4 KiB measured 78.03 ns / 48.9 GB/s, both allocation-free. The pre-SIMD 4 KiB implementation measured about 1.50 us / 2.5 GB/s. `Conn.findHeaderEnd()` uses the canonical SIMD `Mem.indexOfBytes` engine for `\r\n\r\n`. A 4 KiB scan with the terminator at the end measured 211.51 ns / 18.0 GB/s, down from roughly 2.38 us / 1.6 GB/s. A steady-state connection cycle that compacts 4 KiB and stages 8 KiB measured 153.06 ns / 74.8 GB/s. Reusable 4 KiB WebSocket encoding measured 55.78 ns / 68.4 GB/s. Zero-copy frame parsing measured 3.92 ns per frame; payload bandwidth is intentionally not claimed because the parser only reads the header. ## Historical test report The following results are historical claims retained from the package notes; this documentation pass did not rerun them or verify a release artifact. They do not establish the status of a different revision or target. - strict lint passes on macOS, Linux AArch64, Windows x64 and the generic freestanding fallback; - all 57 package tests pass at O0 and O3; - TCP/UDP loopback bind, non-blocking transition and exact-once close pass on macOS; - Windows and Linux AArch64 code generation preserve the common signatures. Native Linux/Windows execution of the close/event/cancel/deadline race matrices remains a production-signoff gate documented in `lib/std/net/VISION.md`. TCP and UDP structured cancellation and deadlines are public only through safe `&Context` overloads and preserve the generation-owned retirement contract. --- Source: https://vex-lang.org/docs/std/net_reference.md # std::net API Reference Public declarations reachable through the documented package entry points. Signatures follow the source snapshot; consult the module guide for support and qualification boundaries. ## Application entry points Use the [networking guide](docs/std/net.md) for typed sockets, context-aware async I/O, DNS and raw status-code boundaries. Import application APIs from `"net"`; platform FFI and internal ownership-transfer helpers below are not portable application facades. ### EVT_READ Import: `"net"`. ```vex export const EVT_READ: i32=1; ``` ### EVT_WRITE Import: `"net"`. ```vex export const EVT_WRITE: i32=2; ``` ### EVT_HUP Import: `"net"`. ```vex export const EVT_HUP: i32=4; ``` ### EVT_ERR Import: `"net"`. ```vex export const EVT_ERR: i32=8; ``` ### WS_CONTINUATION Import: `"net"`. ```vex export const WS_CONTINUATION: u8=0; ``` ### WS_TEXT Import: `"net"`. ```vex export const WS_TEXT: u8=1; ``` ### WS_BINARY Import: `"net"`. ```vex export const WS_BINARY: u8=2; ``` ### WS_CLOSE Import: `"net"`. ```vex export const WS_CLOSE: u8=8; ``` ### WS_PING Import: `"net"`. ```vex export const WS_PING: u8=9; ``` ### WS_PONG Import: `"net"`. ```vex export const WS_PONG: u8=10; ``` ### WS_OK Import: `"net"`. ```vex export const WS_OK: i32=0; ``` ### WS_NEED_MORE Import: `"net"`. ```vex export const WS_NEED_MORE: i32=-1; ``` ### WS_ERR_INVALID Import: `"net"`. ```vex export const WS_ERR_INVALID: i32=-2; ``` ### WS_MAX_BUFFER_BYTES Import: `"net"`. ```vex export const WS_MAX_BUFFER_BYTES: usize=16 * 1024 * 1024 as usize; ``` Shared receive-buffer ceiling for connection-oriented WebSocket users. This is deliberately a transport-neutral frame boundary rather than an application message policy; consumers still bound fragmented messages. ### AddressParseError Import: `"net"`. ```vex export struct AddressParseError ``` Allocation-free parse failure. `position` is the byte offset at which the parser could first prove the input invalid. **Implements:** `Copy` ### AddressFormatError Import: `"net"`. ```vex export struct AddressFormatError ``` Transactional caller-buffer formatting failure. Address formatting never partially modifies the destination: callers either receive the exact byte count or this value with the required capacity. **Implements:** `Copy` ### Ipv4Addr Import: `"net"`. ```vex export struct Ipv4Addr ``` **Implements:** `Copy` & `Eq` & `Display` & `Debug` ### Ipv6Addr Import: `"net"`. ```vex export struct Ipv6Addr ``` **Implements:** `Copy` & `Eq` & `Display` & `Debug` ### SocketAddr Import: `"net"`. ```vex export struct SocketAddr ``` **Implements:** `Copy` & `Eq` & `Display` & `Debug` ### Conn Import: `"net"`. ```vex export struct Conn ``` **Implements:** `Drop` ### Event Import: `"net"`. ```vex export struct Event ``` **Public fields:** - `fd`: `i32` - `flags`: `i32` ### EventLoop Import: `"net"`. ```vex export struct EventLoop ``` **Implements:** `Drop` **Public fields:** - `mem`: `[u8; 32]` - `valid`: `bool` ### ResolveError Import: `"net"`. ```vex export struct ResolveError ``` Allocation-free resolver failure. `nativeCode` retains the target provider's diagnostic code without making its numeric value public API. **Implements:** `Copy` & `Display` & `Debug` ### ResolveOptions Import: `"net"`. ```vex export struct ResolveOptions ``` **Implements:** `Copy` ### Socket Import: `"net"`. ```vex export struct Socket ``` **Implements:** `Drop` **Public fields:** - `fd`: `i64` ### TcpListener Import: `"net"`. ```vex export struct TcpListener ``` An owning, non-blocking TCP listener. **Implements:** `Drop` ### TcpStream Import: `"net"`. ```vex export struct TcpStream ``` An owning connected TCP stream. TcpStream is the canonical AsyncReadWriter implementation. The cancellation-aware overloads below satisfy the contract; context-free overloads remain an explicit zero-overhead convenience for callers that intentionally do not need cancellation propagation. **Implements:** `AsyncReadWriter` & `Drop` ### UdpSocket Import: `"net"`. ```vex export struct UdpSocket ``` **Implements:** `Drop` ### UdpRecvFromResult Import: `"net"`. ```vex export struct UdpRecvFromResult ``` One datagram receive result including its source tuple. `sourceIp` is a zero-terminated IPv4 text buffer; `bytes` never exceeds the caller buffer. **Public fields:** - `bytes`: `usize` - `sourceIp`: `[u8; 64]` - `sourcePort`: `u16` ### UdpDatagram Import: `"net"`. ```vex export struct UdpDatagram ``` Allocation-free modern datagram result. Source address bytes are decoded directly from sockaddr storage and are never round-tripped through text. **Public fields:** - `bytes`: `usize` - `source`: `SocketAddr` ### WsFrame Import: `"net"`. ```vex export struct WsFrame ``` Parsed frame metadata. Payload storage remains owned by the caller's input buffer; this value only carries a zero-copy pointer into it. ### WsFrameStream Import: `"net"`. ```vex export struct WsFrameStream ``` Socket-independent incremental input state for RFC 6455 frames. A frame parser must never equate `recv()` boundaries with frame boundaries. This type retains incomplete headers/payloads and trailing frames, while leaving the transport in charge of readiness, deadlines and I/O ownership. `WsConn` uses it today; Fiber can feed it directly without recreating a second parser or another peer-controlled growable buffer. ### IpFamily Import: `"net"`. ```vex export enum IpFamily ``` **Variants:** - `V4` - `V6` ### AddressParseErrorKind Import: `"net"`. ```vex export enum AddressParseErrorKind ``` **Variants:** - `Empty` - `InvalidSyntax` - `InvalidCharacter` - `OutOfRange` - `MissingPort` ### IpAddr Import: `"net"`. ```vex export enum IpAddr ``` **Variants:** - `V4` - `V6` ### ResolveFamily Import: `"net"`. ```vex export enum ResolveFamily ``` **Variants:** - `Any` - `V4` - `V6` ### ResolveErrorKind Import: `"net"`. ```vex export enum ResolveErrorKind ``` **Variants:** - `InvalidName` - `NotFound` - `TemporaryFailure` - `Unsupported` - `CapacityExceeded` - `System` ### Ipv4Addr Import: `"net"`. ```vex export fn Ipv4Addr(a: u8, b: u8, c: u8, d: u8): Ipv4Addr ``` ### SocketAddr Import: `"net"`. ```vex export fn SocketAddr(address: IpAddr, port: u16): SocketAddr ``` ### readEvent Import: `"net"`. ```vex export fn readEvent(events_base: Ptr, index: i32): Event ``` Read the i-th event from a raw event buffer. Each event is 16 bytes: {fd: i32, flags: i32, userdata: i64}. **Returns:** `Event` ### resolveHostBlocking Import: `"net"`. ```vex export fn resolveHostBlocking(host: str): Result, ResolveError> ``` Resolves a numeric address or DNS hostname through the target system resolver. Results preserve provider order and remove duplicate addresses. This call may block the current operating-system thread. **Returns:** `Result, ResolveError>` ### resolveHostBlocking Import: `"net"`. ```vex export fn resolveHostBlocking(host: str, options: ResolveOptions): Result, ResolveError> ``` **Returns:** `Result, ResolveError>` ### resolveSocketAddrsBlocking Import: `"net"`. ```vex export fn resolveSocketAddrsBlocking(host: str, port: u16): Result, ResolveError> ``` Resolves a hostname and attaches one caller-provided port to every address. **Returns:** `Result, ResolveError>` ### resolveSocketAddrsBlocking Import: `"net"`. ```vex export fn resolveSocketAddrsBlocking(host: str, port: u16, options: ResolveOptions): Result, ResolveError> ``` **Usage contract:** Returns an independent owning vector. Numeric input uses the portable parser; hostname lookup can block the OS thread. This is not an async DNS resolver. **Returns:** `Result, ResolveError>` ### monotonicNs Import: `"net"`. ```vex export fn monotonicNs(): u64 ``` Monotonic clock in nanoseconds. **Returns:** `u64` ### prepareWorkers Import: `"net"`. ```vex export fn prepareWorkers(numWorkers: i32): i32 ``` Ensure the async runtime has enough worker threads ready for server workloads. **Returns:** `i32` ### cpuCount Import: `"net"`. ```vex export fn cpuCount(): i32 ``` Get the number of CPU cores (for multi-worker servers). **Returns:** `i32` ### tcpBlockingFd Import: `"net"`. ```vex export fn tcpBlockingFd(): i64 ``` Create a blocking TCP socket fd. **Returns:** `i64` ### connectFd Import: `"net"`. ```vex export fn connectFd(fd: i64, ip: str, port: u16): i32 ``` Connect an existing fd to ip:port. **Returns:** `i32` ### bindFd Import: `"net"`. ```vex export fn bindFd(fd: i64, ip: str, port: u16): i32 ``` Bind an existing fd to ip:port. **Returns:** `i32` ### listenFd Import: `"net"`. ```vex export fn listenFd(fd: i64, backlog: i32): i32 ``` Listen on an existing fd with backlog. **Returns:** `i32` ### acceptFd Import: `"net"`. ```vex export fn acceptFd(fd: i64): i64 ``` Accept a client fd from a listening fd. **Returns:** `i64` ### setReuseAddrFd Import: `"net"`. ```vex export fn setReuseAddrFd(fd: i64, on: bool): i32 ``` Enable/disable SO_REUSEADDR for a raw fd. **Returns:** `i32` ### setNoDelayFd Import: `"net"`. ```vex export fn setNoDelayFd(fd: i64, on: bool): i32 ``` Enable/disable TCP_NODELAY for a raw fd. **Returns:** `i32` ### recvFd Import: `"net"`. ```vex export fn recvFd(fd: i64, buf: Ptr, len: u64): i64 ``` Receive bytes on a raw fd. **Returns:** `i64` ### sendFd Import: `"net"`. ```vex export fn sendFd(fd: i64, buf: Ptr, len: u64): i64 ``` Send bytes on a raw fd. **Returns:** `i64` ### closeFd Import: `"net"`. ```vex export fn closeFd(fd: i64): i32 ``` Close a raw fd. **Returns:** `i32` ### asyncAcceptFd Import: `"net"`. ```vex export fn asyncAcceptFd(fd: i64): i64 ``` Accept a client fd using non-blocking I/O. Parks goroutine if no connection pending. Returns client fd (pre-set to non-blocking). **Returns:** `i64` ### asyncAcceptFd Import: `"net"`. ```vex export fn asyncAcceptFd(fd: i64, context: &Context): i64 ``` Context-aware accept. The raw cancellation identity is never retained by std/net; VexArch owns it only while the generation-checked wait is armed. **Returns:** `i64` ### asyncRecvFd Import: `"net"`. ```vex export fn asyncRecvFd(fd: i64, buf: Ptr, len: u64): i64 ``` Receive bytes on a raw fd, goroutine-aware. Parks on EAGAIN. **Returns:** `i64` ### asyncRecvFd Import: `"net"`. ```vex export fn asyncRecvFd(fd: i64, buf: Ptr, len: u64, context: &Context): i64 ``` **Returns:** `i64` ### asyncSendFd Import: `"net"`. ```vex export fn asyncSendFd(fd: i64, buf: Ptr, len: u64): i64 ``` Send bytes on a raw fd, goroutine-aware. Parks on EAGAIN. Ensures all bytes are written (handles partial writes). **Returns:** `i64` ### asyncSendFd Import: `"net"`. ```vex export fn asyncSendFd(fd: i64, buf: Ptr, len: u64, context: &Context): i64 ``` **Returns:** `i64` ### setNonBlockFd Import: `"net"`. ```vex export fn setNonBlockFd(fd: i64): i32 ``` Set a socket to non-blocking mode. **Returns:** `i32` ### parseFrame Import: `"net"`. ```vex export fn parseFrame(buf: Ptr, len: u64, frame: &WsFrame!, consumed: &u64!): i32 ``` Parse one complete frame without copying its payload. On `WS_OK`, `frame.payload()` borrows `buf` and `consumed` is the exact frame size. On failure, output parameters are left unchanged. **Returns:** `i32` ### encodeFrameHeader Import: `"net"`. ```vex export fn encodeFrameHeader(buf: Ptr, bufLen: u64, opcode: u8, payloadLen: u64): u64 ``` Encode an unmasked server frame header into caller-owned storage. The returned header length is 2, 4, or 10. Keeping this separate from payload copying lets transports perform bounded write-all without a temporary frame-sized allocation; `encodeFrame` below remains the contiguous-buffer convenience adapter. **Returns:** `u64` ### encodeFrame Import: `"net"`. ```vex export fn encodeFrame(buf: Ptr, bufLen: u64, opcode: u8, payload: Ptr, payloadLen: u64, written: &u64!): i32 ``` Encode one unmasked server frame into caller-owned contiguous storage. **Returns:** `i32` ### encodeText Import: `"net"`. ```vex export fn encodeText(buf: Ptr, bufLen: u64, text: Ptr, textLen: u64, written: &u64!): i32 ``` **Returns:** `i32` ### encodeClose Import: `"net"`. ```vex export fn encodeClose(buf: Ptr, bufLen: u64, code: u16, written: &u64!): i32 ``` **Returns:** `i32` ### encodePing Import: `"net"`. ```vex export fn encodePing(buf: Ptr, bufLen: u64, written: &u64!): i32 ``` **Returns:** `i32` ### encodePong Import: `"net"`. ```vex export fn encodePong(buf: Ptr, bufLen: u64, payload: Ptr, payloadLen: u64, written: &u64!): i32 ``` **Returns:** `i32` ### isControlFrame Import: `"net"`. ```vex export fn isControlFrame(opcode: u8): bool ``` **Returns:** `bool` ### isDataFrame Import: `"net"`. ```vex export fn isDataFrame(opcode: u8): bool ``` **Returns:** `bool` ### IpFamily.op ```vex export fn (self: &IpFamily) op==(other: &IpFamily): bool ``` **Returns:** `bool` ### AddressFormatError.required ```vex export fn (self: &AddressFormatError) required(): usize ``` **Returns:** `usize` ### AddressFormatError.capacity ```vex export fn (self: &AddressFormatError) capacity(): usize ``` **Returns:** `usize` ### AddressFormatError.message ```vex export fn (self: &AddressFormatError) message(): str ``` **Returns:** `str` ### AddressParseError.kind ```vex export fn (self: &AddressParseError) kind(): AddressParseErrorKind ``` **Returns:** `AddressParseErrorKind` ### AddressParseError.position ```vex export fn (self: &AddressParseError) position(): usize ``` **Returns:** `usize` ### AddressParseError.message ```vex export fn (self: &AddressParseError) message(): str ``` **Returns:** `str` ### Ipv4Addr.unspecified ```vex export fn Ipv4Addr.unspecified(): Ipv4Addr ``` **Returns:** `Ipv4Addr` ### Ipv4Addr.loopback ```vex export fn Ipv4Addr.loopback(): Ipv4Addr ``` **Returns:** `Ipv4Addr` ### Ipv4Addr.octets ```vex export fn (self: &Ipv4Addr) octets(): [u8; 4] ``` **Returns:** `[u8; 4]` ### Ipv4Addr.family ```vex export fn (self: &Ipv4Addr) family(): IpFamily ``` **Returns:** `IpFamily` ### Ipv4Addr.isUnspecified ```vex export fn (self: &Ipv4Addr) isUnspecified(): bool ``` **Returns:** `bool` ### Ipv4Addr.isLoopback ```vex export fn (self: &Ipv4Addr) isLoopback(): bool ``` **Returns:** `bool` ### Ipv4Addr.op ```vex export fn (self: &Ipv4Addr) op==(other: &Ipv4Addr): bool ``` **Returns:** `bool` ### Ipv4Addr.copyOctetsTo ```vex export fn (self: &Ipv4Addr) copyOctetsTo(output: Ptr): bool ``` Copies exactly four network-order octets to a native boundary. **Returns:** `bool` ### Ipv6Addr.fromOctets ```vex export fn Ipv6Addr.fromOctets(bytes: [u8; 16]): Ipv6Addr ``` **Returns:** `Ipv6Addr` ### Ipv6Addr.unspecified ```vex export fn Ipv6Addr.unspecified(): Ipv6Addr ``` **Returns:** `Ipv6Addr` ### Ipv6Addr.loopback ```vex export fn Ipv6Addr.loopback(): Ipv6Addr ``` **Returns:** `Ipv6Addr` ### Ipv6Addr.octets ```vex export fn (self: &Ipv6Addr) octets(): [u8; 16] ``` **Returns:** `[u8; 16]` ### Ipv6Addr.family ```vex export fn (self: &Ipv6Addr) family(): IpFamily ``` **Returns:** `IpFamily` ### Ipv6Addr.segments ```vex export fn (self: &Ipv6Addr) segments(): [u16; 8] ``` **Returns:** `[u16; 8]` ### Ipv6Addr.isUnspecified ```vex export fn (self: &Ipv6Addr) isUnspecified(): bool ``` **Returns:** `bool` ### Ipv6Addr.isLoopback ```vex export fn (self: &Ipv6Addr) isLoopback(): bool ``` **Returns:** `bool` ### Ipv6Addr.op ```vex export fn (self: &Ipv6Addr) op==(other: &Ipv6Addr): bool ``` **Returns:** `bool` ### Ipv6Addr.copyOctetsTo ```vex export fn (self: &Ipv6Addr) copyOctetsTo(output: Ptr): bool ``` Copies exactly sixteen network-order octets to a native boundary. **Returns:** `bool` ### IpAddr.family ```vex export fn (self: &IpAddr) family(): IpFamily ``` **Returns:** `IpFamily` ### IpAddr.isUnspecified ```vex export fn (self: &IpAddr) isUnspecified(): bool ``` **Returns:** `bool` ### IpAddr.isLoopback ```vex export fn (self: &IpAddr) isLoopback(): bool ``` **Returns:** `bool` ### IpAddr.op ```vex export fn (self: &IpAddr) op==(other: &IpAddr): bool ``` **Returns:** `bool` ### IpAddr.copyOctetsTo ```vex export fn (self: &IpAddr) copyOctetsTo(output: Ptr): bool ``` Copies the address into a sixteen-byte carrier. IPv4 uses the first four bytes; callers select the valid width through `family()`. **Returns:** `bool` ### SocketAddr.address ```vex export fn (self: &SocketAddr) address(): IpAddr ``` **Returns:** `IpAddr` ### SocketAddr.port ```vex export fn (self: &SocketAddr) port(): u16 ``` **Returns:** `u16` ### SocketAddr.family ```vex export fn (self: &SocketAddr) family(): IpFamily ``` **Returns:** `IpFamily` ### SocketAddr.op ```vex export fn (self: &SocketAddr) op==(other: &SocketAddr): bool ``` **Returns:** `bool` ### Ipv4Addr.tryParse ```vex export fn Ipv4Addr.tryParse(input: str): Result ``` **Returns:** `Result` ### Ipv6Addr.tryParse ```vex export fn Ipv6Addr.tryParse(input: str): Result ``` **Returns:** `Result` ### IpAddr.tryParse ```vex export fn IpAddr.tryParse(input: str): Result ``` **Returns:** `Result` ### SocketAddr.tryParse ```vex export fn SocketAddr.tryParse(input: str): Result ``` **Returns:** `Result` ### Ipv4Addr.textLength ```vex export fn (self: &Ipv4Addr) textLength(): usize ``` Exact canonical text length without allocating. **Returns:** `usize` ### Ipv6Addr.textLength ```vex export fn (self: &Ipv6Addr) textLength(): usize ``` Exact canonical text length without allocating. **Returns:** `usize` ### IpAddr.textLength ```vex export fn (self: &IpAddr) textLength(): usize ``` Exact canonical text length without allocating. **Returns:** `usize` ### SocketAddr.textLength ```vex export fn (self: &SocketAddr) textLength(): usize ``` Exact canonical socket-address text length without allocating. **Returns:** `usize` ### Ipv4Addr.tryWriteTo ```vex export fn (self: &Ipv4Addr) tryWriteTo(output: RawBuf, capacity: usize): Result ``` Write canonical text into caller-owned storage. Capacity is validated before the first store, so failure never publishes a partial address. **Returns:** `Result` ### Ipv6Addr.tryWriteTo ```vex export fn (self: &Ipv6Addr) tryWriteTo(output: RawBuf, capacity: usize): Result ``` Write canonical text into caller-owned storage. Capacity is validated before the first store, so failure never publishes a partial address. **Returns:** `Result` ### IpAddr.tryWriteTo ```vex export fn (self: &IpAddr) tryWriteTo(output: RawBuf, capacity: usize): Result ``` Write canonical text into caller-owned storage. Capacity is validated before the first store, so failure never publishes a partial address. **Returns:** `Result` ### SocketAddr.tryWriteTo ```vex export fn (self: &SocketAddr) tryWriteTo(output: RawBuf, capacity: usize): Result ``` **Usage contract:** Returns the initialized byte count, without a terminator. Insufficient capacity reports required/capacity before any store. Raw-buffer allocation extent and lifetime remain caller obligations; appendTo is the owning-Vec alternative. Write canonical text into caller-owned storage. Capacity is validated before the first store, so failure never publishes a partial endpoint. **Returns:** `Result` ### Ipv4Addr.appendTo ```vex export fn !(self: &Ipv4Addr) appendTo(output: &Vec!): usize ``` Append canonical text to an owning byte vector. The vector is the safe high-level reuse API; reserve once to keep repeated formatting allocation- free. Existing bytes are preserved and the exact appended count is returned. **Returns:** `usize` ### Ipv6Addr.appendTo ```vex export fn !(self: &Ipv6Addr) appendTo(output: &Vec!): usize ``` Append canonical text to an owning byte vector. **Returns:** `usize` ### IpAddr.appendTo ```vex export fn !(self: &IpAddr) appendTo(output: &Vec!): usize ``` Append canonical text to an owning byte vector. **Returns:** `usize` ### SocketAddr.appendTo ```vex export fn !(self: &SocketAddr) appendTo(output: &Vec!): usize ``` Append canonical endpoint text to an owning byte vector. **Returns:** `usize` ### Ipv4Addr.toString ```vex export fn (self: &Ipv4Addr) toString(): string ``` **Returns:** `string` ### Ipv4Addr.debug ```vex export fn (self: &Ipv4Addr) debug(): string ``` **Returns:** `string` ### Ipv6Addr.toString ```vex export fn (self: &Ipv6Addr) toString(): string ``` **Returns:** `string` ### Ipv6Addr.debug ```vex export fn (self: &Ipv6Addr) debug(): string ``` **Returns:** `string` ### IpAddr.toString ```vex export fn (self: &IpAddr) toString(): string ``` **Returns:** `string` ### IpAddr.debug ```vex export fn (self: &IpAddr) debug(): string ``` **Returns:** `string` ### SocketAddr.toString ```vex export fn (self: &SocketAddr) toString(): string ``` **Returns:** `string` ### SocketAddr.debug ```vex export fn (self: &SocketAddr) debug(): string ``` **Returns:** `string` ### Conn.wrap ```vex export fn Conn.wrap(fd: i64): Conn ``` Wrap a raw fd into a buffered connection. **Returns:** `Conn` ### Conn.wrapBorrowed ```vex export fn Conn.wrapBorrowed(fd: i64): Conn ``` Wrap a descriptor without taking ownership of it. This is intended for adapters whose outer object owns the descriptor. The returned connection still tracks an explicit close state but Drop will not close the borrowed descriptor. **Returns:** `Conn` ### Conn.wrapWithLimits ```vex export fn Conn.wrapWithLimits(fd: i64, readLimit: usize, writeLimit: usize): Conn ``` Wrap an owned descriptor with explicit bounded input/output queues. **Returns:** `Conn` ### Conn.wrapBorrowedWithLimits ```vex export fn Conn.wrapBorrowedWithLimits(fd: i64, readLimit: usize, writeLimit: usize): Conn ``` Borrow a descriptor with explicit bounded input/output queues. **Returns:** `Conn` ### Conn.wrapBorrowedWithBuffering ```vex export fn Conn.wrapBorrowedWithBuffering(fd: i64, readLimit: usize, writeLimit: usize, initialRead: usize, initialWrite: usize): Conn ``` Borrow a descriptor with explicit queue limits and initial allocations. Long-lived mostly-idle protocols (for example WebSocket) use this to avoid paying HTTP's larger warm buffers per connection while retaining identical geometric growth and hard safety ceilings under traffic. **Returns:** `Conn` ### Conn.buffered ```vex export fn Conn.buffered(readLimit: usize, writeLimit: usize): Conn ``` Create queue-only transport storage. It owns no descriptor, so `recv` and `flush` fail closed; adapters can still stage/read/consume safely. **Returns:** `Conn` ### Conn.rawFd ```vex export fn (self: &Conn) rawFd(): i64 ``` The wrapped descriptor. Ownership remains with this connection unless it was created with `wrapBorrowed`. **Returns:** `i64` ### Conn.isClosed ```vex export fn (self: &Conn) isClosed(): bool ``` **Returns:** `bool` ### Conn.readable ```vex export fn (self: &Conn) readable(): usize ``` Number of unread bytes available in the buffer. **Returns:** `usize` ### Conn.readPtr ```vex export fn (self: &Conn) readPtr(): Ptr ``` Pointer to start of unread data. **Returns:** `Ptr` ### Conn.readTailSpace ```vex export fn (self: &Conn) readTailSpace(): usize ``` Physical writable bytes currently available at the input tail. Callers that need a minimum must use `ensureReadSpace` first; this accessor is only for sizing the immediate transport read after that reservation succeeds. **Returns:** `usize` ### Conn.ensureReadSpace ```vex export fn (self: &Conn!) ensureReadSpace(required: usize): bool ``` Reserve contiguous tail space for an outer non-blocking transport read. This preserves the same bounded/compacting behavior as `stageRead` without forcing a second copy through a temporary socket buffer. **Returns:** `bool` ### Conn.readWritePtr ```vex export fn (self: &Conn!) readWritePtr(): Ptr ``` Writable tail after `ensureReadSpace` succeeds. **Returns:** `Ptr` ### Conn.commitRead ```vex export fn (self: &Conn!) commitRead(count: usize): bool ``` Commit bytes written through `readWritePtr`. Counts beyond reserved free space are rejected with no state change. **Returns:** `bool` ### Conn.stageRead ```vex export fn (self: &Conn!) stageRead(data: Ptr, len: usize): bool ``` Append bytes that were obtained by an outer transport layer (for example a TLS record decoder) to the readable queue. The append is all-or-nothing and never grows beyond the connection's fixed safety limit. **Returns:** `bool` ### Conn.recv ```vex export fn (self: &Conn!) recv(): i64 ``` Read from socket into the read buffer. Returns bytes read (>0), 0 = EOF, <0 = error/EAGAIN. **Returns:** `i64` ### Conn.consume ```vex export fn (self: &Conn!) consume(n: usize): bool ``` Consume `n` bytes from the read buffer. Returns false without mutation when `n` exceeds the readable range. **Returns:** `bool` ### Conn.consume ```vex export fn (self: &Conn!) consume(n: i32): bool ``` **Returns:** `bool` ### Conn.compactRead ```vex export fn (self: &Conn!) compactRead() ``` Compact read buffer — shift unread data to front. **Receiver:** `self: &Conn!` *(mutable reference)* ### Conn.findHeaderEnd ```vex export fn (self: &Conn) findHeaderEnd(): i32 ``` Scan read buffer for \r\n\r\n (HTTP header terminator). Returns offset past \r\n\r\n relative to rpos, or -1 if not found. **Returns:** `i32` ### Conn.write ```vex export fn (self: &Conn!) write(data: Ptr, len: i32): i32 ``` Write data to the write buffer. Does NOT send to socket yet. Call flush() to actually send. **Returns:** `i32` ### Conn.stageWrite ```vex export fn (self: &Conn!) stageWrite(data: Ptr, len: usize): bool ``` Queue bytes without attempting a socket write. This is useful for framed transports that coalesce output before registering writable interest. **Returns:** `bool` ### Conn.flush ```vex export fn (self: &Conn!) flush(): i64 ``` Flush write buffer to socket. Returns total bytes sent, or <0 on error. **Returns:** `i64` ### Conn.hasPendingWrite ```vex export fn (self: &Conn) hasPendingWrite(): bool ``` Check if there's unsent data in the write buffer. **Returns:** `bool` ### Conn.pendingWriteBytes ```vex export fn (self: &Conn) pendingWriteBytes(): usize ``` **Returns:** `usize` ### Conn.copyPendingWriteTo ```vex export fn (self: &Conn) copyPendingWriteTo(out: &str!): usize ``` Copy the complete pending output prefix without exposing mutable queue storage. This is primarily a transport-adapter/testing seam; short output is rejected atomically so callers never mistake a truncated logical frame for the queued record. **Returns:** `usize` ### Conn.writeAvailable ```vex export fn (self: &Conn) writeAvailable(): usize ``` Remaining bounded output capacity. Framed transports use this to reserve a whole logical record before enqueueing its header, preventing a full queue from leaving an orphaned frame prefix on the wire. **Returns:** `usize` ### Conn.close ```vex export fn (self: &Conn!) close() ``` Close the connection and fd. **Receiver:** `self: &Conn!` *(mutable reference)* ### Conn.drop ```vex export fn (self: &Conn!) drop() ``` **Receiver:** `self: &Conn!` *(mutable reference)* ### Conn.reset ```vex export fn (self: &Conn!) reset() ``` Reset for keep-alive reuse (zero alloc). **Receiver:** `self: &Conn!` *(mutable reference)* ### EventLoop.new ```vex export fn EventLoop.new(): EventLoop ``` Create a new event loop. Check isValid() after creation. **Returns:** `EventLoop` ### EventLoop.isValid ```vex export fn (self: &EventLoop) isValid(): bool ``` Check if the event loop was created successfully. **Returns:** `bool` ### EventLoop.register ```vex export fn (self: &EventLoop!) register(fd: i32, events: i32): i32 ``` Register an fd for events (EVT_READ, EVT_WRITE, or both). **Returns:** `i32` ### EventLoop.modify ```vex export fn (self: &EventLoop!) modify(fd: i32, events: i32): i32 ``` Modify the events monitored for an fd. **Returns:** `i32` ### EventLoop.unregister ```vex export fn (self: &EventLoop!) unregister(fd: i32): i32 ``` Unregister an fd from the event loop. **Returns:** `i32` ### EventLoop.poll ```vex export fn (self: &EventLoop!) poll(out: Ptr, cap: i32, timeout_ms: i32): i32 ``` Poll for events. Returns number of ready events. Events are written to `out` buffer (each event = 16 bytes). `cap` is max number of events. `timeout_ms` = -1 for blocking. Event layout in buffer (per 16 bytes): [0..4) i32 fd [4..8) i32 flags (EVT_READ | EVT_WRITE | EVT_HUP | EVT_ERR) [8..16) i64 userdata **Returns:** `i32` ### EventLoop.close ```vex export fn (self: &EventLoop!) close() ``` Close the event loop. **Receiver:** `self: &EventLoop!` *(mutable reference)* ### EventLoop.drop ```vex export fn (self: &EventLoop!) drop() ``` **Receiver:** `self: &EventLoop!` *(mutable reference)* ### ResolveError.kind ```vex export fn (self: &ResolveError) kind(): ResolveErrorKind ``` **Returns:** `ResolveErrorKind` ### ResolveError.nativeCode ```vex export fn (self: &ResolveError) nativeCode(): i32 ``` **Returns:** `i32` ### ResolveError.message ```vex export fn (self: &ResolveError) message(): str ``` **Returns:** `str` ### ResolveError.toString ```vex export fn (self: &ResolveError) toString(): string ``` **Returns:** `string` ### ResolveError.debug ```vex export fn (self: &ResolveError) debug(): string ``` **Returns:** `string` ### ResolveOptions.default ```vex export fn ResolveOptions.default(): ResolveOptions ``` **Returns:** `ResolveOptions` ### ResolveOptions.new ```vex export fn ResolveOptions.new(family: ResolveFamily, maxResults: usize): ResolveOptions ``` **Returns:** `ResolveOptions` ### ResolveOptions.family ```vex export fn (self: &ResolveOptions) family(): ResolveFamily ``` **Returns:** `ResolveFamily` ### ResolveOptions.maxResults ```vex export fn (self: &ResolveOptions) maxResults(): usize ``` **Returns:** `usize` ### Socket.tcp ```vex export fn Socket.tcp(): Socket ``` Create a non-blocking TCP socket. **Returns:** `Socket` ### Socket.tcpBlocking ```vex export fn Socket.tcpBlocking(): Socket ``` Create a blocking TCP socket. **Returns:** `Socket` ### Socket.udp ```vex export fn Socket.udp(): Socket ``` Create a UDP socket. **Returns:** `Socket` ### Socket.setReuseAddr ```vex export fn (self: &Socket!) setReuseAddr(on: bool) ``` Enable/disable SO_REUSEADDR. ### Socket.setReusePort ```vex export fn (self: &Socket!) setReusePort(on: bool) ``` Enable/disable SO_REUSEPORT (for multi-threaded accept). ### Socket.setNonBlock ```vex export fn (self: &Socket!) setNonBlock(on: bool) ``` Enable/disable O_NONBLOCK. ### Socket.setNoDelay ```vex export fn (self: &Socket!) setNoDelay(on: bool) ``` Enable/disable TCP_NODELAY (Nagle's algorithm off). ### Socket.setNoPush ```vex export fn (self: &Socket!) setNoPush(on: bool) ``` Enable/disable TCP_NOPUSH (macOS/BSD) / TCP_CORK (Linux). Coalesces small writes into full TCP segments. ### Socket.bind ```vex export fn (self: &Socket) bind(ip: str, port: u16): i32 ``` Bind socket to ip:port. Returns 0 on success, negative on error. **Returns:** `i32` ### Socket.listen ```vex export fn (self: &Socket) listen(backlog: i32): i32 ``` Start listening with given backlog. Returns 0 on success. **Returns:** `i32` ### Socket.connect ```vex export fn (self: &Socket) connect(ip: str, port: u16): i32 ``` Connect to remote ip:port. Returns 0 on success. **Returns:** `i32` ### Socket.accept ```vex export fn (self: &Socket) accept(): Socket ``` Accept a new connection. Returns a Socket with the client fd. fd < 0 means no connection available (EAGAIN on non-blocking). **Returns:** `Socket` ### Socket.recv ```vex export fn (self: &Socket) recv(buf: Ptr, len: u64): i64 ``` Read into buffer. Returns bytes read, 0 on EOF, negative on error/EAGAIN. **Returns:** `i64` ### Socket.send ```vex export fn (self: &Socket) send(buf: Ptr, len: u64): i64 ``` Write bytes. Returns bytes written or negative on error/EAGAIN. **Returns:** `i64` ### Socket.close ```vex export fn (self: &Socket!) close() ``` Close the socket. **Receiver:** `self: &Socket!` *(mutable reference)* ### Socket.takeHandle ```vex export fn (self: &Socket!) takeHandle(): i64 ``` Transfer ownership of the native handle out of this Socket. The returned handle must be adopted by another owner or explicitly closed. Drop becomes a no-op after the transfer. **Returns:** `i64` ### Socket.drop ```vex export fn (self: &Socket!) drop() ``` **Receiver:** `self: &Socket!` *(mutable reference)* ### Socket.isValid ```vex export fn (self: &Socket) isValid(): bool ``` Check if socket is valid. **Returns:** `bool` ### TcpListener.bind ```vex export fn TcpListener.bind(ip: str, port: u16): Result ``` Creates a non-blocking listener and completes all socket setup atomically. Any failed setup step closes the native handle before returning its exact canonical OS error. **Returns:** `Result` ### TcpListener.bind ```vex export fn TcpListener.bind(endpoint: SocketAddr): Result ``` Creates a listener from a typed IPv4 or IPv6 endpoint. Address text parsing is outside the native boundary and never repeated by the OS provider. **Returns:** `Result` ### TcpListener.accept ```vex export async fn (self: &TcpListener) accept(): Result ``` Accepts one connection, parking the current Vex task while the listener is not ready. Accepted sockets are explicitly made non-blocking because Unix does not portably inherit that flag from the listener. **Returns:** `Result` ### TcpListener.accept ```vex export async fn (self: &TcpListener) accept(context: &Context): Result ``` Accepts with cancellation/deadline propagation into the native wait registration. Context-free accept remains a separate zero-overhead path. **Returns:** `Result` ### TcpListener.rawHandle ```vex export fn (self: &TcpListener) rawHandle(): i64 ``` Returns the platform-width native socket handle for poller integration. **Returns:** `i64` ### TcpListener.isOpen ```vex export fn (self: &TcpListener) isOpen(): bool ``` **Returns:** `bool` ### TcpListener.localAddr ```vex export fn (self: &TcpListener) localAddr(): Result ``` Returns the endpoint selected by the OS. This is authoritative when bind used port zero and does not format or reparse address text. **Returns:** `Result` ### TcpListener.close ```vex export fn (self: &TcpListener!) close(): Result<(), IoError> ``` Closes exactly once. The local handle is invalidated before entering the OS because retrying a failed close can target a newly reused descriptor. **Returns:** `Result<(), IoError>` ### TcpListener.drop ```vex export fn (self: &TcpListener!) drop() ``` **Receiver:** `self: &TcpListener!` *(mutable reference)* ### TcpStream.adopt ```vex export fn TcpStream.adopt(socket: &Socket!): Result ``` Adopt an already-connected `Socket` into the canonical task-aware stream abstraction. This consumes the socket's ownership; after a successful call its Drop is inert and the returned `TcpStream` is the only closer. Event-loop users must unregister the descriptor before adoption. The method deliberately accepts `Socket`, not an integer handle, so callers cannot accidentally create two owning wrappers for the same native descriptor. The adopted handle is normalized to the same non-blocking + TCP_NODELAY contract used by connect and accept paths. On setup failure it is closed, never returned as a partially initialized stream. **Returns:** `Result` ### TcpStream.connect ```vex export async fn TcpStream.connect(ip: str, port: u16): Result ``` Establishes a task-aware non-blocking connection without exposing a partially initialized stream. Readiness backends park on writable and validate SO_ERROR; Windows completes through ConnectEx/IOCP. **Returns:** `Result` ### TcpStream.connect ```vex export async fn TcpStream.connect(endpoint: SocketAddr): Result ``` **Returns:** `Result` ### TcpStream.connect ```vex export async fn TcpStream.connect( ip: str, port: u16, context: &Context, ): Result ``` **Returns:** `Result` ### TcpStream.connect ```vex export async fn TcpStream.connect( endpoint: SocketAddr, context: &Context, ): Result ``` **Usage contract:** Await the result. Success transfers one owning non-blocking TcpStream; failure returns IoError. DNS is separate and resolveSocketAddrsBlocking must not be hidden inside a latency-sensitive scheduler task. **Returns:** `Result` ### TcpStream.connectBlocking ```vex export fn TcpStream.connectBlocking(ip: str, port: u16): Result ``` Explicit blocking connection establishment for synchronous bootstrap code. The returned stream is switched to the same non-blocking I/O contract as `connect`; application request paths should prefer the async default. **Returns:** `Result` ### TcpStream.connectBlocking ```vex export fn TcpStream.connectBlocking(endpoint: SocketAddr): Result ``` **Returns:** `Result` ### TcpStream.read ```vex export async fn (self: &TcpStream) read(buf: Ptr, len: usize): Result ``` Reads at most `len` bytes, parking the current task on temporary blocking. `Ok(0)` is an orderly peer shutdown. **Returns:** `Result` ### TcpStream.read ```vex export async fn (self: &TcpStream) read( buf: Ptr, len: usize, context: &Context, ): Result ``` **Usage contract:** The task may park until progress, cancellation or deadline. For a non-empty read, Ok(0) is orderly EOF. Null/count checks do not prove backing allocation extent or exclusivity; keep the destination valid for the entire awaited operation. **Returns:** `Result` ### TcpStream.write ```vex export async fn (self: &TcpStream) write(data: Ptr, len: usize): Result ``` Writes at most `len` bytes, parking the current task on temporary blocking. **Returns:** `Result` ### TcpStream.write ```vex export async fn (self: &TcpStream) write( data: Ptr, len: usize, context: &Context, ): Result ``` **Returns:** `Result` ### TcpStream.writeAll ```vex export async fn (self: &TcpStream) writeAll(data: Ptr, len: usize): Result<(), IoError> ``` Writes the complete buffer or returns without losing the unwritten tail. **Returns:** `Result<(), IoError>` ### TcpStream.writeAll ```vex export async fn (self: &TcpStream) writeAll( data: Ptr, len: usize, context: &Context, ): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### TcpStream.writeStr ```vex export async fn (self: &TcpStream) writeStr(value: str): Result ``` **Returns:** `Result` ### TcpStream.writeStr ```vex export async fn (self: &TcpStream) writeStr( value: str, context: &Context, ): Result ``` **Returns:** `Result` ### TcpStream.writeAllStr ```vex export async fn (self: &TcpStream) writeAllStr(value: str): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### TcpStream.writeAllStr ```vex export async fn (self: &TcpStream) writeAllStr( value: str, context: &Context, ): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### TcpStream.rawHandle ```vex export fn (self: &TcpStream) rawHandle(): i64 ``` **Returns:** `i64` ### TcpStream.isOpen ```vex export fn (self: &TcpStream) isOpen(): bool ``` **Returns:** `bool` ### TcpStream.localAddr ```vex export fn (self: &TcpStream) localAddr(): Result ``` **Returns:** `Result` ### TcpStream.peerAddr ```vex export fn (self: &TcpStream) peerAddr(): Result ``` **Returns:** `Result` ### TcpStream.close ```vex export fn (self: &TcpStream!) close(): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### TcpStream.drop ```vex export fn (self: &TcpStream!) drop() ``` **Receiver:** `self: &TcpStream!` *(mutable reference)* ### UdpSocket.bind ```vex export fn UdpSocket.bind(ip: str, port: u16): Result ``` Creates and binds an owning UDP socket. Setup failure cannot leak a native handle and preserves the normalized OS error. **Returns:** `Result` ### UdpSocket.bind ```vex export fn UdpSocket.bind(endpoint: SocketAddr): Result ``` **Returns:** `Result` ### UdpSocket.sendTo ```vex export fn (self: &UdpSocket) sendTo(data: Ptr, len: usize, ip: str, port: u16): Result ``` **Returns:** `Result` ### UdpSocket.sendTo ```vex export fn (self: &UdpSocket) sendTo(data: Ptr, len: usize, endpoint: SocketAddr): Result ``` **Returns:** `Result` ### UdpSocket.sendTo ```vex export async fn (self: &UdpSocket) sendTo( data: Ptr, len: usize, ip: str, port: u16, context: &Context, ): Result ``` Sends one datagram while propagating Context cancellation/deadline into the same generation-owned runtime operation used by TCP. The datagram is never split across resumptions. **Returns:** `Result` ### UdpSocket.sendTo ```vex export async fn (self: &UdpSocket) sendTo( data: Ptr, len: usize, endpoint: SocketAddr, context: &Context, ): Result ``` **Returns:** `Result` ### UdpSocket.recvFrom ```vex export fn (self: &UdpSocket) recvFrom(buf: Ptr, len: usize): Result ``` **Returns:** `Result` ### UdpSocket.recvFrom ```vex export async fn (self: &UdpSocket) recvFrom( buf: Ptr, len: usize, context: &Context, ): Result ``` **Returns:** `Result` ### UdpSocket.recvDatagram ```vex export fn (self: &UdpSocket) recvDatagram(buf: Ptr, len: usize): Result ``` **Returns:** `Result` ### UdpSocket.recvDatagram ```vex export async fn (self: &UdpSocket) recvDatagram( buf: Ptr, len: usize, context: &Context, ): Result ``` **Returns:** `Result` ### UdpSocket.recvFromWithSource ```vex export fn (self: &UdpSocket) recvFromWithSource(buf: Ptr, len: usize): Result ``` **Returns:** `Result` ### UdpSocket.recvFromWithSource ```vex export async fn (self: &UdpSocket) recvFromWithSource( buf: Ptr, len: usize, context: &Context, ): Result ``` **Returns:** `Result` ### UdpSocket.setNonBlock ```vex export fn (self: &UdpSocket!) setNonBlock(on: bool): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### UdpSocket.rawHandle ```vex export fn (self: &UdpSocket) rawHandle(): i64 ``` **Returns:** `i64` ### UdpSocket.isOpen ```vex export fn (self: &UdpSocket) isOpen(): bool ``` **Returns:** `bool` ### UdpSocket.localAddr ```vex export fn (self: &UdpSocket) localAddr(): Result ``` Returns the actual bound endpoint, including the ephemeral port selected for a port-zero bind. **Returns:** `Result` ### UdpSocket.close ```vex export fn (self: &UdpSocket!) close(): Result<(), IoError> ``` **Returns:** `Result<(), IoError>` ### UdpSocket.drop ```vex export fn (self: &UdpSocket!) drop() ``` **Receiver:** `self: &UdpSocket!` *(mutable reference)* ### WsFrame.empty ```vex export fn WsFrame.empty(): WsFrame ``` **Returns:** `WsFrame` ### WsFrameStream.new ```vex export fn WsFrameStream.new(): WsFrameStream ``` **Returns:** `WsFrameStream` ### WsFrameStream.pending ```vex export fn (self: &WsFrameStream) pending(): usize ``` Number of bytes not yet consumed by a parsed frame. **Returns:** `usize` ### WsFrameStream.readPtr ```vex export fn (self: &WsFrameStream) readPtr(): Ptr ``` Start of unread storage. Valid even when `pending() == 0` so callers can pass it directly to `parseNext` without a special empty-buffer path. **Returns:** `Ptr` ### WsFrameStream.writePtr ```vex export fn (self: &WsFrameStream!) writePtr(): Ptr ``` Tail storage for one transport read after `ensureFree` succeeds. **Returns:** `Ptr` ### WsFrameStream.freeSpace ```vex export fn (self: &WsFrameStream) freeSpace(): usize ``` Physical writable tail after a successful `ensureFree` reservation. **Returns:** `usize` ### WsFrameStream.ensureFree ```vex export fn (self: &WsFrameStream!) ensureFree(required: usize): bool ``` Ensure at least `required` contiguous bytes at the writable tail. The request is checked against unread bytes before growing, so a malicious peer cannot force allocation beyond the shared hard ceiling. **Returns:** `bool` ### WsFrameStream.advance ```vex export fn (self: &WsFrameStream!) advance(count: usize): bool ``` Commit bytes written by the transport. Invalid counts are rejected rather than allowing a buggy adapter to move the parser past its allocation. **Returns:** `bool` ### WsFrameStream.feed ```vex export fn (self: &WsFrameStream!) feed(data: Ptr, len: usize): bool ``` Copy a caller-owned chunk into the stream. Event-loop adapters may instead use `ensureFree` + `writePtr` + `advance` to receive without this copy. **Returns:** `bool` ### WsFrameStream.parseNext ```vex export fn (self: &WsFrameStream) parseNext(frame: &WsFrame!, consumed: &u64!): i32 ``` Parse the next complete frame. Frame payload storage remains owned by this stream until `consume` is called; on NEED_MORE or error no state advances. **Returns:** `i32` ### WsFrameStream.consume ```vex export fn (self: &WsFrameStream!) consume(count: usize): bool ``` Release the exact bytes reported by a successful `parseNext` call. **Returns:** `bool` ### WsFrame.fin ```vex export fn (self: &WsFrame) fin(): bool ``` **Returns:** `bool` ### WsFrame.opcode ```vex export fn (self: &WsFrame) opcode(): u8 ``` **Returns:** `u8` ### WsFrame.masked ```vex export fn (self: &WsFrame) masked(): bool ``` **Returns:** `bool` ### WsFrame.payloadLen ```vex export fn (self: &WsFrame) payloadLen(): u64 ``` **Returns:** `u64` ### WsFrame.payload ```vex export fn (self: &WsFrame) payload(): Ptr ``` **Returns:** `Ptr` ### WsFrame.unmaskPayload ```vex export fn (self: &WsFrame) unmaskPayload(data: Ptr, len: u64): bool ``` XOR this frame's masking key into caller-owned payload storage. Keeping the key access inside `WsFrame` avoids exporting an interior raw pointer whose validity would otherwise be tied to the frame borrow. The operation rejects ranges outside the parsed payload before touching memory. Fixed 16-byte values are Vex's portable inline-SIMD representation; target lowering selects the native CPU/GPU vector implementation. --- --- *Generated by vex-doc v2.0 • 2026-10-28* --- Source: https://vex-lang.org/docs/std/rand.md # rand — explicit, fast random streams `rand` provides independently owned `Rng` values based on xoshiro256**. It is intended for simulation, randomized algorithms, games, sampling and tests. It has no hidden global generator. `Rng4` is the explicit parallel companion: four canonical jump-separated streams evaluated with Vex fixed-array SIMD operators. Scalar `Rng` ordering is never silently changed for throughput. ```vex import { Rng } from "rand" let! replayable = Rng.withSeed(42) let! independentlySeeded = Rng.init() let word = replayable.nextU64() let ratio = replayable.nextFloat() // [0.0, 1.0) let index = replayable.nextRange(0, 100) // [0, 100) ``` `Rng.init()` seeds from the target's fail-closed `Crypto.secureRand()` capability. xoshiro output remains non-cryptographic: use the crypto API itself for keys, tokens, nonces and secrets. Randomness alone does not guarantee a unique AEAD nonce; see the [AEAD nonce lifecycle](docs/std/crypto/encryption.md#nonce-and-key-lifecycle). ## Core API | API | Result | |---|---| | `nextU64`, `nextI64`, `nextU32`, `nextI32` | full-width integer output | | `nextFloat`, `nextFloat32` | uniform semi-open floating output | | `nextBelow(upper)` | unbiased `u64` in `[0, upper)` | | `nextRange`, `nextRangeU64`, `nextRangeF` | uniform semi-open ranges; `nextRangeF` rejects non-finite bounds deterministically | | `choose`, `chooseSpan` | borrowed selection without cloning | | `shuffle`, `unsafe shuffleSpan` | ownership-neutral Fisher–Yates shuffle | | `fillBytes(&Vec!)` | safe deterministic pseudorandom fill | | `unsafe fillBytes(&Span!)` | raw-backed fill with caller-proven exclusivity | | `jump`, `longJump` | advance by `2^128` or `2^192` transitions | | `fork` | return the current stream and jump the parent | | `Rng4.withSeed`, `Rng4.init` | create four streams separated by canonical `2^128` jumps | | `Rng4.nextU64x4` | four independent full-width outputs as `[u64; 4]` | | `Rng4.nextFloatx4` | four independent values in `[0, 1)` | | `Rng4.fillBytes` | deterministic lane-interleaved 32-byte batches | Bounded integers use Lemire multiply-high sampling with a rejection threshold, so arbitrary bounds are unbiased without division on the ordinary accepted path. Signed range width is calculated in unsigned space and therefore handles almost the complete `i64` domain without overflow. ## Reusable distributions ```vex import { Normal, Rng, WeightedIndex } from "rand" let! rng = Rng.withSeed(42) let! normal = match Normal.new(10.0, 2.0) { Result.Ok(value) => value, Result.Err(err) => $panic(err.message()), } let value = normal.sample(&rng!) ``` | Type | Constructor contract | Sample behavior | |---|---|---| | `Bernoulli` | finite probability in `[0, 1]` | O(1); exact edges consume no RNG state | | `Normal` | finite mean, finite non-negative deviation | cached Box–Muller pair, zero allocation | | `Exponential` | positive finite rate | stable `log1p` transform, zero allocation | | `WeightedIndex` | finite non-negative weights, positive finite total | owned cumulative table, O(log n), zero allocation | All constructors return `Result<..., DistributionError>` and validate before a reusable distribution becomes observable. ## Parallel streams Give every worker its own `Rng`. Use `longJump()` to partition top-level jobs and `jump()` or `fork()` to partition worker streams. These operations neither allocate nor synchronize. When one hot loop consumes four independent values together, `Rng4` keeps the stream contract explicit and lets the backend legalize one fixed-array dataflow: ```vex import { Rng4 } from "rand" let! streams = Rng4.withSeed(42) let words = streams.nextU64x4() let ratios = streams.nextFloatx4() ``` Lane zero is the ordinary seeded stream. Lanes one, two and three begin one, two and three `jump()` intervals later. Construction pays the partitioning cost once; steady-state calls have no allocation, lock, global state, FFI, or architecture-specific source. A partial `Rng4.fillBytes` step consumes one output from every lane, making state advancement deterministic. ## Measured baseline Apple M2 Max, release `-O3`, 2026-08-25, median of five 250 ms rounds: | Operation | Median | Allocation | |---|---:|---:| | `nextU64` | 3.13 ns | 0 | | `Rng4.nextU64x4` | 4.55 ns / 1.14 ns per output | 0 | | `Rng4.nextFloatx4` | 4.84 ns / 1.21 ns per output | 0 | | dynamic `nextBelow` | 3.25 ns | 0 | | 1 KiB `fillBytes` | 170.22 ns / 5.60 GB/s | 0 | | 1 KiB `Rng4.fillBytes` | 118.49 ns / 8.05 GB/s | 0 | | Bernoulli | 3.21 ns | 0 | | cached-pair Normal | 10.37 ns | 0 | | Exponential | 9.29 ns | 0 | | eight-entry `WeightedIndex` | 5.40 ns | 0 | These values are target-specific evidence, not portable latency guarantees. On this Apple target, `Rng4` produced about 2.75 times the scalar integer output throughput. NEON lacks packed `u64` multiply, so the backend retains vector XOR/shift/rotate/load/store work and distributes the star-star multiply across scalar ALUs. Wider targets may legalize the same source differently. ## Verification ```bash vex lint lib/std/rand --deny-warnings vex test lib/std/rand/tests/basic.test.vx vex test -O3 lib/std/rand/tests/basic.test.vx vex test -O3 --bench --benchmem lib/std/rand/tests/bench.test.vx ``` --- Source: https://vex-lang.org/docs/std/regex/api.md # Regex API (`regex`) ## `Regex` — Compiled Pattern | Method | Description | |--------|-------------| | `Regex.new(pattern)` | Compile pattern with default flags | | `Regex.compile(pattern, flags)` | Compile with explicit flags (`"i"`, `"m"`, `"s"`) | | `Regex.invalid()` | Create an invalid/empty regex sentinel | | `.test(text): bool` | Check if pattern matches anywhere in text | | `.isMatch(text): bool` | Check if pattern matches the full text | | `.exec(text, &match): bool` | Execute and capture groups | | `.valid` | Check if compilation succeeded | | `.source` | Original pattern string | | `.groupCount` | Number of capture groups | Invalid syntax, unknown flags or a pattern exceeding the documented resource budgets returns `Regex.invalid()` (`valid == false`). Compilation does not print to stdout. ## `Match` — Captured Result | Method | Description | |--------|-------------| | `Match.new()` | Create empty match | | `.value(): string` | Full match text (group 0) | | `.group(i): Option` | Get capture group by index | | `.groupCount(): i32` | Number of capture groups (excluding group 0) | | `.start(): i32` | Start position of full match | | `.end(): i32` | End position of full match | `Match` borrows the input text and owns reusable capture/scratch storage. `group(i)` returns a borrowed `str`; keep the original input alive and unchanged while using the match or its groups. Call `toString()` to retain an independent copy. `value()` produces an owned `string`. `start()` and `end()` are byte offsets (end-exclusive), with `-1` when no full-match span exists; they are not Unicode-scalar or grapheme indexes. Reuse one `Match` per concurrent caller; a later `exec` replaces its result. The compiled `Regex` remains immutable during matching. The engine operates on bytes, and case-insensitive matching is ASCII-oriented; use the Unicode package for Unicode normalization/case-fold policy before matching. ## Flags | Flag | Inline | Description | |------|--------|-------------| | `"i"` | `(?i)` | Case-insensitive matching | | `"m"` | `(?m)` | Multiline (`^` and `$` match line boundaries) | | `"s"` | `(?s)` | Dot-all (`.` matches `\n`) | Only `i`, `m` and `s` are accepted by `Regex.compile`. Bare inline flags must appear at the beginning of the pattern. Scoped groups such as `(?i:...)` are currently rejected rather than being compiled with incorrect global semantics. ## Examples ```vex import { Regex, Match } from "regex"; // Case-insensitive let re = Regex.compile("hello", "i"); re.test("Hello World"); // true // Capture groups let re = Regex.new("(\\w+)@(\\w+)\\.(\\w+)"); let! m = Match.new(); if re.exec("user@example.com", &m!) { match m.group(1) { Some(user) => { $println(user); }, // user None => { $println("No capture"); }, } } // Free functions import { test, exec } from "regex"; test(&re, "some text"); ``` --- Source: https://vex-lang.org/docs/std/regex/index.md # regex — Overview `std/regex` is a pure-Vex, byte-oriented regular-expression engine with deterministic resource limits and no catastrophic backtracking. ```vex import { Match, Regex } from "regex"; fn main(): i32 { let regex = Regex.new("(\\w+)@(\\w+\\.\\w+)"); let! result = Match.new(); if regex.exec("mail: user@example.com", &result!) { match result.group(1) { Some(value) => { $println(value); }, None => { $println("No capture"); }, } } return 0; } ``` With the `regex` module available, this example prints `user`. Check the compiler and standard-library versions for your release. The public operations have distinct semantics: - `test` searches anywhere; - `isMatch` requires the entire input; - `exec` returns the leftmost match and capture groups. Internally, pure literals and SIMD-backed prefix searches feed a one-pass DFA or a parallel Thompson NFA. Capture extraction uses a prioritized Pike VM with workspace reused through `Match`. Pattern-specific email/router shortcuts are not part of the engine. ## Validation and performance The source tree contains O0/O3 tests and a benchmark harness that makes inputs opaque and consumes results through a compiler barrier. Historical Apple arm64 O3 figures reported 7.58 ns for literal search, 21.07 ns for group-free literal `exec`, 565.57 ns for capture extraction, and 24.0 GB/s for a 9 KiB prefix miss, with a 1-second measurement cap. These numbers have not been revalidated against this documentation build and are not a current performance guarantee. ## Source layout | File | Responsibility | |---|---| | `parser.vx` | Bounded syntax parser and validation | | `ast.vx` | Pattern, sequence, class and capture types | | `prog.vx` | Thompson bytecode and semantic metadata | | `thompson.vx` | AST-to-bytecode compiler | | `class_match.vx` | Canonical byte-class semantics | | `onepass.vx` | Deterministic transition-table engine | | `thompson_exec.vx` | Linear boolean search/full-match engine | | `pike_vm.vx` | Prioritized capture engine | | `regex.vx` | Public `Regex`, `Matcher` and `Match` API | --- Source: https://vex-lang.org/docs/std/regex/internals.md # Regex Engine Internals ## Pipeline ```text source → bounded parser → AST → Thompson bytecode (Prog) ├─ literal/prefix metadata └─ one-pass DFA when provably deterministic ``` The AST is compile-only and is not retained by the returned `Regex`. Thompson fragments also allocate no side storage: each `Frag` is three `i32` values and its unresolved edges form an intrusive linked list in the unfinished program's target cells. After patching, those same cells contain ordinary instruction targets. The validated instruction budget reserves the four persistent SoA bytecode streams once, avoiding geometric reallocation and copy traffic. Before publication, `Prog.isWellFormed` rejects unresolved intrusive links, invalid opcodes, mismatched SoA lengths, bad class indices and out-of-range targets. Temporary compiler state therefore cannot leak into execution. This gives per-call, thread-local compilation state without a process-global cache, runtime FFI allocator, or forced arena mode. Applications should compile a pattern once and share the resulting immutable `Regex`. The parser fails closed for unknown flags, malformed inline flags, unsupported scoped flags, capture-slot overflow, excessive repeats, oversized patterns and programs whose instruction or capture-scratch budget would be unsafe. ## Execution engines ### Literal and required-literal filters Pure literals use `str` search directly. The compiler may also publish a conservatively proven `requiredLiteral`. It is a rejection filter only; a literal from an optional group or one alternation branch is never treated as globally required. Exact `.*literal.*` shapes can complete directly. Multi-byte prefixes use the built-in `str.indexOf`/`contains` implementation, which inherits Vex's native SIMD lowering. Sparse prefix hits are verified by a bounded candidate engine. After at most two input lengths of speculative work, execution falls back to the parallel Thompson state set. Dense adversarial prefixes therefore remain linear. ### One-pass DFA Eligible programs receive a 256-way transition table. Empty acceptance is stored separately from byte transitions, so `a*` does not turn every non-`a` byte into a match. Position-dependent assertions remain explicit states and are evaluated at the exact input offset. Assertion table targets use a negative sentinel, leaving the ordinary hot loop as a direct table lookup. Multiline programs currently use the general Thompson engine. If branch byte sets overlap, one-pass construction fails closed and the same fallback is used. ### Thompson boolean engine Programs with at most 64 instructions use a register-resident `u64` state set and iterate set bits with `Math.ctz`. All possible unanchored starts coexist in the same state set, so the input is consumed once instead of restarting the NFA for every byte. Larger programs use two reusable vectors per call. Both paths are linear in input length for a fixed program and contain no recursive backtracking. ### Prioritized Pike capture engine `Regex.exec` uses an ordered Pike VM over the same bytecode. Split order carries greedy/lazy priority; a candidate match is retained while higher-priority live threads are allowed to extend it. Capture `Save` slots travel with each thread. Mutable VM scratch belongs to `Match`, not `Regex`. A compiled regex can therefore be shared by concurrent callers, while a caller that reuses its `Match` value pays workspace growth only on the first call. Epsilon generations avoid per-thread clears and wrap safely. ## Complexity and limits - Boolean search/full match: linear in input for a fixed bytecode program. - Capture execution: prioritized Thompson/Pike simulation; no catastrophic recursive backtracking. - Repeat count: at most 1000. - Capture groups: at most 127 (the bytecode's one-byte Save-slot format). - Group nesting: at most 256. - Pattern source: at most 1 MiB. - Compiled program: at most 65,536 instructions. - Capture workspace: at most 16,777,216 `i32` values. ## Metadata `ProgMeta` contains exact minimum length, anchored-start information, pure and prefix literals, a conservative required literal and the exact literal-search-only classification. Metadata is never allowed to change regex semantics; uncertain cases fall back to the complete engine. --- Source: https://vex-lang.org/docs/std/semver.md # semver The `semver` module parses, compares, and matches strict Semantic Versioning 2.0 values using borrowed input and typed comparator semantics. ## Usage ```vex import { Version } from "semver"; let v1 = Version.parse("1.0.0-alpha.1+build.metadata") let v2 = Version.parse("1.0.0") if v1.lt(&v2) { $println("v1 is older than v2") } $println(v1.major) $println(v1.minor) $println(v1.patch) ``` `parse` returns a `Version` even for invalid input: inspect `valid` before using it. For user-supplied versions, prefer `tryParse` and handle the typed failure. The same distinction applies to `VersionReq.parse` and `tryParse`. Build metadata does not change semantic-version precedence; prerelease identifiers do. Compare versions through the provided methods rather than lexicographically comparing their strings. ## Current Surface - `Version.parse(input: str): Version` - `Version.tryParse(input: str): Result` - parse errors expose `kind()`, `position()`, `invalidByte()`, and `message()` - `Version(major, minor, patch): Version` - public fields: `major`, `minor`, `patch`, `pre`, `build`, `valid` - comparison helpers: `lt`, `gt`, `eq`, `lte`, `gte` - mutating helpers: `bumpMajor`, `bumpMinor`, `bumpPatch` - version requirements via `VersionReq.parse(...)` / `tryParse(...)` - typed `ComparatorOp` values rather than operator spelling strings Requirement syntax includes exact and ordered comparators, caret, tilde, comma-separated AND, `*`/`x`/`X`, bare partials (`1`, `1.2`) and component wildcards (`1.*`, `1.2.x`). `||` separates OR clauses. Space-delimited hyphen ranges are structural sugar: `1.2.3 - 2.3.4` includes both full endpoints, `1.2 - 2.3` expands to `>=1.2.0, <2.4.0`, and `1 - 2` expands to `>=1.0.0, <3.0.0`. `VersionReq` stores OR clauses as `ComparatorSet` values and stores typed `Comparator` values inside each set. Matching therefore never reparses or dispatches on source strings. Stable-only ranges do not admit arbitrary prereleases: the same OR clause must explicitly contain a prerelease comparator on the candidate's major/minor/patch tuple. Parsing is single-pass over borrowed views. Precedence comparison walks prerelease identifiers directly and allocates no split vectors. Typed failures are produced by the same parse, with exact byte positions and no error-string allocation. On the 2026-08-23 Apple M2 Max O3 baseline, simple parse is 12.81 ns, SSO metadata parse 25.60–27.70 ns, core comparison 2.07 ns, prerelease comparison 13.16 ns, two-comparator matching 6.36 ns, and matching through a second OR clause 14.06 ns. Parsing AND/OR/hyphen requirements into their owned structural form takes 156.99–224.36 ns. Full `Version.toString` is 54.52 ns after direct builder serialization; these hot rows allocate zero bytes. Full owned metadata remains a visible materialization path. The grammar is intentionally explicit rather than an open-ended npm clone. Unsupported ecosystem-specific spellings return `VersionReqParseError` instead of being guessed. This page documents the tested surface from `lib/std/semver/tests`, rather than accessor-style examples like `v1.major()` or `parse(...).unwrap()` that do not match the current Vex API. --- Source: https://vex-lang.org/docs/std/serde/cbor.md # CBOR (`serde/cbor`) The CBOR module provides comptime-specialized structured codecs and an owning `CborValue` dynamic tree. ## Round trip with a known schema The producer and consumer below use the same struct schema. For external data, use the dynamic parsing and field checks described in the next section. ```vex import { cborMarshal, cborUnmarshalSafe } from "serde/cbor"; struct Stats { public: hp: i64, mp: i64, } let source = Stats { hp: 100, mp: 50 }; let packed = cborMarshal(&source); let! decoded = Stats { hp: 0, mp: 0 }; match cborUnmarshalSafe( packed.raw_ptr() as Ptr, packed.len() as u64, &decoded, ) { Ok(_) => { $println(decoded.hp); } Err(failure) => { $println(failure.message()); } } ``` Dynamic APIs are `cborParseDynamic`, `cborParseDynamicSafe`, `cborParseDynamicWithLimits`, `cborStringifyDynamic` and `cborToJson`. They operate on a pointer and explicit byte length when parsing binary input. ## Safe and trusted paths Binary pointer/length pairs must refer to a live readable allocation of that initialized length. Keep the input owner alive throughout the call; a format validator cannot prove that an arbitrary foreign pointer is valid. Use `cborParseDynamicSafe` or `cborParseDynamicWithLimits` for external bytes, then check the root shape, required fields, exact value types and application ranges before constructing a domain value. The preflight checks wire format and resource budgets; it does not define an application schema. Parse failures return `DecodeError` with a typed kind and byte offset. `cborUnmarshalSafe` and `cborUnmarshalWithLimits` run the same wire-format preflight and then use the typed decoder. They do **not** validate compatibility with `T`, reject every type mismatch or enforce required fields. Use them only when the input schema is already trusted. Post-decode field checks cannot make that unchecked typed traversal suitable for external data. Use a per-protocol budget when the standard defaults are wider than your wire contract: ```vex import { DecodeErrorKind, DecodeLimits, cborParseDynamicWithLimits, } from "serde/cbor"; let! limits = DecodeLimits.standard(); limits.maxTotalBytes = 1024 * 1024 as usize; limits.maxDepth = 32 as usize; limits.maxNodes = 100_000 as usize; match cborParseDynamicWithLimits(data, length, limits) { Ok(value) => { /* consume value */ } Err(failure) => { if failure.isKind(DecodeErrorKind.DepthLimit) { $println("CBOR nesting rejected"); } } } ``` The safe subset accepts definite integers representable as `i64`, byte/text strings, arrays, string-keyed maps, booleans, null and 32/64-bit floats. It rejects truncation, trailing bytes, invalid UTF-8, non-string map keys, over-budget values, tags, indefinite values and unsupported simple values. Tags, `undefined` and indefinite containers need a future lossless representation; silently erasing them would be incorrect. `cborParseDynamic` and `cborUnmarshal` are single-pass trusted-data paths. They do not validate bounds first and must not be used directly on untrusted input. The historical regression matrix covers structured/dynamic round trips and rejection of malformed wire data before struct mutation, plus truncation, forged lengths, trailing bytes, invalid UTF-8, integer overflow, non-string keys and resource budgets at O0 and O3. It does not establish typed-schema validation. Official RFC 8949 corpora, canonical encoding and lossless tag/indefinite-value support remain promotion work. The 2026-08-25 M2 Max O3 short baseline measured coordinate encode/decode at 14.96/17.49 ns, trusted dynamic parse at 488.66 ns, allocation-free validation at 51.87 ns and safe dynamic parse at 545.63 ns. The safe boundary added about 11.7% on this small fixture. These are regression baselines, not portable promises. ## Check a domain field before construction This complete program accepts an object with an integer `id` in `0..=100_000`. It rejects a scalar root, a boolean field and a negative identifier. Extra keys are ignored by this example; define stricter unknown-key and duplicate-key policies separately if your protocol requires them. `asInt()` alone is not a type check, because it returns a default for other variants. ```vex [cbor-schema.vx] import { CborValue, cborMarshal, cborParseDynamicSafe, cborStringifyDynamic } from "serde/cbor"; struct Record { public: id: i64 } struct WrongType { public: id: bool } fn readId(packed: &string): Option { match cborParseDynamicSafe(packed.raw_ptr() as Ptr, packed.len() as u64) { Err(_) => { return None; } Ok(value) => { match &value { CborValue.Object(fields) => { let key = "id"; match fields.get(&key) { Some(field) => { if !field.isInt() { return None; } let id = field.asInt(); if id < 0 || id > 100_000 { return None; } return Some(id as i32); } None => { return None; } } } _ => { return None; } } } } } fn main(): i32 { let valid = cborMarshal(&Record { id: 42 }); match readId(&valid) { Some(id) => { if id != 42 { return 1; } } None => { return 2; } } let wrongRoot = cborStringifyDynamic(&CborValue.Int(7)); let wrongField = cborMarshal(&WrongType { id: true }); let outOfRange = cborMarshal(&Record { id: -1 }); for bytes in [&wrongRoot, &wrongField, &outOfRange] { match readId(bytes) { Some(_) => { return 3; } None => {} } } $println("CBOR schema: PASS"); return 0; } ``` Run `vex run cbor-schema.vx`. Expected stdout is `CBOR schema: PASS`, exit 0. The input strings remain alive for the entire parse; only the checked integer is returned to the application. --- Source: https://vex-lang.org/docs/std/serde/csv.md # CSV (`serde/csv`) CSV exposes `parseCsv`, `parseCsvSafe`, `parseCsvWithLimits`, `CsvParser`, `CsvDocument`, `CsvSerializer` and `CsvDecoder`. ```vex import { parseCsvSafe } from "serde/csv"; match parseCsvSafe("name,age\nAda,36\nGrace,37", true) { Ok(document) => { let name = document.getField(0, "name").or(""); $println(name); // Ada }, Err(failure) => { $println(failure.message()); }, }; ``` `parseCsvSafe(input, has_headers)` borrows a `str` and returns `Result`. The trusted `parseCsv` convenience path returns a document without the safe preflight; use the checked path for external CSV and `parseCsvWithLimits` for application-specific budgets. `getRow` performs indexed row lookup; `getField` resolves a column by the parsed header. The current regression matrix covers header and no-header input, comma-containing quoted fields, escaped quotes and CRLF records. `CsvSerializer` and `CsvDecoder` implement the common serde contracts for explicit row-oriented codec use. There is no exported generic `encode` or `decode` convenience function. > **info Decoder ownership — 2026-09-06** The decoder's numeric/bool reads borrow its selected string; `parseString` returns an independent owned clone without consuming that selection. The implicit `&string` to `str` argument conversion preserves the original owner’s storage, including inline string bytes. It does not clone the string or transfer ownership. Regression tests cover repeated reads and a returned owned string surviving decoder destruction. The older parser benchmarks below have not been rerun as part of this ownership repair. The safe path validates UTF-8 and RFC-style quoting, rejects garbage after a closing quote and ragged rows, and enforces input/field/row/column/node budgets before allocating output. Quoted fields allocate their exact decoded length and row vectors reserve exact column capacity. The 2026-08-26 M2 Max O3 opaque-input baseline measured short trusted parse at 338 ns / 124 MB/s, safe parse at 403 ns / 104 MB/s, quoted parse at 248 ns / 173 MB/s and a 51-row input at 6.28 us / 183 MB/s. All reported parses used the bounded benchmark arena and recorded 0 process-heap allocations per operation. Complete RFC 4180 differential coverage, configurable dialects and a streaming record reader remain promotion work. --- Source: https://vex-lang.org/docs/std/serde/index.md # Serde — Serialization & Deserialization `serde` combines format-independent serialization contracts with comptime field reflection. Concrete struct codecs specialize at compile time; dynamic value trees are available when the payload shape is not known statically. ## Formats | Module | Structured surface | Dynamic surface | | --- | --- | --- | | `serde/json` | `jsonMarshal`, `jsonUnmarshal`, `jsonParse` | `JsonValue`, bounded safe parse, compact/pretty stringify | | `serde/cbor` | `cborMarshal`, `cborUnmarshalSafe` | `CborValue`, bounded safe parse, stringify, JSON conversion | | `serde/msgpack` | `msgpackMarshal`, `msgpackUnmarshalSafe` | `MsgPackValue`, bounded safe parse, stringify, JSON conversion | | `serde/toml` | `TomlSerializer`, `TomlDecoder` | `TomlValue`, trusted and bounded safe parse | | `serde/yaml` | serializer/parser primitives | `YamlValue`, bounded safe parse, stringify, JSON conversion | | `serde/csv` | `CsvSerializer`, `CsvDecoder` | `CsvDocument`, borrowed trusted and bounded safe parse | Import a format-specific module when possible. The root `serde` module re-exports the format facades, but there is intentionally no fictional universal `encode`/`decode` pair. ```vex import { jsonParseDynamicSafe, jsonStringifyDynamic } from "serde/json"; match jsonParseDynamicSafe("{\"ready\":true}") { Ok(value) => { $println(jsonStringifyDynamic(&value)); } Err(failure) => { $println(failure.message()); } } ``` ## Safety and conformance status JSON's safe dynamic path validates complete input grammar, escapes and Unicode surrogate pairs and enforces `DecodeLimits`. YAML, TOML and CSV expose the same `Safe`/`WithLimits` boundary for their documented subsets. CBOR and MessagePack safe dynamic parsers run a complete, allocation-free wire-format preflight before allocating a value tree. `DecodeLimits` bounds total bytes, depth, nodes, strings, binary payloads and container items; `DecodeError` reports a typed failure and byte offset. For external binary data, use `cborParseDynamicSafe` or `msgpackParseDynamicSafe`, then validate the root shape, required fields, exact value types and application ranges before constructing domain values. Typed `*UnmarshalSafe` and `*UnmarshalWithLimits` validate the wire format and budgets only: they do not establish that the document matches `T`. Reserve them for schema-compatible data. Checking the destination after typed decoding is not a substitute for validating the dynamic value first. Trusted non-`Safe` entry points skip wire-format preflight. TOML/YAML unsupported grammar fails closed; CSV safe parsing requires a rectangular document and validates RFC-style quoting. Full official conformance corpora, streaming APIs and canonical/tag/extension policies remain release work. The documentation does not claim unsupported specification features. The 2026-08-26 local checkpoint reported warnings-denied lint and 61 tests at both O0 and O3. An AddressSanitizer probe completed 40,000 valid and malformed safe binary decodes. All format benchmarks use `BenchCtx.iter`/`iterMut`, keep results observable, reuse mutable serializer capacity and reclaim owned temporaries in the bounded benchmark child region. On the local M2 Max O3 baseline, coordinate encode/decode is about 14.6/27.7 ns for JSON, 15.0/17.5 ns for CBOR and 13.4/14.3 ns for MessagePack; allocation-free binary preflight is about 52 ns for CBOR and 50 ns for MessagePack. YAML flat parse is about 389 ns and TOML simple parse about 757 ns. TOML long-document parsing is about 5.41 us with zero process-heap allocation. These are regression baselines, not portable promises. --- Source: https://vex-lang.org/docs/std/serde/json.md # JSON (`serde/json`) JSON exposes comptime-specialized struct codecs and the owning `JsonValue` dynamic tree. The first two snippets are integration fragments; the complete configuration program and its tests follow under “Validate a configuration”. ## Structured values from trusted input ```vex import { jsonMarshal, jsonUnmarshal } from "serde/json"; struct User { public: id: i64, name: string, } let source = User { id: 7, name: "Ada" }; let encoded = jsonMarshal(&source); let! decoded = User { id: 0, name: "" }; jsonUnmarshal(encoded.raw_ptr() as Ptr, encoded.len() as u64, &decoded!); ``` `jsonMarshal` and `jsonUnmarshal` specialize field traversal from comptime type information. They do not require derive macros or runtime field maps. This example decodes bytes just produced by the serializer. `jsonUnmarshal` is a trusted-data path; it is not a substitute for checked parsing of an external request or file. ## Dynamic values and safe parsing ```vex import { jsonParseDynamicSafe, jsonStringifyDynamic, jsonStringifyDynamicPretty, } from "serde/json"; match jsonParseDynamicSafe("{\"items\":[1,true,null]}") { Ok(value) => { $println(jsonStringifyDynamic(&value)); $println(jsonStringifyDynamicPretty(&value)); } Err(failure) => { $println(failure.message()); } } ``` `JsonValue` provides `is*` predicates, scalar accessors, object `get`, array `at` and `len`. The safe path returns `Result` and rejects trailing tokens, malformed numbers, invalid escapes, unpaired Unicode surrogates and malformed arrays/objects. Finite f64 values use the canonical shortest-roundtrip `strconv` formatter, so serialization preserves every representable value without fixed trailing zeros or a temporary string. Because RFC 8259 has no NaN or infinity number, the current infallible serializer emits `null` for non-finite IEEE values. The 2026-08-21 M2 Max O3 observable `BenchCtx.iter` baseline measured a small coordinate struct at about 14.59 ns to encode and 27.72 ns to decode; dynamic parse measured about 453 ns. These are local benchmark samples, not portable guarantees. ## Look up and validate fields These methods borrow the dynamic tree through `self: &JsonValue`: | Method | Return type | Contract | | --- | --- | --- | | `isNull()`, `isBool()`, `isNum()`, `isStr()`, `isArray()`, `isObject()` | `bool` | Check the exact variant before reading its value | | `get(key: string)` | `Option<&JsonValue>` | Borrow an object member; `None` for a missing key or a non-object | | `at(index: usize)` | `Option<&JsonValue>` | Borrow an array element; `None` for an invalid index or a non-array | | `asBool()` | `bool` | Return the boolean; other variants return `false` | | `asNum()` | `f64` | Return the number; other variants return `0.0` | | `asString()` | `string` | Return an owning string clone; other variants return an empty string | | `len()` | `usize` | Return array length or object member count; other variants return zero | `get` and `at` return borrowed references, not cloned subtrees. Keep the parsed root alive while using them. A scalar accessor's default does not establish that a field had the requested type: use `isBool()` before `asBool()`, for example. Checking only the resulting boolean would conflate an invalid field with a valid `false` configuration. ## Validate a configuration and test it This complete example requires an `enabled` boolean, preserves parse errors, and applies a small resource budget. A valid `false` is accepted; a missing field or a string is rejected. Keep these three files in the same directory. ```vex [config.vx] import { DecodeError, DecodeLimits, jsonParseDynamicWithLimits } from "serde/json"; export enum ConfigError { InvalidJson(DecodeError), ExpectedObject, MissingEnabled, EnabledNotBool, } // Accept a JSON object only when its required enabled member is a boolean. export fn parseEnabled(input: string): Result { let! limits = DecodeLimits.standard(); limits.maxTotalBytes = 1024 as usize; limits.maxDepth = 8 as usize; limits.maxNodes = 64 as usize; let document = match jsonParseDynamicWithLimits(input, limits) { Ok(value) => value, Err(failure) => return Err(ConfigError.InvalidJson(failure)), }; if !document.isObject() { return Err(ConfigError.ExpectedObject); } let enabled = match document.get("enabled") { Some(value) => value, None => return Err(ConfigError.MissingEnabled), }; // asBool() defaults non-booleans to false, so check the exact type first. if !enabled.isBool() { return Err(ConfigError.EnabledNotBool); } return Ok(enabled.asBool()); } ``` ```vex [config-demo.vx] import { ConfigError, parseEnabled } from "./config.vx"; fn show(input: string) { match parseEnabled(input) { Ok(enabled) => { $println(f"accepted: enabled={enabled}"); }, Err(ConfigError.InvalidJson(failure)) => { $println(f"rejected: {failure.message()}"); }, Err(ConfigError.ExpectedObject) => { $println("rejected: expected an object"); }, Err(ConfigError.MissingEnabled) => { $println("rejected: missing enabled"); }, Err(ConfigError.EnabledNotBool) => { $println("rejected: enabled must be boolean"); }, }; } fn main(): i32 { show("{\"enabled\":true}"); show("{}"); show("{\"enabled\":\"true\"}"); show("{\"enabled\":"); return 0; } ``` Run `vex run config-demo.vx`. It prints an accepted `enabled=true` result, followed by rejections for a missing field, a string field and truncated JSON. The parsed tree owns its fields until `parseEnabled` returns; the returned boolean is independent of that tree. ```vex [config.test.vx] import { ConfigError, parseEnabled } from "./config.vx"; fn test_enabled_true(): bool { return match parseEnabled("{\"enabled\":true}") { Ok(value) => value, Err(_) => false, }; } fn test_enabled_false(): bool { return match parseEnabled("{\"enabled\":false}") { Ok(value) => !value, Err(_) => false, }; } fn test_enabled_missing(): bool { return match parseEnabled("{}") { Err(ConfigError.MissingEnabled) => true, _ => false, }; } fn test_enabled_string(): bool { return match parseEnabled("{\"enabled\":\"true\"}") { Err(ConfigError.EnabledNotBool) => true, _ => false, }; } fn test_enabled_malformed(): bool { return match parseEnabled("{\"enabled\":") { Err(ConfigError.InvalidJson(_)) => true, _ => false, }; } fn test_enabled_nonobject(): bool { return match parseEnabled("true") { Err(ConfigError.ExpectedObject) => true, _ => false, }; } ``` Run `vex test --run test_enabled config.test.vx`. All six cases should pass, including a valid `false`, malformed JSON and a non-object root. Extra object members are ignored by this schema; define a stricter policy if your protocol requires one. ## Application-specific resource limits `jsonParseDynamicSafe` uses `DecodeLimits.standard()`. Choose tighter limits for a small configuration or request body with `jsonParseDynamicWithLimits`: ```vex import { DecodeLimits, jsonParseDynamicWithLimits } from "serde/json"; let! limits = DecodeLimits.standard(); limits.maxTotalBytes = 64 * 1024 as usize; limits.maxDepth = 16 as usize; limits.maxNodes = 4096 as usize; match jsonParseDynamicWithLimits("{\"ready\":true}", limits) { Ok(value) => { $println(value.len()); }, Err(failure) => { $println(failure.message()); $println(failure.offset); }, }; ``` Validation completes before the owning dynamic tree is allocated. The input `string` has already been materialized before the call; bound the network/file read as well if the transport must not allocate a large input. These limits control bytes, nesting and nodes, not the application schema. Check required keys, value types and ranges after parsing. Streaming APIs and complete official corpus qualification remain separate work from the implemented bounded parse surface. --- Source: https://vex-lang.org/docs/std/serde/msgpack.md # MessagePack (`serde/msgpack`) MessagePack exposes comptime-specialized struct codecs and an owning `MsgPackValue` dynamic tree. ## Round trip with a known schema The producer and consumer below use the same struct schema. For external data, use the dynamic parsing and field checks described in the next section. ```vex import { msgpackMarshal, msgpackUnmarshalSafe } from "serde/msgpack"; struct Sensor { public: id: i64, temperature: f64, active: bool, } let source = Sensor { id: 42, temperature: 23.5, active: true }; let packed = msgpackMarshal(&source); let! decoded = Sensor { id: 0, temperature: 0.0, active: false }; match msgpackUnmarshalSafe( packed.raw_ptr() as Ptr, packed.len() as u64, &decoded, ) { Ok(_) => { $println(decoded.temperature); } Err(failure) => { $println(failure.message()); } } ``` Dynamic APIs are `msgpackParseDynamic`, `msgpackParseDynamicSafe`, `msgpackParseDynamicWithLimits`, `msgpackStringifyDynamic` and `msgpackToJson`. Binary parsers take an explicit pointer and byte length. ## Safe and trusted paths Binary pointer/length pairs must refer to a live readable allocation of that initialized length. Keep the input owner alive throughout the call; a format validator cannot prove that an arbitrary foreign pointer is valid. Use `msgpackParseDynamicSafe` or `msgpackParseDynamicWithLimits` for external bytes, then check the root shape, required fields, exact value types and application ranges before constructing a domain value. The preflight checks wire format and resource budgets; it does not define an application schema. Parse failures return `DecodeError` with a typed kind and byte offset. `msgpackUnmarshalSafe` and `msgpackUnmarshalWithLimits` run the same wire-format preflight and then use the typed decoder. They do **not** validate compatibility with `T`, reject every type mismatch or enforce required fields. Use them only when the input schema is already trusted. Post-decode field checks cannot make that unchecked typed traversal suitable for external data. ```vex import { DecodeLimits, msgpackParseDynamicWithLimits, } from "serde/msgpack"; let! limits = DecodeLimits.standard(); limits.maxTotalBytes = 1024 * 1024 as usize; limits.maxDepth = 32 as usize; limits.maxContainerItems = 65_536 as usize; match msgpackParseDynamicWithLimits(data, length, limits) { Ok(value) => { /* consume value */ } Err(failure) => { $println(failure.message()); } } ``` The safe dynamic subset covers integers representable as `i64`, 32/64-bit floats, strings, binary values, arrays, string-keyed maps, booleans and nil. It rejects truncation, forged lengths, trailing bytes, invalid UTF-8, non-string keys, over-budget values, the reserved marker and extension-family markers. Extensions and timestamps remain rejected until the value model can preserve them losslessly. `msgpackParseDynamic` and `msgpackUnmarshal` are single-pass trusted-data paths; they intentionally skip preflight and are not an untrusted-input API. The historical regression matrix covers structured/dynamic round trips and rejection of malformed wire data before struct mutation, plus truncation, forged lengths, trailing bytes, invalid UTF-8, integer overflow, non-string keys and resource budgets at O0 and O3. It does not establish typed-schema validation. Official conformance corpora, duplicate/canonical policy and lossless extension support remain promotion work. The 2026-08-25 M2 Max O3 short baseline measured coordinate encode/decode at 13.35/14.28 ns, trusted dynamic parse at 477.94 ns, allocation-free validation at 49.94 ns and safe dynamic parse at 530.92 ns. The safe boundary added about 11.1% on this small fixture. These are regression baselines, not portable promises. ## Check a domain field before construction This complete program accepts an object with an integer `id` in `0..=100_000`. It rejects a scalar root, a boolean field and a negative identifier. Extra keys are ignored by this example; define stricter unknown-key and duplicate-key policies separately if your protocol requires them. `asInt()` alone is not a type check, because it returns a default for other variants. ```vex [msgpack-schema.vx] import { MsgPackValue, msgpackMarshal, msgpackParseDynamicSafe, msgpackStringifyDynamic } from "serde/msgpack"; struct Record { public: id: i64 } struct WrongType { public: id: bool } fn readId(packed: &string): Option { match msgpackParseDynamicSafe(packed.raw_ptr() as Ptr, packed.len() as u64) { Err(_) => { return None; } Ok(value) => { match &value { MsgPackValue.Object(fields) => { let key = "id"; match fields.get(&key) { Some(field) => { if !field.isInt() { return None; } let id = field.asInt(); if id < 0 || id > 100_000 { return None; } return Some(id as i32); } None => { return None; } } } _ => { return None; } } } } } fn main(): i32 { let valid = msgpackMarshal(&Record { id: 42 }); match readId(&valid) { Some(id) => { if id != 42 { return 1; } } None => { return 2; } } let wrongRoot = msgpackStringifyDynamic(&MsgPackValue.Int(7)); let wrongField = msgpackMarshal(&WrongType { id: true }); let outOfRange = msgpackMarshal(&Record { id: -1 }); for bytes in [&wrongRoot, &wrongField, &outOfRange] { match readId(bytes) { Some(_) => { return 3; } None => {} } } $println("MessagePack schema: PASS"); return 0; } ``` Run `vex run msgpack-schema.vx`. Expected stdout is `MessagePack schema: PASS`, exit 0. The input strings remain alive for the entire parse; only the checked integer is returned to the application. --- Source: https://vex-lang.org/docs/std/serde/toml.md # TOML (`serde/toml`) The TOML module provides the `TomlValue` dynamic tree, `TomlParser`, `TomlSerializer` and `TomlDecoder`. The current public parsing helper is `parseDynamic`, `parseDynamicSafe` and `parseDynamicWithLimits`; there is no exported generic `encode` or `decode` helper. The root facade exposes the safe forms as `parseTomlSafe` and `parseTomlWithLimits`. ```vex import { parseDynamicSafe } from "serde/toml"; match parseDynamicSafe("[server]\nhost = \"127.0.0.1\"\nport = 8080") { Ok(document) => { match document.get("server") { Some(server) => match server.get("port") { Some(port) => { $println(port.asInteger()); } None => {} }, None => {} } } Err(failure) => { $println(failure.message()); } } ``` The tested surface includes basic values, arrays, inline tables, nested table preservation, exponent and special floating-point forms, and escaped strings. `TomlValue` also exposes type predicates, scalar accessors, `get`, `at`, `len` and `toString`. On the 2026-08-21 Apple M2 Max O3 gate, simple parsing measured about 757 ns, nested-table parsing 1.306 us, struct serialization 106.8 ns and struct decoding 119.9 ns. The ownership-aware path moves parsed key strings directly into Map storage and traverses the active table without an absolute-path clone Vec. The three-round long-document median is 5.409 us with 0 B/op and 0 process-heap allocations. The safe API validates UTF-8, syntax, integer overflow, floating-point representability and `DecodeLimits` before allocating the tree. Multiline strings and array-of-table headers currently return `UnsupportedValue`; they are never silently reinterpreted. Malformed trusted input is also guaranteed to make forward progress. Full TOML conformance, complete datetime validation, duplicate-key policy and streaming remain promotion work. --- Source: https://vex-lang.org/docs/std/serde/yaml.md # YAML (`serde/yaml`) The current YAML surface is an owning dynamic tree with parser and serializer primitives. It deliberately documents the implemented subset rather than claiming complete YAML conformance. ```vex import { yamlParseDynamicSafe, yamlStringifyDynamic, yamlToJson, } from "serde/yaml"; let source = "user:\n name: Ada\nitems:\n - compiler\n - runtime\n"; match yamlParseDynamicSafe(source) { Ok(value) => { $println(yamlStringifyDynamic(&value)); $println(yamlToJson(&value)); } Err(failure) => { $println(failure.message()); } } ``` The tested subset covers mappings, nested mappings, sequences, comments, quoted strings, integers, floats, booleans and null. `YamlValue` supplies type predicates and scalar accessors. `YamlSerializer` and `YamlParser` are also exported for lower-level control; there is no generic exported `encode` or `decode` helper today. Finite floats serialize with the canonical shortest-roundtrip `strconv` engine, including scientific notation and IEEE subnormals. YAML special values use canonical `.nan`, `.inf`, and `-.inf` spellings and parse back as floats. `yamlParseDynamicSafe` validates indentation, quoted escapes, UTF-8, integer and float range, trailing structure and every shared `DecodeLimits` budget before allocating the tree. `yamlParseDynamicWithLimits` accepts a tighter policy. The trusted one-shot parser borrows its source and avoids a complete input copy. The 2026-08-26 M2 Max O3 sample measured flat trusted parse at about 573 ns, allocation-free validation at 151 ns / 283 MB/s and safe parse at 699 ns. Anchors, aliases, tags, the complete block/flow grammar and official conformance corpora remain promotion work. --- Source: https://vex-lang.org/docs/std/sort.md # sort — Sorting and searching The `sort` package provides ownership-safe in-place sorting, stable sorting, ordered searches, and sequence utilities. Generic ordering uses the `Ord` contract; there is no type-name dispatch or hidden C runtime dependency. ## Unstable sorting ```vex import { sort, sortDesc } from "sort"; let! values = [5, 3, 8, 1, 9, 2]; sort(&values); // [1, 2, 3, 5, 8, 9] sortDesc(&values); // [9, 8, 5, 3, 2, 1] ``` `sort` and `sortDesc` are hybrid introsorts. They combine ordered-input fast paths, insertion sort for tiny ranges, median-of-three partitioning, a duplicate-aware three-way path, and a heapsort fallback. Worst-case time is O(n log n), and stack use is O(log n). Structurally Copy four-byte integers can select a pure-Vex high-byte scratch schedule at comptime: a bounded sample rejects narrow distributions, a fixed local image groups wide keys, and 2-through-8-value buckets use fixed comparator networks. The choice depends on integer width/copyability/signedness facts, never an `i32`/`u32` spelling. Generic and owning values retain the allocation-free introsort path. Equal elements are not guaranteed to keep their original order. ## Stable sorting ```vex import { stableSort } from "sort"; let! events = loadEvents(); stableSort(&events); ``` `stableSort` keeps equal elements in their original relative order and does not require `Clone`. Four-byte Copy integers use a stable four-pass LSD radix path from 256 elements upward; signed order is normalized by representation facts, not an `i32` name check. Other Copy values use a direct contiguous merge buffer. Owning values stable-sort indices and then apply the permutation with ownership-safe `Vec.swap` operations. Every choice is structural at comptime. Auxiliary storage is O(n), and an already sorted vector returns before allocating workspace. ## Ordered search ```vex import { binarySearch, lowerBound, upperBound } from "sort"; let values = [1, 3, 3, 5, 7, 9]; let found = binarySearch(&values, 5); // 3 let missing = binarySearch(&values, 4); // -1 let firstThree = lowerBound(&values, 3); // 1 let afterThree = upperBound(&values, 3); // 3 ``` `binarySearch` returns an `i64` index or `-1` when absent. `lowerBound` and `upperBound` return insertion positions in `0..=values.len()`. Use the `binarySearchRef`, `lowerBoundRef`, `upperBoundRef`, and `linearSearchRef` variants when the target is an owning value that should only be borrowed. ## Custom order and key projection Custom ordering is a concrete policy, not a boxed closure or function pointer. The compiler monomorphizes the policy into sorting and search loops. ```vex import { SortKey, sortByKey, stableSortByKey } from "sort"; struct ByScore: SortKey {} inline fn (self: &ByScore) key(value: &Player): i32 { return value.score; } sortByKey(&players, ByScore {}); stableSortByKey(&players, ByScore {}); ``` Use `SortOrder` when comparison needs state, descending order, borrowed compound fields or rules that cannot be represented by a Copy key. The same policy works with `sortBy`, `stableSortBy`, `selectNthBy`, `partialSortBy`, `isSortedBy`, `binarySearchBy`, `lowerBoundBy`, `upperBoundBy` and `equalRangeBy`. The `*ByKey` family supplies the equivalent projected-key API. ## Selection and partial sorting `selectNth` rearranges a vector so the requested index contains the value that would appear there in a full sort. `partialSort(values, count)` orders only the smallest `count` values. Invalid indices/counts fail without mutating input. Selection uses introspective quickselect with a deterministic median-of-medians fallback; partial sorting uses a sparse top-K heap and then orders the prefix. ```vex import { partialSort, selectNth } from "sort"; let median = selectNth(&values, values.len() / 2 as usize); let ok = partialSort(&values, 10 as usize); // values[0..10] is sorted ``` ## Total floating-point order Generic float comparison is not silently redefined. When deterministic order must include signed zero, infinities and NaN payloads, use `TotalF32Order`, `TotalF64Order`, `sortF32Total` or `sortF64Total`. ```vex import { sortF64Total } from "sort"; sortF64Total(&values); ``` The order key uses zero-cost `Math.toBits`: LLVM receives an SSA bitcast and integer bit operations, with no temporary memory or FFI call. ## Utilities The package also exports `linearSearch`, `isSorted`, `isSortedDesc`, `unique`, `minElement`, and `maxElement`. Prefer `minElementRef` and `maxElementRef` in allocation-sensitive code; their owned counterparts require `Clone` and clone only the selected result. `unique` removes consecutive duplicates, so sort the vector first when duplicates are not already adjacent. Natural ordered operations require a lawful total `Ord` implementation. A custom `SortOrder` must remain irreflexive and transitive for the duration of the call. --- Source: https://vex-lang.org/docs/std/strconv.md # `strconv` — string conversions `strconv` parses borrowed `str` values without allocation and formats primitive values into owned `string` values. Every parser returns builtin `Result`; parsing never panics or wraps on overflow. ## Parse text ```vex import { parseInt64, parseFloat64 } from "strconv"; match parseInt64("12345") { Result.Ok(value) => $println(value), Result.Err(error) => { $println(error.message()); $println(error.position); }, }; let ratio = parseFloat64("1.25e-3")?; ``` The package supports signed and unsigned 8/16/32/64-bit integers, bases 2 through 36, binary/octal/hex prefixes, f32/f64 scientific notation, and case-insensitive booleans. ASCII edge whitespace is accepted; trailing junk is rejected. A `str` slice does not need NUL termination. Width-specific integer errors point at the first digit that exceeds the target type itself (`parseInt8("128")` reports byte 2). Representable subnormals are kept, including the minimum f64 boundary written as `5e-324`. Float parsing is correctly rounded to nearest-even, including halfway, subnormal, overflow, and long-decimal cases. Ordinary decimals use bounded native paths; wide exponents use an allocation-free pure-Vex cached-power conversion with `u128` products. Only ambiguous rounding boundaries use the pure-Vex exact bigint fallback. f32 values are checked for midpoint double rounding instead of blindly narrowing through f64. The fallback uses a fixed, allocation-free workspace sized from the complete 1,100-digit finite IEEE envelope. Division and nearest-even rounding reuse the same owned numerator buffer for the quotient remainder instead of returning or copying large temporary bigints. ## Format values ```vex import { formatInt, formatFloat, formatFloat64Shortest, formatHexPrefix, boolToString } from "strconv"; let count: string = formatInt(42); // "42" let ratio: string = formatFloat(3.14159, 2); // "3.14" let exact: string = formatFloat64Shortest(5.0e-324); // "5e-324" let flags: string = formatHexPrefix(255); // "0xff" let enabled: string = boolToString(true); // "true" ``` All integer radices from 2 through 36 have explicit lowercase/uppercase owned and caller-buffer APIs. For example, `formatIntBase(-255, 16)` returns `Ok("-ff")`, while `formatUIntBaseUpper(35, 36)` returns `Ok("Z")`. The `*To` variants write into a supplied `RawBuf`, allocate nothing, and return a typed error without partially mutating an undersized destination. Float formatting handles NaN, infinities, negative zero, rounding carry, and huge/tiny finite values without unsafe float-to-integer conversion. See the [complete reference](docs/std/strconv_reference.md) for all functions and exact grammar. Shortest formatting is a separate exact mode. `formatFloat64Shortest` and `formatFloat32Shortest` select the shortest decimal that parses back to the same IEEE value. Their `*To` variants write transactionally into 24-byte f64 or 16-byte f32 caller storage without allocation. Binary32 uses its own Ryu path instead of widening through f64. Decimal integer formatting is implemented in pure Vex. The runtime formatter consumes two digits per iteration using constant divisors, writes directly into the caller-owned destination, and commits no partial result when capacity is insufficient. Signed formatting shares the same engine instead of formatting and copying through a second temporary buffer. Power-of-two radices use mask-and-shift extraction; other radices issue one division per digit and derive the remainder by multiply/subtract. Compiler optimization levels do not change these semantics: O0 through O3 retain strict IEEE floating-point behavior unless a separate explicit relaxed math policy is selected internally. ## Error model `ParseError` exposes `kind`, zero-based byte `position`, and `invalidByte`. Its `message()` is a static borrowed description, so error construction stays allocation-free. Categories are `Empty`, `InvalidChar`, `InvalidFormat`, `InvalidBase`, `Overflow`, and `Underflow`. --- Source: https://vex-lang.org/docs/std/strconv_reference.md # `strconv` `strconv` performs strict, locale-independent conversion between borrowed text and primitive values. Parsers accept length-aware `str` and allocate nothing; formatters return language-owned `string` values. This first fragment belongs inside a function returning a compatible `Result`; both parse calls can return `ParseError`. ```vex import { parseInt64, parseFloat64, formatHex } from "strconv"; let port = parseInt64("8080")?; let rate = parseFloat64("1.25e-3")?; let flags: string = formatHex(255); // "ff" ``` ## Parsers | Function | Return type | | --- | --- | | `parseInt64` / `parseUInt64` | `Result` | | `parseInt32/16/8` | Checked matching signed result | | `parseUInt32/16/8` | Checked matching unsigned result | | `parseIntBase` / `parseUIntBase` | Checked base 2 through 36 | | `parseHex` / `parseOctal` / `parseBinary` | `Result` | | `parseFloat64` / `parseFloat32` | Checked decimal/scientific float | | `parseBool` | `Result` | Integer helpers accept optional matching `0x`, `0o`, or `0b` prefixes. Float syntax includes decimal fractions and `e`/`E` exponents. Boolean values are `true`, `yes`, `1`, `false`, `no`, and `0`, case-insensitively. ASCII whitespace may surround a value, but trailing junk is rejected. Inputs may be slices and do not need a C terminator. Narrow signed and unsigned parsers check their own limits while accumulating digits. Overflow and underflow therefore report the exact triggering byte, not a later wrapper-level cast. Float parsing preserves representable subnormals; `5e-324` is accepted while values that round to zero report underflow. Decimal f32/f64 results are rounded to nearest-even over the full finite IEEE domain. Exactly representable mantissa/power combinations use the smallest hardware path. Wider exponents use a pure-Vex Eisel-Lemire cached-power tier; only products whose IEEE result is unambiguous are accepted. Remaining values use an allocation-free pure-Vex bigint fallback. f32 midpoint detection prevents decimal → f64 → f32 double rounding. Convenience overloads are available as `parseInt`, `parseUInt`, `parseFloat`, and `parseBoolStr`. ## Parse errors ```vex enum ParseErrorKind { Empty, InvalidChar, InvalidFormat, InvalidBase, Overflow, Underflow, } struct ParseError { kind: ParseErrorKind, position: usize, invalidByte: u8, } ``` The position is a zero-based byte offset. Errors allocate no message object; use `message()` for a static description, `isKind()` for category matching, or `code()` for a stable numeric code. ```vex match parseInt64("12x") { Result.Ok(value) => $println(value), Result.Err(error) => { $println(error.message()); $println(error.position); // 2 }, }; ``` ## Formatters | Function | Result | | --- | --- | | `formatInt64`, `formatInt32` | Owned signed decimal `string` | | `formatUInt64`, `formatUInt32` | Owned unsigned decimal `string` | | `formatHex`, `formatHexUpper`, `formatHexPrefix` | Owned hexadecimal `string` | | `formatBinary` | Owned binary `string` | | `formatUIntBase` / `formatUIntBaseUpper` | `Result` for base 2 through 36 | | `formatIntBase` / `formatIntBaseUpper` | `Result` for signed base 2 through 36 | | `formatUIntBaseTo` / `formatUIntBaseUpperTo` | Allocation-free caller-buffer result | | `formatIntBaseTo` / `formatIntBaseUpperTo` | Allocation-free signed caller-buffer result | | `formatFloat64`, `formatFloat32` | Owned rounded decimal `string` | | `formatFloat64To` | Write rounded f64 text into caller-owned storage without allocation | | `formatFloat64Shortest`, `formatFloat32Shortest` | Owned shortest-roundtrip IEEE decimal | | `formatFloat64ShortestTo` | Allocation-free shortest f64; requires 24 bytes | | `formatFloat32ShortestTo` | Allocation-free shortest f32; requires 16 bytes | | `formatBool` | Owned `true`/`false` string | `formatFloat64(value, precision)` clamps precision to 0 through 18. Common values use fixed notation. Magnitudes at least `1e19`, and nonzero magnitudes below `1e-6`, use scientific notation. This prevents unsafe integer conversion for huge values and preserves tiny nonzero values. Special output is `nan`, `inf`, or `-inf`; negative zero keeps its sign. Shortest formatting uses independent binary32/binary64 pure-Vex Ryu paths. It preserves signed zero, writes integral finite values with `.0`, and uses lowercase `e` without a redundant positive exponent sign. `floatToString` uses this shortest-roundtrip mode; explicit precision remains available via `formatFloat64(value, precision)`. ```vex $assert(formatInt64(-42) == "-42"); $assert(formatHexPrefix(255) == "0xff"); $assert(formatFloat64(9.999, 2) == "10.00"); $assert(formatFloat64(1.0e100, 2) == "1.00e+100"); $assert(formatFloat64Shortest(1.2345678901234567) == "1.2345678901234567"); $assert(formatFloat64Shortest(5.0e-324) == "5e-324"); ``` Aliases include `intToString`, `floatToString`, `boolToString`, `formatInt`, and `formatFloat`. Radix formatters return `Result<..., FormatError>`. Valid bases are 2 through 36. The default variants use `a` through `z`; `Upper` variants use `A` through `Z`. Caller-buffer forms are transactional: invalid base or insufficient capacity returns an error without changing the destination. Signed output uses a leading minus sign in every radix and safely handles `MIN_I64`. ### Caller-buffer float formatting `formatFloat64To(value, precision, out, outCap)` is the allocation-free source of truth used by `strings.StringBuilder`. The caller supplies a writable `RawBuf` with at least 64 bytes of capacity. The function returns the number of initialized bytes and never appends a terminator. If the buffer is null or too small, it returns zero without modifying the destination. ```vex import { formatFloat64To } from "strconv/format" let! storage: [u8; 64] = [0; 64] let output = RawBuf.of(&storage as Ptr) let length = formatFloat64To(9.999e100, 2, output, 64 as usize) let rendered = str.fromRaw(&storage as Ptr, length) $assert(rendered == "1.00e+101") ``` `rendered` borrows `storage`; consume or copy it before the local array dies and before reusing that storage. The raw constructor does not extend its lifetime. This API is intended for builders, serializers and protocol writers that already own output capacity. Application code that needs an owned value should continue to use `formatFloat64`. The shortest caller-buffer variants have the same transactional contract. Use 24 writable bytes for f64 and 16 for f32; insufficient capacity returns zero without modifying the destination. ## Runtime properties - No libc, native shim, C-string scan, or external package dependency. - Parsing is allocation-free. Common values need one digit pass; cached powers handle unambiguous wide exponents, while rare exact fallbacks re-read the borrowed digits without copying them. - Decimal integer formatting consumes two digits per loop. Radices 2/4/8/16/32 use masks and shifts; generic radices use one division per digit. - Owned formatting performs one final copy into a Vex-owned string; `formatFloat64To` writes directly into existing caller storage. - Shortest conversion uses complete cached-power tables and native `u128` products; its caller-buffer forms do not allocate. - Extreme float normalization has bounded work. - O0 through O3 keep strict IEEE floating-point semantics; optimization level alone never enables relaxed math. The 2026-08-14 M2 Max O3 parser baselines are 6.50 ns for fixed-width f64, 23.48 ns for a general exact-operand decimal, 44.71 ns for a cached-power wide exponent, and 75.83 ns for a cached-power long decimal. A true exact halfway fallback is 873.31 ns and is not paid by ordinary or interval-proven inputs. Timings vary by host. The 2026-08-25 M2 Max O3 caller-buffer shortest baselines are 17.34 ns for f32, 21.26 ns for f64 pi, 33.17 ns for an integral f64, and 27.32 ns for the maximum finite scientific f64. Owned f64/f32 output measured 41.09/22.43 ns. See the package's `REFERENCE.md`, tests, and benchmarks for the complete engineering contract. --- Source: https://vex-lang.org/docs/std/strings.md # strings `strings` provides allocation-free byte/ASCII search and an automatically managed builder for incremental output. Common operations such as `split`, `join`, `trim`, `repeat`, `replace`, `startsWith`, and `endsWith` already live on the prelude `str`/`string` types and are not duplicated here. ## StringBuilder ```vex import { StringBuilder } from "strings" let! builder = StringBuilder.new() builder.writeStr("item=") builder.writeI64(42) let output = builder.toString() // "item=42" ``` Use `StringBuilder(capacity)` or `StringBuilder.new(capacity)` when the expected size is known. The builder grows automatically, checks capacity arithmetic, and follows Vex's allocator region automatically. Arena-backed storage is reclaimed in bulk at region exit; a builder that needs persistent storage uses the normal heap and releases it through `Drop`. Cross-region growth is promoted safely without exposing this distinction to application code. There is no raw buffer field, manual `free`, reference-count choice, or thread-tracking API. Available methods: | Method | Purpose | |---|---| | `writeStr(value: str)` | Append borrowed UTF-8 bytes in one copy | | `writeByte(value: u8)` | Append one byte | | `writeI64(value: i64)` | Append signed decimal text | | `writeU64(value: u64)` | Append unsigned decimal text | | `writeF64(value: f64, precision: i32)` | Append rounded fixed/scientific text without an intermediate string | | `toString()` | Copy current bytes into an owned `string`; later builder reuse cannot change it | | `asStr()` | Borrow initialized bytes without copying; end this view before mutating the builder | | `len()` / `isEmpty()` | Inspect logical content | | `capacity()` | Inspect reserved byte capacity | | `reset()` | Clear content while retaining capacity | | `discardPrefix(count: usize)` | Remove leading bytes in place with an overlap-safe move; retain capacity and allocator region | Use `discardPrefix` to consume a parsed prefix of an incremental byte buffer. Do not reset a builder and append a view into that same builder: `writeStr` requires disjoint source storage, and growing the buffer can invalidate the view. `discardPrefix` requires exclusive access, performs no allocation, and moves only the remaining bytes. Zero is a no-op; consuming the entire buffer keeps its allocation; a count greater than `len()` panics. Counts are bytes, so UTF-8 text consumers must choose a character boundary. ## Search ```vex import { indexOf, indexOfFrom, contains, count, indexOfIgnoreCase, containsIgnoreCase, } from "strings" let first = indexOf("alpha beta", "beta") let next = indexOfFrom("go go go", "go", 3 as usize) let found = containsIgnoreCase("Content-Type", "content") ``` Search inputs are borrowed `str` values and the search operations do not allocate. Index-returning operations use `i64` UTF-8 byte offsets with `-1` for no match; `contains*` returns `bool`. `count` and `countIgnoreCase` count non-overlapping matches. Ignore-case operations fold ASCII letters only; non-ASCII bytes are compared verbatim. Single-byte variants are also available: `indexOfByte`, `indexOfByteFrom`, `lastIndexOfByte`, `countByte`, and `containsByte`. Complete ranges use Vex's target-independent `[u8; 16]` and `Mask<16>` operations. Substring search delegates to the same VexArch `Mem.indexOfBytes` implementation used by prelude `str`, so the package does not maintain a slower second search engine. Exact tails remain bounded scalar code. Ignore-case comparisons fold only ASCII `A`–`Z` lanes; punctuation and non-ASCII bytes are never changed. On an Apple M2 Max with O3 and runtime-backed 64 KiB inputs, the 2026-08-16 baseline is roughly 37 GB/s byte search, 24 GB/s substring search, 37 GB/s ASCII validation and 11.6 GB/s all-case-different ASCII equality. These are regression baselines for that machine, not cross-platform guarantees. `StringBuilder.writeF64` writes through `strconv`'s caller-buffer formatter. It shares canonical NaN, infinity, negative-zero, rounding and scientific notation behavior without allocating a temporary formatted string. `writeF64Shortest` appends exact shortest-roundtrip f64 text through the allocation-free 24-byte caller-buffer path. ## ASCII helpers `isAscii`, `equals`, `eqIgnoreCaseAscii`, `toLowerAscii`, and `toUpperAscii` make byte/ASCII semantics explicit. For Unicode text processing, use the `unicode` package. ## Ownership model Application code works with ordinary values and `Box`. VUMM determines any required sharing and thread-safe physical representation automatically. The `strings` API never exposes reference counts or asks a developer to track threads. --- Source: https://vex-lang.org/docs/std/sys.md # sys — typed hosted-system boundaries `sys` provides process identity and control, environment access, command-line arguments, and hosted OS facts. It is target-routed and opt-in: VexArch and the prelude remain freestanding when `sys` is not imported. ```vex import { argView, getEnv, parentPid, pid, platform } from "sys"; $println("target: ", platform()); $println("pid: ", pid()); match parentPid() { Result.Ok(Some(parent)) => $println("parent: ", parent), Result.Ok(None) => $println("no exposed parent"), Result.Err(err) => $println(err), } match getEnv("HOME") { Result.Ok(Some(home)) => $println(home), Result.Ok(None) => $println("HOME is missing"), Result.Err(err) => $println(err), } match argView(0 as usize) { Some(program) => $println(program), None => { /* the host supplied no argv[0] */ }, } ``` ## Process control `ProcessId` is a nonzero `u32` identity. `ExitStatus` preserves normal exit and signal termination as different variants. | API | Contract | |---|---| | `pid()` | Allocation-free current `ProcessId`. | | `parentPid()` | `Result, ProcessError>`. | | `exit(code)`, `abort()` | Immediate termination without Vex destructor unwinding. | | `execReplace(file, args)` | PATH-based process-image replacement; success never returns. | | `runShell(command)` | Shell execution with normalized `ExitStatus`; do not concatenate untrusted input. | | `unsafe forkProcess()` | True POSIX fork; the parent receives an owned `Child`, while Windows reports `Unsupported`. | | `Command.new(program).arg(value)` | Fluent owned builder; arguments are never shell-concatenated. | | `Command.spawn()`, `Command.status()` | Shell-free spawn, or spawn plus blocking wait. | | `Child.id()` | Typed nonzero child identity. | | `Child.tryWait()`, `Child.wait()` | Poll or reap; completed status is cached. | | `Child.kill()` | Request termination; follow with `wait()` to reap and observe status. | `ProcessId` is identity-only. There is intentionally no safe raw-PID wait surface: `Command.spawn()` and the parent branch of `forkProcess()` each produce one owned `Child`, so polling, reaping and killing cannot race a second capability after PID reuse. `forkProcess` is unsafe because a multithreaded child may call only async-signal-safe operations before `execReplace`. The package does not emulate fork on Windows with incompatible semantics. Normal process creation uses `Command`, not `runShell`: ```vex import { Command } from "sys"; let command = Command.new("tool".toString()) .arg("--output".toString()) .arg("path with spaces".toString()); match command.status() { Result.Ok(status) if status.success() => { /* completed */ }, Result.Ok(status) => $println("child failed: ", status), Result.Err(err) => $println("spawn failed: ", err), } ``` POSIX routes through `posix_spawnp`, so no managed Vex operation runs in a post-fork child. Windows uses `CreateProcessW` and exact inverse CRT quoting. Dropping a Windows child closes its native handle. POSIX callers explicitly `wait`—including after `kill`—because drop never blocks or kills an independent process. ## Environment ```vex import { getEnv, setEnv, unsetEnv } from "sys"; match getEnv("APP_MODE") { Result.Ok(Some(value)) => $println(value), Result.Ok(None) => $println("not configured"), Result.Err(err) => $println(err), } unsafe { let _ = setEnv("APP_MODE", "production"); let _ = unsetEnv("OLD_APP_MODE"); } ``` `getEnv(key: str)` returns `Result, EnvError>`, so missing and present-empty variables remain distinct. Common short keys do not allocate; present values are owned `string` values. `setEnv` and `unsetEnv` are unsafe because environment storage is process-global and foreign code may access it without Vex synchronization. Repeated queries can use `getEnvInto(key, destination)`. It replaces reusable `Vec` storage, clears it on missing/error, and allocates nothing after an adequate reserve. Native providers receive the exact writable capacity and never append a hidden terminator beyond the returned byte count. ## Arguments and ownership | API | Ownership | |---|---| | `argCount()` | Process argument count as `usize`. | | `argView(index)`, `programNameView()` | Zero-copy process-lifetime `str` views. | | `argViews()` | Allocates only Vec index storage; argument bytes are borrowed. | | `arg(index)`, `args()`, `programName()` | Independent owned snapshots. | | `argInto(index, destination)` | Reusable byte snapshot; clears on `None`. | Invalid indices return `None`, never an invented empty string. ## Platform facts `platform()` and `arch()` are zero-cost compile-target facts. Hosted queries return typed results: - `logicalCpuCount(): Result` - `pageSize(): Result` - `hostname(): Result` - `currentDir(): Result` - `currentDirInto(destination): Result` - `currentExe(): Result` - `currentExeInto(destination): Result` - `homeDir(): Result, EnvError>` - `tempDir(): Result, EnvError>` No API silently substitutes `/tmp`, `.`, or another plausible path after an OS failure. `currentExe` is the OS-reported snapshot, not a canonical path or a security-stable executable identity. ## Target status The retained package report describes native macOS provider tests and cross-target semantic/strict-lint checks for the Linux POSIX provider. These are historical results, not a fresh validation of the 0.4.0 release artifact. Windows uses UTF-16 native APIs for environment, cwd and hostname, Toolhelp for parent PID, and `CreateProcessW` for shell-free child ownership; POSIX fork is unsupported by design. Native Linux and Windows execution remain release gates, so cross-target compilation is not presented as native certification. Targets without a `native..vxc` provider fail at compilation; `sys` never reuses a guessed POSIX/Darwin ABI as a generic compatibility fallback. ## Performance baseline Apple M2 Max, release `-O3`, bounded 100 ms sample on 2026-08-26: `pid` 2.60 ns and `argView(0)` 14.04 ns. Reusable `argInto`, `getEnvInto`, `hostnameInto`, `currentDirInto`, and `currentExeInto` measure 20.65 ns, 808.67 ns, 402.41 ns, 13.12 us, and 26.01 ns respectively. Their owned counterparts measure 58.86 ns, 1.58 us, 403.49 ns, 13.03 us, and 107.47 ns. Cwd remains dominated by `getcwd`; owned APIs still promise snapshots rather than allocation-free execution. Shell-free `/usr/bin/true` spawn plus wait measures 1.44 ms and is dominated by native process creation rather than Vex argument dispatch. ```bash vex lint --standard-library lib/std/sys --deny-warnings vex lint --standard-library --target aarch64-unknown-linux-gnu lib/std/sys --deny-warnings vex lint --standard-library --target x86_64-pc-windows-msvc lib/std/sys --deny-warnings vex test -O0 lib/std/sys/tests vex test -O3 lib/std/sys/tests vex test -O3 --bench --benchtime 300ms lib/std/sys/tests/bench.test.vx ``` --- Source: https://vex-lang.org/docs/std/testing.md # testing `testing` provides the contexts and assertions used by `vex test`. Discovery, isolation, timeouts, parallel files and benchmark reporting belong to the CLI; there is no library-side runner to call manually. ```vex import { TestCtx } from "testing"; fn test_addition(t: &TestCtx!) { t.assertEq(2 + 2, 4); t.assertTrue(4 > 0); t.assertStrEq("vex", "vex"); } ``` Test files use `.test.vx` or `_test.vx`. Functions beginning with `test_` or `Test` are tests; functions beginning with `bench_` or `Benchmark` are benchmarks. Do not define `main` in a discovered test file—the generated runner owns it and rejects a custom main to prevent false-green suites. ## TestCtx | API | Meaning | | --- | --- | | `err(message)` | Mark the test failed | | `skip(reason)` / `skipIf(...)` | Mark the test skipped | | `failed()` / `skipped()` / `passed()` | Observe sealed outcome state | | `assertEq`, `assertNe` | `i64` equality checks | | `assertStrEq` | Owned/borrowed string equality check | | `assertTrue`, `assertFalse` | Boolean checks | | `assertGt`, `assertLt`, `assertGte`, `assertLte` | `i64` ordering checks | | `assertApproxEq` | `f64` absolute tolerance check; NaN/negative epsilon fail | | `run(name, child)` | Run a synchronous named child and propagate failure | Message-bearing variants are `assertEqMsg`, `assertStrEqMsg` and `assertTrueMsg`. Standalone status helpers `eq`, `ne`, `ok`, `okMsg`, `gt`, `lt`, `gte`, and `lte` return `0` on success and `1` on failure. For fallible fixture setup, report the failure before returning from the test: ```vex let fixture = match createFixture() { Some(value) => value, None => { t.err("fixture initialization failed"); return; } }; ``` Do not use `!> || { return; }` here: it returns unit from the fallback closure, not from the test function. A benchmark setup failure must also be visible; panic with a fixture-specific message instead of silently returning before `b.iter` and reporting an empty measurement. ## BenchCtx ```vex import { BenchCtx } from "testing"; fn bench_parse(b: &BenchCtx!) { b.setBytes(8); b.iter(12345678 as i64, |value: i64| parseValue(value)); } ``` `iter` supplies a compiler barrier and bounded temporary-arena reclamation. Use `iterMut` for evolving caller-owned state and `iterString` for owned string results. `resetTimer`, `startTimer`, and `stopTimer` exclude setup; repeated start/stop intervals accumulate. `blackBox(value)` is available when a manual `b.n` loop is necessary. Independent benchmark files compile in a bounded parallel pool, then execute serially to preserve measurement isolation. The runner artifact is reused for every requested `--count` round. ```bash vex test lib/my_package/tests vex test --run parser lib/my_package/tests vex test --bench -O3 --benchtime 1s --benchmem lib/my_package/tests ``` --- Source: https://vex-lang.org/docs/std/time/api.md # Time & Duration API ## `Time` Struct `Time` stores a UTC Unix timestamp in signed `i64` nanoseconds. Use the public constructors to make units explicit; use `Instant` for elapsed time and deadlines. ### Constructors | Function | Description | |----------|-------------| | `now()` | Current wall-clock time | | `Time.fromUnixNanos(value)` | From signed Unix nanoseconds | | `Time.unix(seconds, nanoseconds)` | Normalize seconds plus an offset; panic on overflow | | `Time.checkedUnix(seconds, nanoseconds)` | The same conversion as `Option