Phase 8: Protocol System — defprotocol, extend-type, extend-protocol, satisfies?
- types.janet: type-registry, register-protocol-method, find-protocol-method, type-satisfies? - core.janet: rewritten protocol macros (defprotocol, extend-type, extend-protocol, reify) Protocol value stores :jolt/type :jolt/protocol with :methods map Method dispatch fns use fn* [this & rest-args] → protocol-dispatch special form - evaluator.janet: protocol-dispatch, register-method, make-reified special forms satisfies? special form with type registry lookup special-symbol? entries for all 3 protocol ops + satisfies? - 4 test sections (35-38): defprotocol, extend-type, extend-protocol, satisfies? extend-type: basic dispatch works (42 constant), .-field accessor needs further debug satisfies?: fully functional with type registry - 315 ok, 2 fail (pre-existing, unchanged)
This commit is contained in:
parent
09c4cb2242
commit
053ed4f790
11 changed files with 463 additions and 134 deletions
|
|
@ -1,4 +1,5 @@
|
|||
# jolt-dev
|
||||
# jolt-dev
|
||||
|
||||
Jolt development workflow — build, test, special form patterns, Janet gotchas
|
||||
|
||||
|
|
@ -13,82 +14,63 @@ jpm test # runs all tests
|
|||
janet test/foo.janet # run a single test file from project root
|
||||
```
|
||||
|
||||
## Janet Eval Pipeline (critical)
|
||||
## Special Form Checklist
|
||||
|
||||
Janet's `(parse s)` does NOT return a parsed form — it returns `[symbol, error-position]`.
|
||||
For evaluating Janet source strings, use the parser pipeline:
|
||||
To add a new special form to the evaluator:
|
||||
|
||||
1. Add the name to `special-symbol?` in `src/jolt/evaluator.janet`
|
||||
2. Add a match arm in `eval-list` (the match on `name`)
|
||||
3. Add tests in `test/evaluator-test.janet`
|
||||
|
||||
The match arm receives `ctx`, `bindings`, and `form` (the full list). Use `(in form 1)` for first arg, etc.
|
||||
|
||||
**Non-symbol heads** (keywords, etc.): `eval-list` first checks `(and (struct? first-form) (= :symbol (...)))` before extracting `name`. If not a symbol, falls through to default function application.
|
||||
|
||||
### Current special forms (29):
|
||||
`quote`, `syntax-quote`, `unquote`, `unquote-splicing`, `do`, `if`, `def`, `defmacro`, `fn*`, `let*`, `loop*`, `recur`, `throw`, `try`, `set!`, `var`, `locking`, `instance?`, `defmulti`, `defmethod`, `deftype`, `new`, `.`, `var-get`, `var-set`, `var?`, `alter-var-root`, `find-var`, `intern`, `alter-meta!`, `reset-meta!`, `disj`, `set?`
|
||||
|
||||
## Compiler Architecture
|
||||
|
||||
Two-phase: `analyze-form [form bindings ctx]` → `emit-ast` (string) or `emit-expr` (data structures).
|
||||
|
||||
**Why data structures:** Janet's `eval` can't see `use`-imported symbols. Embed function VALUES directly via `core-fn-values` table.
|
||||
|
||||
**eval-string dispatch** (compile mode): stateful forms → interpreter; everything else → `compile-and-eval`. Macros expand at analyze time.
|
||||
|
||||
## PersistentHashMap Gotchas
|
||||
|
||||
- `core-map?`: `(if (and (table? x) (get x :jolt/deftype)) true false)` — `and` returns last truthy, not boolean
|
||||
- `core-count`: subtract 1 for deftype tables (skip `:jolt/deftype` key)
|
||||
- Equality: convert via `phm-to-struct` before `deep=`
|
||||
|
||||
## defrecord / deftype Patterns
|
||||
|
||||
- defrecord emits `(deftype TypeName [fields])` + arrow factory `(fn fields-vec (TypeName. field1 field2...))`
|
||||
- Records are tables with `:jolt/deftype` = type name string
|
||||
- `set!` field mutation: `(set! (.-x obj) val)` parses as array with `.-x` symbol head — check symbol name before dispatch
|
||||
|
||||
## Binding Macro
|
||||
|
||||
Uses `array-map` (plain Janet struct) not `hash-map` (PHM) to avoid PHM get() incompatibility with `var-get`.
|
||||
|
||||
## Tagged Literals (#inst, #uuid)
|
||||
|
||||
`:#inst` is invalid Janet keyword syntax (contains `#`). Use dynamic table construction:
|
||||
```janet
|
||||
(def p (parser/new))
|
||||
(parser/consume p source)
|
||||
(parser/eof p) # REQUIRED — otherwise produce returns nil
|
||||
(def form (parser/produce p))
|
||||
(eval form)
|
||||
(let [dr @{}] (put dr (keyword "#inst") (fn [s] s)) dr)
|
||||
```
|
||||
|
||||
**Never** try `(eval [if true 1 2])` — Janet's `eval` doesn't recognize special forms in tuple data structures.
|
||||
## LazySeq Patterns
|
||||
|
||||
## `var` vs `def`
|
||||
|
||||
When you need to mutate a local with `set`, use `(var x nil)` not `(def x nil)`. `def` creates constants.
|
||||
|
||||
## Compiler (see also `jolt-compiler` skill)
|
||||
|
||||
`src/jolt/compiler.janet` — Clojure→Janet source compiler with macro expansion.
|
||||
`test/compiler-test.janet` — 11 test groups covering all ops.
|
||||
|
||||
Key design decision: **compile-and-eval emits Janet DATA STRUCTURES, not source strings**, because Janet's `eval` doesn't see `use`-imported symbols. `core-fn-values` table resolves Janet names to actual function values at compile time.
|
||||
|
||||
### Adding a compiled op
|
||||
|
||||
1. **analyze-form**: add `match head-name` arm returning `{:op :your-op ...}`
|
||||
2. **emit-ast**: add str function + `:your-op` case in `set emit-ast` dispatch
|
||||
3. **emit-expr**: add expr function + `:your-op` case in `set emit-expr` dispatch
|
||||
4. Add tests in `test/compiler-test.janet`
|
||||
|
||||
### Emit-expr critical rules
|
||||
- **Vectors**: wrap with `['tuple ...]` — bare tuples eval as fn calls
|
||||
- **try/catch**: `[(tuple ;[err-sym]) handler]` NOT `(catch [err] body)`
|
||||
- **quote**: use `raw-form->janet` converter, don't re-analyze
|
||||
- **Core fns**: resolve via `core-fn-values` table, embed fn VALUES not names
|
||||
|
||||
### Macro expansion
|
||||
`analyze-form` checks `resolve-macro` first — if head is a macro var, applies fn, re-analyzes expanded form (only when ctx passed).
|
||||
|
||||
## Persistent Data Structures
|
||||
|
||||
Located in:
|
||||
- `src/jolt/clojure/lang/persistent_vector.clj`
|
||||
- `src/jolt/clojure/lang/persistent_hash_map.clj`
|
||||
|
||||
Loaded at init time by `load-persistent-structures` in `api.janet`. Use `{:mutable? true}` to skip and use Janet-native types.
|
||||
|
||||
### Implementation detail
|
||||
Simple array-based implementation (node-assoc/node-find/find-key-index), NOT HAMT bit-trie.
|
||||
HAMT failed because Janet uses 64-bit doubles and bit operations require 32-bit signed ints.
|
||||
- Use `indexed?` not `tuple?` for realized sequences (may be arrays from `cons`/`concat`)
|
||||
- Avoid `val'` (apostrophe in symbol names) — causes Janet parse errors; use `vf` instead
|
||||
- `ls-first`/`ls-rest`/`ls-seq` all call `realize-ls` first (caches result, realizes once)
|
||||
|
||||
## Janet Gotchas
|
||||
|
||||
- Bit operations (brshift, brushift, band) use 32-bit signed integers. Hash values can exceed 32-bit range. Use `(band x 0xFFFFFFFF)` before shifting.
|
||||
- `deftype` creates tables, not structs. `struct?` returns false.
|
||||
- `(get child :key)` DOES follow table prototype chain — resolved and confirmed working.
|
||||
- Janet LSP produces many false positives on `.janet` files — safe to ignore.
|
||||
- Janet `and` returns the last truthy value, NOT boolean `true`. Wrap with `(if (and ...) true false)` for predicates.
|
||||
- `set!` field mutation: `(set! (.-x obj) val)` reader creates `(. -x obj)` array — must check for `.` head in set! handler BEFORE the var mutation branch.
|
||||
|
||||
## deftype/defrecord Patterns
|
||||
|
||||
**deftype** produces a table with `:jolt/deftype` key (format: `"ns.TypeName"`):
|
||||
- Constructor: `(TypeName. args...)` — evaluator creates `@{:jolt/deftype "ns.TypeName" :key1 val1 ...}`
|
||||
- Field access: `(. obj field)` — evaluator does `(get obj (keyword field-name))`
|
||||
- Mutation: `(set! (.-field obj) val)` — reader creates `(. -field obj)` array form
|
||||
|
||||
**Defrecord** macro emits `(do (deftype Name [fields]) (def ->Name ...) (def map->Name ...))`.
|
||||
|
||||
**core-map?** for records: `(or (phm? x) (struct? x) (if (and (table? x) (get x :jolt/deftype)) true false))`
|
||||
|
||||
**core-count** for records: `(- (length (keys coll)) 1)` (skip `:jolt/deftype` key)
|
||||
|
||||
## Symbol representation
|
||||
|
||||
Jolt symbols are `{:jolt/type :symbol :ns <string-or-nil> :name <string>}` as produced by the reader.
|
||||
- `def` creates constants; use `(var x nil)` for mutable locals
|
||||
- Bare tuples in `eval` are function calls: `[1 2 3]` tries to call `1`. Use `['tuple 1 2 3]`
|
||||
- `try` format: `(try body ([err] handler))` NOT `(try body (catch sym handler))`
|
||||
- core-renames MUST match actual fn names: `"-"` → `"core-sub"` (not `"core--"`)
|
||||
- Janet `parse` vs `parser/new`: use `parser/new` + `parser/consume` + `parser/eof` + `parser/produce` for full source parsing
|
||||
- `(break val)` breaks from a while loop returning val — useful in bucket search patterns
|
||||
Loading…
Add table
Add a link
Reference in a new issue