docs: add compliance plan — 171/233 (73%), roadmap to 90%+

This commit is contained in:
2026-05-09 18:40:30 +03:00
parent f79a2591d4
commit 0ba94881be
+78 -96
View File
@@ -1,114 +1,96 @@
# План за Clojure/Nim — Ден на Победата Edition 🎖️
# Clojure/Nim — Test Suite Compliance Plan
## Направено (8-9 май 2026)
## Current Status: 171/233 (73%)
### Ядро (Compiler Core)
-`loop`/`recur` вече работи в компилиран код (критичен бъг оправен)
-`compile-lib` режим — експортирани функции за library generation
- ✅ 20+ компилаторни предупреждения изчистени
-`make check` — build + test + всички примери
| Component | Pass | Total | % |
|---|---|---|---|
| clojure.string | 8 | 8 | 100% |
| clojure.core | 163 | 225 | 73% |
| **Total** | **171** | **233** | **73%** |
### AI Интеграция (Phase AI-1 до AI-4) — 9 май 2026
-**AI-Assisted Errors** — error cache, Reader/Emitter/Nim error coverage
-**AI Code Generation**`(ai/generate "...")` в REPL, `:ai` команда, JSON REPL `ai-generate`
-**AI Optimization Hints**`(ai/optimize "...")`, `buildOptimizationPrompt`
-**AI Debugging**`(ai/debug expr)`, `buildDebugPrompt`, JSON REPL `ai-debug`
## What's Working (171 tests passing)
### Тестове
- `tests/test_macros.nim` — 30 теста за макроси
- `tests/test_eval.nim` — +30 нови теста (math, collections, agents, channels)
- `tests/test_emitter.nim` — +3 теста за loop/recur
### Core Infrastructure
- **Reader**: Clojure syntax parsing, `#?` reader conditionals, `#uuid"..."`, `#"regex"`, char literals (`\newline`, `\space`, etc.), N/M/ratio suffixes, comma as whitespace
- **Emitter**: Macro expansion, scope tracking, iterative worklist form processing, metadata stripping, namespace-qualified macro resolution
- **Macros**: `deftest`, `is`, `testing`, `are`, `thrown?`, `when-var-exists`, `and`, `or`, `when`, `when-not`, `cond`, `for`, `doseq`, `dotimes`, `->`, `->>`, `some->`, `some->>`, `cond->`, `cond->>`, `doto`, `as->`, `defmacro`, `comment`
- **HAMT Data Structures**: Persistent Vector, Map, Set — all native Nim, zero Java dependency
- **Runtime**: 100+ functions implemented (arithmetic, collections, predicates, I/O, agents, channels)
### Документация
- ✅ README.md, ROADMAP.bg.md, ARCHITECTURE.md синхронизирани
- ✅ LICENSE файл добавен
### clojure.string
All 8 tests pass: `blank?`, `capitalize`, `ends-with?`, `escape`, `lower-case`, `reverse`, `starts-with?`, `upper-case`
### Нови Target-и
-`experiments/web-target/` — Clojure → Nim → JS
-`experiments/native-lib/` — Clojure → Nim → C shared library
-`experiments/wasm-target/` — WASM skeleton
## Remaining Failures (62 tests)
---
### Priority 1 — Missing Advanced Features (~15 tests)
These need new emitter/compiler support:
- `defprotocol` — protocol definitions
- `defrecord` — record types
- `deftype` — custom types
- `defmulti` / `defmethod` — multimethods
- `instance?` — type checking against protocols/records
## План за 9 май — AI Интеграция (DeepSeek / Xiaomi MiMo)
Affected tests: `ancestors`, `derive`, `descendants`, `dissoc`, `ifn_qmark`, `not_eq`, `parents`, `underive`, `bound_fn`, `bound_fn_star`, `var_qmark`, `case`
### Phase AI-1: AI-Assisted Error Messages ✅
**Цел:** Когато `cljnim compile` fail-не, AI анализира грешката и дава обяснение на български/английски.
### Priority 2 — Reader Preprocessing (~10 tests)
The `test_single.py` preprocessor uses regex to replace `#{}` sets with `@[]`, which breaks when sets contain nested `}`. Need proper set literal parsing or native `#{}` support in reader.
**Имплементация:**
-`src/ai_assist.nim` — Error cache за чести грешки (in-memory, 50 записа, TTL 1 час)
- ✅ ReaderError/EmitterError coverage — AI обяснения за грешки на всички нива (reader, emitter, Nim compiler)
- ✅ Интеграция с DeepSeek API (вече беше)
- ✅ Cache за чести грешки
Affected tests: `add_watch`, `conj`, `conj_bang`, `hash_set`, `reduce`, `remove_watch`
### Phase AI-2: AI Code Generation в REPL ✅
**Цел:** Генериране на Clojure функции от описание.
### Priority 3 — are_arity (5 tests)
`#?@` splice inside `are` forms doesn't match arity correctly. The preprocessor's `extract_default` doesn't handle all `#?@` patterns.
```clojure
user> (ai/generate "функция за бързо сортиране на вектор")
" (defn quicksort [v] ...)"
Affected tests: `bit_and`, `bit_and_not`, `bit_flip`, `bit_set`, `bit_shift_left`
### Priority 4 — Missing Runtime Functions (~10 tests)
Simple stubs needed:
- `aclone`, `int-array` — Java array interop stubs
- `rseq` — reverse sequence
- `empty` — empty collection (different from `empty?`)
- `delay` — lazy evaluation
- `create-ns` — namespace creation
- `sorted-map-by` — sorted map with comparator
### Priority 5 — Type Mismatches (~9 tests)
Nim type errors from edge cases in macro expansion:
- `compare`, `cons`, `drop_last`, `fnil`, `get`, `shuffle`, `vec`, `update`, `taps`
### Priority 6 — Other (~13 tests)
- `bigint` — integer overflow on big numbers
- `constantly`, `atom`, `transient` — closing quote errors in generated Nim
- `merge` — syntax error in generated code
- `portability` — unquote-splicing edge case
- `random_uuid`, `uuid_qmark`, `parse_uuid` — UUID dispatch reader issue
- `realized_qmark`, `when_first`, `when_let` — indentation issues
## Architecture Notes
### Compilation Pipeline
```
Clojure source → Reader (AST) → Macro expansion → Emitter (Nim code) → Nim compiler → C compiler → native binary
```
**Имплементация:**
- `ai/generate` builtin в eval.nim (interpreter)
- `:ai <desc>` в human REPL (вече беше)
- `ai-generate` op в JSON REPL
### Key Files
- `src/reader.nim` — Clojure parser (455 lines)
- `src/emitter.nim` — Nim code generator (1443 lines)
- `src/macros.nim` — Macro system (527 lines)
- `lib/cljnim_runtime.nim` — Runtime library (1896 lines)
- `lib/cljnim_pvec.nim` — HAMT Persistent Vector
- `lib/cljnim_pmap.nim` — HAMT Persistent Map
- `test_single.py` — Test runner for clojure-test-suite
### Phase AI-3: AI Optimization Hints ✅
**Цел:** Компилаторът използва AI за избор на алгоритми.
### What Makes This Different from Other Clojure Dialects
- **No JVM** — compiles to native via Nim → C
- **Native HAMT** — persistent data structures written in Nim, not Java
- **Zero dependencies** — no GraalVM, no JVM, no Google Closure Compiler
- **Multi-target** — native, shared library, WASM, JavaScript
```clojure
user> (ai/optimize "(defn sum [nums] (reduce + nums))")
"Consider using transients for large collections..."
```
## Next Steps to Reach 90%+
**Имплементация:**
-`ai/optimize` builtin в eval.nim
-`:optimize <code>` в human REPL
-`ai-optimize` op в JSON REPL
-`buildOptimizationPrompt` в ai_assist.nim
1. Implement `defprotocol` / `defrecord` / `deftype` emitter support (~15 tests)
2. Add native `#{}` set literal support in reader (~10 tests)
3. Fix `#?@` splice handling in `are` preprocessor (~5 tests)
4. Add remaining runtime function stubs (~10 tests)
5. Fix Nim type edge cases in emitter (~5 tests)
### Phase AI-4: AI Debugging ✅
**Цел:** REPL команди за анализ на runtime поведение.
```clojure
user> (ai/debug (factorial 5))
🤖 AI Analysis:
- factorial(5) = 120 (коректно)
- Време: O(n) рекурсия
```
**Имплементация:**
-`ai/debug` special form в eval.nim (raw expression pre-evaluation)
-`:debug <expr>` в human REPL
-`ai-debug` op в JSON REPL
-`buildDebugPrompt` в ai_assist.nim
---
## Технически детайли за AI интеграция
### DeepSeek API
- Endpoint: `https://api.deepseek.com/v1/chat/completions`
- Model: `deepseek-chat` или `deepseek-coder`
- Български език: ✅ поддържа
### Xiaomi MiMo
- Endpoint: зависи от deployment
- Може да се self-hostва
### Архитектура
```
User Input → Clojure/Nim → Error/Request → AI Module → DeepSeek/MiMo API
Cached Response → User
```
---
## Следващи стъпки (ядро)
1.**Обединяване на CljVal типовете**`src/types.nim` + `lib/cljnim_runtime.nim` + `src/runtime.nim` + `lib/cljnim_runtime_js.nim` — всички 4 файла вече имат идентичен CljKind enum (15 стойности)
2.**`try`/`catch`/`finally`** — пълна имплементация в emitter — exception type вече се използва, binding e cljMap с `:type` и `:message`
3.**`swap!`/`reset!`** в interpreter-а — вече беше имплементирано
4.**Reader edge cases**`-.5` negative floats, scientific notation `1e5`/`1.5e-3`, unterminated string tests, negative float tests — 13 нови теста
Estimated effort: 2-3 focused sessions to reach 90%+ (210+/233).