# 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](../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](../guide/introduction.md) if you want language semantics.
- Start in [CLI Reference](../references/vex-cli-reference.md) if you want execution and command behavior.
- Start in [GPU & SIR](../guide/gpu/index.md) and [SIMD](../guide/simd/index.md) if you care about the graph path.

## Architecture Pages

- [Compiler Pipeline](compiler-pipeline.md): source to HIR to native/SIR lowering
- [Comptime Pipeline](comptime-pipeline.md): CTFE, typed residualization, declaration expansion, caching, and fusion
- [SIR & Backends](sir-and-backends.md): graph path, backend maturity, and acceleration routing
- [Runtime & Tooling](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](../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](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<i32>`
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](../guide/introduction.md) - Language syntax and semantics
- [Contributing](../guide/contributing.md) - How to contribute
- [Reference](../references/index.md) - CLI, test, package, and documentation tools
