From 10e4ec07d6be38645df191f9dc7fa2104705bcb5 Mon Sep 17 00:00:00 2001 From: dimgigov Date: Fri, 8 May 2026 23:24:47 +0300 Subject: [PATCH] docs: reorganize into en/ and bg/ subfolders with numbered indices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - New docs/index.md with language selector - docs/en/ — 01-getting-started, 02-architecture, 03-ai-integration, 04-api-reference, 05-user-guide, 06-roadmap - docs/bg/ — same structure in Bulgarian - Root README.md trimmed to quick-start + links to docs/ - Removed old flat docs/ files (ARCHITECTURE.md, AI_FIRST.md, etc.) - Added swap!/reset! examples to getting-started guides --- README.md | 259 +++--------------- docs/PHASE5_HAMT.md | 71 ----- docs/README.bg.md | 106 ------- docs/bg/01-getting-started.md | 127 +++++++++ .../02-architecture.md} | 23 +- .../03-ai-integration.md} | 5 + docs/{API.bg.md => bg/04-api-reference.md} | 5 + docs/{GUIDE.bg.md => bg/05-user-guide.md} | 9 +- docs/{ROADMAP.bg.md => bg/06-roadmap.md} | 66 ++--- docs/bg/index.md | 36 +++ docs/en/01-getting-started.md | 127 +++++++++ .../02-architecture.md} | 23 +- docs/{AI_FIRST.md => en/03-ai-integration.md} | 5 + docs/{API.md => en/04-api-reference.md} | 5 + docs/{GUIDE.md => en/05-user-guide.md} | 9 +- docs/{ROADMAP.md => en/06-roadmap.md} | 5 + docs/en/index.md | 36 +++ docs/index.md | 16 ++ 18 files changed, 490 insertions(+), 443 deletions(-) delete mode 100644 docs/PHASE5_HAMT.md delete mode 100644 docs/README.bg.md create mode 100644 docs/bg/01-getting-started.md rename docs/{ARCHITECTURE.bg.md => bg/02-architecture.md} (81%) rename docs/{AI_FIRST.bg.md => bg/03-ai-integration.md} (98%) rename docs/{API.bg.md => bg/04-api-reference.md} (98%) rename docs/{GUIDE.bg.md => bg/05-user-guide.md} (93%) rename docs/{ROADMAP.bg.md => bg/06-roadmap.md} (60%) create mode 100644 docs/bg/index.md create mode 100644 docs/en/01-getting-started.md rename docs/{ARCHITECTURE.md => en/02-architecture.md} (79%) rename docs/{AI_FIRST.md => en/03-ai-integration.md} (98%) rename docs/{API.md => en/04-api-reference.md} (98%) rename docs/{GUIDE.md => en/05-user-guide.md} (93%) rename docs/{ROADMAP.md => en/06-roadmap.md} (99%) create mode 100644 docs/en/index.md create mode 100644 docs/index.md diff --git a/README.md b/README.md index cd153e0..1f2fa5d 100644 --- a/README.md +++ b/README.md @@ -1,259 +1,76 @@ # Clojure/Nim -> A Clojure dialect that compiles to Nim, then to C, then to native binaries. +> A Clojure dialect that compiles to Nim → C → native binaries. -## What is this? - -Clojure/Nim is an **AI-first** implementation of the Clojure language targeting the Nim ecosystem. Instead of running on the JVM or JavaScript, it compiles Clojure code directly to Nim source, which then compiles to C and finally to a native binary. - -### Why? - -- **Native Performance**: Compiles to C via Nim. No JVM warmup, no GC pauses. -- **Tiny Binaries**: Single-file executables, often under 1MB. -- **Nim Ecosystem**: Direct access to Nim and C libraries via FFI. -- **AI-Native**: Built for AI agents working in terminals — structured JSON REPL, batch evaluation, git integration. +[![Tests](https://img.shields.io/badge/tests-276%2B-green)]() [![Nim](https://img.shields.io/badge/nim-%3E%3D2.0-blue)]() [![License](https://img.shields.io/badge/license-MIT-yellow)]() ## Quick Start ```bash -# Clone git clone https://gitlab.com/balvatar/lisp-nim.git cd lisp-nim - -# Build make build - -# Run a file +make check ./cljnim run examples/hello.clj - -# Start human REPL -./cljnim repl - -# Start AI REPL (JSON mode) -./cljnim repl --json ``` -## Examples +## Documentation -### Hello World -```clojure -;; examples/hello.clj -(println "Hello, Nim world!") -(println (+ 1 2 3)) -``` +- **[English](docs/en/index.md)** — Getting started, architecture, AI integration, API reference +- **[Български](docs/bg/index.md)** — Първи стъпки, архитектура, AI интеграция, API справочник -```bash -$ ./cljnim run examples/hello.clj -Hello, Nim world! -6 -``` +## What is this? + +Clojure/Nim is an **AI-first** Clojure implementation targeting the Nim ecosystem. It compiles Clojure source directly to Nim, then to C, and finally to a native binary. + +### Why? + +- **Native Performance** — No JVM warmup, no GC pauses +- **Tiny Binaries** — Single-file executables, often under 1MB +- **Nim Ecosystem** — Direct access to Nim and C libraries via FFI +- **AI-Native** — JSON REPL, batch evaluation, AI-assisted error messages and code generation + +## Key Features + +| Feature | Status | +|---------|--------| +| Compiler (Clojure → Nim → C → native) | ✅ | +| REPL with JSON protocol | ✅ | +| Macro system (`defmacro`, `syntax-quote`, `->`, `->>`) | ✅ | +| Persistent data structures (HAMT vector/map) | ✅ | +| Atoms, Agents, Channels | ✅ | +| `loop`/`recur` | ✅ | +| `try`/`catch`/`finally` | ✅ | +| AI integration (DeepSeek, OpenAI, MiMo) | ✅ | +| Cross-compilation targets (JS, WASM, shared libs) | ✅ | +| 276+ tests | ✅ | + +## Example -### Functions & Recursion ```clojure ;; examples/math.clj -(defn square [x] - (* x x)) - (defn factorial [n] (if (= n 0) 1 (* n (factorial (- n 1))))) -(let [a 5] - (println (square a)) - (println (factorial a))) +(println (factorial 5)) ;; => 120 ``` ```bash $ ./cljnim run examples/math.clj -25 120 ``` -## AI-First REPL - -Clojure/Nim is built for AI agents. The JSON REPL provides structured I/O perfect for programmatic interaction. +## AI-Powered Development ```bash -$ ./cljnim repl --json -{"status":"ready","ns":"user","mode":"json"} - -> {"op":"eval","form":"(+ 1 2 3)"} -{"status":"ok","result":{"printed":"6"},"meta":{"ms":861}} - -> {"op":"eval","form":"(defn square [x] (* x x))"} -{"status":"ok","result":{"type":"var","name":"square"}} - -> {"op":"eval","form":"(square 5)"} -{"status":"ok","result":{"printed":"25"}} - -> {"op":"quit"} -{"status":"ok","bye":true} -``` - -### Supported REPL Operations - -| Operation | Description | -|---|---| -| `eval` | Evaluate a single Clojure form | -| `eval-batch` | Evaluate multiple forms at once | -| `get-defs` | List all defined vars in current session | -| `clear` | Clear all session definitions | -| `quit` | Exit the REPL | - -See [`docs/AI_FIRST.md`](docs/AI_FIRST.md) for the full AI integration design. - -## AI-Powered Assistance - -Clojure/Nim can use paid AI APIs (DeepSeek, OpenAI, Xiaomi MiMo) to help you write and debug code. - -### Setup - -Set one of these environment variables: - -```bash -# DeepSeek (recommended, fast & cheap) export DEEPSEEK_API_KEY="sk-..." - -# OpenAI / OpenRouter -export OPENAI_API_KEY="sk-..." - -# Xiaomi MiMo -export MIMO_API_KEY="..." +./cljnim ai "function that sums a list using loop/recur" ``` -### Features - -**Auto-error explanation** — When compilation fails, the compiler automatically asks AI for a fix: -```bash -$ ./cljnim run broken.clj -Compilation failed -Error: type mismatch: got but expected -💡 AI Suggestion: - The function `greet` expects a string but you passed an integer. - Fix: (defn greet [name] (str "Hello " name)) -``` - -**REPL AI command** — Generate code interactively: -```bash -$ ./cljnim repl -user> :ai function that calculates fibonacci using loop/recur -🤖 Thinking... -💡 AI Suggestion: - (defn fib [n] - (loop [a 0 b 1 i n] - (if (= i 0) - a - (recur b (+ a b) (dec i))))) -``` - -**CLI code generation** — Generate code from terminal: -```bash -$ ./cljnim ai "function that reads a file line by line" -(defn read-lines [filename] - (let [content (slurp filename)] - (clojure.string/split-lines content))) -``` - -## Architecture - -``` -Clojure Source (.clj) - ↓ - Reader (EDN parser) - ↓ - Macro Expansion (Clojure macros) - ↓ - Analyzer (special forms, locals) - ↓ - Emitter (Clojure AST → Nim AST) - ↓ - Nim Compiler → C Code - ↓ - C Compiler → Native Binary -``` - -See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for details. - -## Project Structure - -``` -├── src/ -│ ├── cljnim.nim # CLI entry point -│ ├── reader.nim # Clojure reader / EDN parser -│ ├── emitter.nim # Nim code generator -│ ├── repl.nim # Human & AI REPL -│ ├── eval.nim # Tree-walking interpreter -│ ├── deps.nim # Dependency resolution -│ ├── core.nim # Core runtime functions -│ ├── types.nim # Clojure value types -│ ├── macros.nim # Macro expansion engine -│ └── runtime.nim # Runtime implementation -├── lib/ -│ ├── cljnim_runtime.nim # Clojure runtime in Nim -│ ├── cljnim_pvec.nim # Persistent Vector (HAMT) -│ ├── cljnim_pmap.nim # Persistent Map (HAMT) -│ └── cljnim_async.nim # core.async channels -├── examples/ -│ ├── hello.clj -│ ├── math.clj -│ ├── core.clj -│ ├── macros.clj -│ ├── ffi.clj -│ ├── interop.clj -│ └── ai_tools.clj -├── docs/ # Documentation (EN + BG) -├── tests/ -├── Makefile -└── cljnim.nimble -``` - -## Supported Features - -### Working Now ✅ -- Reader: numbers, strings, symbols, keywords, lists `()`, vectors `[]`, maps `{}` -- Special forms: `def`, `defn`, `fn`, `let`, `if`, `do`, `quote` -- Arithmetic: `+`, `-`, `*`, `/`, `=`, `<`, `>` -- Functions: `println`, `map`, `filter`, `reduce` -- Human REPL and JSON REPL -- AOT compilation to native binaries -- Persistent data structures (Vector, Map, Set) via HAMT -- Macro system (`defmacro`, `->`, `->>`, `and`, `or`, `when`, `cond`) -- Nim/C interop -- File and Git operations from REPL -- Tree-walking interpreter for fast REPL eval -- Atoms, Agents, and core.async channels - -See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the full roadmap. - -## Requirements - -- Nim >= 2.0 -- GCC or Clang -- make - -## Documentation - -| Document | Description | -|---|---| -| [`docs/README.bg.md`](docs/README.bg.md) | Българско README | -| [`docs/GUIDE.md`](docs/GUIDE.md) | User guide (English) | -| [`docs/GUIDE.bg.md`](docs/GUIDE.bg.md) | Ръководство за потребителя | -| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Architecture & design | -| [`docs/ARCHITECTURE.bg.md`](docs/ARCHITECTURE.bg.md) | Архитектура и дизайн | -| [`docs/AI_FIRST.md`](docs/AI_FIRST.md) | AI-first design philosophy | -| [`docs/AI_FIRST.bg.md`](docs/AI_FIRST.bg.md) | AI-first философия | -| [`docs/API.md`](docs/API.md) | REPL API reference | -| [`docs/API.bg.md`](docs/API.bg.md) | REPL API референция | -| [`docs/ROADMAP.md`](docs/ROADMAP.md) | Development roadmap | -| [`docs/ROADMAP.bg.md`](docs/ROADMAP.bg.md) | Пътна карта | +See [docs/en/03-ai-integration.md](docs/en/03-ai-integration.md) for details. ## License -MIT License — see [LICENSE](LICENSE). - -## Acknowledgments - -- [Clojure](https://clojure.org/) — Rich Hickey and team -- [Nim](https://nim-lang.org/) — Andreas Rumpf and community -- Inspired by ClojureScript, Babashka, Ferret, and Pixie +MIT — see [LICENSE](LICENSE) diff --git a/docs/PHASE5_HAMT.md b/docs/PHASE5_HAMT.md deleted file mode 100644 index 2b50847..0000000 --- a/docs/PHASE5_HAMT.md +++ /dev/null @@ -1,71 +0,0 @@ -# Phase 5: HAMT Persistent Vector - -## Status: COMPLETE - -### What was implemented - -**Hash Array Mapped Trie (HAMT) Persistent Vector** — 32-way branching trie with path-copying structural sharing, matching Clojure's `PersistentVector` semantics. - -- `lib/cljnim_pvec.nim` — Core implementation - - `PersistentVector[T]` — root pointer + count + shift + tail - - `pvecConj` — O(log₃₂ N) append with structural sharing - - `pvecNth` — O(log₃₂ N) random access - - `pvecAssoc` — O(log₃₂ N) update with path copying - - `pvecPop` — O(log₃₂ N) remove last - - `newPersistentVector` — builder from `seq[T]` - - `toSeq` — convert back to `seq[T]` - - `len`, `[]` overloads for seq-like interface - -**Integration into Runtime** -- `lib/cljnim_runtime.nim`: `ckVector` now stores `PersistentVector[CljVal]` -- All 51 `vecData` references migrated to use `pvecNth`/`toSeq`/`count` -- `cljVector` constructor builds from `seq[CljVal]` via `newPersistentVector` - -### Architecture Decisions - -1. **Tail optimization**: Like Clojure, maintains a 32-element tail buffer for fast append of recent items -2. **Lazy tree growth**: Root promotion only happens when tree is full (`needsNewRoot` check) -3. **Path copying**: Every `conj`/`assoc` copies only the nodes along the path to the changed leaf -4. **Seq compatibility**: Added `len` and `[]` overloads so `mapIt`, `join`, `items` iterator work transparently - -### Bug fixes during implementation - -- **Recursive `pushLeaf` bug**: When `child.isNil` and `shift != BRANCHING_BITS`, was creating empty internal nodes without recursing to place the leaf. Fixed by calling `pushLeaf(newInternalNode(), index, shift-5, val)` instead of just `newInternalNode()`. - -### Tests - -- `tests/test_pvec.nim` — 14 tests covering: - - Empty vector, single element, few elements - - `conj` one-by-one (100 elements) - - `conj` across tail boundary (32) - - `conj` across second level (1024) - - `conj` large (10000) - - `assoc` in tail and tree - - `assoc` preserves old vector (structural sharing) - - `pop` from tail, across boundary, to empty - -### Performance Characteristics - -| Operation | Complexity | Notes | -|-----------|-----------|-------| -| `conj` | O(log₃₂ N) | ~1-3 node copies | -| `nth` | O(log₃₂ N) | ~3-5 pointer hops | -| `assoc` | O(log₃₂ N) | ~1-3 node copies | -| `pop` | O(log₃₂ N) | May pull leaf into tail | -| `toSeq` | O(N) | Full traversal | - -For N ≤ 1M, depth ≤ 3 (shift ≤ 15), making operations effectively constant-time. - -### Migration Guide for Other AIs - -If you need to work with vectors in `cljnim_runtime.nim`: - -```nim -# Instead of: -v.vecData.len # Use: v.vecData.count -v.vecData[0] # Use: pvecNth(v.vecData, 0) -v.vecData[1..^1] # Use: toSeq(v.vecData)[1..^1] -for item in v.vecData: # Use: for item in v.vecData.items: -``` - -`mapIt` from `sequtils` works transparently thanks to `len` + `items` iterator overloads. diff --git a/docs/README.bg.md b/docs/README.bg.md deleted file mode 100644 index 60351f6..0000000 --- a/docs/README.bg.md +++ /dev/null @@ -1,106 +0,0 @@ -# Clojure/Nim - -> Диалект на Clojure, който се компилира до Nim, после до C, и накрая до native бинарен файл. - -## Какво е това? - -Clojure/Nim е **AI-first** имплементация на езика Clojure за екосистемата на Nim. Вместо да работи върху JVM или JavaScript, компилира Clojure код директно до Nim, оттам до C, и накрая до native бинарен файл. - -### Защо? - -- **Native Performance**: Компилира се до C през Nim. Без JVM warmup, без GC паузи. -- **Малки Бинарни Файлове**: Единични изпълними файлове, често под 1MB. -- **Nim Ecosystem**: Директен достъп до Nim и C библиотеки през FFI. -- **AI-Native**: Построен за AI агенти, работещи в терминал — структуриран JSON REPL, batch evaluation, git интеграция. - -## Бърз Старт - -```bash -# Клониране -git clone https://gitlab.com/balvatar/lisp-nim.git -cd lisp-nim - -# Изграждане -make build - -# Изпълнение на файл -./cljnim run examples/hello.clj - -# Човешки REPL -./cljnim repl - -# AI REPL (JSON режим) -./cljnim repl --json -``` - -## Примери - -### Hello World -```clojure -;; examples/hello.clj -(println "Здравей, Nim свят!") -(println (+ 1 2 3)) -``` - -```bash -$ ./cljnim run examples/hello.clj -Здравей, Nim свят! -6 -``` - -### Функции и Рекурсия -```clojure -;; examples/math.clj -(defn square [x] - (* x x)) - -(defn factorial [n] - (if (= n 0) - 1 - (* n (factorial (- n 1))))) - -(let [a 5] - (println (square a)) - (println (factorial a))) -``` - -```bash -$ ./cljnim run examples/math.clj -25 -120 -``` - -## AI-First REPL - -Clojure/Nim е построен за AI агенти. JSON REPL предоставя структуриран I/O, идеален за програмно взаимодействие. - -```bash -$ ./cljnim repl --json -{"status":"ready","ns":"user","mode":"json"} - -> {"op":"eval","form":"(+ 1 2 3)"} -{"status":"ok","result":{"printed":"6"},"meta":{"ms":861}} - -> {"op":"eval","form":"(defn square [x] (* x x))"} -{"status":"ok","result":{"type":"var","name":"square"}} - -> {"op":"eval","form":"(square 5)"} -{"status":"ok","result":{"printed":"25"}} - -> {"op":"quit"} -{"status":"ok","bye":true} -``` - -## Документация - -| Документ | Описание | -|---|---| -| [`GUIDE.bg.md`](GUIDE.bg.md) | Ръководство за потребителя | -| [`ARCHITECTURE.bg.md`](ARCHITECTURE.bg.md) | Архитектура и дизайн | -| [`AI_FIRST.bg.md`](AI_FIRST.bg.md) | AI-first философия | -| [`API.bg.md`](API.bg.md) | REPL API референция | -| [`ROADMAP.bg.md`](ROADMAP.bg.md) | Пътна карта за разработка | - -## Лиценз - -MIT License — вижте [LICENSE](../LICENSE). diff --git a/docs/bg/01-getting-started.md b/docs/bg/01-getting-started.md new file mode 100644 index 0000000..2c608b0 --- /dev/null +++ b/docs/bg/01-getting-started.md @@ -0,0 +1,127 @@ + +[← Към индекса](index.md) + +--- + +# Първи стъпки + +> Диалект на Clojure, който се компилира до Nim → C → нативен бинарен файл. + +## Изисквания + +- **Nim** >= 2.0.0 +- **GCC** или **Clang** +- **make** +- **curl** (за AI функциите, незадължително) + +## Инсталация + +```bash +git clone https://gitlab.com/balvatar/lisp-nim.git +cd lisp-nim +make build +``` + +## Проверка + +```bash +make check # компилация + 276+ теста + всички примери +``` + +## CLI Команди + +| Команда | Описание | +|---------|----------| +| `./cljnim compile ` | Компилиране до Nim изходен код | +| `./cljnim compile-lib ` | Компилиране с експортирани функции (`*`) | +| `./cljnim run ` | Компилиране и изпълнение | +| `./cljnim read ` | Парсиране и печат на AST | +| `./cljnim repl` | Стартиране на човешки REPL | +| `./cljnim repl --json` | JSON REPL (за AI агенти) | +| `./cljnim deps` | Разрешаване на зависимости от `deps.edn` | +| `./cljnim -e '<код>'` | Оценка на израз | +| `./cljnim ai '<описание>'` | Генериране на Clojure код с AI | + +## Бързи примери + +### Hello World +```clojure +;; examples/hello.clj +(println "Hello, Nim world!") +(println (+ 1 2 3)) +``` + +```bash +$ ./cljnim run examples/hello.clj +Hello, Nim world! +6 +``` + +### Функции и рекурсия +```clojure +(defn square [x] (* x x)) +(defn factorial [n] + (if (= n 0) + 1 + (* n (factorial (- n 1))))) + +(let [a 5] + (println (square a)) + (println (factorial a))) +``` + +### loop/recur +```clojure +(defn sum [n] + (loop [acc 0 i 1] + (if (> i n) + acc + (recur (+ acc i) (inc i))))) +(println (sum 10)) ;; => 55 +``` + +### Atoms (REPL) +```clojure +user> (def a (atom 0)) +user> (swap! a inc) +1 +user> (reset! a 42) +42 +user> (deref a) +42 +``` + +## AI Настройка (незадължително) + +```bash +export DEEPSEEK_API_KEY="sk-..." +# или OPENAI_API_KEY, или MIMO_API_KEY +``` + +Виж [03-ai-integration.md](03-ai-integration.md) за пълна AI документация. + +## Структура на проекта + +``` +├── src/ # Изходен код на компилатора +│ ├── cljnim.nim # CLI входна точка +│ ├── reader.nim # EDN парсер +│ ├── emitter.nim # Clojure AST → Nim +│ ├── eval.nim # Интерпретатор (REPL бърз път) +│ └── ai_assist.nim # AI API интеграция +├── lib/ # Runtime библиотеки +│ ├── cljnim_runtime.nim # Нативен runtime +│ └── cljnim_runtime_js.nim # JS runtime +├── tests/ # Тестове (8 файла, 276+ теста) +├── examples/ # Примери .clj +├── benchmarks/ # Бенчмаркове +├── docs/ # Документация +└── experiments/ # Web, WASM, native-lib target-и +``` + +## Следващи стъпки + +- [02-architecture.md](02-architecture.md) — Как работи компилаторът +- [03-ai-integration.md](03-ai-integration.md) — AI-асистирана разработка +- [04-api-reference.md](04-api-reference.md) — JSON REPL протокол +- [05-user-guide.md](05-user-guide.md) — Макроси, interop, напреднали шаблони diff --git a/docs/ARCHITECTURE.bg.md b/docs/bg/02-architecture.md similarity index 81% rename from docs/ARCHITECTURE.bg.md rename to docs/bg/02-architecture.md index 50d0442..9a45364 100644 --- a/docs/ARCHITECTURE.bg.md +++ b/docs/bg/02-architecture.md @@ -1,3 +1,8 @@ + +[← Към индекса](index.md) + +--- + # Архитектура на Clojure/Nim ## Общ Преглед @@ -67,14 +72,16 @@ Clojure/Nim е **компилатор**, не интерпретатор. Сле - `cljAdd`, `cljMul`, и т.н. — полиморфна аритметика - `cljRepr` — текстово представяне -### 4. Nim Interop (Бъдеще) -Вместо Java interop, ще имаме Nim interop: +### 4. Nim Interop +Вместо Java interop, имаме директен Nim interop: ```clojure -(nim/import "strutils") -(nim/call "strutils.join" ", " ["a" "b"]) +(nim/math/sin x) +(nim/strutils/toUpper s) ``` +Nim модулите се импортират автоматично при извикване през `nim/module/fn` шаблона. + ## Отговорности на Модулите | Модул | Роля | @@ -82,13 +89,19 @@ Clojure/Nim е **компилатор**, не интерпретатор. Сле | `src/reader.nim` | Парсира `.clj` текст към `CljVal` AST | | `src/emitter.nim` | Трансформира `CljVal` AST в Nim изходен код | | `src/repl.nim` | Имплементация на human и AI REPL | +| `src/eval.nim` | Tree-walking interpreter за бързо in-memory eval | +| `src/deps.nim` | Резолюция на зависимости (deps.edn формат) | +| `src/core.nim` | Core runtime функции (AOT компилирани) | | `src/types.nim` | Типове на AST възли (използват се от reader/emitter) | | `src/macros.nim` | Двигател за разширяване на макроси | | `src/runtime.nim` | Допълнителни runtime помощници | | `lib/cljnim_runtime.nim` | Основна runtime библиотека | +| `lib/cljnim_pvec.nim` | Persistent Vector (HAMT имплементация) | +| `lib/cljnim_pmap.nim` | Persistent Hash Map (HAMT имплементация) | +| `lib/cljnim_async.nim` | core.async channels runtime | ## Модел на Паметта - Използва Nim's ORC garbage collector - `CljVal` е `ref object` (заделя се на heap) -- Бъдеще: persistent структури от данни използват структурно споделяне +- Persistent структури от данни (Vector, Map, Set) използват структурно споделяне през HAMT diff --git a/docs/AI_FIRST.bg.md b/docs/bg/03-ai-integration.md similarity index 98% rename from docs/AI_FIRST.bg.md rename to docs/bg/03-ai-integration.md index 1b0dc23..a5666e3 100644 --- a/docs/AI_FIRST.bg.md +++ b/docs/bg/03-ai-integration.md @@ -1,3 +1,8 @@ + +[← Към индекса](index.md) + +--- + # AI-First Философия на Дизайна ## Защо AI-First? diff --git a/docs/API.bg.md b/docs/bg/04-api-reference.md similarity index 98% rename from docs/API.bg.md rename to docs/bg/04-api-reference.md index a93220a..e82ba88 100644 --- a/docs/API.bg.md +++ b/docs/bg/04-api-reference.md @@ -1,3 +1,8 @@ + +[← Към индекса](index.md) + +--- + # REPL API Референция ## JSON REPL Протокол diff --git a/docs/GUIDE.bg.md b/docs/bg/05-user-guide.md similarity index 93% rename from docs/GUIDE.bg.md rename to docs/bg/05-user-guide.md index 8887e4c..0f9b5ab 100644 --- a/docs/GUIDE.bg.md +++ b/docs/bg/05-user-guide.md @@ -1,3 +1,8 @@ + +[← Към индекса](index.md) + +--- + # Ръководство за Потребителя — Clojure/Nim ## Инсталация @@ -83,8 +88,8 @@ make build ; Ключови думи (def person {:name "Алиса" :age 30}) -; В момента картите и множествата са ограничени. -; Пълни persistent структури (HAMT) са в разработка. +; Картите и множествата използват persistent HAMT структури +; със structural sharing и O(log₃₂ n) операции. ``` ### Рекурсия diff --git a/docs/ROADMAP.bg.md b/docs/bg/06-roadmap.md similarity index 60% rename from docs/ROADMAP.bg.md rename to docs/bg/06-roadmap.md index 4d4a637..18cdd90 100644 --- a/docs/ROADMAP.bg.md +++ b/docs/bg/06-roadmap.md @@ -1,3 +1,8 @@ + +[← Към индекса](index.md) + +--- + # Пътна Карта за Разработка ## Фаза 0: Компилаторно Ядро ✅ @@ -41,42 +46,41 @@ - [x] Файлови операции: `(file/ls "dir")`, `(file/exists? "path")` - [x] Git операции: `(git/status)`, `(git/commit "msg")`, `(git/push)` - [x] Git операции: `(git/diff)`, `(git/log)` -- [ ] nREPL протокол съвместимост -- [ ] Tool-call формат за интеграция с AI frameworks +- [x] nREPL протокол съвместимост (JSON over TCP, `--tcp PORT`) +- [x] Tool-call формат за интеграция с AI frameworks -## Фаза 5: Persistent Структури от Данни -- [ ] Persistent Vector (Hash Array Mapped Trie) -- [ ] Persistent Map (HAMT) -- [ ] Persistent Set -- [ ] `conj`, `assoc`, `dissoc`, `get`, `get-in` -- [ ] `nth`, `first`, `rest`, `last`, `count` върху persistent колекции -- [ ] Transients за batch мутации +## Фаза 5: Persistent Структури от Данни ✅ (Завършена) +- [x] Persistent Vector (Hash Array Mapped Trie, 32-way branching) +- [x] Persistent Map (HAMT) — `pmapAssoc`, `pmapDissoc`, `pmapGet` в O(log₃₂ n) +- [x] Persistent Set +- [x] `conj`, `assoc`, `dissoc`, `get`, `get-in` +- [x] `nth`, `first`, `rest`, `last`, `count` върху persistent колекции +- [x] Transients за batch мутации +- [x] `conj!`, `assoc!`, `persistent!` -## Фаза 6: Clojure Core Библиотека -- [ ] `range`, `repeat`, `cycle`, `iterate` -- [ ] `take`, `drop`, `partition`, `interleave`, `concat` -- [ ] `str`, `pr-str`, `println`, `prn` -- [ ] `slurp`, `spit`, `read-line` -- [ ] `meta`, `with-meta`, `vary-meta` -- [ ] `type`, `instance?`, `satisfies?` +## Фаза 6: Clojure Core Библиотека ✅ (Завършена) +- [x] `range`, `repeat`, `cycle`, `iterate` +- [x] `take`, `drop`, `partition`, `interleave`, `concat` +- [x] `str`, `pr-str`, `println`, `prn` +- [x] `slurp`, `spit`, `read-line` +- [x] `meta`, `with-meta`, `vary-meta` +- [x] `type`, `instance?`, `satisfies?` -## Фаза 7: Компилация на Проекти -- [ ] Компилиране на цели проекти (не само отделни файлове) -- [ ] Система за namespaces (`ns`, `require`, `use`) -- [ ] Кеширане на модули за по-бърз REPL старт -- [ ] Резолюция на зависимости +## Фаза 7: Компилация на Проекти ✅ +- [x] Компилиране на цели проекти (не само отделни файлове) +- [x] Система за namespaces (`ns`, `(:require [lib :as alias])`) +- [x] Кеширане на модули за по-бърз REPL старт +- [x] Резолюция на зависимости (deps.edn, Git deps към .deps/) -## Фаза 8: Self-Hosted REPL -- [ ] Компилиране на форми в паметта (без temp файлове) -- [ ] Бърз REPL старт (< 100ms) -- [ ] Hot code reloading +## Фаза 8: Self-Hosted REPL ✅ +- [x] Компилиране на форми в паметта (tree-walking interpreter, <1ms eval) +- [x] Бърз REPL старт (~0.02ms на eval спрямо 1133ms компилиран) +- [x] Hot code reloading (def/defn обновяват средата незабавно) -## Фаза 9: Конкурентност -- [ ] Atoms (compare-and-swap) -- [ ] Agents -- [ ] core.async channels (упростен вариант) +## Фаза 9: Конкурентност ✅ +- [x] Atoms (compare-and-swap) +- [x] Agents (send, await, deref — sync dispatch в interpreter) +- [x] core.async channels (chan, >!, >` threading macro с вложени `map`/`reduce` изисква правилен macro expansion контекст -- REPL дефинициите се прекомпилират от нулата при всяка оценка (бавно, но коректно) -- Няма истински persistent структури от данни (runtime използва Nim seq/tables) diff --git a/docs/bg/index.md b/docs/bg/index.md new file mode 100644 index 0000000..cc57eb4 --- /dev/null +++ b/docs/bg/index.md @@ -0,0 +1,36 @@ + +[← Към индекса](index.md) + +--- + +# Clojure/Nim Документация (Български) + +> Диалект на Clojure, който се компилира до Nim → C → нативен бинарен файл. + +## Съдържание + +| # | Документ | Описание | +|---|----------|----------| +| 01 | [Първи стъпки](01-getting-started.md) | Инсталация, компилация, CLI команди, бързи примери | +| 02 | [Архитектура](02-architecture.md) | Компилационен pipeline, дизайн решения, вътрешна структура | +| 03 | [AI Интеграция](03-ai-integration.md) | DeepSeek, OpenAI, MiMo — помощ при грешки, генериране на код, оптимизация, дебъг | +| 04 | [API Справочник](04-api-reference.md) | JSON REPL протокол, операции, tool-call формат | +| 05 | [Ръководство](05-user-guide.md) | Макроси, threading, interop, напреднали шаблони | +| 06 | [Пътна карта](06-roadmap.md) | Завършени фази, бъдещи планове, цели за перформанс | + +## Бърз старт + +```bash +git clone https://gitlab.com/balvatar/lisp-nim.git +cd lisp-nim +make build +make check # компилация + тестове + примери +./cljnim repl # човешки REPL +``` + +## Статистика + +- **Тестове:** 276+ в 8 suite-а +- **Компилатор:** Nim → C → нативен код +- **Target-и:** Linux, macOS, Windows, JS, WASM, C shared libraries +- **AI Поддръжка:** DeepSeek API, OpenAI-compatible, Xiaomi MiMo diff --git a/docs/en/01-getting-started.md b/docs/en/01-getting-started.md new file mode 100644 index 0000000..e61c7c9 --- /dev/null +++ b/docs/en/01-getting-started.md @@ -0,0 +1,127 @@ + +[← Back to Index](index.md) + +--- + +# Getting Started + +> A Clojure dialect that compiles to Nim → C → native binaries. + +## Prerequisites + +- **Nim** >= 2.0.0 +- **GCC** or **Clang** +- **make** +- **curl** (for AI features, optional) + +## Installation + +```bash +git clone https://gitlab.com/balvatar/lisp-nim.git +cd lisp-nim +make build +``` + +## Verify Installation + +```bash +make check # build + 276+ tests + all examples +``` + +## CLI Commands + +| Command | Description | +|---------|-------------| +| `./cljnim compile ` | Compile to Nim source | +| `./cljnim compile-lib ` | Compile to Nim with exported functions (`*`) | +| `./cljnim run ` | Compile and run binary | +| `./cljnim read ` | Parse and print AST | +| `./cljnim repl` | Start human REPL | +| `./cljnim repl --json` | Start JSON REPL (for AI agents) | +| `./cljnim deps` | Resolve dependencies from `deps.edn` | +| `./cljnim -e ''` | Evaluate expression | +| `./cljnim ai ''` | Generate Clojure code with AI | + +## Quick Examples + +### Hello World +```clojure +;; examples/hello.clj +(println "Hello, Nim world!") +(println (+ 1 2 3)) +``` + +```bash +$ ./cljnim run examples/hello.clj +Hello, Nim world! +6 +``` + +### Functions & Recursion +```clojure +(defn square [x] (* x x)) +(defn factorial [n] + (if (= n 0) + 1 + (* n (factorial (- n 1))))) + +(let [a 5] + (println (square a)) + (println (factorial a))) +``` + +### loop/recur +```clojure +(defn sum [n] + (loop [acc 0 i 1] + (if (> i n) + acc + (recur (+ acc i) (inc i))))) +(println (sum 10)) ;; => 55 +``` + +### Atoms (REPL) +```clojure +user> (def a (atom 0)) +user> (swap! a inc) +1 +user> (reset! a 42) +42 +user> (deref a) +42 +``` + +## AI Setup (Optional) + +```bash +export DEEPSEEK_API_KEY="sk-..." +# or OPENAI_API_KEY, or MIMO_API_KEY +``` + +See [03-ai-integration.md](03-ai-integration.md) for full AI documentation. + +## Project Structure + +``` +├── src/ # Compiler source +│ ├── cljnim.nim # CLI entry point +│ ├── reader.nim # EDN parser +│ ├── emitter.nim # Clojure AST → Nim +│ ├── eval.nim # Tree-walking interpreter (REPL fast path) +│ └── ai_assist.nim # AI API integration +├── lib/ # Runtime libraries +│ ├── cljnim_runtime.nim # Native runtime +│ └── cljnim_runtime_js.nim # JS runtime +├── tests/ # Test suites (8 files, 276+ tests) +├── examples/ # Example .clj files +├── benchmarks/ # Performance benchmarks +├── docs/ # Documentation +└── experiments/ # Web, WASM, native-lib targets +``` + +## Next Steps + +- [02-architecture.md](02-architecture.md) — How the compiler works +- [03-ai-integration.md](03-ai-integration.md) — AI-powered development +- [04-api-reference.md](04-api-reference.md) — JSON REPL protocol +- [05-user-guide.md](05-user-guide.md) — Macros, interop, advanced patterns diff --git a/docs/ARCHITECTURE.md b/docs/en/02-architecture.md similarity index 79% rename from docs/ARCHITECTURE.md rename to docs/en/02-architecture.md index f1ffbb5..0763f16 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/en/02-architecture.md @@ -1,3 +1,8 @@ + +[← Back to Index](index.md) + +--- + # Clojure/Nim Architecture ## Overview @@ -67,14 +72,16 @@ The `lib/cljnim_runtime.nim` module provides: - `cljAdd`, `cljMul`, etc. — polymorphic arithmetic - `cljRepr` — string representation -### 4. Nim Interop (Future) -Instead of Java interop, we will have Nim interop: +### 4. Nim Interop +Instead of Java interop, we have direct Nim interop: ```clojure -(nim/import "strutils") -(nim/call "strutils.join" ", " ["a" "b"]) +(nim/math/sin x) +(nim/strutils/toUpper s) ``` +Nim modules are auto-imported when called via the `nim/module/fn` pattern. + ## Module Responsibilities | Module | Role | @@ -82,13 +89,19 @@ Instead of Java interop, we will have Nim interop: | `src/reader.nim` | Parses `.clj` text into `CljVal` AST | | `src/emitter.nim` | Transforms `CljVal` AST into Nim source | | `src/repl.nim` | Human and AI REPL implementation | +| `src/eval.nim` | Tree-walking interpreter for fast in-memory eval | +| `src/deps.nim` | Dependency resolution (deps.edn format) | +| `src/core.nim` | Core runtime functions (AOT compiled) | | `src/types.nim` | AST node types (used by reader/emitter) | | `src/macros.nim` | Macro expansion engine | | `src/runtime.nim` | Additional runtime helpers | | `lib/cljnim_runtime.nim` | Core runtime library | +| `lib/cljnim_pvec.nim` | Persistent Vector (HAMT implementation) | +| `lib/cljnim_pmap.nim` | Persistent Hash Map (HAMT implementation) | +| `lib/cljnim_async.nim` | core.async channels runtime | ## Memory Model - Uses Nim's ORC garbage collector - `CljVal` is a `ref object` (heap-allocated) -- Future: persistent data structures use structural sharing +- Persistent data structures (Vector, Map, Set) use structural sharing via HAMT diff --git a/docs/AI_FIRST.md b/docs/en/03-ai-integration.md similarity index 98% rename from docs/AI_FIRST.md rename to docs/en/03-ai-integration.md index 19fb527..c451b33 100644 --- a/docs/AI_FIRST.md +++ b/docs/en/03-ai-integration.md @@ -1,3 +1,8 @@ + +[← Back to Index](index.md) + +--- + # AI-First Design Philosophy ## Why AI-First? diff --git a/docs/API.md b/docs/en/04-api-reference.md similarity index 98% rename from docs/API.md rename to docs/en/04-api-reference.md index db2a706..401d8e8 100644 --- a/docs/API.md +++ b/docs/en/04-api-reference.md @@ -1,3 +1,8 @@ + +[← Back to Index](index.md) + +--- + # REPL API Reference ## JSON REPL Protocol diff --git a/docs/GUIDE.md b/docs/en/05-user-guide.md similarity index 93% rename from docs/GUIDE.md rename to docs/en/05-user-guide.md index b83f78a..3de35c4 100644 --- a/docs/GUIDE.md +++ b/docs/en/05-user-guide.md @@ -1,3 +1,8 @@ + +[← Back to Index](index.md) + +--- + # Clojure/Nim User Guide ## Installation @@ -83,8 +88,8 @@ Shows the Clojure AST as S-expressions. ; Keywords (def person {:name "Alice" :age 30}) -; Currently, maps and sets are limited. Full persistent -; data structures (HAMT) are in development. +; Maps and sets use persistent HAMT data structures +; with structural sharing and O(log₃₂ n) operations. ``` ### Recursion diff --git a/docs/ROADMAP.md b/docs/en/06-roadmap.md similarity index 99% rename from docs/ROADMAP.md rename to docs/en/06-roadmap.md index 4e585a2..f6a86ed 100644 --- a/docs/ROADMAP.md +++ b/docs/en/06-roadmap.md @@ -1,3 +1,8 @@ + +[← Back to Index](index.md) + +--- + # Development Roadmap ## Phase 0: Compiler Core ✅ diff --git a/docs/en/index.md b/docs/en/index.md new file mode 100644 index 0000000..39fd4dc --- /dev/null +++ b/docs/en/index.md @@ -0,0 +1,36 @@ + +[← Back to Index](index.md) + +--- + +# Clojure/Nim Documentation (English) + +> A Clojure dialect that compiles to Nim → C → native binaries. + +## Table of Contents + +| # | Document | Description | +|---|----------|-------------| +| 01 | [Getting Started](01-getting-started.md) | Installation, build, CLI commands, quick examples | +| 02 | [Architecture](02-architecture.md) | Compiler pipeline, design decisions, internal structure | +| 03 | [AI Integration](03-ai-integration.md) | DeepSeek, OpenAI, MiMo — error assistance, code generation, optimization, debugging | +| 04 | [API Reference](04-api-reference.md) | JSON REPL protocol, operations, tool-call format | +| 05 | [User Guide](05-user-guide.md) | Macros, threading, interop, advanced patterns | +| 06 | [Roadmap](06-roadmap.md) | Completed phases, future plans, performance targets | + +## Quick Start + +```bash +git clone https://gitlab.com/balvatar/lisp-nim.git +cd lisp-nim +make build +make check # build + tests + examples +./cljnim repl # human REPL +``` + +## Stats + +- **Tests:** 276+ across 8 suites +- **Compiler:** Nim → C → native +- **Targets:** Linux, macOS, Windows, JS, WASM, C shared libraries +- **AI Support:** DeepSeek API, OpenAI-compatible, Xiaomi MiMo diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..810de5d --- /dev/null +++ b/docs/index.md @@ -0,0 +1,16 @@ +# Clojure/Nim Documentation + +> A Clojure dialect that compiles to Nim → C → native binaries. + +## Choose Language / Избор на език + +| 🇬🇧 English | 🇧🇬 Български | +|------------|-------------| +| [English Documentation](en/index.md) | [Българска Документация](bg/index.md) | + +## Quick Links + +- **GitHub/GitLab:** [lisp-nim](https://gitlab.com/balvatar/lisp-nim) +- **Build:** `make build && make check` +- **Tests:** 276+ tests across 8 test suites +- **AI Integration:** DeepSeek API, OpenAI-compatible, Xiaomi MiMo