Phase 4: Macro expansion in compiler
- resolve-macro: resolve symbols to macro vars via ctx - Macro expansion in analyze-form: detects macro heads, expands, re-analyzes - compile-ast: emits Janet data structures with resolved core fn values - compile-and-eval uses compile-ast (no source parse roundtrip) - eval-string routes macros through compiler (expanded at analyze time) - Fix - mapping: core-sub (core-- doesn't exist) - All 317 tests pass + 6 new Phase 4 macro tests
This commit is contained in:
parent
ab7ff85816
commit
a8c453183f
9 changed files with 448 additions and 188 deletions
|
|
@ -1,5 +1,5 @@
|
|||
Compiler Phases 1-3 COMPLETE. src/jolt/compiler.janet (342 lines): analyze-form→emit-ast two-phase. Phase 2: symbol classification (locals→core→symbol, shadowing works). Phase 3: compile-and-eval via parser→consume→eof→produce→eval pipeline, :compile? flag in types.janet context, loader.janet (80 lines) for namespace loading, api.janet updated (compile-string, compile-file, compile-aware eval-string). Stateful forms (def, defmacro, ns, deftype, defmulti, defmethod, require, in-ns) always route to interpreter. All 317 tests pass. Next: Phase 4 (macro integration), Phase 5 (remaining ops: loop/recur, try/throw, quote, syntax-quote, set!, .), Phase 6 (benchmarks).
|
||||
Compiler in `src/jolt/compiler.janet` (~470 lines). Three emit modes: 1) compile-form → Janet source string (debug/display) 2) compile-ast → Janet data structures with resolved fn values (for eval) 3) compile-and-eval → compile-ast + eval. core-renames maps Clojure→Janet STRING names. core-fn-values maps Janet string names→actual function VALUES (used by compile-ast). analyze-form [form bindings ctx] — ctx optional for macro expansion. Macro expansion: when head symbol resolves to macro var, apply macro fn to args and re-analyze expanded form. Ops: const, do, if, def, fn*, let*, invoke, symbol (local/core/qualified), quote, vector, map. Symbol classification: locals → core-symbol → symbol (shadowing works). compile-form and compile-ast accept optional ctx arg.
|
||||
§
|
||||
Compiler is in `src/jolt/compiler.janet` (342 lines). Two-phase: `analyze-form [form bindings]` → annotated AST with `:op` keys, `emit-ast` dispatches on `:op` → Janet source string via StringBuffer. `compile-form` for source output, `compile-and-eval` for direct eval via `eval-janet-source` (parser/new→consume→eof→produce→eval pipeline). `core-renames` table maps Clojure→Janet names. Ops covered: const, do, if, def, fn*, let*, invoke, symbol (local/core-symbol/qualified classification), quote. Symbol classification order: locals → core-symbol → symbol (shadowing works). Stateful forms (def, defmacro, etc.) must use interpreter path, not compile-and-eval.
|
||||
Compiler tests in `test/compiler-test.janet` (172 lines, 11 test groups). Groups: 1-literals, 2-do, 3-if, 4-def, 5-fn, 6-let, 7-invoke, 8-local classification, 9-compile-and-eval round-trip, 10-compile flag, 11-macro expansion (defn, when, let, fn, and/or via compile?). All 317 tests pass.
|
||||
§
|
||||
Compiler tests in `test/compiler-test.janet` (143 lines, 10 test groups). Phase 1: 7 groups, 19 string-output assertions. Phase 2: local classification (3 assertions: shadowing, param shadowing, nested let). Phase 3: compile-and-eval round-trip (9 assertions) + :compile? flag tests (7 assertions). All 317 tests pass. Run with `janet test/compiler-test.janet` or `jpm test`.
|
||||
Janet's `eval` runs in Janet's default environment and does NOT have access to symbols imported via `(use ...)` in the calling file. `(eval '(core-inc 1))` fails with "unknown symbol core-inc" even when the file does `(use ./core)`. FIX: emit Janet data structures where function VALUES are embedded directly (e.g. `[core-inc 1]`) rather than source strings `"(core-inc 1)"`. The `core-fn-values` table resolves Janet symbol names to actual function values at compile time.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
Janet LSP produces false positives on `.janet` files — it doesn't understand Janet syntax (thinks docstring lines are unresolved symbols, doesn't know `declare-project`/`declare-source` macros, etc.). These are pre-existing and should be ignored — they don't affect runtime correctness.
|
||||
§
|
||||
Janet `(parse s)` returns `[symbol, error-position]` for forms — e.g., `(parse "(+ 1 2)")` gives `[+ 1]`, not a parsed tuple. For proper evaluation of special forms, must use the parser pipeline: `parser/new` → `parser/consume` → `parser/eof` → `parser/produce` → `eval`. Without `parser/eof`, `produce` returns nil for simple forms like numbers. Janet's `eval` also doesn't support special forms natively in data structures — `(eval [if true 1 2])` fails with "unknown symbol if". Must parse strings, not eval tuples.
|
||||
Janet eval scope & source-to-source failure: `(eval '(core-inc 1))` fails with "unknown symbol core-inc" even when the file does `(use ./core)`. Janet's `eval` runs in the default environment and doesn't see `use`-imported symbols. NEVER emit Janet source strings for eval. Instead emit Janet data structures where function VALUES are embedded directly: `[core-inc 1]` not `"(core-inc 1)"`. Use a `core-fn-values` table to resolve names at compile time. The `(parse s)` function returns `[symbol, error-position]` — must use parser pipeline for proper eval: `parser/new→consume→eof→produce→eval`. Without `parser/eof`, numbers/literals return nil from produce. Janet's `eval` also doesn't support special forms natively in data structures — `(eval [if true 1 2])` fails with "unknown symbol if". Must parse strings, not eval tuples.
|
||||
§
|
||||
When you need to mutate a local with `set`, use `(var x nil)` not `(def x nil)`. `def` creates constants — `(set ns-name ...)` on a `def` fails with "cannot set constant". This hit us in loader.janet ns-name extraction loop.
|
||||
§
|
||||
core-renames MUST match actual function names defined in core.janet. `"-"` maps to `core-sub` NOT `core--`. `"not"` maps to `core-not` (defined as `(defn core-not ...)`). Missing entries cause silent nil returns. When adding to core-renames, grep core.janet for the actual `(defn core-XXX ...)` or `(def core-XXX ...)` name. Then add matching entry to core-fn-values.
|
||||
|
|
|
|||
|
|
@ -1,22 +1,12 @@
|
|||
{
|
||||
"jpm-build": {
|
||||
"created_by": "agent",
|
||||
"use_count": 0,
|
||||
"view_count": 11,
|
||||
"patch_count": 0,
|
||||
"last_viewed_at": "2026-06-02T17:43:38.327259+00:00",
|
||||
"created_at": "2026-06-01T20:56:39.144222+00:00",
|
||||
"state": "active",
|
||||
"pinned": false
|
||||
},
|
||||
"jolt-dev": {
|
||||
"created_by": "agent",
|
||||
"use_count": 25,
|
||||
"view_count": 36,
|
||||
"patch_count": 31,
|
||||
"last_used_at": "2026-06-02T19:13:37.620054+00:00",
|
||||
"last_viewed_at": "2026-06-02T19:13:37.612317+00:00",
|
||||
"last_patched_at": "2026-06-02T19:14:06.338745+00:00",
|
||||
"use_count": 26,
|
||||
"view_count": 37,
|
||||
"patch_count": 32,
|
||||
"last_used_at": "2026-06-02T19:38:51.833410+00:00",
|
||||
"last_viewed_at": "2026-06-02T19:38:51.825602+00:00",
|
||||
"last_patched_at": "2026-06-02T19:39:44.919664+00:00",
|
||||
"created_at": "2026-06-01T21:26:06.614465+00:00",
|
||||
"state": "active",
|
||||
"pinned": false
|
||||
|
|
@ -25,7 +15,8 @@
|
|||
"created_by": "agent",
|
||||
"use_count": 0,
|
||||
"view_count": 0,
|
||||
"patch_count": 0,
|
||||
"patch_count": 1,
|
||||
"last_patched_at": "2026-06-02T19:40:03.526270+00:00",
|
||||
"created_at": "2026-06-02T17:54:38.690279+00:00",
|
||||
"state": "active",
|
||||
"pinned": false
|
||||
|
|
@ -41,5 +32,15 @@
|
|||
"created_at": "2026-06-01T21:49:51.101718+00:00",
|
||||
"state": "active",
|
||||
"pinned": false
|
||||
},
|
||||
"jpm-build": {
|
||||
"created_by": "agent",
|
||||
"use_count": 0,
|
||||
"view_count": 11,
|
||||
"patch_count": 0,
|
||||
"last_viewed_at": "2026-06-02T17:43:38.327259+00:00",
|
||||
"created_at": "2026-06-01T20:56:39.144222+00:00",
|
||||
"state": "active",
|
||||
"pinned": false
|
||||
}
|
||||
}
|
||||
|
|
@ -1,82 +1,97 @@
|
|||
---
|
||||
description: Jolt compiler architecture and implementation plan
|
||||
triggers:
|
||||
- "compile jolt"
|
||||
- "jolt compiler"
|
||||
- "Clojure to Janet compilation"
|
||||
- "add new op to compiler"
|
||||
- "fix compiler"
|
||||
---
|
||||
|
||||
# Jolt Compiler
|
||||
|
||||
Two-phase source-to-source compiler: Clojure forms → annotated AST → Janet source → Janet bytecode.
|
||||
Source-to-source Clojure→Janet compiler. Two-phase: analyze-form (classify + macro expand) → emit-ast (generate).
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Clojure source → Reader → raw AST
|
||||
↓
|
||||
analyze-form (classify symbols, produce :op AST)
|
||||
↓
|
||||
emit* dispatch (generate Janet source string)
|
||||
↓
|
||||
Janet compile → bytecode
|
||||
Clojure form → analyze-form [form bindings ctx] → AST {:op ...}
|
||||
↓ (if head = macro var)
|
||||
expand → re-analyze expanded form
|
||||
↓
|
||||
emit-ast (source string) or emit-expr (data structure)
|
||||
```
|
||||
|
||||
Follows CLJS `cljs.analyzer` / `cljs.compiler` pattern.
|
||||
Three public entry points:
|
||||
- `(compile-form form &opt ctx)` → Janet source string (debug/display)
|
||||
- `(compile-ast form &opt ctx)` → Janet data structure (for eval)
|
||||
- `(compile-and-eval form ctx)` → compile-ast + eval
|
||||
|
||||
## Key decisions
|
||||
## Why data structures, not source strings
|
||||
|
||||
- **Target**: Janet source text (fed to Janet's `compile`), not direct bytecode. Simpler, debuggable, portable across Janet versions.
|
||||
- **Mode gating**: Opt-in per context via `:compile?` flag on `init`. `eval-string` still interprets unless opted in.
|
||||
- **Caching**: In-memory bytecode cache in context first. Disk persistence (`.jimage` files) as follow-up.
|
||||
|
||||
## AST ops (CLJS subset + Jolt-specific)
|
||||
|
||||
Core: `const`, `var`, `local`, `binding`, `if`, `do`, `let`, `loop`, `recur`, `fn`, `fn-method`, `def`, `invoke`, `quote`, `try`, `throw`, `set!`, `new`, `host-field`, `host-call`
|
||||
|
||||
Jolt-specific: `deftype`, `defmulti`, `defmethod`, `syntax-quote`
|
||||
|
||||
## File layout
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `src/jolt/compiler.janet` | `analyze-form`, `emit*` dispatch, `compile-form`, symbol classifier |
|
||||
| `src/jolt/loader.janet` | `load-ns`, `reload-ns`, in-memory bytecode cache |
|
||||
| `test/compiler-test.janet` | Round-trip: compile-form → Janet eval → assert |
|
||||
|
||||
Modified files:
|
||||
- `evaluator.janet` — add compiler fast-path for `def`/`defn`/`defmacro` when `:compile?` set
|
||||
- `types.janet` — add `:compiled-cache` table to context
|
||||
- `api.janet` — expose `compile-string`, `load-ns`, `compile-file`; `init` gets `:compile?` flag
|
||||
- `reader.janet` — **no change**
|
||||
- `core.janet` — **no change**
|
||||
|
||||
## Emit target advantages
|
||||
|
||||
Both input and output are parenthesized prefix syntax, so many forms pass through almost unchanged:
|
||||
Janet's `eval` does NOT have access to `use`-imported symbols from the calling file. `(eval "(core-inc 1)")` fails with "unknown symbol core-inc". The fix: emit Janet tuples where function VALUES are embedded: `[core-inc 1]`.
|
||||
|
||||
```
|
||||
Clojure: (defn f [x] (+ x 1))
|
||||
AST: {:op :def :name "f" :init {:op :fn :methods [...]}}
|
||||
Janet: (defn f [x] (+ x 1)) ← nearly identical
|
||||
core-fn-values table: "core-inc" → core-inc (the actual function)
|
||||
emit-core-symbol-expr → (get core-fn-values janet-name)
|
||||
```
|
||||
|
||||
Main work:
|
||||
- Symbol resolution (Clojure's `clojure.core/+` → Janet's `core-+`)
|
||||
- Truthiness wrapping (`nil`/`false` are falsey in Clojure, Janet only `nil`)
|
||||
- Special form mapping (`loop*`/`recur` → Janet `loop` + explicit recur vars)
|
||||
- Vars → Janet table lookups
|
||||
Source-to-source (`compile-form` + `emit-ast`) still exists for debugging but is NOT used by `compile-and-eval`.
|
||||
|
||||
## Implementation phases
|
||||
## Macro expansion
|
||||
|
||||
| Phase | What | Deliverable |
|
||||
|-------|------|-------------|
|
||||
| 1 | `compiler.janet` — `analyze-form` skeleton + `emit*` for `const`, `do`, `if`, `let`, `fn`, `def`, `invoke` | Basic forms compile and run |
|
||||
| 2 | Symbol classifier — resolve locals/vars/core at analyze time | No runtime `resolve-sym` in compiled code |
|
||||
| 3 | `loader.janet` + `api.janet` wiring — `:compile?` flag, `load-ns`, caching | File-based namespace loading works |
|
||||
| 4 | Macro integration — expand at analyze time via interpreter | Macros work in compiled code |
|
||||
| 5 | Remaining ops: `loop`/`recur`, `try`/`throw`, `quote`, `syntax-quote`, `set!`, `deftype`, `.` | Full language coverage |
|
||||
| 6 | Tests + benchmarks | Correctness + speedup measurement |
|
||||
`analyze-form` checks whether the head symbol of a list resolves to a macro var before dispatching to special form handling:
|
||||
|
||||
## Pitfalls
|
||||
1. Look up symbol in current ns → core ns via `resolve-macro`
|
||||
2. If `var-macro?` is true, call `(var-get macro-var)` to get the fn
|
||||
3. `(apply macro-fn (tuple/slice form 1))` to expand
|
||||
4. `(analyze-form expanded ...)` to re-analyze the result
|
||||
|
||||
- Janet `compile` produces bytecode tied to Janet version — source-to-source avoids this
|
||||
- CLJS analyzer is ~5000 lines; Jolt's can be simpler because emit target is s-expressions
|
||||
- Symbol resolution must happen at analyze time, not runtime, for compiled code
|
||||
- Macro expansion still uses interpreter at analyze time — macros are not AOT-compiled
|
||||
Macros expand at analyze time, before emission. `defn` expands to `(def name (fn* ...))`, `when` to `(if test (do ...) nil)`, etc.
|
||||
|
||||
## Symbol classification (in analyze-form)
|
||||
|
||||
Order: qualified ns → local binding → core-symbol → bare symbol
|
||||
|
||||
```
|
||||
(if (form :ns) → :qualified-symbol
|
||||
(get bindings name) → :local
|
||||
(get core-renames name) → :core-symbol
|
||||
→ :symbol)
|
||||
```
|
||||
|
||||
core-renames MUST match actual fn names: `"-"` → `"core-sub"` (not `"core--"`), `"not"` → `"core-not"`. Verify against `core.janet` bindings.
|
||||
|
||||
## core-fn-values
|
||||
|
||||
Maps Janet string names to actual function values. Must be kept in sync with core-renames. When adding a new core fn, update BOTH tables.
|
||||
|
||||
Functions that need special mapping (name differs):
|
||||
- `"apply"` → `apply` (Janet built-in)
|
||||
- `"-"` → `"core-sub"` (not `core--`)
|
||||
- `"some"` → `core-some?` (shared with `core-some?`)
|
||||
- `"pr-str"` → `core-str` (alias)
|
||||
- `"nth"` → `core-get` (alias)
|
||||
|
||||
## Stateful forms (must use interpreter, NOT compiler)
|
||||
|
||||
These forms modify context state and cannot be compiled:
|
||||
- `defmacro`, `ns`, `deftype`, `defmulti`, `defmethod`, `require`, `in-ns`
|
||||
|
||||
Note: `def` IS handled by the compiler (compiles to Janet `def`).
|
||||
|
||||
## Adding a new op
|
||||
|
||||
1. Add `analyze-form` match arm for the special form
|
||||
2. Add `emit-ast` match arm (source string path)
|
||||
3. Add `emit-expr` match arm (data structure path)
|
||||
4. Add `core-renames` entry if it's a core fn (name → Janet string name)
|
||||
5. Add `core-fn-values` entry (Janet string name → actual fn value)
|
||||
6. Add tests in `test/compiler-test.janet`
|
||||
|
||||
## Test patterns
|
||||
|
||||
- Source output tests: `(assert (= "(expected)" (compile-str "(input)")) "label")`
|
||||
- Round-trip tests: `(assert (= val (compile-eval-str "(input)")) "label")`
|
||||
- Compile flag tests: `(eval-string ctx "(input)")` with `{:compile? true}`
|
||||
|
||||
Run: `janet test/compiler-test.janet` or `jpm test`
|
||||
|
|
|
|||
|
|
@ -37,9 +37,16 @@ For evaluating Janet source strings, use the parser pipeline:
|
|||
|
||||
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.
|
||||
|
||||
## Special Form Checklist
|
||||
|
||||
To add a new special form to the evaluator:
|
||||
To add a new special form to the evaluator AND compiler:
|
||||
|
||||
1. Add the name to `special-symbol?` in `src/jolt/evaluator.janet`
|
||||
2. Add a match arm in `eval-list` (the match on `name`)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue