# Axioma

**Compile-time declarative macros for static JSON-to-Matrix topology projection.**

> *Don't parse the tree. Be the grid.*

Axioma is a pure declarative macro library that projects dynamic, hierarchical JSON structures directly into static 2D coordinate spaces (Sparse Grids) at **compile time**.

It achieves this without generating Rust `struct`s, without `Vec`s or `HashMap`s, without runtime parsing loops, and with **zero external dependencies**. Instead, it constructs pure logical circuits and static offset tables that map `(Row, Col)` coordinates directly to their underlying values.

---

## ⚡ Features

  * **Zero Dependencies:** Axioma is entirely self-contained. It has completely severed ties with `serde` and `serde_json`, producing pure, standalone binary footprints with zero bloat.
  * **Compile-Time Routing:** Navigation happens entirely via compile-time code generation. Axioma relies on structurally constant-time routing (`O(1)` jump tables) or `O(log N)` hierarchical skip-searches. No runtime tree traversal, no iterators, no recursion.
  * **Struct-less & Stateless:** No need to define `Deserialize` structs. No schema generation, no derive macros, no runtime reflection.
  * **Minimal Compile-Time Bloat:** Implemented entirely using `macro_rules!`. No procedural macro overhead (bypassing `syn` and `quote` compile-time costs). Even massive JSON payloads expand in milliseconds.

---

## 🚀 Quick Start (Accessing Values)

Using Axioma is straightforward: define your matrix using one of the three engines, and access any element by passing its `(row, col)` coordinates directly to the generated closure.

### 1. Basic Access (Kotowari / Imprint)
For high-performance or large-scale data where you only need the value.

```rust,ignore
use axioma::prelude::*;

let engine = kotowari!({
    "metadata": { "id": 101, "stable": true }
});

// Direct O(1) access to the value at (0, 1) -> "id" value
let val = engine(0, 1); 

if let AxiValue::Num(n) = val {
    println!("ID: {}", n);
}
```

### 2. Lossless Access (Axioma)
When you need to know the node type or skip to the next element.

```rust,ignore
let engine = axioma!({ "status": "ok" });

// Returns (NodeKind, next_c, AxiValue)
let (kind, next_c, val) = engine(0, 0);

println!("Node Kind: {:?}", kind); // e.g., ObjKey
println!("Next Column: {}", next_c); // Offset to skip the current node
```

### 3. Data Segment Access (Imprint)
Optimized for massive datasets stored in the `.rodata` segment. Usage is identical to `kotowari!`, but access complexity is `O(log N)`.

```rust,ignore
let engine = imprint!({ /* massive nested JSON */ });
let val = engine(row, col);
```

---

## 📐 Coordinate Model & Topology Physics

Axioma assigns each JSON node a completely deterministic `(Row, Col)` coordinate during macro expansion. You access values by calling the generated matrix closure:

```rust,ignore
let value = matrix(row, col);
```

How does Axioma translate a tree into a 2D grid? It follows a strict set of spatial rules (Topology Physics):

| Structure | Projection Logic | Coordinate Transmutation |
| :--- | :--- | :--- |
| **Object** `{ K: V }` | **Vertical Drop.** Key stays, Value drops. | `Key: (r, c)` <br> `Val: (r+1, c)` |
| **Array** `[ A, B ]` | **Horizontal Spread.** Transparent container. | `A: (r, c)` <br> `B: (r, c + width(A))` |
| **Empty** `{}`, `[]` | **Void Consumption.** Consumes 1 column. | `(r, c) -> Null` |
| **Leaf** `Value` | **Materialization.** | `(r, c) -> AxiValue` |

*Arrays spread horizontally to ensure **Total Addressability**. Every atomic value has a unique, immutable coordinate without collapsing into a single cell.*

---

## 🚀 The Three Projection Engines

Axioma provides three distinct projection engines tailored for specific runtime and compile-time requirements.

### 1\. `kotowari!` (Lossy Engine)

**The ultimate O(1) value lookup.**
Drops topology reconstruction entirely and maps coordinates directly to values. This results in the fastest possible compile time and raw value access speed.

  * **Best for:** Point-and-shoot value retrieval where structural traversal (knowing the node type or sibling width) is unnecessary.
  * **Yields:** `AxiValue`

<!-- end list -->

```rust
use axioma::prelude::*;

fn main() {
    let matrix = kotowari!({
        "server": { "host": "localhost", "port": 8080 }
    });

    let host_val = matrix(1, 0); // O(1) access
}
```

### 2\. `axioma!` (Lossless Engine)

**Full topology preservation via O(1) routing.**
Compiles JSON into a massive, highly-optimized `match` statement. It retains the topological data, allowing you to know the `NodeKind` and the `next_c` (skip width) for traversal algorithms, all while maintaining strict `O(1)` access time.

  * **Best for:** Core configurations, Hot-path routing, Structural algorithms.
  * **Yields:** `(NodeKind, AxiValue, next_c)`

<!-- end list -->

```rust
use axioma::prelude::*;

fn main() {
    let matrix = axioma!({
        "server": { "host": "localhost", "port": 8080 }
    });

    // Returns a tuple preserving full topology
    let (kind, val, skip) = matrix(1, 0);
}
```

### 3\. `imprint!` (Drive Engine)

**Static data projection via O(log N) Skip-offset Traversal.**
Compiles JSON into a statically embedded tuple table `&[(row, col, skip, width, value)]` in the `.rodata` segment. Uses CPS (Continuation-Passing Style) to pre-calculate skip offsets at compile time, bypassing entire subtrees instantly during runtime.

  * **Best for:** Massive datasets, UI bindings, Cold storage, Binary size optimization.
  * **Yields:** `AxiValue`

<!-- end list -->

```rust
use axioma::prelude::*;

fn main() {
    let matrix = imprint!([
        "item1", "item2", "item3"
    ]);

    let item2 = matrix(0, 1); // O(log N) skip search
}
```

---

## 🔍 Debugging & Visualization API

To help you understand and verify the spatial projection of your JSON structures, Axioma provides a built-in debugging API. This tool allows you to instantly visualize the raw 2D coordinate grid and the topology skeleton generated by the `axioma!` engine at compile time.

*Note: The Debug API is designed exclusively for the `axioma!` (Lossless) engine, as it requires the topological data (`NodeKind` and `next_c`) to reconstruct the spatial boundaries.*

### Usage

Simply wrap your generated matrix in an `AxiomaGrid` and call the visualization methods:

```rust
use axioma::prelude::*;

fn main() {
    let matrix = axioma!({
        "server": {
            "cluster": [
                { "id": 1, "role": "gateway" },
                { "id": 2, "role": "worker" }
            ],
            "active": true
        }
    });

    // 1. Initialize the grid viewer
    let grid = AxiomaGrid::new(matrix);

    // 2. Validate exact topology size and deterministic nodes
    println!("Matrix Dimension: {} rows x {} columns", grid.rows, grid.cols);
    println!("Total Structural Nodes: {}", grid.count_nodes());

    // 3. View the Topology Skeleton (Filters out scalar leaves)
    grid.show_outline();

    // 4. View the physical 2D Matrix (Specify max columns to display safely)
    grid.show_grid(4);
}
```

### `show_outline()`
Outputs a clean, `tree`-like outline of your topology. It filters out scalar primitives, allowing you to instantly see the structural skeleton (objects and arrays) and their hierarchical relationships without noise.

```text
===============================
=== Axioma Topology Outline ===
===============================
.
└── server
    └── cluster
        ├── [{}]
        └── [{}]
```

### `show_grid(max_cols: usize)`
Visualizes the true physical layout of the projected 2D space. It prints a paginated table showing the exact `(Row, Col)` coordinates, the evaluated `NodeKind`, and the actual `AxiValue` residing in each cell.

The `max_cols` argument automatically restricts the number of columns rendered per block to prevent terminal line-wrapping issues, ensuring a perfect grid representation.

```text
===================================
=== 2D Matrix Burned by Axioma! ===
===================================
[ Tree 0: Column 0 to 3 ]
---------------------------------------------------------------------------------
(0, 0)             | (1, 0)             | (2, 0)             | (3, 0)             | 
ObjKey             | Null               | Null               | Null               | 
Str("server")      | Null               | Null               | Null               | 
---------------------------------------------------------------------------------
(0, 1)             | (1, 1)             | (2, 1)             | (3, 1)             | 
ObjKey             | ObjKey             | ObjValue           | Null               | 
Str("cluster")     | Str("id")          | Num("1")           | Null               | 
---------------------------------------------------------------------------------
...
```

---

## 🏎️ Performance Benchmarks

Axioma is designed to break the limits of both the Rust compiler and runtime execution. Tested against a highly dense JSON payload—comprising **119 structural nodes** that project into a strictly deterministic Sparse Grid of exactly **325 computed cells (5 rows × 65 columns)** (which pushes the pure `macro_rules!` engine to require `#![recursion_limit = "1024"]` for full AST expansion)—the engines yield the following metrics:

| Engine | Compile Time (AST Expansion) | Runtime Access (Deep Element) | Complexity | Target Segment |
| :--- | :--- | :--- | :--- | :--- |
| **`kotowari!`** | **\~92 ms** | **\~43.8 ns** | `O(1)` | Text Segment |
| **`axioma!`** | \~515 ms | **\~44.0 ns** | `O(1)` | Text Segment |
| **`imprint!`** | \~144 ms | \~93.2 ns | `O(log N)` | Data Segment |

*Note: Runtime metrics measured via `criterion` for worst-case deep-tree access. Axioma and Kotowari run at nearly identical sub-50ns speeds because LLVM perfectly optimizes away the tuple-construction overhead in the Lossless engine.*

---

## 📦 Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
axioma = "0.2.0"
```

### ⚠️ Note on Recursion Limit

Since Axioma performs deep recursive token munching (TT-munching) at compile time to construct its static geometries, you **must** increase the recursion limit in your crate root (`main.rs` or `lib.rs`) when dealing with large structures:

```rust,ignore
#![recursion_limit = "1024"] // Adjust based on your JSON depth/size
```

---

## ⚠️ The Philosophy of Scale: Optimize the World First

Axioma is designed to project well-structured topologies, not to brute-force parse bloated, monolithic JSON dumps. If your traversal is hitting performance bottlenecks, the solution is not to change the macro—it is to optimize your JSON geometry before projection.

In the Cognitive OS architecture, Axioma is only the final "Materialization" furnace. To shape, mutate, and optimize your JSON topologies for maximum projection efficiency, rely on Axioma's sibling engines:

  * **[Opejson (The Scalpel)](https://github.com/rhetro/opejson)** - For structural mutation and auto-vivification.
  * **[Xopsy (The Eye)](https://github.com/rhetro/xopsy)** - For CPS-based intent extraction and pre-routing.

---

## 🧠 Architecture: The Cognitive OS

**Axioma is not a parser; it is a compile-time compiler that freezes JSON topology into the binary's instruction stream.**

It eliminates the traditional distinction between "data" and "structure," treating JSON as a spatial topology rather than a tree. Axioma is the physical materialization layer of a broader architectural paradigm that minimizes traditional stateful structure management in favor of topology-driven programming.

To understand the core theory and the architecture behind this project, please refer to the upcoming Cognitive OS manifesto.

---

## 🛡️ License

This project is licensed under either of

  * Apache License, Version 2.0 ([LICENSE-APACHE](https://www.google.com/search?q=LICENSE-APACHE) or [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0))
  * MIT license ([LICENSE-MIT](https://www.google.com/search?q=LICENSE-MIT) or [http://opensource.org/licenses/MIT](http://opensource.org/licenses/MIT))

at your option.
