Merge pull request #160 from jolt-lang/spike/chez-bootstrap
Rehost on Chez Scheme; remove the Janet host
This commit is contained in:
commit
6b87f8dc73
307 changed files with 18407 additions and 28406 deletions
67
.github/workflows/tests.yml
vendored
67
.github/workflows/tests.yml
vendored
|
|
@ -1,6 +1,7 @@
|
|||
name: tests
|
||||
|
||||
# Run the full test suite (jpm test) on every push and pull request.
|
||||
# Run the gate (make test) on every push and pull request. Chez is the sole
|
||||
# substrate; the JVM is used only as the conformance oracle (certify).
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
|
@ -8,53 +9,33 @@ on:
|
|||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
JANET_VERSION: v1.41.2 # bump to match the version Jolt is developed against
|
||||
# Per-file deadline for the clojure-test-suite battery. Finite files finish
|
||||
# in well under 1s; the genuinely-infinite ones get killed at any deadline.
|
||||
# A generous value gives slow CI runners headroom so a sub-second file
|
||||
# spiking doesn't time out and drop total-pass below the baseline.
|
||||
JOLT_SUITE_TIMEOUT: "20"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
# Submodules: vendor/sci (SCI bootstrap/runtime tests) and
|
||||
# vendor/clojure-test-suite (the cross-dialect conformance battery,
|
||||
# asserted against a baseline by clojure-test-suite-test.janet).
|
||||
submodules: recursive
|
||||
submodules: recursive # vendor/irregex, used by the Chez regex shim
|
||||
|
||||
- name: Cache Janet build
|
||||
id: cache-janet
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: /tmp/janet
|
||||
key: janet-${{ env.JANET_VERSION }}-${{ runner.os }}
|
||||
|
||||
- name: Build Janet
|
||||
if: steps.cache-janet.outputs.cache-hit != 'true'
|
||||
- name: Install Chez Scheme
|
||||
run: |
|
||||
git clone --depth 1 --branch "$JANET_VERSION" https://github.com/janet-lang/janet.git /tmp/janet
|
||||
make -C /tmp/janet
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y chezscheme
|
||||
# the gate invokes `chez`; Debian/Ubuntu installs it as `scheme`. A symlink
|
||||
# won't do — Chez derives its boot-file name from argv0, so `chez` would look
|
||||
# for a nonexistent chez.boot. A wrapper that exec's `scheme` keeps argv0.
|
||||
if ! command -v chez >/dev/null 2>&1; then
|
||||
printf '#!/bin/sh\nexec scheme "$@"\n' | sudo tee /usr/local/bin/chez >/dev/null
|
||||
sudo chmod +x /usr/local/bin/chez
|
||||
fi
|
||||
chez --version || true
|
||||
|
||||
- name: Install Janet
|
||||
run: sudo make -C /tmp/janet install
|
||||
|
||||
- name: Install jpm
|
||||
- name: Install JDK + Clojure (certify oracle)
|
||||
run: |
|
||||
git clone --depth 1 https://github.com/janet-lang/jpm.git /tmp/jpm
|
||||
# bootstrap.janet resolves jpm/cli.janet relative to the cwd, so it
|
||||
# must run from inside the jpm checkout.
|
||||
cd /tmp/jpm
|
||||
sudo janet bootstrap.janet
|
||||
sudo apt-get install -y default-jdk rlwrap
|
||||
curl -L -O https://github.com/clojure/brew-install/releases/latest/download/linux-install.sh
|
||||
sudo bash linux-install.sh
|
||||
clojure --version
|
||||
|
||||
- name: Janet version
|
||||
run: janet -v
|
||||
|
||||
- name: Build executable
|
||||
run: jpm build
|
||||
|
||||
- name: Run tests
|
||||
# Parallel runner (same file set as `jpm test`, across CPU workers).
|
||||
# The executable is built in the previous step, so binary-spawning tests
|
||||
# don't skip.
|
||||
run: janet run-tests.janet
|
||||
- name: Gate
|
||||
# `make ci` runs the behavior gates (corpus/unit/smoke/sci/certify). The
|
||||
# self-host byte-fixpoint (make selfhost) is a dev-machine check — it only
|
||||
# holds on the Chez that minted the seed. See jolt-8479.
|
||||
run: make ci
|
||||
|
|
|
|||
6
.gitmodules
vendored
6
.gitmodules
vendored
|
|
@ -1,6 +1,6 @@
|
|||
[submodule "vendor/irregex"]
|
||||
path = vendor/irregex
|
||||
url = https://github.com/ashinn/irregex.git
|
||||
[submodule "vendor/sci"]
|
||||
path = vendor/sci
|
||||
url = https://github.com/borkdude/sci.git
|
||||
[submodule "vendor/clojure-test-suite"]
|
||||
path = vendor/clojure-test-suite
|
||||
url = https://github.com/jank-lang/clojure-test-suite.git
|
||||
|
|
|
|||
93
CLAUDE.md
93
CLAUDE.md
|
|
@ -53,75 +53,64 @@ bd close <id> # Complete work
|
|||
|
||||
## Build & Test
|
||||
|
||||
```bash
|
||||
jpm build # build/jolt (one binary; ctx baked at build time)
|
||||
jpm build; janet run-tests.janet # FULL gate, PARALLEL (across CPU workers) — build first so binary-spawning tests don't skip; JOLT_TEST_JOBS overrides worker count, -v shows all output
|
||||
jpm test # FULL gate, serial (same file set; slower — recursive over test/)
|
||||
janet test/spec/<f>.janet # one spec file
|
||||
janet test/integration/conformance-test.janet # 3-mode conformance (interpret/compile/self-host)
|
||||
JOLT_BENCH=1 janet test/bench/core-bench.janet # bench (opt-in; skipped in the gate) — back-to-back vs main, never absolute
|
||||
```
|
||||
|
||||
**Run the gate with a REAL exit code.** `jpm test | grep ...` reports grep's
|
||||
exit, not jpm's — this once shipped masked spec failures. Correct form:
|
||||
No build step — `bin/joltc` runs off the checked-in seed (`host/chez/seed/`).
|
||||
The gate is pure Chez (+ Clojure for the JVM oracle).
|
||||
|
||||
```bash
|
||||
jpm test > /tmp/gate.out 2>&1; echo "EXIT: $?"
|
||||
grep -E "non-zero exit|All tests" /tmp/gate.out
|
||||
bin/joltc -e EXPR # run a Clojure expression on Chez
|
||||
make test # FULL gate (self-host + corpus + unit + smoke + certify)
|
||||
make corpus # conformance corpus vs the JVM-sourced spec (floor 2678)
|
||||
make unit # host-specific unit cases (test/chez/unit.edn)
|
||||
make selfhost # bootstrap fixpoint (rebuild == checked-in seed)
|
||||
make certify # JVM oracle (skips if clojure absent)
|
||||
chez --script host/chez/run-corpus.ss # the corpus gate directly; JOLT_CORPUS_LIMIT=N for a fast stride
|
||||
make remint # re-mint the seed after a seed-source change
|
||||
```
|
||||
|
||||
The literal `All tests passed.` line must be present. CI (.github/workflows/
|
||||
tests.yml) runs the same gate on every push/PR.
|
||||
**Re-mint after changing a seed source.** The reader (`host/chez/reader.ss`), the
|
||||
analyzer/IR/backend (`jolt-core/jolt/*.clj`), or the `clojure.core` overlay
|
||||
(`jolt-core/clojure/core/*.clj`) are baked into the seed — change one and run
|
||||
`make remint` (iterates `host/chez/bootstrap.ss` to a byte-fixpoint) or `make
|
||||
selfhost` fails. Runtime-only `host/chez/*.ss` shims do NOT need a re-mint.
|
||||
|
||||
`jpm build` output goes STALE silently — `rm -rf build && jpm clean` before
|
||||
trusting the binary, or test from source (authoritative).
|
||||
**Run the gate with a REAL exit code.** `make test > /tmp/gate.out 2>&1; echo
|
||||
"EXIT: $?"` — the final `OK: all gates passed` line must be present. CI
|
||||
(`.github/workflows/tests.yml`) runs `make test` on every push/PR.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
Clojure on Janet. A shrinking Janet seed (`src/jolt/*.janet`: reader, value
|
||||
layer, vars/ns, evaluator, the self-hosted pipeline's back end) hosts a
|
||||
Clojure overlay (`jolt-core/`): the analyzer/IR (`jolt-core/jolt/`) and
|
||||
`clojure.core` in dependency-ordered tiers (`jolt-core/clojure/core/NN-*.clj`,
|
||||
loaded in order: 00-syntax, 00-kernel (bootstrap-compiled), 10-seq, 20-coll,
|
||||
25-sorted, 30-macros, 40-lazy, 50-io). Compile is the default path (analyzer
|
||||
-> IR -> Janet bytecode, hybrid with interpreter fallback); `JOLT_INTERPRET=1`
|
||||
forces the tree-walking interpreter, `JOLT_INTERPRET_MACROS=1` additionally
|
||||
keeps macro expanders interpreted (the pure oracle). `api/init-cached` serves
|
||||
a disk-cached ctx image (~5ms vs ~2.4s); the cache key fingerprints sources +
|
||||
env knobs — add any NEW ctx-shaping env var to `image-cache-path` in
|
||||
api.janet or tests will see stale language behavior.
|
||||
Clojure on Chez Scheme — the sole substrate. A small Chez runtime
|
||||
(`host/chez/*.ss`: value model, persistent collections, seqs, vars/ns, host
|
||||
interop) hosts a portable Clojure overlay (`jolt-core/`): the
|
||||
reader/analyzer/IR/backend (`jolt-core/jolt/`) and `clojure.core` in
|
||||
dependency-ordered tiers (`jolt-core/clojure/core/NN-*.clj`, loaded in order:
|
||||
00-syntax, 00-kernel, 10-seq, 20-coll, 25-sorted, 30-macros, 40-lazy, 50-io).
|
||||
The stdlib namespaces (`clojure.string`/`set`/`walk`/`edn`/`pprint`/…) are
|
||||
portable Clojure under `src/jolt/clojure/`.
|
||||
|
||||
`bin/joltc` (`host/chez/cli.ss`) loads the checked-in seed
|
||||
(`host/chez/seed/{prelude,image}.ss`) + the spine and compiles+evals on Chez
|
||||
(read → analyze → IR → emit → eval). `host/chez/bootstrap.ss` rebuilds that seed
|
||||
from source on pure Chez; the build is a self-hosting fixpoint (a rebuild
|
||||
reproduces the checked-in seed byte-for-byte — `make selfhost`). The correctness
|
||||
oracle is the JVM-sourced conformance corpus (`test/chez/corpus.edn`,
|
||||
`test/conformance/`).
|
||||
|
||||
Issue tracking and design notes live in beads (`bd prime`, `bd memories`).
|
||||
|
||||
## Conventions & Patterns
|
||||
|
||||
Porting seed fns to the overlay (the jolt-tzo shrink ladder) — traps that have
|
||||
each bitten at least once:
|
||||
|
||||
- **Verify leaf-ness first**: grep ALL `src/jolt/*.janet` for the `core-X`
|
||||
name (defn + core-bindings entry only), and check that tiers loading
|
||||
EARLIER than the target tier don't call it. Nothing the analyzer/ir use may
|
||||
move below the kernel tier.
|
||||
- **Delete the seed defn + binding in the same change.** A leftover stub
|
||||
breaks direct-linked self-recursion: the overlay fn's recursive call binds
|
||||
to the STUB's root at compile time (line-seq once truncated after one
|
||||
element this way).
|
||||
- **A tier may only use macros from tiers that load before it.** Compile mode
|
||||
expands macros at tier LOAD; the interpreter expands lazily — so an
|
||||
if-let (30-macros) inside a 20-coll fn passes every interpreted test and
|
||||
breaks compiled init.
|
||||
expands macros at tier LOAD, so an `if-let` (30-macros) inside a 20-coll fn
|
||||
breaks compiled init even though it passes when expanded lazily. Same ordering
|
||||
for expander-called fns (empty?/keys/vals live in 00-syntax).
|
||||
- **Never read your own wrapper's fields with `get`** in attached-ops values
|
||||
(sorted colls): `get` on the wrapper IS the dispatched lookup and recurses
|
||||
forever. Use `jolt.host/ref-get`.
|
||||
- **Map literals with `:jolt/type` as a key** parse as tagged reader forms —
|
||||
don't tag overlay value maps in source.
|
||||
- **Expander-called fns live in 00-syntax** (empty?/keys/vals): expansion
|
||||
first happens during the kernel-tier compile, before later tiers exist.
|
||||
Early defns and expanders are interpreted during init and recompiled by the
|
||||
staged passes (recompile-defns!/recompile-macros!) once the analyzer is
|
||||
alive.
|
||||
- **Fix latent bugs to match Clojure** rather than preserving them, with a
|
||||
regression spec row. Canonical Clojure definitions are preferred verbatim.
|
||||
- **Gate every batch**: conformance x3 modes, suite >= baseline
|
||||
(clojure-test-suite-test.janet — raise the baseline when it rises), full
|
||||
jpm test with a real exit code, bench back-to-back vs main.
|
||||
regression case. Match the JVM (or provide a superset); the JVM-sourced corpus
|
||||
is the contract.
|
||||
- **Gate every change**: `make test` with a real exit code (self-host fixpoint,
|
||||
corpus floor, unit, cli smoke, certify). Re-mint if a seed source changed.
|
||||
|
|
|
|||
64
Makefile
Normal file
64
Makefile
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
# jolt — Clojure on Chez Scheme. Single substrate, no Janet.
|
||||
#
|
||||
# bin/joltc runs jolt directly off the checked-in seed (host/chez/seed/); there is no
|
||||
# build step. `make test` is the full gate. `make remint` rebuilds the seed after a
|
||||
# source change.
|
||||
|
||||
.PHONY: test ci values corpus unit smoke selfhost sci certify ffi transient remint
|
||||
|
||||
# Full gate (dev machine). Includes the self-host byte-fixpoint, which only holds
|
||||
# on the same Chez that minted the seed.
|
||||
test: selfhost ci
|
||||
@echo "OK: all gates passed"
|
||||
|
||||
# CI gate: behavior only. The checked-in seed is a minted artifact (like a
|
||||
# lockfile) — it RUNS correctly on any Chez, but `selfhost` rebuilds it and a
|
||||
# different Chez version may emit byte-different (gensym/order) output, so the
|
||||
# byte-fixpoint is a dev-machine check, not a CI one (jolt-8479).
|
||||
ci: values corpus unit smoke sci ffi transient certify
|
||||
@echo "OK: CI gates passed"
|
||||
|
||||
# Self-host fixpoint: bootstrap.ss rebuild == checked-in seed.
|
||||
selfhost:
|
||||
@sh host/chez/selfcheck.sh
|
||||
|
||||
# Value-model unit tests (nil/truthiness/collections on Chez).
|
||||
values:
|
||||
@chez --script test/chez/values-test.ss
|
||||
|
||||
# Corpus conformance vs JVM-sourced expecteds (allowlist + floor).
|
||||
corpus:
|
||||
@chez --script host/chez/run-corpus.ss
|
||||
|
||||
# Host-specific unit cases.
|
||||
unit:
|
||||
@chez --script host/chez/run-unit.ss
|
||||
|
||||
# Real-CLI smoke over bin/joltc.
|
||||
smoke:
|
||||
@sh host/chez/smoke.sh
|
||||
|
||||
# SCI conformance: load borkdude/sci's source through joltc (floor-gated).
|
||||
sci:
|
||||
@chez --script host/chez/run-sci.ss
|
||||
|
||||
# FFI + threading: HTTP server GC-safety (blocking calls deactivate the thread)
|
||||
# and http-client temp-file uniqueness, plus a live request.
|
||||
ffi:
|
||||
@chez --script test/chez/ffi-server-test.ss
|
||||
|
||||
# Transients: mutable backing, snapshot on persistent!, and linear-time builds.
|
||||
transient:
|
||||
@chez --script test/chez/transient-test.ss
|
||||
|
||||
# JVM oracle: certify the corpus against reference Clojure. Skips if clojure absent.
|
||||
certify:
|
||||
@if command -v clojure >/dev/null 2>&1; then \
|
||||
clojure -M test/conformance/certify.clj; \
|
||||
else \
|
||||
echo "certify: clojure not on PATH — skipped"; \
|
||||
fi
|
||||
|
||||
# Re-mint the seed after changing a seed source (reader/analyzer/backend/core).
|
||||
remint:
|
||||
@sh host/chez/remint.sh
|
||||
308
README.md
308
README.md
|
|
@ -2,266 +2,108 @@
|
|||
|
||||
[](https://github.com/jolt-lang/jolt/actions/workflows/tests.yml)
|
||||
|
||||
A Clojure implementation on top of [Janet](https://janet-lang.org). Jolt reads Clojure source and, by default, compiles each form to native Janet bytecode — falling back to a tree-walking interpreter for forms the compiler doesn't handle, so results always match the interpreter. It ships a Clojure-compatible standard library. The goal is a Janet-hosted [SCI](https://github.com/borkdude/sci)-style runtime with a minimal bootstrap.
|
||||
A Clojure implementation on [Chez Scheme](https://cisco.github.io/ChezScheme/).
|
||||
Jolt reads Clojure source, analyzes it to a host-neutral IR, emits Scheme, and
|
||||
runs it on Chez. The compiler is self-hosted: it is written in Clojure
|
||||
(`jolt-core/`) and compiles itself. It ships a Clojure-compatible standard library.
|
||||
|
||||
## Requirements
|
||||
|
||||
Only [Chez Scheme](https://cisco.github.io/ChezScheme/) (the gate invokes it as
|
||||
`chez`). The conformance gate additionally uses Clojure on the JVM as an oracle,
|
||||
but running jolt does not.
|
||||
|
||||
## Build
|
||||
|
||||
There is no build step. The bootstrap seed (`host/chez/seed/{prelude,image}.ss`)
|
||||
is checked in, so a fresh clone runs immediately:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/jolt-lang/jolt.git
|
||||
git clone --recurse-submodules https://github.com/jolt-lang/jolt.git
|
||||
cd jolt
|
||||
git submodule update --init # pulls vendor/sci and vendor/clojure-test-suite
|
||||
jpm build # builds build/jolt (one binary)
|
||||
bin/joltc -e '(+ 1 2)' # => 3
|
||||
```
|
||||
|
||||
Requires `jpm` and a recent Janet (CI-tested against 1.41). See
|
||||
[docs/building-and-deps.md](docs/building-and-deps.md) for build details, the
|
||||
`jpm clean` caveat, how namespaces are resolved (`JOLT_PATH`), and pulling
|
||||
Clojure libraries from a `deps.edn` (resolved by `jolt` itself — `jolt -M:…`,
|
||||
`jolt run`, `jolt path`).
|
||||
After changing a compiler source — the reader (`host/chez/reader.ss`), the
|
||||
analyzer/IR/backend (`jolt-core/jolt/*.clj`), or the `clojure.core` overlay
|
||||
(`jolt-core/clojure/core/*.clj`) — re-mint the seed:
|
||||
|
||||
```bash
|
||||
make remint # iterates host/chez/bootstrap.ss to a byte-fixpoint
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
bin/joltc -e EXPR # evaluate a Clojure expression and print the result
|
||||
```
|
||||
build/jolt # start a REPL
|
||||
build/jolt file.clj [args] # run a file (binds *command-line-args* and *file*)
|
||||
build/jolt -e EXPR [args] # evaluate EXPR and print the result
|
||||
build/jolt -m NS [args] # require NS and call its -main
|
||||
build/jolt nrepl-server [addr] # start an nREPL server ([host:]port, default 7888)
|
||||
build/jolt --version # print the version
|
||||
build/jolt -h | --help # help
|
||||
```
|
||||
|
||||
The REPL accumulates multi-line forms until they balance:
|
||||
|
||||
```
|
||||
user=> (defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
|
||||
#'user/fib
|
||||
user=> (map fib (range 10))
|
||||
(0 1 1 2 3 5 8 13 21 34)
|
||||
```
|
||||
|
||||
Running a file evaluates its top-level forms:
|
||||
|
||||
```
|
||||
$ echo '(println "hello" (* 6 7))' > hello.clj
|
||||
$ build/jolt hello.clj
|
||||
hello 42
|
||||
```
|
||||
|
||||
## Use as a library
|
||||
|
||||
```janet
|
||||
(use jolt/api)
|
||||
|
||||
(def ctx (init))
|
||||
(eval-string ctx "(+ 1 2)") # → 3
|
||||
(eval-string ctx "(map inc [1 2 3])") # → (2 3 4) ; a lazy seq, like Clojure
|
||||
```
|
||||
|
||||
`(init)` returns a context with `clojure.core` loaded. Each context is isolated; use separate contexts for separate environments.
|
||||
|
||||
### Evaluation pipeline: interpreted and compiled
|
||||
|
||||
Every form passes through one router (`loader/eval-toplevel`) that decides *per
|
||||
form* whether to tree-walk it or compile it to Janet bytecode. The shipped
|
||||
runtime **compiles by default**; set `JOLT_INTERPRET=1` to force the interpreter.
|
||||
|
||||
**Hybrid, always correct.** The compiler is incomplete by design: a form it can't
|
||||
compile correctly throws `jolt/uncompilable`, and the router falls back to the
|
||||
tree-walking interpreter (`eval-form`) for that form. So the result *always*
|
||||
matches the interpreter — compilation is a transparent speedup, never a semantic
|
||||
change. Only the compile step is guarded; runtime errors in compiled code
|
||||
propagate normally (no double-evaluation, no hidden errors).
|
||||
|
||||
What compiles: `def`/`defn`, multi-arity / named / variadic fns, `recur` (in
|
||||
`loop` and directly in `fn`), `let`/`if`/`do`/`try`/`throw`/`quote`, map and
|
||||
vector literals, and calls. What falls back to the interpreter: context-modifying
|
||||
and definitional forms (`ns`, `defmacro`, `deftype`, `defprotocol`,
|
||||
`defmulti`/`defmethod`, `reify`, `require`, `binding`, …), destructuring, regex
|
||||
literals, and the handful of interpreter-only special forms.
|
||||
|
||||
**Live redefinition.** Compiled global references deref through Jolt **var cells**
|
||||
(Janet early-binds plain symbols, which would freeze redefinition), so redefining
|
||||
a `def`/`defn` at the REPL is visible to already-compiled callers — Clojure's var
|
||||
model. Hot numeric primitives (`+ - * < > <= >=`) emit native Janet ops, and
|
||||
calls compile to direct Janet calls.
|
||||
|
||||
```janet
|
||||
(def ctx (init {:compile? true}))
|
||||
(eval-string ctx "(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))")
|
||||
(eval-string ctx "(fib 30)") ; → 832040, native Janet bytecode
|
||||
```
|
||||
|
||||
For compute-heavy code the compiled path is dramatically faster than tree-walking,
|
||||
at native Janet speed.
|
||||
|
||||
**Validated at parity.** The conformance suite passes 258/258 under *all three*
|
||||
execution paths — interpreter, compiler, and the self-hosted compiler
|
||||
(`conformance-test.janet` runs all three in CI) — and the full clojure-test-suite
|
||||
matches its baseline across ~4.6k assertions — evidence the hybrid path doesn't
|
||||
diverge.
|
||||
|
||||
**AOT.** `aot.janet` marshals a compiled namespace to a Janet bytecode image
|
||||
(`save-ns`) and loads it back into a fresh context (`load-ns-image`), skipping
|
||||
parse/analyze/emit/compile on reload. Core fns are referenced by name against the
|
||||
baked-in runtime; only user bytecode and var cells are serialized.
|
||||
|
||||
## Host interop
|
||||
|
||||
Jolt exposes CLJS-style host interop through `.` on any Janet table or struct — a field holding a function is called with the receiver as the first argument:
|
||||
|
||||
```clojure
|
||||
(def obj {:greet (fn [self name] (str "Hello " name))})
|
||||
(. obj greet "Alice") ; → "Hello Alice"
|
||||
(.-greet obj) ; field access (reader sugar for (. obj :greet))
|
||||
```
|
||||
|
||||
### The `janet` interop bridge
|
||||
|
||||
The whole Janet standard library is reachable from Clojure through an explicit
|
||||
`janet` namespace segment, which marks every crossing into host code (where
|
||||
Clojure semantics no longer hold):
|
||||
|
||||
```clojure
|
||||
(janet.os/clock) ; → a Janet module fn: os/clock
|
||||
(janet.string/join ["a" "b"] ",") ; → janet `string/join` (NB: takes a Janet
|
||||
; tuple, not a Jolt vector — convert first)
|
||||
(janet/slurp "deps.edn") ; → a Janet root builtin: slurp
|
||||
(janet/type [1 2]) ; → :table
|
||||
```
|
||||
|
||||
The rule is `janet/<name>` for a Janet root binding and `janet.<module>/<name>`
|
||||
for a module binding. Because the boundary is explicit, you can tell at the call
|
||||
site that a form drops into the host — and that values cross the boundary as
|
||||
their Janet representations (a Jolt vector is a Janet table, etc.), so a Janet
|
||||
function expecting a tuple needs an explicit conversion. The `jolt.interop`,
|
||||
`jolt.shell`, and `jolt.http` namespaces are thin Clojure wrappers built on this.
|
||||
|
||||
This bridge is what makes networking (and everything else in Janet's stdlib)
|
||||
available to ordinary Clojure — for example, `jolt.nrepl` (below) is plain
|
||||
Clojure over `janet.net/*`. It also reaches any **jpm-installed module**:
|
||||
the first reference to `janet.<module>/<name>` requires the module from the
|
||||
janet module path and caches its bindings — so after `jpm install spork`,
|
||||
`janet.spork.http/*` just works. The `jolt.http` client and the Ring adapter
|
||||
in [examples/ring-app](https://github.com/jolt-lang/examples/tree/main/ring-app)
|
||||
are built on spork/http this way, and a project can declare the requirement
|
||||
in `deps.edn` with a `:jpm/module` coordinate (see docs/tools-deps.md).
|
||||
|
||||
```clojure
|
||||
(require '[jolt.interop :as j])
|
||||
(j/janet-type [1 2]) ; → :tuple
|
||||
(j/janet-table-keys {:a 1 :b 2}) ; → [:b :a]
|
||||
```
|
||||
|
||||
## nREPL
|
||||
|
||||
Jolt ships an [nREPL](https://nrepl.org) server and client (`jolt.nrepl`),
|
||||
written in Clojure on top of the `janet.net/*` bridge. Start a server from the
|
||||
CLI — it writes `.nrepl-port` so editors (CIDER, Calva, …) auto-connect:
|
||||
|
||||
```bash
|
||||
jolt nrepl-server # listen on 127.0.0.1:7888, write .nrepl-port
|
||||
jolt nrepl-server 12345 # choose a port
|
||||
jolt nrepl-server 0.0.0.0:12345 # choose host and port (alias: nrepl)
|
||||
$ bin/joltc -e '(->> (range 10) (filter even?) (map (fn [x] (* x x))) (reduce +))'
|
||||
120
|
||||
$ bin/joltc -e '(/ 1 2)'
|
||||
1/2
|
||||
```
|
||||
|
||||
In a project with a `deps.edn`, `jolt nrepl-server` auto-resolves it, so the
|
||||
server starts with the project and its dependencies on the path — connect your
|
||||
editor, then `(require 'your.app)`. (Equivalently, add `:aliases {:nrepl
|
||||
{:main-opts ["nrepl-server"]}}` and run `jolt -M:nrepl`.)
|
||||
## Architecture
|
||||
|
||||
Supported ops: `clone`, `describe`, `eval`, `load-file`, `close`, `ls-sessions`,
|
||||
`interrupt` (acknowledged; an in-flight eval can't actually be interrupted), and
|
||||
`eldoc`. `eval` streams `out`, reports the current `ns`, evaluates each form in
|
||||
the message, and returns an `eval-error` status (the session stays usable) on
|
||||
failure. One Jolt runtime backs the server and sessions share it, so `def`s
|
||||
persist across a connection like a normal dev REPL.
|
||||
A small Chez runtime (`host/chez/*.ss`: value model, persistent collections, seqs,
|
||||
vars/namespaces, host interop) hosts a portable Clojure overlay (`jolt-core/`): the
|
||||
reader/analyzer/IR/backend (`jolt-core/jolt/`) and `clojure.core` in
|
||||
dependency-ordered tiers (`jolt-core/clojure/core/NN-*.clj`). The stdlib namespaces
|
||||
(`clojure.string`/`set`/`walk`/`edn`/`pprint`/…) are portable Clojure under
|
||||
`src/jolt/clojure/`.
|
||||
|
||||
It's also usable as a library — embed a server, or drive another nREPL as a
|
||||
client:
|
||||
|
||||
```clojure
|
||||
(require '[jolt.nrepl :as nrepl])
|
||||
(def server (nrepl/start-server! {:port 7888}))
|
||||
;; ... later ...
|
||||
(nrepl/stop-server! server)
|
||||
|
||||
(def c (nrepl/connect {:port 7888}))
|
||||
(def session (nrepl/client-clone c))
|
||||
(nrepl/client-eval c "(+ 1 2)" session) ; → responses incl. {"value" "3"}
|
||||
(nrepl/client-close c)
|
||||
```
|
||||
`bin/joltc` loads the checked-in seed and the spine, then compiles and evaluates on
|
||||
Chez (read → analyze → IR → emit → eval). `host/chez/bootstrap.ss` rebuilds that
|
||||
seed from source on pure Chez; the build is a self-hosting fixpoint (a rebuild
|
||||
reproduces the checked-in seed byte-for-byte).
|
||||
|
||||
## Differences from Clojure
|
||||
|
||||
Jolt targets Clojure semantics but runs on Janet, not the JVM. The notable divergences:
|
||||
Jolt targets Clojure semantics but runs on Chez, not the JVM.
|
||||
|
||||
- **Host platform.** No JVM and no Java interop — `import`, `gen-class`, `proxy` of Java classes, and `java.*` are unavailable. `instance?` recognizes a small set of built-in types (`clojure.lang.Atom`, `Number`, `String`, …).
|
||||
- **Numbers.** Janet integers and doubles. `(/ 1 3)` is `0.3333…` and large products lose precision. No ratios or `BigDecimal` (`ratio?` is always false, `bigdec` falls back to a double); `bigint`/`biginteger` use Janet's 64-bit `int/s64`, not arbitrary precision. The reader still accepts Clojure's numeric literal syntaxes — the BigInt/BigDecimal suffixes (`42N`, `1.5M`), ratios (`1/2`), radixed integers (`2r1010`, `16rFF`), and exponents (`1e3`) — but reads them as plain Janet numbers (a ratio becomes its double quotient). The auto-promoting `+'`/`-'`/`*'`/`inc'`/`dec'` are aliases for the plain ops, since Janet numbers don't overflow. `quot`/`rem`/`mod` follow Clojure's sign rules. The symbolic values `##Inf`/`##-Inf`/`##NaN` read, and `infinite?`/`NaN?` work. Janet represents an integer and an integer-valued double identically, so `1` and `1.0` are indistinguishable: `(float?/double? 1.0)` is `false` and `(int? 1.0)` is `true` — `float?`/`double?` are true only for values with a fractional part or `##Inf`/`##NaN`.
|
||||
- **Collections.** By default Jolt uses immutable persistent data structures: vectors are 32-way branching tries (structural-sharing persistent vectors with O(log₃₂ n) `conj`/`assoc`/`nth`), lists are persistent singly-linked cons cells (O(1) `conj`/`cons` prepend with structural sharing), and maps/sets are persistent hash structures. Value equality and sequence operations are Clojure-compatible, but hash-map/hash-set iteration order is unspecified and differs from Clojure — use `sorted-map`/`sorted-set` when order matters.
|
||||
- **Mutable build mode.** Jolt can be compiled to use fast Janet-native *mutable* collections instead, via a build-time flag: `JOLT_MUTABLE=1 jpm build` (default `jpm build` is immutable). In mutable mode vectors and lists share one mutable array representation (so `conj` mutates in place and appends, and `vector?`/`list?` no longer distinguish them) — a performance/looseness trade-off. The default immutable build has full Clojure value semantics.
|
||||
- **Concurrency / STM.** No refs, `dosync`, agents, or `send`; `locking` evaluates its body without real locking. Atoms, volatiles, promises, and delays are supported.
|
||||
- **Futures.** `future` runs its body on a *real* OS thread (Janet's `ev/thread`), so it can use a second core for CPU-bound work — unlike the cooperatively-scheduled `go` blocks. `deref`/`@` parks until the result is ready (with the optional `(deref f timeout-ms timeout-val)` arity); `future?`, `future-done?`, `realized?`, `future-cancel`, and `future-cancelled?` are supported. Two important divergences from the JVM: (1) **snapshot semantics** — Janet threads have separate heaps, so the body and the state it closes over are *copied* to the worker thread and only the return value is copied back; mutating a captured atom does not propagate to the parent (communicate via the return value). (2) **no thread interruption** — Janet OS threads can't be cancelled mid-run, so `future-cancel` marks the *future* cancelled (deref then throws and the predicates flip) but the underlying computation still runs to completion in the background. As on the JVM, a live future thread keeps the process alive until it finishes (the JVM's non-daemon future pool behaves the same).
|
||||
- **core.async.** `clojure.core.async` runs on Janet fibers and channels (`chan`, `go`, `go-loop`, `<!`/`>!`/`<!!`/`>!!`, `close!`, `alts!`, `timeout`, `put!`/`take!`, `buffer`/`dropping-buffer`/`sliding-buffer`, and channel transducers via `(chan n xform)`). Because Janet fibers are stackful coroutines, a `go` block is just its body run in a fiber — no CPS/state-machine rewrite — so `<!`/`>!` work *anywhere*, including inside `try`, nested `fn`s, and loops (positions Clojure's `go` macro forbids). Go blocks are cooperatively scheduled on one OS thread, so parking (`<!`) and blocking (`<!!`) coincide; `thread` runs cooperatively too. Dynamic-var bindings are conveyed into `go` blocks (each go block sees the bindings in effect when it was spawned).
|
||||
- **Regex.** Compiled to Janet's PEG engine (Janet has no regex). Supported: capturing groups (`[whole g1 …]`), greedy and lazy quantifiers with backtracking, `(?:…)`, lookahead `(?=…)`/`(?!…)`, alternation, anchors `^ $ \b \B`, character classes, and the `(?i)` flag. Not supported: lookbehind, backreferences (`\1`), named groups (`(?<name>…)`), and Unicode property classes (`\p{Lu}`).
|
||||
- **Arrays.** Java-style arrays map onto Janet's native types: `byte-array` is a Janet buffer (contiguous, C-backed); `object-array`/`int-array`/`double-array`/etc. are Janet arrays. `aget`/`aset`/`alength`/`aclone` work over both.
|
||||
- **Transients.** `transient`/`conj!`/`assoc!`/`dissoc!`/`disj!`/`pop!`/`persistent!` are real mutable scratch collections backed by Janet's native arrays and tables (vectors → arrays, maps/sets → tables), so building a collection with them avoids the per-step copying of the persistent path (notably for maps/sets). `persistent!` freezes back to a persistent value.
|
||||
- **Not implemented.** JVM reflection, `proxy`, and the `clojure.repl`/`clojure.template` namespaces.
|
||||
- **Host platform.** No JVM and no Java interop — `import`, `gen-class`, `proxy` of
|
||||
Java classes, and `java.*` are unavailable. A class token resolves to a name; a
|
||||
small set of host classes is recognized for `instance?`.
|
||||
- **Numbers.** The full Scheme numeric tower, matching the JVM: exact integers and
|
||||
bignums, exact ratios (`(/ 1 2)` ⇒ `1/2`), and flonum doubles. `=` is
|
||||
category-aware (`(= 3 3.0)` ⇒ `false`); `==` is value-equality (`(== 3 3.0)` ⇒
|
||||
`true`). `integer?`/`int?` are exact integers, `float?`/`double?` are flonums,
|
||||
`ratio?` is an exact non-integer. No `BigDecimal` (`decimal?` is always false).
|
||||
- **Concurrency.** `future`/`promise`/`agent`/`pmap` run on real OS threads over a
|
||||
**shared heap**, matching JVM semantics (not isolated-heap snapshots). Atoms use a
|
||||
per-atom mutex with JVM-style CAS. `clojure.core.async` provides blocking channels
|
||||
and `go`/`<!`/`>!`/`alts!`/`timeout`.
|
||||
- **Regex.** Backed by [irregex](https://github.com/ashinn/irregex) (vendored),
|
||||
PCRE/Java-style patterns.
|
||||
- **Collections.** Immutable persistent vectors, cons lists, and HAMT maps/sets.
|
||||
Hash-map/hash-set iteration order is unspecified — use `sorted-map`/`sorted-set`
|
||||
when order matters. Transients are real mutable scratch collections.
|
||||
|
||||
Supported and Clojure-compatible: chars as a distinct type, lazy/infinite sequences, transducers, destructuring, multimethods with hierarchies, protocols/records (`deftype`/`defrecord`/`reify`/`extend-protocol`), metadata, namespaces, and the reader (`#()`, `#_`, `#?`, tagged literals, `#"…"`).
|
||||
Supported and Clojure-compatible: lazy/infinite sequences, transducers,
|
||||
destructuring, multimethods with hierarchies, protocols/records
|
||||
(`deftype`/`defrecord`/`reify`/`extend-protocol`), metadata, namespaces, runtime
|
||||
`eval`/`load-string`/`defmacro`, and the reader (`#()`, `#_`, `#?`, tagged literals,
|
||||
`#"…"`).
|
||||
|
||||
## Test
|
||||
|
||||
```
|
||||
jpm test # full suite (recurses test/)
|
||||
janet test/spec/sequences-spec.janet # a single spec
|
||||
janet test/integration/conformance-test.janet
|
||||
```bash
|
||||
make test # the full gate
|
||||
make corpus # conformance corpus vs the JVM-sourced spec
|
||||
make unit # host-specific unit cases
|
||||
make selfhost # bootstrap fixpoint (rebuild == checked-in seed)
|
||||
make smoke # bin/joltc CLI smoke
|
||||
make sci # load borkdude/sci's source through joltc (compat stress)
|
||||
make ffi # HTTP-server GC-safety + http-client temp paths
|
||||
make transient # transient mutation + linear-time builds
|
||||
make certify # JVM oracle (skips if clojure is absent)
|
||||
```
|
||||
|
||||
Tests are organized in three layers:
|
||||
|
||||
- **`test/spec/`** — the contract. Black-box, behavior-defining tables (one file
|
||||
per public API area) that collectively pin down Jolt's defined behavior. This
|
||||
is the authoritative description of what Jolt promises.
|
||||
- **`test/integration/`** — cross-cutting and regression batteries: the Clojure
|
||||
conformance suite (run in all three execution modes), SCI bootstrap/runtime
|
||||
loading, jank conformance, the cross-dialect
|
||||
[clojure-test-suite](https://github.com/jank-lang/clojure-test-suite) (a git
|
||||
submodule at `vendor/clojure-test-suite`, run via a minimal `clojure.test` shim
|
||||
and baseline-guarded), compile-mode tests, the library API, and a broad
|
||||
systematic-coverage net.
|
||||
- **`test/unit/`** — white-box tests for individual components (reader,
|
||||
evaluator, types, persistent collections, regex, compiler).
|
||||
|
||||
`test/support/harness.janet` provides the shared `defspec` table runner (cases
|
||||
are `["label" expected actual]`, compared with Jolt's own `=`) plus
|
||||
`expect=`/`expect-throws` for unit tests.
|
||||
|
||||
The syntactic half of the contract — the surface syntax the reader accepts — is
|
||||
specified as an EBNF grammar in [`docs/grammar.ebnf`](docs/grammar.ebnf), with
|
||||
Jolt-vs-Clojure deviations noted inline. `test/spec/reader-syntax-spec.janet`
|
||||
exercises it.
|
||||
|
||||
### clojure-test-suite conformance
|
||||
|
||||
The [clojure-test-suite](https://github.com/jank-lang/clojure-test-suite) battery
|
||||
(vendored as a git submodule) runs ~3980 assertions green. Jolt validates its
|
||||
arguments like Clojure — arithmetic on non-numbers, comparisons against `nil`,
|
||||
out-of-range indices, malformed `conj!`/`assoc!`/`merge`, non-seqable
|
||||
`first`/`seq`/`vec`, and lazy transformers (`map`/`filter`/…) realized over a
|
||||
non-seqable all throw. The lazy seq fns return seqs (not vectors), so
|
||||
`seq?`/`vector?`/`sequential?` of their results match Clojure. The assertions
|
||||
that remain failing are accounted for by the platform/design differences above,
|
||||
not by missing behavior:
|
||||
|
||||
- **No bignum/ratio/BigDecimal** — `bigint`/`numerator`/`denominator`/`bigdec`,
|
||||
the `big-int?`/auto-promotion checks, and the `2N`/`1/2`/`1.0M` literals read
|
||||
but don't carry those exact types.
|
||||
- **Integer/float identity** — Janet represents `1` and `1.0` identically, so
|
||||
`quot`/`rem`/`mod`'s `double?`/`int?` result-type assertions and many
|
||||
`float?`/`double?` cases can't distinguish them (`(str 0.0)` is `"0"`).
|
||||
- **64-bit integers / Unicode** — `bit-and` etc. on full-width 64-bit constants
|
||||
lose precision (doubles), and `subs`/`count` work on bytes, not code points.
|
||||
The conformance corpus (`test/chez/corpus.edn`) is a host-neutral language spec
|
||||
whose expected values are sourced from reference JVM Clojure. See
|
||||
[test/conformance/SPEC.md](test/conformance/SPEC.md).
|
||||
|
||||
## License
|
||||
|
||||
|
|
|
|||
|
|
@ -53,7 +53,6 @@ the broadening (2026-06-16), ratios cluster by axis:
|
|||
## Running
|
||||
|
||||
```sh
|
||||
jpm build && export PATH="$PWD/build:$PATH"
|
||||
bench/run.sh # whole-program optimization on (default)
|
||||
JOLT_WHOLE_PROGRAM=0 bench/run.sh # WP off, to measure what WP buys
|
||||
bench/run.sh binary-trees 16 # one benchmark, custom size
|
||||
|
|
@ -62,7 +61,7 @@ bench/run.sh binary-trees 16 # one benchmark, custom size
|
|||
## A/B against a change
|
||||
|
||||
To measure a pass, run the suite on `main`, then on the branch, back to back
|
||||
(same machine, quiet) — the protocol used for `test/bench/core-bench.janet` and
|
||||
the ray tracer. Each benchmark prints `runs: [...]` and `mean: N ms`; compare
|
||||
(same machine, quiet) — the same protocol used for the ray tracer. Each
|
||||
benchmark prints `runs: [...]` and `mean: N ms`; compare
|
||||
the means. A pass is worth landing when it moves a benchmark whose axis it
|
||||
targets, even if the ray tracer stays flat.
|
||||
|
|
|
|||
|
|
@ -1,28 +0,0 @@
|
|||
# Dump the Janet that jolt's backend emits for the mandelbrot hot fns, so we can
|
||||
# A/B it against bench/mandelbrot-hand.janet and localize the ~1.43x jolt-over-
|
||||
# hand-Janet gap measured in the foundational-runtime spike (jolt-5vsp).
|
||||
(import ../src/jolt/api :as api)
|
||||
(import ../src/jolt/backend :as backend)
|
||||
(import ../src/jolt/reader :as reader)
|
||||
|
||||
(def ctx (api/init-cached {:compile? true}))
|
||||
(put (ctx :env) :direct-linking? true)
|
||||
(put (ctx :env) :inline? true)
|
||||
(api/eval-string ctx "(ns mandelbrot)")
|
||||
|
||||
(def count-point-src
|
||||
"(defn count-point [cr ci cap] (loop [i 0 zr 0.0 zi 0.0] (if (or (>= i cap) (> (+ (* zr zr) (* zi zi)) 4.0)) i (recur (inc i) (+ (- (* zr zr) (* zi zi)) cr) (+ (* 2.0 (* zr zi)) ci)))))")
|
||||
|
||||
(def run-src
|
||||
"(defn run [n] (let [cap 200 nd (* 1.0 n)] (loop [y 0 acc 0] (if (< y n) (let [ci (- (/ (* 2.0 y) nd) 1.0) row (loop [x 0 a 0] (if (< x n) (let [cr (- (/ (* 2.0 x) nd) 1.5)] (recur (inc x) (+ a (count-point cr ci cap)))) a))] (recur (inc y) (+ acc row))) acc))))")
|
||||
|
||||
(api/eval-string ctx count-point-src)
|
||||
(api/eval-string ctx run-src)
|
||||
|
||||
(defn emit [src]
|
||||
(string/format "%p" (backend/emit-ir ctx (backend/analyze-form ctx (reader/parse-string src)))))
|
||||
|
||||
(print "===== count-point emitted Janet =====")
|
||||
(print (emit count-point-src))
|
||||
(print "\n===== run emitted Janet =====")
|
||||
(print (emit run-src))
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
# mandelbrot — hand-written Janet that MIRRORS jolt's loop-lowering: every loop/
|
||||
# recur becomes a self-recursive local closure stored in a var and called once
|
||||
# per iteration (see bench/dump-mandelbrot-emit.janet). If this lands at jolt's
|
||||
# ~219ms (vs the while-loop mandelbrot-hand.janet's ~153ms), the ~1.43x jolt-
|
||||
# over-hand-Janet gap is the recursive-closure loop lowering, not anything else.
|
||||
# janet bench/mandelbrot-hand-rec.janet 200
|
||||
|
||||
(defn count-point [cr ci cap]
|
||||
(var loopfn nil)
|
||||
(set loopfn (fn [i zr zi]
|
||||
(if (let [t (>= i cap)] (if t t (> (+ (* zr zr) (* zi zi)) 4)))
|
||||
i
|
||||
(loopfn (+ i 1)
|
||||
(+ (- (* zr zr) (* zi zi)) cr)
|
||||
(+ (* 2 (* zr zi)) ci)))))
|
||||
(loopfn 0 0 0))
|
||||
|
||||
(defn run [n]
|
||||
(def cap 200)
|
||||
(def nd (* 1 n))
|
||||
(var yloop nil)
|
||||
(set yloop (fn [y acc]
|
||||
(if (< y n)
|
||||
(let [ci (- (/ (* 2 y) nd) 1)
|
||||
row (do
|
||||
(var xloop nil)
|
||||
(set xloop (fn [x a]
|
||||
(if (< x n)
|
||||
(let [cr (- (/ (* 2 x) nd) 1.5)]
|
||||
(xloop (+ x 1) (+ a (count-point cr ci cap))))
|
||||
a)))
|
||||
(xloop 0 0))]
|
||||
(yloop (+ y 1) (+ acc row)))
|
||||
acc)))
|
||||
(yloop 0 0))
|
||||
|
||||
(defn main [& args]
|
||||
(def n (if (> (length args) 1) (scan-number (get args 1)) 1000))
|
||||
(repeat 2 (run (div n 2)))
|
||||
(def times @[])
|
||||
(var last-r 0)
|
||||
(repeat 3
|
||||
(def t0 (os/clock))
|
||||
(def r (run n))
|
||||
(array/push times (* 1000.0 (- (os/clock) t0)))
|
||||
(set last-r r))
|
||||
(printf "mandelbrot n %d result %d" n last-r)
|
||||
(print "runs: " (string/join (map |(string (/ (math/round (* $ 10.0)) 10.0)) times) " "))
|
||||
(printf "mean: %.1f ms" (/ (sum times) 3)))
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
# mandelbrot — hand-written idiomatic Janet, same nested loop as bench/mandelbrot.clj.
|
||||
# This is the "optimal Janet" leg of the foundational-runtime spike (jolt-5vsp):
|
||||
# comparing jolt-emitted Janet vs this vs JVM localizes the 15x compute floor —
|
||||
# jolt-backend overhead vs the Janet VM's own floor.
|
||||
#
|
||||
# janet bench/mandelbrot-hand.janet 200
|
||||
|
||||
(defn count-point [cr ci cap]
|
||||
(var i 0)
|
||||
(var zr 0.0)
|
||||
(var zi 0.0)
|
||||
(while (and (< i cap) (<= (+ (* zr zr) (* zi zi)) 4.0))
|
||||
(def nzr (+ (- (* zr zr) (* zi zi)) cr))
|
||||
(def nzi (+ (* 2.0 (* zr zi)) ci))
|
||||
(set zr nzr)
|
||||
(set zi nzi)
|
||||
(++ i))
|
||||
i)
|
||||
|
||||
(defn run [n]
|
||||
(def cap 200)
|
||||
(def nd (* 1.0 n))
|
||||
(var acc 0)
|
||||
(var y 0)
|
||||
(while (< y n)
|
||||
(def ci (- (/ (* 2.0 y) nd) 1.0))
|
||||
(var x 0)
|
||||
(var a 0)
|
||||
(while (< x n)
|
||||
(def cr (- (/ (* 2.0 x) nd) 1.5))
|
||||
(set a (+ a (count-point cr ci cap)))
|
||||
(++ x))
|
||||
(set acc (+ acc a))
|
||||
(++ y))
|
||||
acc)
|
||||
|
||||
(defn main [& args]
|
||||
(def n (if (> (length args) 1) (scan-number (get args 1)) 1000))
|
||||
# warmup
|
||||
(repeat 2 (run (div n 2)))
|
||||
(def runs 3)
|
||||
(def times @[])
|
||||
(var last-r 0)
|
||||
(repeat runs
|
||||
(def t0 (os/clock))
|
||||
(def r (run n))
|
||||
(def ms (* 1000.0 (- (os/clock) t0)))
|
||||
(set last-r r)
|
||||
(array/push times ms))
|
||||
(def mean (/ (sum times) runs))
|
||||
(printf "mandelbrot n %d result %d" n last-r)
|
||||
(print "runs: " (string/join (map |(string (/ (math/round (* $ 10.0)) 10.0)) times) " "))
|
||||
(printf "mean: %.1f ms" mean))
|
||||
19
bin/joltc
Executable file
19
bin/joltc
Executable file
|
|
@ -0,0 +1,19 @@
|
|||
#!/bin/sh
|
||||
# joltc — the pure-Chez jolt runtime. NO Janet.
|
||||
#
|
||||
# Compiles and evaluates jolt (Clojure) on Chez using the checked-in bootstrap
|
||||
# seed (host/chez/seed/). With only Chez installed it runs jolt end to end:
|
||||
#
|
||||
# joltc -e "(+ 1 2)" evaluate an expression
|
||||
# joltc run -m app.core [args] resolve deps.edn, run a namespace's -main
|
||||
# joltc -M:alias [args] run an alias's :main-opts
|
||||
# joltc repl | path | <task> REPL, print roots, or a deps.edn task
|
||||
#
|
||||
# The launcher cd's to the jolt repo root so the runtime's relative loads work;
|
||||
# the user's original cwd (the project dir, where deps.edn lives) is passed in
|
||||
# JOLT_PWD.
|
||||
root="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
JOLT_PWD="${JOLT_PWD:-$PWD}"
|
||||
export JOLT_PWD
|
||||
cd "$root" || exit 1
|
||||
exec chez --script host/chez/cli.ss "$@"
|
||||
|
|
@ -1,267 +0,0 @@
|
|||
# Architecture Refactor Plan
|
||||
|
||||
Goal: make the jolt codebase easier to understand and safe to change — for human
|
||||
maintainers and, specifically, for LLM agents. An agent should be able to find
|
||||
where a feature lives, see its related code, and make a change without scanning
|
||||
3000-line files or keeping invisible global state in mind.
|
||||
|
||||
This plan synthesizes a six-part architectural review (one reviewer per
|
||||
subsystem). It is organized as **independent, gate-validated phases**, ordered by
|
||||
value-to-risk. Each phase is a PR-sized unit. Nothing here changes behavior; it is
|
||||
pure reorganization plus a small set of dead-code/bug deletions.
|
||||
|
||||
## Non-negotiable constraints (apply to every phase)
|
||||
|
||||
- **Every phase passes the full gate**: `jpm test` green (conformance ×3 modes,
|
||||
`clojure-test-suite` ≥ baseline, bench back-to-back vs main, real exit code).
|
||||
`rm -rf build && jpm clean` before trusting the binary.
|
||||
- **Load order is load-bearing.** The Janet seed (`src/jolt/*.janet`) and the
|
||||
Clojure overlay tiers (`jolt-core/clojure/core/NN-*.clj`) load in a fixed order;
|
||||
a module may only use what loads before it. Splitting a file must preserve the
|
||||
net load order (a new file is imported where the old code ran).
|
||||
- **Seed-tier discipline** (the jolt-tzo rules in CLAUDE.md): nothing the
|
||||
analyzer/IR use may move below the kernel tier; a tier may only use macros from
|
||||
earlier tiers; expander-called fns stay in 00-syntax.
|
||||
- **One concern per PR.** Do not combine a file split with a behavior fix.
|
||||
Dead-code/bug deletions (Phase 0) land first and separately so later diffs are
|
||||
pure moves.
|
||||
|
||||
## Guiding principles (the target state)
|
||||
|
||||
1. **One obvious home per feature.** Adding a `.someMethod` interop shim, a reader
|
||||
macro, or a clojure.core fn should have exactly one file an agent edits.
|
||||
2. **Files map to concerns, not to history.** No 3000-line grab-bags; no module
|
||||
whose name lies about its contents (`javatime.janet` is 80% not java.time;
|
||||
`phm.janet` contains LazySeq; `types.janet` holds seven concerns).
|
||||
3. **Make implicit contracts explicit and checked.** The seed↔overlay split, the
|
||||
ctx-shaping env-knob list, and the IR op set are tribal knowledge today; turn
|
||||
each into a single source of truth with a drift check.
|
||||
4. **No copy-paste dispatch.** Where the same op-set / member-dispatch / cache
|
||||
dance is hand-written N times, extract one combinator.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — Dead code & concrete bugs (low risk, do first)
|
||||
|
||||
Pure deletions and small fixes, each with a regression row. These remove
|
||||
*actively misleading* code (comments that contradict behavior) before any moves.
|
||||
|
||||
| Item | Location | Note |
|
||||
|---|---|---|
|
||||
| `find` defined twice; the dead copy returns a plain vector and is *wrong* | `jolt-core/clojure/core/20-coll.clj:347-349` | live def at :787 returns a real map-entry; delete the dead one |
|
||||
| `core-satisfies?` always returns `false` (latent bug + misleading comment) | `src/jolt/core.janet:2412` | either implement over the protocol registry or document why inert; fix the `eval-list` comment that claims it's an overlay fn |
|
||||
| `File.toURL` stores `:url` but every `:jolt/url` method reads `:spec` | `src/jolt/javatime.janet:636` | broken shim; use `:spec`, add a spec row |
|
||||
| `core-type->str` — zero references | `src/jolt/core.janet:2416` | delete defn + binding |
|
||||
| `core-resolve` — unreachable (overridden by `install-stateful-fns!`) | `src/jolt/core.janet:2365` | delete defn + binding; fix stale comment |
|
||||
| `mark-hint` — unreachable | `jolt-core/jolt/passes.clj:836` | delete |
|
||||
| `pad2` defined twice | `src/jolt/javatime.janet:41,522` | keep one |
|
||||
| `phs-to-struct`, `shape-vals`, `ns-imports-fn` — zero references | `phm.janet:302`, `types.janet:655`, `types.janet:527` | delete unless reserved API |
|
||||
| `pl-rest` no-op `(if (plist? r) r r)` | `src/jolt/plist.janet:62` | collapse / fix; regression check |
|
||||
| `read-quote` unused `pos` param | `src/jolt/reader.janet:608` | drop |
|
||||
| Stale/contradictory comments (`extend`, orphan `;; trampoline:` / `;; rand-int:` headers, migration breadcrumbs) | `30-macros.clj:402-404`, `20-coll.clj:558-560,780,790` | sweep |
|
||||
| **`:map-shapes?` missing from the deps-image cache key** (possible stale-image correctness gap) | `src/jolt/main.janet:440-448` | add to key; confirm with a test |
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Extract the host-interop subsystem (highest value)
|
||||
|
||||
**Problem (corroborated by 3 reviewers).** The JVM-emulation shim layer is the
|
||||
single worst sprawl, and it is exactly where the recent hiccup/markdown/malli work
|
||||
landed ad hoc. A single class is split across up to three files:
|
||||
|
||||
- registry *machinery* (`class-statics`/`tagged-methods`/`class-ctors` +
|
||||
`register-*!`) lives in `evaluator.janet:624-651`;
|
||||
- four static tables (`Math`/`Thread`/`System`/`Long`/`Number`) are hardcoded in
|
||||
`evaluator.janet:537-619` and dispatched *outside* the registry in `resolve-sym`
|
||||
(780-794); instance-method tables (`string/number/object-methods`, 698-775) are
|
||||
likewise inline;
|
||||
- the bulk of the shims are in `javatime.janet` (674 lines, ~80% not java.time:
|
||||
java.io/util/net/nio/sql/text/math all in one `install-io!`);
|
||||
- `api.janet:18-56` wires the malli statics + `set-coll-interop!` as load-time
|
||||
side effects in the public-API module;
|
||||
- `core.janet` holds `File`/JDBC constructors; `types.janet` holds the `:jolt/inst`
|
||||
representation.
|
||||
|
||||
**Target.** A `src/jolt/interop/` directory, one mechanism file + one file per JDK
|
||||
area, each owning a class's *full* surface (ctor + statics + methods + `instance?`
|
||||
predicate + canonical name) and exposing one `install!`:
|
||||
|
||||
```
|
||||
src/jolt/interop/
|
||||
registry.janet # MOVED from evaluator: class-statics/tagged-methods/class-ctors,
|
||||
# register-*!, canonical-names, value-overrides, instance? registry
|
||||
coerce.janet # shared: chr, char->byte, render-piece/writer-piece, pad2,
|
||||
# the date-format token walker (kills the pad2/render-piece dups)
|
||||
java_time.janet java_io.janet java_net.janet java_util.janet
|
||||
java_lang.janet # absorbs evaluator's inline Math/Thread/System/Long/Number +
|
||||
# string/number/object method tables — the registry becomes the
|
||||
# ONLY static/method-dispatch mechanism
|
||||
jdbc.janet
|
||||
install.janet # (install-all! ctx) — the ONE place api.janet calls (replaces api 18-56)
|
||||
```
|
||||
|
||||
`evaluator.janet`'s `resolve-sym` and the dot-dispatch consult only the registry.
|
||||
`regex.janet` and `async.janet` stay put — they are engines/library-ports consumed
|
||||
by interop, not shims.
|
||||
|
||||
**Cheap 80% if the full split is too big for one PR:** rename
|
||||
`javatime.janet`→`host_interop.janet`, pull the four inline static tables + three
|
||||
method tables out of `evaluator.janet` into it, move `api.janet:18-56` into it,
|
||||
dedup `pad2`/`chr`/`render-piece`. Collapses the scatter from 5 files to 2.
|
||||
|
||||
**Risk:** medium — touches the hot dot-dispatch path; load order must keep the
|
||||
registry available before any `install!`. Validate with `host-interop-spec` +
|
||||
the hiccup/markdown/malli example apps + full gate.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Decompose the god-files
|
||||
|
||||
The three biggest interpreter/runtime files are the top LLM-navigability tax.
|
||||
Split along the cohesive clusters the review mapped (line ranges in the review
|
||||
notes). Each split is a mechanical move + import; behavior unchanged.
|
||||
|
||||
### 2a. `evaluator.janet` (2681 → ~5 files)
|
||||
- `special_forms.janet` — explode the **680-line `eval-list`** (1921-2599) into
|
||||
named `eval-<form>` fns (`eval-fn*`, `eval-let*`, `eval-try`, `eval-dot`, …) +
|
||||
a dispatch table. This is the highest-leverage single change: today "where is
|
||||
`try` handled" means scanning a 680-line body.
|
||||
- `resolution.janet` — `resolve-sym`/`resolve-var`/binding/destructuring.
|
||||
- `ns_loader.janet` — module/bridge plumbing + require/in-ns/use/import/refer.
|
||||
- `runtime_registration.janet` — protocol/defmulti/deftype/reify setup +
|
||||
`install-stateful-fns!` (1506-1909) split into per-domain registration fns.
|
||||
- (host-interop already left in Phase 1.)
|
||||
- **De-dup the two `.method` dot arms** (2456-2507 vs 2512-2550): extract one
|
||||
`dispatch-member [target field-name args]` used by both. They are copy-pasted
|
||||
today and must be hand-synced on every interop change.
|
||||
|
||||
### 2b. `core.janet` (3017 → ~6 leaf files)
|
||||
Clusters are already sequential and mostly leaf — low risk:
|
||||
`core-types` (predicates/eq/arith/bits), `core-coll` (assoc/seq/transducers/lazy/
|
||||
transients), `core-print` (pr-str/str), `core-io`, `core-refs` (atoms/vars/delays/
|
||||
arrays/type), `core-bindings` (the table + `init-core!` + a *labeled* stub
|
||||
section). The `core-bindings` table stays the single registration point.
|
||||
|
||||
### 2c. `passes.clj` (1487 → 3-4 files behind one façade)
|
||||
The Louvain communities and the cycle analysis agree: the IR-rewriting passes and
|
||||
the type subsystem are weakly coupled (only `run-passes` + `dirty` shared).
|
||||
- `jolt/passes.clj` (keep, ~150 lines): `run-passes` + shared state + re-exports —
|
||||
the only file the back end imports.
|
||||
- `jolt/passes/fold.clj` — const-fold (always-on).
|
||||
- `jolt/passes/inline.clj` — inline + flatten-lets + scalar-replace (share the
|
||||
alpha-rename invariant).
|
||||
- `jolt/passes/types.clj` — type lattice + `infer` + success-checker + driver API
|
||||
(kept as one module to respect the inference↔checker cycle; no `declare`
|
||||
gymnastics). Extract the `infer` `:invoke` arm (1051-1160) into per-shape
|
||||
helpers regardless of the split.
|
||||
- Fix the **stale ns docstring** (lists 4 passes, omits the type system that is
|
||||
>50% of the file).
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Kill the structural duplication
|
||||
|
||||
### 3a. One IR op-walk combinator
|
||||
There are **11 hand-written recursive walks** over the IR op set (const-fold,
|
||||
inline, subst, body-closed?, pure?, flatten-lets, local-escapes?, subst-lookup,
|
||||
scalar-replace, infer, backend `emit`). Adding an IR op means editing all of them,
|
||||
and the "unknown ops pass through" promise is only partly kept. Introduce one
|
||||
`map-ir-children` (in `ir.clj` or `jolt/ir/walk.clj`) that knows each op's child
|
||||
positions; rewrite the walks as `(map-ir-children f node)` + their few specials.
|
||||
Collapses ~400 lines and makes adding an op a one-site change.
|
||||
|
||||
### 3b. IR shape hygiene
|
||||
`:let`/`:loop` bindings are `[name init]` vectors, `:map` pairs are `[k v]`, `:fn`
|
||||
arities are maps; optional keys are present-or-absent, which is *why* the backend
|
||||
needs `norm-node`/phm-densification everywhere. Make `ir.clj` constructors always
|
||||
emit optional keys (nil-valued); delete the defensive `norm-node` calls.
|
||||
|
||||
### 3c. Smaller dedups
|
||||
- `read-delimited` driver for the 4 collection readers (`read-list/vec/set/kvs`)
|
||||
in `reader.janet` (the skip/splice logic already drifted once).
|
||||
- `bucket-index-of` for the 5 stride-2 bucket scans in `phm.janet`.
|
||||
- Unify the kw-lookup head-matching reimplemented in analyzer/passes/backend
|
||||
(a kw-lookup the inference tags but the backend doesn't specialize is a silent
|
||||
miss) behind one shared predicate + fn-name table.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Config & caching coherence
|
||||
|
||||
### 4a. Lift run-mode/config resolution into `config.janet`
|
||||
`config.janet` is 15 lines (one constant); meanwhile `main.janet:585-630` holds
|
||||
~45 lines of pure env-knob policy (`open-mode?`/`dl`/`optimize?`/shape/whole-program
|
||||
gates) that can't be unit-tested without the CLI and that the cache keys need to
|
||||
share. Promote it: `config/resolve-run-mode [argv env] → {:direct-linking? :inline?
|
||||
:shapes? :map-shapes? :whole-program? :direct-link-auto?}`, plus a canonical
|
||||
`ctx-shaping-env-vars` list. `main` shrinks to: parse argv → resolve → install →
|
||||
dispatch.
|
||||
|
||||
### 4b. One ctx-image module, two policies
|
||||
`init-cached` (core image, api.janet) and the deps-image (main.janet) duplicate the
|
||||
fork→validate→reinstall-print-cb→atomic-publish dance, each with a **hand-built
|
||||
positional `%q|...` cache key** that silently misaligns if a knob is added.
|
||||
Extract `ctx_image.janet`: `load-image [path predicate]`, `save-image [ctx path]`,
|
||||
`ctx-cache-key [pairs]` (derived from `ctx-shaping-env-vars`, impossible to
|
||||
misalign). Both callers differ only in the validity predicate (source-fingerprint
|
||||
vs mtime-manifest). This also closes the cache-key footgun for good and resolves
|
||||
`aot.janet`'s status (fold its marshal helpers in, or delete it — it is exercised
|
||||
only by one integration test and is on no run path).
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Data structures, reader, types, and the seed↔overlay index
|
||||
|
||||
### 5a. `types.janet` (699 → 3-4 files)
|
||||
Seven concerns share a generic name. Split: `value.janet` (char/inst/uuid),
|
||||
keep the cohesive `var`+`ns`+`ctx` core, `protocols.janet` (the protocol/type
|
||||
registry, `type-satisfies?`), `records.janet` (shape-records). Minimum win:
|
||||
extract the protocol registry + shape-records (the two least "types"-like).
|
||||
|
||||
### 5b. `phm.janet` (303 → 3 files)
|
||||
Split out `lazyseq.janet` (LazySeq has nothing to do with hash maps — pure
|
||||
mislabel) and `phs.janet` (PersistentHashSet). `phm.janet` keeps the map.
|
||||
|
||||
### 5c. Internal collection protocol
|
||||
phm/pv/plist each re-implement count/seq/conj/predicate/meta with diverging
|
||||
naming, and `core.janet` dispatches on them with giant per-op `cond`s (every new
|
||||
structure edits every cond). A minimal `:jolt/type`-keyed vtable (`-count -seq
|
||||
-conj`) lets core dispatch once. Normalize the trio's naming (`pv` vs `pvec`,
|
||||
`->`/`-to-`, `EMPTY` vs `EMPTY-PLIST`).
|
||||
|
||||
### 5d. Make the seed↔overlay boundary self-documenting
|
||||
Five fns exist in both the seed (`core-X`) and overlay (`X`) as dispatch twins with
|
||||
no cross-reference; nothing indexes which copy is authoritative (`transduce` is
|
||||
overlay-public but `into` is seed-public — surprising and undocumented). Add:
|
||||
- a generated `REGISTRY` (name → home → public-source → seed-twin? → dispatch-only?)
|
||||
with a build-time drift check;
|
||||
- `SEED-TWIN:` provenance comments on each twin (greppable);
|
||||
- a distinct prefix for dispatch-only seed helpers so they don't read like public
|
||||
ones. Mirrors the existing "delete the seed defn + binding in the same change"
|
||||
rule.
|
||||
|
||||
### 5e. Boundary doc-comments
|
||||
Add rep-vs-API pointers between the data structures and `core.janet` (e.g. "the
|
||||
persistent vector trie lives in `pv.janet`; Clojure-facing vector ops and
|
||||
tuple/pvec polymorphism live in `core.janet`"), so an agent grepping "vector" in
|
||||
core knows where the representation is.
|
||||
|
||||
---
|
||||
|
||||
## Sequencing & rationale
|
||||
|
||||
```
|
||||
Phase 0 (dead code/bugs) — independent, do first, unblocks clean diffs
|
||||
Phase 1 (host-interop extract) — highest value; isolates the recent shim sprawl
|
||||
Phase 2 (god-file splits) — biggest navigability win; 2a/2b/2c independent
|
||||
Phase 3 (op-walk + IR hygiene) — removes the largest single duplication tax
|
||||
Phase 4 (config + caching) — fixes the cache-key footgun; makes boot legible
|
||||
Phase 5 (data/reader/types + index) — finishes the "one home per feature" goal
|
||||
```
|
||||
|
||||
Phases are independent; within a phase the sub-items (2a/2b/2c, etc.) are separate
|
||||
PRs. Highest LLM-friendliness per unit risk: **Phase 1**, **2a (`eval-list` split)**,
|
||||
**3a (op-walk combinator)**, and **5d (seed↔overlay index)**.
|
||||
|
||||
Each PR: one concern, full gate green, no behavior change (Phase 0 deletions carry
|
||||
a regression row).
|
||||
|
|
@ -1,40 +1,32 @@
|
|||
# Building and dependencies
|
||||
|
||||
How to build Jolt from source and how to pull Clojure libraries into a project.
|
||||
How to run Jolt from source and how to pull Clojure libraries into a project.
|
||||
|
||||
## Building
|
||||
## Running
|
||||
|
||||
```bash
|
||||
git clone https://github.com/jolt-lang/jolt.git
|
||||
cd jolt
|
||||
git submodule update --init # vendor/sci (used by the SCI bootstrap tests)
|
||||
jpm build
|
||||
bin/joltc -e '(println "hello")'
|
||||
```
|
||||
|
||||
This produces `build/jolt` — one binary that is both the runtime (REPL,
|
||||
file/expr runner, nREPL server) and the dependency front-end (`deps.edn`
|
||||
resolution, see below). The whole `.clj` standard library
|
||||
(`clojure.string`/`set`/`walk`/`edn`/`zip`, `jolt.http`/`interop`/`shell`/
|
||||
`nrepl`) is baked in at build time, so it loads from any directory — the artifact
|
||||
is self-contained. (`clojure.core` is built into the runtime in Janet and
|
||||
auto-referred, so it's always available.)
|
||||
There is **no build step**. `bin/joltc` (`host/chez/cli.ss`) loads the
|
||||
checked-in bootstrap seed (`host/chez/seed/{prelude,image}.ss`) plus the spine
|
||||
and compiles+evals on Chez (read → analyze → IR → emit → eval), so a fresh
|
||||
clone runs immediately. The whole `.clj` standard library
|
||||
(`clojure.string`/`set`/`walk`/`edn`/`pprint`/…) and `clojure.core` are part of
|
||||
the overlay, so they're always available.
|
||||
|
||||
The runtime **core** stays deps-agnostic: it only reads source roots from
|
||||
`JOLT_PATH`. Dependency resolution lives in a separate CLI front-end module
|
||||
(`src/jolt/deps.janet`) that the `jolt` entry point calls *before* running your
|
||||
code, and that lazily loads `jpm` (for git fetch + cache) only when it actually
|
||||
resolves. So a run with no `deps.edn` never touches the resolver, and an app
|
||||
baked from its own entry — which imports `jolt/api`, not the CLI — never links
|
||||
it at all. (`build/` also contains a `jolt-deps` shim that just forwards to
|
||||
`jolt` so old scripts keep working; prefer calling `jolt` directly.)
|
||||
`bin/joltc` is both the runtime (REPL, file/expr runner) and the dependency
|
||||
front-end (`deps.edn` resolution, see below). A run with no `deps.edn` never
|
||||
touches the resolver.
|
||||
|
||||
Needs `jpm` and a recent Janet — developed and CI-tested against **1.41**. The
|
||||
futures and core.async layers use Janet's threaded `ev/` channels (`ev/thread`,
|
||||
`ev/thread-chan`), so older Janets may not run the full suite.
|
||||
|
||||
`jpm build` doesn't always notice source changes; run `jpm clean && jpm build`
|
||||
after editing `src/` to be sure the binaries are current. `jpm test` runs against
|
||||
the source directly, so it never goes stale.
|
||||
The bootstrap seed is **checked in**. After changing a seed source — the reader
|
||||
(`host/chez/reader.ss`), the analyzer/IR/backend (`jolt-core/jolt/*.clj`), or the
|
||||
`clojure.core` overlay (`jolt-core/clojure/core/*.clj`) — re-mint the seed with
|
||||
`make remint` (it iterates `host/chez/bootstrap.ss` to a byte-fixpoint), or
|
||||
`make selfhost` fails. Runtime-only `host/chez/*.ss` shims don't need a re-mint.
|
||||
|
||||
## How namespaces are found
|
||||
|
||||
|
|
@ -47,99 +39,74 @@ come from:
|
|||
at runtime;
|
||||
- the `:paths` option to `init` when embedding Jolt as a library.
|
||||
|
||||
If a namespace isn't found on any root, the loader falls back to the stdlib baked
|
||||
into the binary — that's how `clojure.string` and friends resolve when you run
|
||||
the binary outside the source tree.
|
||||
If a namespace isn't found on any root, the loader falls back to the stdlib in
|
||||
the overlay — that's how `clojure.string` and friends resolve when you run
|
||||
outside the source tree.
|
||||
|
||||
So you can point Jolt at a directory of Clojure source with no deps machinery at
|
||||
all:
|
||||
|
||||
```bash
|
||||
JOLT_PATH=/path/to/lib/src build/jolt myfile.clj
|
||||
JOLT_PATH=/path/to/lib/src bin/joltc run myfile.clj
|
||||
```
|
||||
|
||||
## Dependencies via deps.edn
|
||||
|
||||
`jolt` reads a `deps.edn` in the current directory, fetches its dependencies,
|
||||
and puts the resolved source directories on `JOLT_PATH` for the run. A `deps.edn`
|
||||
in the working dir is **auto-resolved** for the runnable commands (`repl`, `-m`,
|
||||
`-e`, `nrepl-server`, a `FILE`); the explicit subcommands below also work
|
||||
anywhere:
|
||||
`bin/joltc` reads a `deps.edn` in the current directory, fetches its
|
||||
dependencies, and prepends the resolved source directories to the source roots
|
||||
for the run. The CLI commands (`jolt.deps` + `jolt.main`):
|
||||
|
||||
```bash
|
||||
jolt -M:test [args] # run the :test alias's :main-opts (the usual entry)
|
||||
jolt -A:dev repl # run a command with the :dev alias's extra paths/deps
|
||||
jolt run FILE [args] # resolve, then run FILE
|
||||
jolt path # print the resolved roots (':'-joined)
|
||||
jolt tasks # list :tasks from deps.edn
|
||||
jolt task NAME [args] # run a task
|
||||
bin/joltc run -m NS [args] # resolve deps.edn, load NS, call its -main
|
||||
bin/joltc run FILE # resolve deps.edn, load a Clojure file
|
||||
bin/joltc -M:alias [args] # run the alias's :main-opts
|
||||
bin/joltc -A:alias [args] # add the alias's paths/deps, then run the rest
|
||||
bin/joltc repl # start a line REPL
|
||||
bin/joltc path # print the resolved source roots (':'-joined)
|
||||
bin/joltc <task> # run a deps.edn :tasks entry
|
||||
```
|
||||
|
||||
So, for example, to start an nREPL server that loads a project and its deps,
|
||||
add `:aliases {:nrepl {:main-opts ["nrepl-server"]}}` to `deps.edn` and run
|
||||
`jolt -M:nrepl` (or just `jolt nrepl-server`, which auto-resolves the `deps.edn`).
|
||||
|
||||
Example `deps.edn`:
|
||||
|
||||
```clojure
|
||||
{:paths ["src"]
|
||||
:deps {weavejester/medley {:git/url "https://github.com/weavejester/medley"
|
||||
:git/tag "1.0.0"}
|
||||
:git/sha "<full-sha>"}
|
||||
my/helpers {:local/root "../helpers"}}}
|
||||
```
|
||||
|
||||
```bash
|
||||
jolt run -m myapp.main
|
||||
bin/joltc run -m myapp.main
|
||||
```
|
||||
|
||||
### What's supported
|
||||
|
||||
- **git deps** — `{:git/url … :git/tag …}` or `{:git/url … :git/sha …}` (use a
|
||||
full SHA; `git fetch` can't resolve a short one). Transitive deps from each
|
||||
dependency's own `deps.edn` are resolved too.
|
||||
- **git deps** — `{:git/url … :git/sha …}` (use a full SHA; `git fetch` can't
|
||||
resolve a short one), with an optional `:deps/root` for a subdirectory.
|
||||
Transitive deps from each dependency's own `deps.edn` are resolved too.
|
||||
- **local deps** — `{:local/root "../path"}`.
|
||||
- The project's own `:paths` (default `["src"]`) are included.
|
||||
- **aliases** — `:aliases {:dev {:extra-paths ["dev"] :extra-deps {…}
|
||||
:main-opts ["-e" "…"]}}`, selected with `-A:dev` (or several: `-A:dev:test`).
|
||||
`:extra-paths`/`:extra-deps` accumulate across selected aliases;
|
||||
`:main-opts` is last-wins and runs via `-M:alias`.
|
||||
- **user config** — a `deps.edn` under `$JOLT_CONFIG` (else
|
||||
`$XDG_CONFIG_HOME/jolt`, else `~/.jolt`) merges beneath the project's, the
|
||||
way `~/.clojure/deps.edn` does: `:deps`/`:aliases`/`:tasks` merge per key
|
||||
with the project winning.
|
||||
- **tasks** — `:tasks {clean "rm -rf target" test {:doc "run the suite"
|
||||
:main-opts ["-e" "(run-tests)"]}}`. A string task is a shell command; a map
|
||||
task runs jolt with its `:main-opts`. `jolt tasks` lists, `jolt task NAME`
|
||||
runs.
|
||||
- **tasks** — `:tasks {clean "rm -rf target" test {:main-opts ["-m" "…"]}}`.
|
||||
A string task is a shell command; a map task runs jolt with its `:main-opts`.
|
||||
Run one with `bin/joltc <taskname>`.
|
||||
|
||||
Conflicts resolve the tools.deps way: resolution is breadth-first, so a
|
||||
top-level coordinate always beats a transitive one for the same lib, and
|
||||
conflicting coordinates print a warning naming both.
|
||||
Resolution is breadth-first, so a top-level coordinate always beats a transitive
|
||||
one for the same lib.
|
||||
|
||||
Git clones land in a global, sha-immutable cache shared across projects —
|
||||
`$JOLT_GITLIBS`, else `<config-dir>/gitlibs` (the `~/.gitlibs` model). The
|
||||
resolved roots are cached per project in `.cpcache/jolt-deps.jdn`, keyed on a
|
||||
hash of the project `deps.edn` + the user `deps.edn` + the selected aliases.
|
||||
`$JOLT_GITLIBS`, else `~/.jolt/gitlibs`.
|
||||
|
||||
### What's not
|
||||
|
||||
- **No Maven.** `:mvn/version` deps are ignored — git and local only.
|
||||
- **No Maven.** `:mvn/version` deps are skipped with a warning — git and local
|
||||
only.
|
||||
- **Pure `clj`/`cljc` only.** A library that needs the JVM (Java interop, host
|
||||
classes) or a `clojure.core` feature Jolt doesn't implement will fail to load
|
||||
or fail at a call. Coverage is per-function: a namespace can load with most
|
||||
functions working and a few not.
|
||||
|
||||
### Bundling into one file
|
||||
|
||||
`jolt uberscript OUT.clj -m NS` bundles `NS` and every namespace it requires —
|
||||
your code plus its dependencies — into a single `.clj` in dependency order,
|
||||
ending with a call to `NS/-main`. Run it from a project dir and the `deps.edn`
|
||||
is resolved first, so dependency namespaces are on the path to bundle. The
|
||||
result runs on a plain `jolt` with no `JOLT_PATH`, no deps fetched, and no jpm:
|
||||
|
||||
```bash
|
||||
jolt uberscript app.clj -m myapp.main
|
||||
jolt app.clj arg1 arg2
|
||||
```
|
||||
|
||||
See [`tools-deps.md`](tools-deps.md) for the design rationale.
|
||||
|
|
|
|||
|
|
@ -1,198 +0,0 @@
|
|||
# Foundational Runtime Epic — Handoff
|
||||
|
||||
**Epic:** jolt-5vsp · **Predecessor:** jolt-ffn (targeted specialization — concluded)
|
||||
**Date:** 2026-06-16
|
||||
|
||||
This is a cold-start handoff. Read it top to bottom before touching code. Its
|
||||
whole point is to keep the fresh session from re-running the experiments that
|
||||
already came back flat, and to start from the one measurement that actually
|
||||
tells us where to invest.
|
||||
|
||||
## Why this epic exists
|
||||
|
||||
The targeted-specialization epic (jolt-ffn) tried to close jolt's constant-factor
|
||||
gap vs JVM Clojure with per-form compiler passes. Three independent attempts all
|
||||
came back flat:
|
||||
|
||||
| Attempt | Bead | Result |
|
||||
|---|---|---|
|
||||
| Record field-read guard removal (bare field reads) | jolt-3ko | ~3% on dispatch (shipped #141 — kept for correctness, not speed) |
|
||||
| Protocol inline cache (runtime, per-method) | jolt-ez5h | ~0% — the per-dispatch gen-check exactly cancels the find-protocol-method saving; `find` was never the bottleneck |
|
||||
| Record-ctor descriptor-baking (fewer allocs/record) | jolt-p7fo | flat on binary-trees + broke the gate; reverted |
|
||||
|
||||
The conclusion: **the gap is structural to jolt-on-Janet, not a missing
|
||||
optimization.** Targeted passes remove only the cheap parts; the structural floor
|
||||
remains.
|
||||
|
||||
## The scorecard (jolt / JVM Clojure)
|
||||
|
||||
Regenerate any time with `JVM=1 bench/run.sh` (the absolute-reference mode).
|
||||
|
||||
| Axis | Bench | jolt/JVM |
|
||||
|---|---|---|
|
||||
| Pure float compute | `mandelbrot` | **~15× ← THE FLOOR** |
|
||||
| Persistent collections (HAMT) | `collections` | ~28× |
|
||||
| Recursion (call + arith) | `fib` | ~37× |
|
||||
| Megamorphic dispatch | `dispatch` | ~76× |
|
||||
| Monomorphic dispatch | `mono-dispatch` | ~109× |
|
||||
| Allocation / GC | `binary-trees` | ~314× (≈150× at depth 10) |
|
||||
|
||||
`mandelbrot` is the floor: pure tight arithmetic loops — no dispatch, no
|
||||
allocation, no collections — and native arith already fires (jolt-3pl). So ~15×
|
||||
is what jolt's *execution substrate* costs on the simplest possible workload.
|
||||
Every other axis adds structural overhead **on top** of that floor.
|
||||
|
||||
**Machine caveat:** the dev machine swaps heavily (~13 GB). Alloc-heavy benches
|
||||
(`binary-trees`, `collections`) inflate badly; light benches (`mandelbrot`,
|
||||
`fib`, `dispatch`) are trustworthy. Get absolute alloc numbers on a clean machine.
|
||||
|
||||
## The four structural walls
|
||||
|
||||
1. **Bytecode-VM execution.** jolt's backend emits **Janet** (a register-bytecode
|
||||
VM) and runs it on the Janet interpreter loop — no JIT, no native code. Every
|
||||
op is bytecode dispatch. This is the `mandelbrot` 15× floor.
|
||||
2. **Mark-sweep GC.** Janet's GC scans all live objects each cycle (no
|
||||
generations). Live-data + alloc-heavy workloads (`binary-trees` retains the
|
||||
tree) pay O(live) per GC. The JVM's generational GC makes young-object churn
|
||||
nearly free.
|
||||
3. **Indirect calls.** Protocol dispatch and fn calls go through indirection
|
||||
(closures, the protocol registry). The JVM inlines/devirtualizes. jolt's
|
||||
devirt (jolt-41m) only fires on *statically*-proven monomorphic sites;
|
||||
`reduce`/`mapv` over a collection doesn't give that proof, so the common
|
||||
runtime-monomorphic case pays full dispatch (that's why `mono-dispatch` is
|
||||
*worse* than megamorphic — the JVM inline-caches it to near-free, jolt doesn't).
|
||||
4. **Boxed / generic representations.** Records are tuples `[descriptor field…]`;
|
||||
field access goes through a tag guard unless the type is proven. Generic ops
|
||||
carry runtime type checks. (Open question: are Janet *numbers* boxed? Verify
|
||||
in the spike — it decides whether unboxing is a lever or already done.)
|
||||
|
||||
## Foundational levers (ranked)
|
||||
|
||||
1. **Native codegen — emit C, not Janet bytecode.** The Stalin approach. Compile
|
||||
jolt IR → C → machine code via the system compiler. The *only* lever that
|
||||
moves the 15× compute floor; could approach C/JVM speed on compute-bound code.
|
||||
Massive (a new backend). Plausible incremental shape: a jolt-IR→C compiler for
|
||||
*hot* fns with a fallback to the existing bytecode path for unsupported forms —
|
||||
mirroring today's interpret/compile hybrid. Needs to confirm Janet's C-API /
|
||||
native-module story can be targeted incrementally.
|
||||
2. **Structural GC-pressure reduction.** Value-type small records (avoid heap),
|
||||
transient/editable-node hot paths (RFC 0003 future work — pvec/phm/sorted are
|
||||
now tries/HAMT/RB, so O(1) `transient`/`persistent!` via editable nodes is
|
||||
open). Helps the alloc-bound axes (`binary-trees`, `collections`). Does **not**
|
||||
touch the compute floor.
|
||||
3. **Deeper devirt + body inline.** Propagate element/return types so devirt
|
||||
fires on runtime-monomorphic collections, then inline the method body
|
||||
(jolt-4x9 element types + jolt-t6r). Helps dispatch. Bounded ceiling (still
|
||||
bytecode underneath).
|
||||
|
||||
## STATUS (2026-06-16) — lever 1 (native codegen) built and working
|
||||
|
||||
The spike ran and lever 1 is now implemented. Full writeups:
|
||||
`docs/foundational-runtime-spike-results.md` (floor localization) and
|
||||
`docs/foundational-runtime-lever1-native-codegen.md` (native codegen).
|
||||
|
||||
Done (all merged to main, PRs #143–#148):
|
||||
- **Floor localized:** the 15.4× decomposes into a **Janet-VM floor ≈10.8× JVM**
|
||||
(only native codegen moves it) + a **jolt loop-lowering ≈1.43×** (cheap backend
|
||||
win, bead **jolt-v28u**). Janet numbers are already unboxed (not a lever).
|
||||
- **Native codegen (jolt-ihdp, CLOSED):** `src/jolt/cgen.janet` translates
|
||||
numeric-leaf fns (numeric in/out, native-op arithmetic + loop/recur/if/let/do)
|
||||
to C. Wired into the backend `:def` emit under **`JOLT_CGEN=1`** (opt-in). The
|
||||
`.so` is content-addressed + cached. **mandelbrot 224ms → 12.4ms (~18×)**,
|
||||
beats JVM. Leaf-first falls out free (callers stay bytecode, call native fn).
|
||||
- **Build-time AOT (jolt-a7ds, partial):** `:cgen-collect?` records leaf fns at
|
||||
build, `aot-build` compiles them into one `.so` + manifest; `:cgen-prebuilt` +
|
||||
`load-aot` install them at deploy with **no cc** (proven with cc off PATH).
|
||||
|
||||
Open work under epic jolt-5vsp:
|
||||
- **jolt-a7ds** — fuse the prebuilt `.so` + manifest into the `jpm` exe for a
|
||||
literal single binary (+ a `jolt cgen-build -m app` CLI). The heaviest piece;
|
||||
into jpm executable-build, not the compiler.
|
||||
- **jolt-v28u** — `while`-loop lowering for tail `recur` (cheap ~30%, independent
|
||||
of cgen; helps ALL loops, not just cgen candidates).
|
||||
- **jolt-l1l4** — widen cgen numeric grammar (mod/rem/bit-ops/min/max, mixed fns).
|
||||
- **jolt-qx70** — hot-fn auto-detection (drop the global `JOLT_CGEN` knob).
|
||||
- Lever 2 (GC-pressure) and lever 3 (deeper devirt) — untouched; see below.
|
||||
|
||||
The original spike instructions are preserved below for context.
|
||||
|
||||
**Localize the 15× floor.** Build three `mandelbrot` implementations and compare:
|
||||
|
||||
- **jolt-compiled** `mandelbrot` (already in `bench/mandelbrot.clj`),
|
||||
- **hand-written Janet** `mandelbrot` (the same nested loop, idiomatic Janet —
|
||||
write it directly, no jolt),
|
||||
- **JVM Clojure** `mandelbrot`.
|
||||
|
||||
Two ratios fall out:
|
||||
|
||||
- **jolt-emitted-Janet vs hand-Janet** → how much overhead jolt's *backend* adds
|
||||
over optimal Janet. To see jolt's emitted Janet, use the backend emit path
|
||||
(`backend/emit-ir` on the analyzed `run`/`count-point` fns) — note `:arities`
|
||||
etc. are jolt pvecs, so introspection is awkward; easier to read the emitted
|
||||
Janet via the compile path or just A/B the timings.
|
||||
- **hand-Janet vs JVM** → the Janet VM's own floor.
|
||||
|
||||
Decision:
|
||||
|
||||
- If **hand-Janet ≈ jolt** and hand-Janet is ~15× JVM → the floor is **Janet's
|
||||
bytecode VM**. Native codegen (lever 1) is the only fix. Commit to the spike of
|
||||
a jolt-IR→C path for one hot fn and measure.
|
||||
- If **jolt ≫ hand-Janet** → jolt's backend emits suboptimal Janet; there's
|
||||
headroom in the **backend** (cheaper, no new runtime). Find what it emits that
|
||||
hand-Janet doesn't.
|
||||
|
||||
Also measure the **GC share** on `binary-trees` (Janet GC stats around the run —
|
||||
`(gccollect)` / `gcinterval`, or count allocations) to size lever 2 honestly.
|
||||
|
||||
## Key files / mechanisms
|
||||
|
||||
- **Backend (IR → Janet emit):** `src/jolt/backend.janet`. `native-ops` (~L322)
|
||||
emits native Janet arith; `emit-ir` (~L674) runs passes then emits. A native-C
|
||||
backend would branch here.
|
||||
- **Passes / inference:** `jolt-core/jolt/passes.clj` (`run-passes`),
|
||||
`jolt-core/jolt/passes/types.clj` (inference; the `:fn` branch ~L527 now seeds
|
||||
^Record param hints — #141), `jolt-core/jolt/passes/inline.clj`
|
||||
(scalar-replace, `ctor-shape`).
|
||||
- **Record representation:** `src/jolt/types_protocols.janet` — `make-record`
|
||||
(~L145, the ~5-alloc/record path), `record-shape-for` (~L139, rebuilds its
|
||||
cache key every call), `record-tag`. Records are tuples `[descriptor field…]`.
|
||||
- **Dispatch + ctors:** `src/jolt/eval_runtime.janet` —
|
||||
`protocol-dispatch-impl` (~L62), `make-deftype-ctor-impl` (~L382).
|
||||
- **Config knobs:** `src/jolt/config.janet` — `JOLT_DIRECT_LINK`,
|
||||
`JOLT_WHOLE_PROGRAM`, `JOLT_OPTIMIZE`, the `ctx-shaping-env-vars` list (any new
|
||||
ctx-shaping env var MUST be added there and to `image-cache-path`).
|
||||
- **Self-hosting design:** `docs/self-hosting-compiler.md` (the kernel/value-layer
|
||||
boundary), `docs/rfc/0003-transients.md` (editable-node future work).
|
||||
|
||||
## How to build, run, measure
|
||||
|
||||
```sh
|
||||
jpm build # build/jolt (ctx baked, ~20ms startup); from-source is ~8s cold
|
||||
export PATH="$PWD/build:$PATH"
|
||||
bench/run.sh # jolt only, WP on
|
||||
JVM=1 bench/run.sh # jolt vs JVM scorecard (needs `clojure` on PATH)
|
||||
bench/run.sh mandelbrot 400 # one bench, custom size
|
||||
JOLT_WHOLE_PROGRAM=0 bench/run.sh # measure what WP buys
|
||||
```
|
||||
|
||||
Gate: `jpm build; janet run-tests.janet` (parallel, ~100s; `JOLT_TEST_JOBS`
|
||||
overrides). Bench memory hygiene (`bd memories bench-isolation-gotcha`): never run
|
||||
a perf matrix while other CPU work runs — it starves later configs and produces
|
||||
bogus numbers. Sandwich A/B/A.
|
||||
|
||||
## What NOT to repeat (already flat — see beads for detail)
|
||||
|
||||
- Runtime protocol inline cache (jolt-ez5h): gen-check cancels the saving.
|
||||
- Field-read guard removal as a *speed* play (jolt-3ko): ~3%; machinery dominates.
|
||||
(The #141 change is kept for correctness + the `with-meta`-on-symbols fix.)
|
||||
- `make-record` descriptor-baking (jolt-p7fo): flat — `binary-trees` is dominated
|
||||
by the live retained tree + GC, not the short-lived intermediate allocs.
|
||||
|
||||
## Open questions for the spike
|
||||
|
||||
- Are Janet numbers boxed? (Lever or already done.)
|
||||
- Does Janet expose a native-module / C-codegen path jolt can target incrementally
|
||||
(hot fns → C, rest → bytecode)?
|
||||
- What fraction of `binary-trees` is GC vs execution?
|
||||
- Is there a cheaper record representation (Janet struct vs tuple-with-descriptor)
|
||||
that lowers field-read + alloc cost without a new backend?
|
||||
|
|
@ -1,173 +0,0 @@
|
|||
# Lever 1 — Native codegen (jolt-IR → C): feasibility spike
|
||||
|
||||
**Epic:** jolt-5vsp · **Date:** 2026-06-16
|
||||
**Predecessor:** the localization spike (`docs/foundational-runtime-spike-results.md`)
|
||||
showed the 15.4× mandelbrot floor is ~70% Janet-VM floor (only native codegen
|
||||
moves it) + ~30% loop-lowering (cheap backend fix, jolt-v28u). This spike probes
|
||||
**lever 1's ceiling and the incremental hot-fn-in-C strategy** before committing
|
||||
to a backend.
|
||||
|
||||
All legs return the identical result (3288753 at n=200). Numbers are means of 3
|
||||
after warmup; the dev machine swaps, so treat these as orders-of-magnitude (the
|
||||
≈ vs JVM call is robust; ±2ms is noise).
|
||||
|
||||
## The native-C ceiling — it beats JVM
|
||||
|
||||
Native mandelbrot built as a Janet native module (`spike/native/mandel.c`):
|
||||
|
||||
| Leg | mean | vs jolt (219ms) | vs JVM (14.2ms) |
|
||||
|---|---|---|---|
|
||||
| **native-C whole run** (pure C, no Janet in loop) | **~10–12 ms** | **~18–22× faster** | **faster than JVM** |
|
||||
| Janet loop → C hot-fn (forward crossing) | ~11–13 ms | ~18× faster | ≈ JVM |
|
||||
| C loop → `janet_call` bytecode (reverse crossing) | ~152 ms | ~no better | ~11× slower |
|
||||
| *(reference)* jolt-compiled | 219 ms | — | 15.4× |
|
||||
| *(reference)* JVM Clojure | 14.2 ms | — | 1.0× |
|
||||
|
||||
**Verdict: lever 1 is validated and its ceiling is excellent.** Compiling the hot
|
||||
compute path to C makes it ~18–22× faster than today's jolt and *edges out JVM
|
||||
Clojure* — native code has no VM-dispatch floor at all. This is the only lever
|
||||
that touches the ~10.8× Janet-VM floor, and the payoff is the full gap.
|
||||
|
||||
## The crossing-direction rule (the key strategic finding)
|
||||
|
||||
The boundary cost is wildly asymmetric:
|
||||
|
||||
- **Forward (bytecode → C): nearly free.** A Janet bytecode loop calling a C
|
||||
hot-fn n² (=40 000) times runs at ~11–13 ms — within ~15% of pure C. So you can
|
||||
compile just the *inner* hot fn to C and capture ~95% of the win while the outer
|
||||
loop stays bytecode. **Incremental adoption works.**
|
||||
- **Reverse (C → `janet_call` → bytecode): ~3.5 µs/call.** A C fn calling a
|
||||
bytecode helper per iteration runs at ~152 ms — *no better than jolt today*. The
|
||||
`janet_call` cost (entering the VM/fiber per call) dominates.
|
||||
|
||||
**Design constraint → compile leaf-first / whole-hot-cluster.** A fn is a
|
||||
profitable C-compilation candidate only if its hot path calls **nothing that stays
|
||||
in bytecode** — only primitives or other C-compiled fns. Cross the boundary only at
|
||||
*cold* edges. For mandelbrot, `count-point` is a leaf (calls only arithmetic
|
||||
primitives) → the ideal first target; compiling it alone captures the win
|
||||
(forward crossing), but a half-compiled hybrid that `janet_call`s back per
|
||||
iteration buys nothing.
|
||||
|
||||
## The dynamic-compile path works (no jpm needed)
|
||||
|
||||
jolt's compile model is dynamic (analyze → IR → Janet → eval at runtime). Native
|
||||
codegen fits the same shape: a `.so` compiled with a **plain `cc` invocation**
|
||||
(no jpm/project.janet) loads at runtime via `require` and runs at full native
|
||||
speed (verified: `run-c(200)` correct, 13.5 ms cold).
|
||||
|
||||
```
|
||||
cc -shared -fPIC -O2 -I/opt/homebrew/include -undefined dynamic_lookup \
|
||||
mandel.c -o mandel.so # macOS; Linux drops -undefined dynamic_lookup
|
||||
(require "path/to/mandel") # loads at runtime, cfunctions callable
|
||||
```
|
||||
|
||||
So the native tier mirrors today's interpret/compile hybrid: emit C for a hot
|
||||
fn → shell to `cc` → `require` the `.so` → bytecode callers call into it via the
|
||||
(cheap, forward) native-module call path. Caching keyed by fn-source-hash mirrors
|
||||
the existing ctx image cache.
|
||||
|
||||
## Toolchain confirmed (this machine)
|
||||
|
||||
- `janet.h` present (`/opt/homebrew/include/janet.h`, Janet 1.41.2).
|
||||
- `jpm declare-native` builds a `.so` cleanly.
|
||||
- Direct `cc` (no jpm) builds a loadable `.so`.
|
||||
- C API used: `janet_getnumber/getinteger`, `janet_wrap_number`, `janet_fixarity`,
|
||||
`janet_getfunction`, `janet_call`, `janet_cfuns`, `JANET_MODULE_ENTRY`.
|
||||
|
||||
## Status: wired into the compile path (JOLT_CGEN, opt-in)
|
||||
|
||||
`src/jolt/cgen.janet` (IR→C translator) is wired into the backend's `:def` emit
|
||||
via `cgen-root`, gated behind **`JOLT_CGEN=1`** (off by default; needs
|
||||
direct-linking). When on, a plain defn of a numeric-leaf fn is compiled to C at
|
||||
def time and the cfunction installed as the var root — so direct-linked callers
|
||||
embed native code. The fn is NOT inline-stashed when cgen fires (callers must
|
||||
call the C fn, not inline the bytecode body). `^:redef`/`^:dynamic` defns stay
|
||||
bytecode.
|
||||
|
||||
The leaf-first rule emerges for free: `run` calls `count-point` (a user var, not
|
||||
a native-op), so `run` isn't a numeric leaf and stays bytecode — calling the
|
||||
native `count-point` over the cheap forward crossing.
|
||||
|
||||
**Measured end-to-end (`jolt -m mandelbrot 200`): 224 ms → 12.4 ms, ~18×**, with
|
||||
the correct result — matching the spike's native-C ceiling. The default gate
|
||||
(cgen off) is unchanged. Tests: `test/integration/cgen-pipeline-test.janet`.
|
||||
|
||||
Known limitation: building *core* with `JOLT_CGEN=1` would try to cgen core
|
||||
numeric-leaf fns into the cached ctx image, where embedded cfunctions may not
|
||||
serialize — keep cgen for app/user code until image-cache interaction is handled.
|
||||
|
||||
## Build-time AOT: native speed without a toolchain on the target (jolt-a7ds)
|
||||
|
||||
The JIT path above runs `cc` at runtime. The AOT path moves compilation to build
|
||||
time so the deploy target needs no `cc`/`janet.h`:
|
||||
|
||||
- **Build phase** (`:cgen-collect?`, needs cc): loading the app records every
|
||||
numeric-leaf defn's IR; `cgen/aot-build` compiles them all into ONE native
|
||||
module (`gen-c-module`) and `write-manifest` persists `{sopath, [{ns name sym}]}`.
|
||||
- **Deploy phase** (`:cgen-prebuilt`, NO cc): `cgen/load-aot` loads the prebuilt
|
||||
`.so` (via the `native` builtin — no compiler) into a qname→cfunction map; the
|
||||
backend's `:def` hook installs each as the var root with the same timing as the
|
||||
JIT path, so callers direct-link to native code.
|
||||
|
||||
**Proven** (`spike/native/aot-demo.janet`, two processes): build with cc, then
|
||||
deploy with `cc` removed from PATH → `count-point` is still native, mandelbrot =
|
||||
3288753 at **12.4 ms** (full 18×). Test: `test/integration/cgen-aot-test.janet`.
|
||||
|
||||
This removes the runtime-toolchain dependency — the core of the deployment story.
|
||||
|
||||
### The literal single binary (`jolt cgen-build`, done)
|
||||
|
||||
`src/jolt/cgen_build.janet` + the `jolt cgen-build -m NS -o OUT` CLI fuse the
|
||||
native code into the executable, so an app ships as ONE static file — no sidecar
|
||||
`.so`, no toolchain to run. The driver:
|
||||
|
||||
1. loads the app with `:cgen-collect?` to get its numeric-leaf fns + the source
|
||||
files loaded (the uberscript-style bundle);
|
||||
2. emits `cg.c` (one native module of those fns via `cgen/gen-c-module`) + a
|
||||
positional manifest;
|
||||
3. stages a build dir: `src`/`jolt-core` symlinks into the jolt tree, `cg.c`, the
|
||||
app bundle, and an entry that bakes the runtime, installs the native fns as var
|
||||
roots (`:cgen-prebuilt`), and runs `-main`;
|
||||
4. runs `jpm build` there — `declare-native` builds `cg.a`, `declare-executable`
|
||||
static-links it into the final exe (jpm's `create-executable` marshals the
|
||||
module's cfunctions and calls its static entry at startup).
|
||||
|
||||
Build needs `cc` + `jpm`; the result needs neither. Proven end-to-end:
|
||||
`test/integration/cgen-build-test.janet` builds the mandelbrot fixture, runs it
|
||||
from a clean dir with no `src/` and no `cg.so`, and gets the right total at native
|
||||
speed (the count-point leaf is the linked cfunction).
|
||||
|
||||
Build mechanics that bit (codified in `cgen_build.janet`): `stdlib_embed` slurps
|
||||
`.clj` relative to cwd, so the build runs in a dir mirroring the repo layout (the
|
||||
symlinks); jpm hardcodes `./project.janet` and sets `syspath = modpath`; the
|
||||
executable's dofile imports `cg` and static-links `cg.a`, neither ordered nor
|
||||
release-built by default, so the deps are wired explicitly; cleanup must `lstat`
|
||||
(never follow the tree symlinks). The inner build runs `--workers=1` so it doesn't
|
||||
saturate cores inside the parallel test gate.
|
||||
|
||||
Open follow-ups (filed): widen the cgen grammar (jolt-l1l4) so more of an app's
|
||||
hot fns qualify; hot-fn auto-detection (jolt-qx70) to drop the manual collect;
|
||||
DCE on the bundled source (the uberscript path already does it).
|
||||
|
||||
## Open questions for the implementation (next beads)
|
||||
|
||||
1. **IR→C for the numeric subset.** Translate jolt IR → C for proven-double
|
||||
arithmetic + tail `loop`/`recur` (count-point's shape). The native-arith type
|
||||
proof (jolt-3pl) that already gates native *Janet* arith is the same proof that
|
||||
gates C unboxing — reuse it. Start narrow: unbox doubles at entry, primitive
|
||||
ops inline, rebox at exit; bail to bytecode for any unsupported form.
|
||||
2. **Boundary policy.** Non-primitive args stay Janet values (no unbox);
|
||||
per-iteration calls allowed only to other C-compiled fns. Encode the
|
||||
leaf-first/cluster rule as the compile-candidate predicate.
|
||||
3. **Trigger + cache.** AOT at build/first-run vs lazy JIT on hot fns; `.so`
|
||||
cache keyed by source hash + flags (add to `ctx-shaping-env-vars` /
|
||||
image-cache machinery if it becomes a ctx knob).
|
||||
4. **Coverage.** Closures/upvalues, multi-arity, `recur` across the C boundary,
|
||||
portability of `cc` flags per platform.
|
||||
|
||||
## Artifacts (`spike/native/`)
|
||||
|
||||
- `mandel.c` — native mandelbrot: `run-c` (pure C), `count-point-c` (leaf cfn),
|
||||
`run-callback` (C loop → `janet_call` back, the reverse-crossing probe)
|
||||
- `project.janet` — `declare-native` build
|
||||
- `bench-native.janet` — the three-leg benchmark + harness
|
||||
|
|
@ -1,92 +0,0 @@
|
|||
# Foundational Runtime Spike — Results (the 15× floor, localized)
|
||||
|
||||
**Epic:** jolt-5vsp · **Date:** 2026-06-16
|
||||
**Spike:** the START HERE section of `docs/foundational-runtime-handoff.md` —
|
||||
jolt vs hand-written-Janet vs JVM `mandelbrot`, to localize the ~15× compute
|
||||
floor before committing to native codegen (lever 1) vs a backend fix.
|
||||
|
||||
## Setup
|
||||
|
||||
Three implementations of the same nested mandelbrot loop, all returning the
|
||||
identical result (3288753 at n=200, confirming correctness across all legs):
|
||||
|
||||
- **jolt-compiled** — `bench/mandelbrot.clj` (`jolt -m mandelbrot 200`, WP + direct-link on)
|
||||
- **hand-Janet (`while`)** — `bench/mandelbrot-hand.janet` (idiomatic Janet: `while` + `var`/`set`)
|
||||
- **JVM Clojure** — `bench/mandelbrot.clj` on the JVM
|
||||
|
||||
Plus a diagnostic fourth leg:
|
||||
|
||||
- **hand-Janet (recursive)** — `bench/mandelbrot-hand-rec.janet`: hand Janet that
|
||||
*mirrors jolt's loop lowering* (self-recursive local closure called per
|
||||
iteration), to test whether the loop lowering alone explains jolt's overhead.
|
||||
|
||||
Numbers are stable and sandwiched (A/B/A/B); machine noise < 1%.
|
||||
|
||||
## The numbers (n=200, mean of 3, after warmup)
|
||||
|
||||
| Leg | mean | × JVM |
|
||||
|---|---|---|
|
||||
| JVM Clojure | 14.2 ms | 1.0× |
|
||||
| **hand-Janet (`while`)** | **153.4 ms** | **10.8×** |
|
||||
| hand-Janet (recursive, mirrors jolt) | 215.3 ms | 15.2× |
|
||||
| **jolt-compiled** | **219.0 ms** | **15.4×** |
|
||||
|
||||
## What this localizes
|
||||
|
||||
The 15.4× floor **decomposes into two distinct layers**:
|
||||
|
||||
1. **Janet VM floor ≈ 10.8× JVM** (70% of the gap). Optimal hand-written Janet —
|
||||
pure `while` loop over unboxed doubles, zero allocation — is still ~11× slower
|
||||
than JVM Clojure. This is the cost of the Janet bytecode VM itself (no JIT, no
|
||||
native code). **Only native codegen (lever 1) can touch this.** It is the
|
||||
dominant share and validates lever 1 as the big structural lever.
|
||||
|
||||
2. **jolt backend loop-lowering ≈ 1.43× on top** (the remaining 30%). jolt is
|
||||
`219 / 153 = 1.43×` slower than optimal Janet. The diagnostic leg pins this
|
||||
*entirely* to one cause: jolt lowers every `loop`/`recur` to a **self-recursive
|
||||
local closure called once per iteration**, not a `while` loop. Hand-Janet
|
||||
written that same way (recursive leg) lands at **215 ms ≈ jolt's 219 ms** —
|
||||
so the recursive-closure lowering accounts for essentially all of jolt's
|
||||
backend overhead on pure-compute code.
|
||||
|
||||
See the emitted Janet (`bench/dump-mandelbrot-emit.janet`): `emit-loop`
|
||||
(`src/jolt/backend.janet:210`) produces
|
||||
`(do (var L nil) (set L (fn (i zr zi) … (L (+ i 1) …))) (let (…) (L …)))`
|
||||
and `emit-recur` (`:228`) produces the per-iteration call `(L …)`. It relies
|
||||
on Janet TCO for stack safety, but each iteration still pays a function
|
||||
invocation (frame setup + arg bind) that a `while` loop skips.
|
||||
|
||||
## Decision
|
||||
|
||||
The handoff posed it as binary (Janet-VM floor *or* backend headroom). It is
|
||||
**both**, now sized:
|
||||
|
||||
- **Native codegen (lever 1) is the only thing that moves the dominant ~70%.**
|
||||
Confirmed as the big lever. Pursue the incremental jolt-IR→C spike for one hot
|
||||
fn next, per the handoff.
|
||||
- **A cheap, localized ~30% win sits in the backend**, independent of any new
|
||||
runtime: lower tail-position `loop`/`recur` with scalar bindings to a Janet
|
||||
`while` + `var`/`set` instead of a recursive closure. Closes the 1.43×, taking
|
||||
`mandelbrot` from 15.4× → ~10.8× JVM. Filed separately (see epic children).
|
||||
|
||||
## Open questions answered
|
||||
|
||||
- **Are Janet numbers boxed?** No — already unboxed. The `while` leg does pure
|
||||
double arithmetic at a steady 153 ms with no allocation and no GC stutter, and
|
||||
matches the other legs bit-for-bit. Janet's `number` is an immediate IEEE
|
||||
double (stored inline in the Janet value, not heap-allocated). **Unboxing is
|
||||
not a lever; it's done.**
|
||||
- **GC share of `binary-trees`** — not measured here (the dev machine swaps
|
||||
heavily, which distorts alloc-heavy benches; the handoff flags this). Size
|
||||
lever 2 on a clean machine. The `mandelbrot` legs are alloc-free so are
|
||||
unaffected and trustworthy.
|
||||
- **Janet native-module / incremental C path** — not yet confirmed; this is the
|
||||
gating question for the lever-1 spike (hot fns → C, rest → bytecode).
|
||||
|
||||
## Artifacts (kept in `bench/`)
|
||||
|
||||
- `mandelbrot-hand.janet` — optimal `while` Janet (the Janet VM floor reference)
|
||||
- `mandelbrot-hand-rec.janet` — recursive-closure Janet (the loop-lowering diagnostic)
|
||||
- `dump-mandelbrot-emit.janet` — dumps the Janet jolt emits for the hot fns
|
||||
|
||||
The bench harness (`bench/run.sh`) ignores these (it iterates a fixed bench list).
|
||||
|
|
@ -50,11 +50,12 @@ collection = list | vector | map ;
|
|||
nil = "nil" ;
|
||||
boolean = "true" | "false" ;
|
||||
|
||||
(* Numbers. Jolt accepts Clojure's numeric literal syntaxes, but — since Jolt
|
||||
numbers are Janet ints/doubles — it has no distinct bignum, ratio or
|
||||
BigDecimal types: the BigInt suffix N and BigDecimal suffix M are read as the
|
||||
plain number, a ratio a/b is read as its double quotient, and radixed
|
||||
integers are computed by base. The symbolic floats ##Inf/##-Inf/##NaN are
|
||||
(* Numbers. Jolt carries a real numeric tower (JVM parity): an integer literal
|
||||
reads as an exact integer (arbitrary precision), a ratio a/b as an exact
|
||||
Ratio, a decimal/exponent literal as a double. The BigDecimal suffix M reads
|
||||
as a real BigDecimal (unscaled x 10^-scale) — 1.5M, 0.0M, 3M; class is
|
||||
java.math.BigDecimal. The BigInt suffix N reads as an exact integer. Radixed
|
||||
integers are computed by base; the symbolic floats ##Inf/##-Inf/##NaN are
|
||||
also read. (No octal-with-leading-0 literal.) *)
|
||||
number = symbolic-value
|
||||
| [ sign ] , ( radix-int | ratio | hex-int | decimal ) ;
|
||||
|
|
@ -62,10 +63,10 @@ sign = "+" | "-" ;
|
|||
integer = digit , { digit } ;
|
||||
hex-int = "0" , ( "x" | "X" ) , hex-digit , { hex-digit } , [ "N" ] ;
|
||||
radix-int = integer , ( "r" | "R" ) , alnum , { alnum } ; (* base 2..36: 2r1010, 16rFF, 36rZ *)
|
||||
ratio = integer , "/" , integer ; (* read as a double quotient *)
|
||||
ratio = integer , "/" , integer ; (* exact Ratio *)
|
||||
decimal = integer , [ "." , digit , { digit } ] , [ exponent ] , [ num-suffix ] ;
|
||||
exponent = ( "e" | "E" ) , [ sign ] , digit , { digit } ;
|
||||
num-suffix = "N" | "M" ; (* BigInt / BigDecimal in Clojure; plain number in Jolt *)
|
||||
num-suffix = "N" | "M" ; (* N = exact integer (BigInt); M = BigDecimal *)
|
||||
symbolic-value = "##Inf" | "##-Inf" | "##NaN" ;
|
||||
digit = "0".."9" ;
|
||||
hex-digit = digit | "a".."f" | "A".."F" ;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# Clojure libraries known to work with Jolt
|
||||
|
||||
Libraries confirmed to load and pass their conformance checks on Jolt
|
||||
(see `test/integration/deps-conformance-test.janet` and the
|
||||
(see the [examples](https://github.com/jolt-lang/examples), e.g. the
|
||||
[ring-app example](https://github.com/jolt-lang/examples/tree/main/ring-app)).
|
||||
|
||||
* [config](https://github.com/yogthos/config)
|
||||
|
|
@ -19,7 +19,7 @@ Libraries confirmed to load and pass their conformance checks on Jolt
|
|||
* [honeysql](https://github.com/seancorfield/honeysql) — full formatter + helpers
|
||||
(select/insert/update/delete/joins/:inline), loaded unmodified from git
|
||||
* [clojure.jdbc](https://github.com/yogthos/clojure.jdbc) — as [jolt-lang/db](https://github.com/jolt-lang/db)'s
|
||||
`jdbc.core`, reimplemented over janet sqlite3/pq drivers (SQLite + PostgreSQL)
|
||||
`jdbc.core`, over the built-in SQLite access (libsqlite3 via Chez's FFI)
|
||||
* [next.jdbc](https://github.com/seancorfield/next-jdbc) — a compatibility layer in
|
||||
[jolt-lang/db](https://github.com/jolt-lang/db) (`next.jdbc`, `next.jdbc.sql`,
|
||||
`next.jdbc.prepare`, `next.jdbc.transaction`) over `jdbc.core`, for libraries
|
||||
|
|
@ -33,10 +33,7 @@ Libraries confirmed to load and pass their conformance checks on Jolt
|
|||
`logf`/`logp`, `spy`, and `enabled?` all work; output goes to stderr.
|
||||
* [migratus](https://github.com/yogthos/migratus) — database migrations; loads
|
||||
unmodified and runs filesystem SQL/EDN migrations against SQLite through the
|
||||
next.jdbc layer above. `migrate`/`rollback` round-trip end to end. Caveat:
|
||||
migration ids are 14-digit timestamps, and the janet-lang/sqlite3 driver
|
||||
currently truncates INTEGER columns to 32 bits, so completion tracking needs
|
||||
the one-line upstream fix (`sqlite3_column_int64`); ids under 2^31 work as is.
|
||||
next.jdbc layer above. `migrate`/`rollback` round-trip end to end.
|
||||
* [malli](https://github.com/metosin/malli) — data schema validation, on the
|
||||
[malli-app example](https://github.com/jolt-lang/examples/tree/main/malli-app).
|
||||
`m/validate` and `m/explain` work across the vocabulary (predicates, `:int`/
|
||||
|
|
|
|||
|
|
@ -170,9 +170,9 @@ Signature(s), since-version
|
|||
## Open questions
|
||||
|
||||
1. Numerics: the reference has longs/doubles/ratios/BigInt with promotion
|
||||
rules; CLJS has JS numbers; jolt has Janet numbers. Likely answer: specify
|
||||
an integer/float core with a host-numeric-tower extension point — needs
|
||||
its own design note in §4.
|
||||
rules; CLJS has JS numbers. Resolved: jolt carries the Scheme numeric tower
|
||||
(exact integers/bignums, exact ratios, flonum doubles), matching the
|
||||
reference's tower — see the numerics note in §4.
|
||||
2. Where do `*print-length*`-style dynamic vars land — host-dependent
|
||||
interface or portable with defaults?
|
||||
3. License/venue if the spec outgrows this repo (likely CC-BY; separate repo
|
||||
|
|
|
|||
|
|
@ -1,50 +1,49 @@
|
|||
# RFC 0003: Transients — semantics and why they live in the Janet seed
|
||||
# RFC 0003: Transients — semantics and the Chez mutable backing
|
||||
|
||||
Status: accepted (design note)
|
||||
|
||||
This note pins down what transients *are* in Jolt, where their behavior
|
||||
deviates from JVM Clojure and why, and why the transient machinery is part of
|
||||
the irreducible Janet seed rather than a candidate for the core-in-Clojure
|
||||
migration (jolt-tzo). It exists so the kernel-shrink ladder doesn't revisit
|
||||
deviates from JVM Clojure and why, and how the transient machinery is
|
||||
represented in the Chez runtime. It exists so the design doesn't revisit
|
||||
transients every round.
|
||||
|
||||
## What a transient is in Jolt
|
||||
|
||||
A transient is a tagged Janet table wrapping a *native* mutable host value
|
||||
(`core.janet`, "Transients" section):
|
||||
A transient is a Chez record (`jolt-transient`, `host/chez/transients.ss`)
|
||||
wrapping *true mutable* host backing, snapshotted to the immutable collection on
|
||||
`persistent!`. The backing is per kind:
|
||||
|
||||
- transient vector — `@{:jolt/type :jolt/transient :kind :vector :arr ARRAY}`,
|
||||
a Janet array.
|
||||
- transient map — `:kind :map :tbl TABLE`, a Janet table mapping
|
||||
`canon-key(k)` → `@[k v]`. Keying by canonical key keeps collection keys
|
||||
comparing by value across representations (`[1 2]` the pvec and `[1 2]` the
|
||||
tuple are one key), and storing the `@[k v]` pair preserves the *original*
|
||||
key for the rebuilt persistent map.
|
||||
- transient set — `:kind :set :tbl TABLE` mapping `canon-key(x)` → `x`.
|
||||
- transient vector — a growable Scheme vector (a capacity buffer plus a fill
|
||||
count `n`). `conj!`/`pop!` are in-place, amortized O(1); the buffer doubles on
|
||||
growth.
|
||||
- transient map — a Chez hashtable keyed by `key-hash` / `jolt=`
|
||||
(value-equality, nil-safe). Hashing by value keeps collection keys comparing
|
||||
across representations.
|
||||
- transient set — a Chez hashtable of elements.
|
||||
- `cow` — a copy-on-write fallback for anything else (e.g. a sorted coll).
|
||||
|
||||
`transient` accepts pvecs, mutable-build arrays, tuples (reader vectors and
|
||||
map entries — added in the seed-shrink rounds so `(into [] (first {:a 1}))`
|
||||
works through the vector fast path), sets, phms, and untagged struct maps.
|
||||
Sorted collections are rejected, as on the JVM (not editable).
|
||||
`transient` accepts pvecs, pmaps, psets, and the exotic colls handled by the
|
||||
`cow` path. Each kind copies its source into the matching mutable backing once.
|
||||
|
||||
The bang ops (`conj!`, `assoc!`, `dissoc!`, `disj!`, `pop!`) mutate that host
|
||||
value in place and return the transient — O(1) per op (amortized for array
|
||||
push). `persistent!` rebuilds a persistent value from the host value and
|
||||
invalidates the transient (`:jolt/persistent` flag; any further bang op or a
|
||||
second `persistent!` throws "Transient used after persistent! call", matching
|
||||
Clojure's invalidation contract).
|
||||
The bang ops (`conj!`, `assoc!`, `dissoc!`, `disj!`, `pop!`) mutate that backing
|
||||
in place and return the transient — O(1) per op (amortized for the vector push).
|
||||
`persistent!` snapshots a persistent value from the backing (folding the
|
||||
hashtable into a pmap/pset, handing off the buffer as a pvec) and invalidates the
|
||||
transient (the record's active flag clears; any further bang op or a second
|
||||
`persistent!` throws "transient used after persistent!", matching Clojure's
|
||||
invalidation contract).
|
||||
|
||||
Read ops work on an active transient where Clojure supports them: `get`,
|
||||
`contains?`, `count`, and `nth` (vector kind) branch on the transient tag.
|
||||
`contains?`, `count`, and `nth` (vector kind) see through the transient.
|
||||
`seq` on a transient is not supported, as in Clojure.
|
||||
|
||||
## Deviations from JVM Clojure (deliberate)
|
||||
|
||||
**O(n) edges, O(1) middle.** Clojure's `(transient v)` is O(1) — the transient
|
||||
*shares* the persistent trie and marks nodes editable; `persistent!` is O(1)
|
||||
too. Jolt's `transient` copies the source into a native array/table (O(n)) and
|
||||
`persistent!` rebuilds (O(n)). The bang ops in between are native-host O(1),
|
||||
which is *faster* per-op than trie editing. So the asymptotics of the usual
|
||||
too. Jolt's `transient` copies the source into a mutable buffer/hashtable (O(n))
|
||||
and `persistent!` snapshots back (O(n)). The bang ops in between are host-mutable
|
||||
O(1), which is *faster* per-op than trie editing. So the asymptotics of the usual
|
||||
pattern
|
||||
|
||||
(persistent! (reduce conj! (transient []) coll))
|
||||
|
|
@ -53,13 +52,12 @@ are identical (O(n) total either way) with a better constant in the loop and a
|
|||
worse constant at the two edges. The pattern transients exist for — batch
|
||||
construction — is fully served. What is NOT served is transient-editing a
|
||||
*large* collection to change a few keys: that's O(n) in Jolt vs O(log n) in
|
||||
Clojure, because `transient` flattens the pvec trie / phm HAMT into a
|
||||
native array/table and `persistent!` rebuilds them.
|
||||
Clojure, because `transient` copies the source into a growable Scheme vector /
|
||||
Chez hashtable and `persistent!` snapshots it back.
|
||||
|
||||
**No thread-ownership check.** JVM Clojure ≥1.7 also dropped the owner-thread
|
||||
assertion (for fork/join), keeping only "don't use after persistent!", which
|
||||
Jolt enforces. Jolt code is fiber-concurrent; when real OS-thread futures land
|
||||
(jolt-ejx), a transient handed across threads is a data race exactly as in
|
||||
Jolt enforces. A transient handed across threads is a data race exactly as in
|
||||
Clojure — documented, not checked, same as the JVM.
|
||||
|
||||
**`(conj!)` / `(conj! t)` arities** follow Clojure's transducer-era contract:
|
||||
|
|
@ -68,51 +66,43 @@ zero args makes a fresh `(transient [])`, one arg returns it untouched.
|
|||
lenient kvs walk of Jolt's `assoc`.
|
||||
|
||||
**No transient sorted variants** — same as Clojure. One leniency: Clojure
|
||||
throws on `(transient '(1))`, but Jolt's lists are Janet arrays underneath and
|
||||
fall into the mutable-build branch, yielding a transient *vector*. Harmless
|
||||
(the result of `persistent!` is a vector, never silently a list) but
|
||||
non-Clojure; tighten if it ever bites.
|
||||
throws on `(transient '(1))`, but Jolt routes a list through the `cow` fallback
|
||||
path, yielding a transient. Harmless but non-Clojure; tighten if it ever
|
||||
bites.
|
||||
|
||||
## Why transients stay in the Janet seed
|
||||
## Why transients live in the host
|
||||
|
||||
The migration ladder (jolt-tzo) moves anything expressible as *pure Clojure
|
||||
over existing primitives* out of the seed. Transients fail that test on three
|
||||
Transients are part of the value/representation layer in the Chez runtime
|
||||
(`host/chez/transients.ss`), not the portable `clojure.core` overlay, on three
|
||||
grounds:
|
||||
|
||||
1. **They are the mutation kernel.** A transient's entire value is direct
|
||||
mutation of a host array/table. The overlay's only mutation seam is
|
||||
`jolt.host/ref-put!` (a single table-put). Re-expressing `tr-conj!` etc. in
|
||||
Clojure would mean either growing the host surface one-for-one
|
||||
(`host-array-push!`, `host-table-put!`, …, i.e. moving the same code behind
|
||||
more indirection) or simulating mutation over persistent values (defeating
|
||||
the point of transients). Either way the Janet line count moves, it doesn't
|
||||
shrink.
|
||||
mutation of a host buffer/hashtable. The overlay has no mutation seam of its
|
||||
own. Re-expressing the bang ops in Clojure would mean either growing the host
|
||||
surface one-for-one (a host-vector-push, a host-hashtable-put, …, i.e. moving
|
||||
the same code behind more indirection) or simulating mutation over persistent
|
||||
values (defeating the point of transients).
|
||||
|
||||
2. **They sit under the seed's own dispatch.** `conj`/`assoc`/`get`/`count`/
|
||||
`contains?` in the seed branch on the transient tag. Hoisting the transient
|
||||
ops above that dispatch (the hierarchy-port pattern of lazily-resolved
|
||||
overlay vars) would put an interpreted/compiled-Clojure call inside the
|
||||
hottest native paths for no semantic gain — transients have no semantics to
|
||||
*fix* (unlike hierarchy, which had real correctness gaps).
|
||||
2. **They sit under the collection dispatch.** `conj`/`assoc`/`get`/`count`/
|
||||
`contains?` see through a transient. Hoisting the transient ops above that
|
||||
dispatch would put a compiled-Clojure call inside the hottest paths for no
|
||||
semantic gain — transients have no semantics to *fix*.
|
||||
|
||||
3. **The value layer is declared irreducible.** The self-hosting design doc
|
||||
(docs/self-hosting-compiler.md, "The kernel") keeps the value/representation
|
||||
layer — persistent collections and, with them, their mutable scratch
|
||||
counterparts — in the host. Transients are representation, not library.
|
||||
3. **The value layer is the host's job.** The persistent collections and, with
|
||||
them, their mutable scratch counterparts, live in the Chez runtime alongside
|
||||
the value model. Transients are representation, not library.
|
||||
|
||||
What CAN move (and mostly has): anything *derived* — e.g. `into`'s
|
||||
transient-using fast path, or future `update!`-style conveniences — is plain
|
||||
Clojure over `transient`/bang-ops/`persistent!` and belongs in the overlay
|
||||
tiers as ordinary migration batches.
|
||||
What lives in the overlay: anything *derived* — e.g. `into`'s transient-using
|
||||
fast path, or `update!`-style conveniences — is plain Clojure over
|
||||
`transient`/bang-ops/`persistent!`.
|
||||
|
||||
## Future work
|
||||
|
||||
- pvec is already a 32-way trie with structural sharing (pv.janet), so
|
||||
Clojure-style O(1) `transient`/`persistent!` via editable nodes is a real
|
||||
option for vectors — an internal change behind the same surface, not a
|
||||
semantics change. phm is now a HAMT with structural sharing too (jolt-684u),
|
||||
and sorted maps/sets are a red-black tree (jolt-0hbr), so the same editable-
|
||||
node trick is open for those as well — the transient surface here is still the
|
||||
copy-to-native-table flatten.
|
||||
- The persistent map/set are a bitmap HAMT with structural sharing
|
||||
(`host/chez/collections.ss`), so Clojure-style O(1) `transient`/`persistent!`
|
||||
via editable nodes is a real option there — an internal change behind the same
|
||||
surface, not a semantics change. The persistent vector is a flat
|
||||
copy-on-write Scheme vector rather than a trie, so the transient surface for
|
||||
it stays the copy-to-growable-vector path.
|
||||
- `transient?` (Jolt extension, useful in tests) stays; Clojure has no public
|
||||
predicate, so it must not leak into portability-sensitive code.
|
||||
|
|
|
|||
|
|
@ -11,26 +11,19 @@ measured effect, so later work does not relitigate it.
|
|||
## Background: why the lookup carries a guard
|
||||
|
||||
A Jolt map value has several runtime representations (see RFC on collections and
|
||||
`src/jolt/core.janet`): a Janet struct for a small all-scalar-key literal map, a
|
||||
persistent hash map (a table tagged `:jolt/type :jolt/phm`) when a key is a
|
||||
collection or a value is nil, plus sorted maps, transients, and record/deftype
|
||||
instances. A record instance is a Janet table tagged `:jolt/deftype` but, like a
|
||||
struct, it carries no `:jolt/type`, so a raw Janet `(get inst :field)` reads its
|
||||
fields directly.
|
||||
`host/chez/collections.ss`): a persistent hash map (a bitmap HAMT) for the
|
||||
general case, plus sorted maps, transients, and record/deftype instances. A
|
||||
record instance is a Chez record (`jrec`) whose fields are read directly off the
|
||||
record's storage, while a HAMT lookup runs the full `jolt=`/`jolt-hash`-keyed
|
||||
collection path.
|
||||
|
||||
A constant-keyword lookup `(:k m)` compiles to a guarded form:
|
||||
|
||||
```janet
|
||||
(if (get m :jolt/type) (core-get m k) (get m k))
|
||||
```
|
||||
|
||||
The guard is one opcode. A non-nil `:jolt/type` routes phm/sorted/transient/
|
||||
lazy-seq values to `core-get`'s full semantics; everything else (structs,
|
||||
records, nil, scalars) takes the bare Janet `get`, which matches `core-get` for
|
||||
keyword keys. The guard is correct and cheap, but on a struct it is a second
|
||||
`get`: profiling the ray tracer (a naive all-maps program) found keyword lookups
|
||||
are about half of a render, and the guard is the only avoidable part of each
|
||||
one. A bare get is roughly 20ns where the guarded form is roughly 36ns.
|
||||
A constant-keyword lookup `(:k m)` compiles to a guarded form: it inspects the
|
||||
subject's representation and routes a HAMT/sorted/transient/lazy-seq value to the
|
||||
full `jolt-get` semantics, while a record/raw-get-safe value takes the direct
|
||||
field read, which matches `jolt-get` for keyword keys. The guard is correct and
|
||||
cheap, but on a raw-get-safe value it is wasted work: profiling the ray tracer (a
|
||||
naive all-maps program) found keyword lookups are about half of a render, and the
|
||||
guard is the only avoidable part of each one.
|
||||
|
||||
Dropping the guard is only safe when the subject is known to be a plain
|
||||
struct/record rather than a tagged collection. Jolt does not infer that
|
||||
|
|
@ -59,27 +52,27 @@ optimization.
|
|||
## How it flows
|
||||
|
||||
The reader already keeps `^hint` metadata on the binding symbol and is otherwise
|
||||
transparent (`reader.janet`, `meta-form->map`). The change threads that fact to
|
||||
the lookup site:
|
||||
transparent (`host/chez/reader.ss`). The change threads that fact to the lookup
|
||||
site:
|
||||
|
||||
1. The analyzer (`jolt-core/jolt/analyzer.clj`) records a `:struct` hint per
|
||||
local in its env when a param or `let` binding carries `^:struct` or a
|
||||
record-type tag, and attaches `:hint :struct` to that local's `:local` IR
|
||||
node. Resolving a record-type tag uses a new host contract function
|
||||
`record-type?` (`src/jolt/host_iface.janet`), which checks for the `->Name`
|
||||
constructor.
|
||||
2. The back end (`emit-kw-lookup` in `src/jolt/backend.janet`) emits the bare get
|
||||
node. Resolving a record-type tag uses the host contract function
|
||||
`record-type?` (`jolt.host`, backed by `host/chez/host-contract.ss`), which
|
||||
checks for the `->Name` constructor.
|
||||
2. The back end (`jolt-core/jolt/backend_scheme.clj`) emits the direct field read
|
||||
when the lookup subject is a `:local` carrying the hint, and the guarded form
|
||||
otherwise. The unhinted path is byte-identical to before.
|
||||
otherwise. The unhinted path is identical to before.
|
||||
3. The inline pass (`jolt-core/jolt/passes.clj`) propagates the hint: when it
|
||||
binds a non-trivial call argument to a fresh local, it carries the called
|
||||
function's parameter hint onto that local, so lookups inside the spliced body
|
||||
keep the bare path. Without this, inlining a hinted function would erase the
|
||||
keep the direct path. Without this, inlining a hinted function would erase the
|
||||
benefit, because the hinted parameter is replaced by an unhinted temporary.
|
||||
|
||||
The same machinery covers both `(:k m)` and `(get m :k [default])` when the key
|
||||
is a constant keyword. A `get` with a variable, numeric, or string key falls
|
||||
through to `core-get` unchanged.
|
||||
through to `jolt-get` unchanged.
|
||||
|
||||
## Record hints across namespaces, and as inference seeds
|
||||
|
||||
|
|
@ -98,15 +91,14 @@ the function where the hot reads actually happen.
|
|||
|
||||
**It resolves across namespaces.** A hint may name a record defined in another
|
||||
namespace, in either spelling — `^Vec3` where the type is `:refer`-ed, or
|
||||
`^v/Vec3` where the namespace is `:as`-aliased. Resolution (`record-ctor-key` in
|
||||
`src/jolt/host_iface.janet`, backed by `record-hint-ctor-key` in
|
||||
`src/jolt/evaluator.janet`) runs against the *compile* namespace and maps the
|
||||
type to its home constructor key through a constructor-value index — keyed by the
|
||||
constructor value, not a var's namespace, so a `:refer`-interned var (whose
|
||||
namespace is the referring one) still resolves home. The reader keeps a tag's
|
||||
namespace qualifier (`^v/Vec3` → `"v/Vec3"`, not `"Vec3"`) so the aliased
|
||||
spelling has something to resolve. Both `defrecord` field hints and function
|
||||
parameter hints use this resolution.
|
||||
`^v/Vec3` where the namespace is `:as`-aliased. Resolution (`record-ctor-key`,
|
||||
a `jolt.host` contract function backed by `host/chez/host-contract.ss`) runs
|
||||
against the *compile* namespace and maps the type to its home constructor key
|
||||
through a constructor-value index — keyed by the constructor value, not a var's
|
||||
namespace, so a `:refer`-interned var (whose namespace is the referring one)
|
||||
still resolves home. The reader keeps a tag's namespace qualifier (`^v/Vec3` →
|
||||
`"v/Vec3"`, not `"Vec3"`) so the aliased spelling has something to resolve. Both
|
||||
`defrecord` field hints and function parameter hints use this resolution.
|
||||
|
||||
## Soundness and the checked mode
|
||||
|
||||
|
|
@ -120,8 +112,8 @@ To make a lie visible without taxing the fast path, `JOLT_CHECK_HINTS=1` keeps
|
|||
the guard but throws on the tagged arm with a message naming the local and key:
|
||||
|
||||
```
|
||||
type hint violated on `m`: (:a m) — value carries :jolt/type
|
||||
(a phm/sorted/transient/lazy-seq), not the plain struct/record the
|
||||
type hint violated on `m`: (:a m) — value is a
|
||||
phm/sorted/transient/lazy-seq, not the plain struct/record the
|
||||
^:struct/^Record hint asserts
|
||||
```
|
||||
|
||||
|
|
@ -134,7 +126,7 @@ off). The flag is part of the image-cache fingerprint.
|
|||
Type hints parse in every position Clojure accepts them and are inert except for
|
||||
the optimization above. This matches Clojure's "parse and otherwise do nothing"
|
||||
model, with the difference that Clojure additionally uses hints to avoid
|
||||
reflection and select primitive arithmetic, which do not apply to a Janet host.
|
||||
reflection and select primitive arithmetic, which do not apply to the Chez host.
|
||||
|
||||
## Measured effect
|
||||
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ A type `T` is one of:
|
|||
`:nonnil` for "provably not nil and not false", which is what the struct-vs-phm
|
||||
decision needs; see below.)
|
||||
- `:nil`.
|
||||
- `{:struct {field -> T}}` — a raw-get-safe map (Janet struct or record) whose
|
||||
- `{:struct {field -> T}}` — a raw-get-safe map (a record) whose
|
||||
field `k` has type `(fields k)` or `:any` if absent. The degenerate
|
||||
`{:struct {}}` is "a struct, fields unknown" and replaces today's
|
||||
`:struct-map`.
|
||||
|
|
@ -65,7 +65,7 @@ A type `T` is one of:
|
|||
|
||||
Types are immutable values comparable by structural equality, exactly like the
|
||||
current `{:vec ELEM}` representation, so they flow across the portable
|
||||
inference and the Janet orchestrator unchanged.
|
||||
inference and the host unchanged.
|
||||
|
||||
### Join (least upper bound)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,80 +1,45 @@
|
|||
# Seed ↔ Overlay Registry
|
||||
|
||||
Jolt is "Clojure on Janet": a shrinking **Janet seed** (`src/jolt/*.janet`)
|
||||
hosts a **Clojure overlay** (`jolt-core/clojure/core/NN-*.clj`). Both define
|
||||
`clojure.core`-facing functions, and for a handful of names *both* tiers carry a
|
||||
definition. Which copy is authoritative has been tribal knowledge. This document
|
||||
is the single source of truth; `test/unit/seed-overlay-registry-test.janet` is a
|
||||
build-time drift check that fails if reality diverges from what is written here.
|
||||
Jolt is Clojure on Chez Scheme. `clojure.core` is built from two tiers that both
|
||||
define `clojure.core`-facing vars, and for a handful of names *both* tiers carry
|
||||
a definition. This document records how the two tiers relate and which copy is
|
||||
authoritative.
|
||||
|
||||
## The registration mechanism
|
||||
## The two tiers
|
||||
|
||||
Seed core functions are named with a `core-` prefix (`core-into`, `core-conj`,
|
||||
`core-transduce`) and registered into the `clojure.core` namespace by the
|
||||
`core-bindings` table in `src/jolt/core.janet`. Each entry maps a **public
|
||||
Clojure name** (the string key) to a seed function value:
|
||||
- **Native shims** (`host/chez/natives-*.ss`) bind a set of `clojure.core` vars
|
||||
directly to Scheme runtime values via `def-var!` — collection constructors,
|
||||
seq fns, numeric/string ops, and so on. These cover names the overlay assumes
|
||||
exist as bare `clojure.core` vars but does not define itself.
|
||||
- **The Clojure overlay** (`jolt-core/clojure/core/NN-*.clj`) defines the rest of
|
||||
`clojure.core` in dependency-ordered tiers, loaded in order: `00-syntax`,
|
||||
`00-kernel`, `10-seq`, `20-coll`, `25-sorted`, `30-macros`, `40-lazy`, `50-io`.
|
||||
|
||||
```janet
|
||||
(def- core-bindings
|
||||
@{"into" core-into
|
||||
"reduce" core-reduce
|
||||
...})
|
||||
```
|
||||
|
||||
`init-core!` (`src/jolt/core.janet`) interns every pair into `clojure.core`.
|
||||
The overlay tiers load afterwards (`api.janet`: 00-syntax, 00-kernel, 10-seq,
|
||||
20-coll, 25-sorted, 30-macros, 40-lazy, 50-io). When an overlay tier `(defn X …)`
|
||||
for a name that `core-bindings` already registered, the **overlay def shadows the
|
||||
seed binding** — the seed `core-X` then survives only if some other seed code
|
||||
still calls it directly.
|
||||
The overlay loads after the native shims. When an overlay tier `(defn X …)` for a
|
||||
name a native shim already bound, the **overlay def shadows the native binding** —
|
||||
user code sees the overlay copy. The native binding then survives only if some
|
||||
other native/runtime code still calls the Scheme value directly.
|
||||
|
||||
So a name's *home* is determined by two facts:
|
||||
|
||||
1. is it a key in `core-bindings`? (registered ⇒ the seed `core-X` is reachable)
|
||||
2. does an overlay tier `(defn X …)`? (defined ⇒ the overlay copy shadows)
|
||||
1. is it bound by a native shim? (the Scheme value is reachable from the runtime)
|
||||
2. does an overlay tier `(defn X …)`? (the overlay copy is what user code sees)
|
||||
|
||||
## Dispatch-only seed helpers: the `__` prefix
|
||||
## The compiled seed
|
||||
|
||||
Seed functions that are **not** public Clojure vars but must be reachable by
|
||||
name from compiled/overlay code (compiler hooks, macro-expansion targets) are
|
||||
registered under a `__`-prefixed key — e.g. `"__sq1"`, `"__write"`,
|
||||
`"__bit-and"`, `"__jdbc-conn-raw"`. The `__` prefix is unreadable as a
|
||||
user-level symbol, so these never collide with or masquerade as public API. When
|
||||
you add a dispatch-only hook, give it a `__` key; do not register it under a bare
|
||||
name.
|
||||
`clojure.core` is compiled ahead of time into the checked-in seed
|
||||
(`host/chez/seed/{prelude,image}.ss`) as Scheme `def-var!` forms. The seed's
|
||||
source twin is the overlay (`jolt-core/clojure/core/*.clj` plus the stdlib
|
||||
namespaces under `src/jolt/clojure/`); `host/chez/emit-image.ss` re-emits the
|
||||
prelude from those sources on Chez. The build is a byte-fixpoint: rebuilding from
|
||||
an up-to-date seed reproduces it exactly.
|
||||
|
||||
## Dispatch twins
|
||||
## Consistency guard
|
||||
|
||||
A **twin** is a name with *both* a seed `core-X` defn and an overlay `(defn X …)`.
|
||||
There are exactly five. Each seed site carries a greppable `SEED-TWIN:` comment.
|
||||
|
||||
| name | overlay (authoritative public) | seed copy (`core-X`) | registered? | role of the seed copy |
|
||||
|---------------|----------------------------------------|--------------------------------------|-------------|------------------------|
|
||||
| `char?` | `20-coll.clj` `char?` | `core_types.janet` `core-char?` | no | internal type dispatch |
|
||||
| `sorted-map?` | `25-sorted.clj` `sorted-map?` | `core_types.janet` `core-sorted-map?`| no | internal dispatch (sorted-op) |
|
||||
| `sorted-set?` | `25-sorted.clj` `sorted-set?` | `core_types.janet` `core-sorted-set?`| no | internal dispatch |
|
||||
| `sorted?` | `25-sorted.clj` `sorted?` | `core_types.janet` `core-sorted?` | no | internal dispatch |
|
||||
| `transduce` | `20-coll.clj` `transduce` | `core_coll.janet` `core-transduce` | no | internal helper for `core-into` only |
|
||||
|
||||
None of the five is registered in `core-bindings`: the overlay copy is the public
|
||||
one, and the seed copy is reached only by other *seed* code (so editing the seed
|
||||
copy alone will not change what user code sees — change both, or move the logic).
|
||||
|
||||
## The surprising asymmetry: `into` vs `transduce`
|
||||
|
||||
`into` and `reduce` are **seed-public**: registered in `core-bindings`, and the
|
||||
overlay deliberately does *not* redefine them (they sit on the perf wall — see
|
||||
the "into stays in the seed" note in `20-coll.clj`). `transduce`, by contrast, is
|
||||
**overlay-public**: the overlay `transduce` is the real one, and `core-transduce`
|
||||
remains only because `core-into` calls it directly. So two functions that read as
|
||||
a matched pair have opposite homes. That asymmetry is intentional and is the
|
||||
reason this registry exists.
|
||||
|
||||
## Drift check
|
||||
|
||||
`test/unit/seed-overlay-registry-test.janet` recomputes the twin set from source
|
||||
(names with both a seed `core-X` defn and an overlay `defn X`) and asserts it
|
||||
equals the five above. It also asserts none of the twins is registered in
|
||||
`core-bindings`, and that every non-`__` `core-bindings` key is a plausible
|
||||
public name (no accidental `__`-less dispatch helper). If you add, remove, or
|
||||
re-home a twin, update this table and that test together.
|
||||
There is no separate drift-check test for the registry. The self-hosting
|
||||
fixpoint is the guard: after changing a seed source (a core tier, the compiler
|
||||
namespaces, the host contract, the reader, or `emit-image.ss`) you must re-mint
|
||||
the seed (`make remint`), and `make selfhost` fails if the checked-in seed and
|
||||
its sources have drifted. So if the overlay's shadowing relationship changes, the
|
||||
re-minted prelude changes with it, and the fixpoint check keeps source and seed
|
||||
in agreement.
|
||||
|
|
|
|||
|
|
@ -1,138 +0,0 @@
|
|||
# Self-hosting architecture: portable jolt-core over a host runtime
|
||||
|
||||
Design for splitting Jolt into a **portable Clojure-in-Clojure core** and a
|
||||
**host runtime** (Janet today, another runtime tomorrow), so the language is
|
||||
truly self-hosted and `jolt-core` can be lifted out and re-hosted.
|
||||
|
||||
This is the design that must be right *before* writing the compiler in Clojure —
|
||||
see [[self-hosting-compiler]] for the staged plan it plugs into.
|
||||
|
||||
## What "truly self-hosted + portable" requires
|
||||
|
||||
Two independent properties:
|
||||
|
||||
1. **Self-hosted** — the compiler and most of `clojure.core` are written in
|
||||
Clojure and compiled by Jolt itself.
|
||||
2. **Portable** — that Clojure code (`jolt-core`) depends only on a small,
|
||||
explicit **host contract**, never on Janet directly. Re-hosting means
|
||||
implementing the contract for a new runtime; `jolt-core` is reused verbatim.
|
||||
|
||||
The enemy is `jolt-core` calling `janet/tuple`, `make-vec`, `ns-find`, etc.
|
||||
directly — that welds it to Janet. Every host dependency must go through the
|
||||
contract.
|
||||
|
||||
## Prior art (the seam everyone uses)
|
||||
|
||||
- **Clojure (JVM).** `clojure.lang.*` (Java) is the host: `RT`/`Numbers` runtime
|
||||
helpers, the `Compiler` (form → JVM bytecode), persistent data structures,
|
||||
`Var`/`Namespace`, the reader. `clojure/core.clj` is the language, in Clojure.
|
||||
Seam: ~20 primitive special forms + `RT` static methods. Everything else is
|
||||
Clojure.
|
||||
- **ClojureScript (self-hosted).** Two portable passes — `cljs.analyzer`
|
||||
(form → AST **as data**, reading a **compiler-state map** of
|
||||
namespaces/defs/macros, *not* host objects) and `cljs.compiler` (AST → JS, the
|
||||
host-specific back end). `cljs.core` is Clojure compiled to JS. Platform splits
|
||||
live in `.cljc` reader conditionals. This is the closest model to what we want:
|
||||
**the analyzer is host-agnostic; only the back end and the runtime are
|
||||
host-specific.**
|
||||
- **Nanopass / Guile Tree-IL.** A high-level IR is the portability seam; multiple
|
||||
back ends consume it.
|
||||
- **ClojureCLR / ClojureDart / jank.** Same shape every time: portable analyzer +
|
||||
host back end + host runtime.
|
||||
|
||||
The invariant across all of them: **the IR (analyzer output) and a small runtime
|
||||
protocol are the contract; the front end is portable, the back end and runtime
|
||||
are per-host.**
|
||||
|
||||
## Decisions (locked)
|
||||
|
||||
- **Seam = a minimal host protocol.** `jolt-core` calls a small documented set of
|
||||
host fns (in ns `jolt.host`): `resolve-sym`, `macro?`, `macroexpand-1`,
|
||||
`current-ns`, `intern!`, plus the `RT` primitives. Each host provides `jolt.host`
|
||||
(+ RT). Re-hosting = reimplement that handful of fns. The protocol *is* the
|
||||
boundary; `jolt-core` never touches Janet directly.
|
||||
- **Physical split now.** Portable Clojure lives under `jolt-core/` (a new source
|
||||
root, embedded into the binary like the rest of the stdlib); host Janet code for
|
||||
the new pipeline under `host/janet/`. Legacy host modules under `src/jolt/*.janet`
|
||||
are the existing Janet host and get relocated under `host/janet/` in a later
|
||||
mechanical pass (tracked) — not moved big-bang now, to keep the suite green.
|
||||
|
||||
## The Jolt split
|
||||
|
||||
```
|
||||
jolt-core/ PORTABLE Clojure — no Janet. Depends only on the contract.
|
||||
ir the IR spec (data shapes the analyzer emits)
|
||||
analyzer form -> IR (macroexpands; resolves via host protocol)
|
||||
macros when/cond/->/defn/... (the macro library, in Clojure)
|
||||
core clojure.core fns expressible in Clojure, over RT primitives
|
||||
|
||||
host/janet/ THE HOST — Janet. Implements the contract.
|
||||
reader text -> jolt forms
|
||||
rt data structures + RT primitive fns (cons/first/+/get/apply…)
|
||||
backend IR -> Janet forms -> Janet compile -> bytecode (the emitter)
|
||||
cenv the compile-time host protocol impl (resolve/macro?/intern)
|
||||
bootstrap load jolt-core, wire analyzer+backend into the loader
|
||||
interop janet.* bridge
|
||||
```
|
||||
|
||||
Two contracts cross the seam:
|
||||
|
||||
### 1. The IR (analyzer → back end)
|
||||
The existing `:op`-tagged AST, made **host-neutral**:
|
||||
- `{:op :const :val v}`, `:if`, `:do`, `:let`, `:fn` (arities), `:invoke`,
|
||||
`:vector`/`:map`/`:set`, `:quote`, `:throw`/`:try`, `:loop`/`:recur`.
|
||||
- **Globals reference vars by NAME, not by host cell:**
|
||||
`{:op :var :ns "clojure.core" :name "map"}`. (compiler.janet today embeds the
|
||||
Janet var cell as a constant — that's a host leak and breaks AOT. Name-based
|
||||
refs are both portable and AOT-friendly; the back end resolves the cell.)
|
||||
- No embedded host function values. Calls to runtime primitives are
|
||||
`{:op :rt :name "cons"}` resolved by the back end to the host's RT fn.
|
||||
|
||||
### 2. The host contract (two protocols)
|
||||
- **Compile-time (`cenv`)** — what the analyzer needs from the host while
|
||||
analyzing: `(current-ns)`, `(resolve-sym sym) -> {:kind :var|:macro|:local|:special|:host, :ns, :name}`,
|
||||
`(macroexpand-1 form)`, `(intern! ns sym meta)`. The analyzer calls only these;
|
||||
it never touches Janet ns/var tables. (CLJS keeps this as pure data; we use a
|
||||
small protocol — a minimal, documented boundary — because Jolt already has live
|
||||
ns/var objects. The protocol *is* the seam.)
|
||||
- **Runtime (`RT`)** — the primitive fns emitted code and `jolt-core` call by
|
||||
stable name: arithmetic/compare, `cons/first/rest/seq/conj/get/assoc/count`,
|
||||
`apply`, `=`, vector/map/set constructors, var deref/bind, keyword/symbol
|
||||
construction. The back end maps each to the host (on Janet, mostly the existing
|
||||
`core-*`). To re-host, implement this set.
|
||||
|
||||
## Why name-based vars (not embedded cells)
|
||||
|
||||
`compiler.janet` compiles a global ref to a closure over the Janet var cell. That
|
||||
(a) is a Janet value baked into the IR — not portable, and (b) can't be marshaled
|
||||
for AOT without the runtime-dict trick. Compiling instead to *resolve var by
|
||||
(ns,name) at call time* through an RT primitive keeps redefinition live, makes the
|
||||
IR host-neutral, and makes images trivially portable. The per-call lookup is the
|
||||
cost; it can be cached/direct-linked later as an opt-in optimization.
|
||||
|
||||
## Bootstrap & staging (keeps the suite green throughout)
|
||||
|
||||
`compiler.janet` stays as the **bootstrap back end** until the Clojure pipeline is
|
||||
proven. Order:
|
||||
|
||||
1. **Freeze the IR** spec and refactor `compiler.janet`'s emit to consume
|
||||
name-based `:var` (no behavior change; bootstrap still works).
|
||||
2. **Define the host contract** (`cenv` + `RT`) and implement it on Janet,
|
||||
exposed under a stable namespace the Clojure core can call.
|
||||
3. **Write `jolt.analyzer` in Clojure** producing IR, against `cenv`. Diff its IR
|
||||
against the Janet analyzer on the conformance corpus until identical.
|
||||
4. **Janet back end consumes IR** from the Clojure analyzer; wire into the loader
|
||||
behind a flag. Validate at parity (dual-mode conformance + clojure-test-suite).
|
||||
5. **Flip** the loader to the Clojure analyzer + Janet back end; `compiler.janet`
|
||||
shrinks to the back end only.
|
||||
6. **Move `clojure.core`** macros then fns into `jolt-core` incrementally, each
|
||||
compiled by the prior stage, isolating host bits behind `RT`.
|
||||
|
||||
Guards at every step: the dual-mode conformance harness (interpret vs compile)
|
||||
and the clojure-test-suite baseline.
|
||||
|
||||
## The portability test
|
||||
|
||||
When done, re-hosting Jolt to runtime X means writing only: `host/X/{reader, rt,
|
||||
backend, cenv, bootstrap}`. `jolt-core/{ir, analyzer, macros, core}` is reused
|
||||
unchanged. That is the concrete bar for "truly self-hosted and portable."
|
||||
|
|
@ -1,175 +0,0 @@
|
|||
# Toward a self-hosting Jolt compiler
|
||||
|
||||
Research and design notes for evolving Jolt from "interpreter + opt-in ad-hoc
|
||||
compiler" toward a self-hosting Clojure-in-Clojure compiler that emits Janet
|
||||
bytecode, keeps full REPL live-redefinition, and rests on a minimal Janet
|
||||
bootstrap. This is a design doc, not a changelog — it describes where we are, the
|
||||
prior art, the constraints we verified, and a recommended path.
|
||||
|
||||
## The goal
|
||||
|
||||
- **Self-hosting, Clojure-in-Clojure.** A small kernel in the host (Janet) is
|
||||
enough to start; the rest of Clojure — including the compiler — is written in
|
||||
Clojure and compiled by Jolt itself, growing the language as it compiles more
|
||||
of itself.
|
||||
- **Janet bytecode out.** Compiled code runs as native Janet bytecode (fast),
|
||||
not tree-walking.
|
||||
- **Full runtime flexibility.** `def`/`defn` redefinition, vars, protocols,
|
||||
multimethods, and everything else stay live and redefinable at the REPL even
|
||||
for compiled code.
|
||||
- **Minimal host requirement.** Shrink what must exist in Janet to the
|
||||
irreducible base.
|
||||
|
||||
## Where Jolt is today
|
||||
|
||||
- ~5,500 lines of **Janet** implement `clojure.core` (`core.janet`) and a
|
||||
tree-walking interpreter (`evaluator.janet`); ~1k lines of **Clojure** are the
|
||||
stdlib (`clojure.string/set/walk/…`, `jolt.*`). So the language is mostly in
|
||||
the host, inverted from the Clojure-in-Clojure ideal.
|
||||
- The interpreter (`eval-form`) is the complete reference path.
|
||||
- The compiler (`compiler.janet`) — `analyze-form` (reader form → `:op` AST) →
|
||||
`emit` (AST → Janet form) → Janet `compile`/`eval` — is now **on by default**
|
||||
in the shipped runtime (`JOLT_INTERPRET=1` opts out). It is a *hybrid*: forms
|
||||
it can't compile correctly throw `jolt/uncompilable` and fall back to the
|
||||
interpreter (`loader/eval-toplevel`), so results always match the interpreter.
|
||||
Validated at parity — conformance 218/218 under both interpret and compile, and
|
||||
the clojure-test-suite under compile passes 3932 (vs the 3913 interpreter
|
||||
baseline) across ~4.6k assertions.
|
||||
- Done so far: var-indirection (globals deref through var cells, so compiled code
|
||||
is REPL-redefinable); hybrid fallback; compilation of multi-arity / named /
|
||||
variadic fns and `recur` inside `fn`; map and vector literal compilation
|
||||
(mode-correct via `make-vec` / `build-map-literal`); resolution that mirrors
|
||||
the interpreter (current ns → `clojure.core` → Janet-env fallback); and AOT
|
||||
(`aot.janet`) that marshals a compiled namespace to a Janet bytecode image
|
||||
against the baked-in runtime dictionary and loads it back.
|
||||
- Still open — the actual self-hosting: the compiler and most of `clojure.core`
|
||||
are still Janet. Rewriting them in Clojure (compiled by Jolt) is the remaining
|
||||
Clojure-in-Clojure work.
|
||||
|
||||
## What the host gives us (verified)
|
||||
|
||||
Janet already is the backend and the AOT story — we don't need a custom bytecode
|
||||
emitter:
|
||||
|
||||
- `(compile form env source)` → a **function** (compiled bytecode). Jolt's job is
|
||||
Clojure form → correct Janet form → `compile`.
|
||||
- `marshal`/`unmarshal`, `make-image`/`load-image` → serialize a compiled
|
||||
environment to a **bytecode image** and load it back: this is Phase 4 AOT.
|
||||
- `asm`/`disasm` → bytecode assembler/disassembler if we ever want to bypass the
|
||||
form layer (we shouldn't need to).
|
||||
|
||||
**The catch we verified:** Janet *early-binds* top-level references. Compile
|
||||
`(defn caller [] foo)`, then redefine `foo` — the compiled `caller` still returns
|
||||
the old value. So emitting Jolt globals as plain Janet symbols (what the current
|
||||
compiler largely does) is fundamentally incompatible with REPL redefinition. This
|
||||
is the single most important design constraint below.
|
||||
|
||||
## Prior art
|
||||
|
||||
- **Clojure (JVM).** A Java runtime + compiler bootstraps `clojure.core`, which is
|
||||
written in Clojure; thereafter Clojure compiles Clojure to JVM bytecode. Only
|
||||
~20 special forms are primitive; everything else is macros/functions. Crucially,
|
||||
compiled call sites go **through Var objects** (a deref), so redefining a var is
|
||||
visible to existing compiled callers — that's how speed and live redefinition
|
||||
coexist. Clojure 1.8 added opt-in **direct linking** (inline the call, drop the
|
||||
var indirection) for speed where you don't need redefinition (used for core in
|
||||
production). AOT compiles namespaces to `.class` files.
|
||||
- **ClojureScript self-hosting.** Two stages: an **analyzer** (source → AST plus
|
||||
a "compiler state" map of namespaces/defs/macros) and a **compiler** (AST → JS).
|
||||
`cljs.js` exposes compile/eval at runtime; bootstrapped CLJS compiles CLJS at
|
||||
~2× the JVM compiler. The host VM (JS engine) is the backend — the same shape we
|
||||
want with Janet as the backend.
|
||||
- **Nanopass (Chez Scheme).** A compiler as *many small passes* over *formally
|
||||
specified* intermediate languages, with autogenerated boilerplate to recur
|
||||
through unchanged forms and checks that each pass's output matches its grammar.
|
||||
The lesson for "grow the language as it compiles itself": keep passes small and
|
||||
IRs explicit so adding a form is local and verifiable.
|
||||
- **Guile.** A Lisp on a bytecode VM: source → Tree-IL (high-level IR) → CPS
|
||||
(optimization IR) → VM bytecode, with several front-end languages targeting
|
||||
Tree-IL. The closest analog to "Lisp → bytecode on a VM."
|
||||
|
||||
## Assessment: is the current approach the right one?
|
||||
|
||||
The overall *shape* is right and matches ClojureScript: front-end (analyze →
|
||||
emit) with the host VM as the backend, emitting host forms that the host compiles
|
||||
to bytecode. Two things need to change to reach the goal:
|
||||
|
||||
1. **Late binding for globals.** Compile a reference to a Jolt var as a **deref
|
||||
through the var cell**, not as a Janet symbol. Jolt vars are already cells
|
||||
(`{:jolt/type :jolt/var :root …}`); a compiled global call becomes roughly
|
||||
`((var-root cell) args…)` instead of `(janet-symbol args…)`. Redefinition
|
||||
updates the cell's root, so compiled callers see it — exactly Clojure's model.
|
||||
One indirection per global call; locals and control flow stay direct and fast.
|
||||
Offer opt-in **direct linking** for hot/AOT code that doesn't need redefinition.
|
||||
2. **Move the compiler and core into Clojure.** Today both are Janet. Self-hosting
|
||||
means the compiler is Clojure compiled by Jolt, and most of `clojure.core` is
|
||||
Clojure. That's the bulk of the work and where the "language builds itself"
|
||||
payoff lives.
|
||||
|
||||
So: keep the emit-to-Janet target (it's correct and gives us bytecode + AOT for
|
||||
free), fix global binding, and progressively self-host.
|
||||
|
||||
## Recommended architecture
|
||||
|
||||
**Pipeline (nanopass-lite).** Keep the data-driven `:op` AST and grow it as small,
|
||||
named passes rather than one big walker:
|
||||
|
||||
1. *read* — reader → forms (already have it).
|
||||
2. *macroexpand* — fully expand to special forms + calls (the interpreter already
|
||||
expands; share one expander).
|
||||
3. *analyze* — forms → AST, resolving locals vs vars and tagging ops.
|
||||
4. *(optional) optimize* — constant-fold, direct-link hot calls, etc.
|
||||
5. *emit* — AST → Janet form, with globals as var-cell derefs.
|
||||
6. *compile* — Janet `compile` → bytecode; `make-image` for AOT.
|
||||
|
||||
Make each pass total over the IR so an unhandled node is an explicit gap, not a
|
||||
silent miss.
|
||||
|
||||
**The kernel (minimal Janet bootstrap).** The irreducible base that must exist in
|
||||
the host before any Clojure can run: the reader; the value/representation layer
|
||||
(vars, namespaces, symbols, keywords, persistent collections, chars); host
|
||||
interop (the `janet.*` bridge); `fn`/`if`/`do`/`let`/`quote`/`def`/`loop`/`recur`
|
||||
evaluation; and `compile`/`eval`. Everything else — the rest of `clojure.core`,
|
||||
the macros, and the compiler — is Clojure loaded and (eventually) compiled by the
|
||||
kernel. Today the kernel is far larger than this; shrinking it is a long game.
|
||||
|
||||
**Hybrid interpret/compile (Phase 3, and a bootstrap safety net).** When a pass
|
||||
can't yet compile a sub-form, emit a call back into the interpreter (`eval-form`)
|
||||
for that sub-form instead of erroring. This lets the compiler be incomplete and
|
||||
still correct (hot paths compile, cold/unsupported paths interpret), lets us grow
|
||||
coverage incrementally, and de-risks the self-hosting bootstrap.
|
||||
|
||||
**Live flexibility.** Vars stay first-class cells; compiled code derefs them;
|
||||
`def` updates the root; protocol/multimethod dispatch stays dynamic. Direct
|
||||
linking seals a call against redefinition, so the interactive modes — the REPL,
|
||||
`-e`, the nREPL server — always stay live (indirect). Running a *program* (a
|
||||
file, `-m`/`-M`) direct-links by default, since it's a closed world; opt back out
|
||||
with `JOLT_NO_DIRECT_LINK`. (See RFC 0005, "Compilation modes and defaults".)
|
||||
|
||||
## A staged path
|
||||
|
||||
1. **Var-indirection in the emitter** — *done*. Global refs compile as var-cell
|
||||
derefs, so a compiled `defn` is redefinable at the REPL.
|
||||
2. **Hybrid fallback + coverage** (`jolt-1bj`) — *done*. Forms the compiler can't
|
||||
compile throw `jolt/uncompilable` and fall back to the interpreter, so compile
|
||||
mode is always correct. Covered: multi-arity/named/variadic fns, `recur` in
|
||||
`fn`, map/vector literals, and resolution matching the interpreter.
|
||||
Destructuring compiles via the shared `destructure` expander: the `fn`/`let`/
|
||||
`loop`/`defn` macros desugar to plain-symbol `fn*`/`let*`/`loop*`, so it no
|
||||
longer falls back — and the primitives reject patterns outright, matching
|
||||
Clojure (`jolt-f79`).
|
||||
5. **Compile-by-default + AOT** (`jolt-7j9`) — *done, done out of order*. Once the
|
||||
hybrid path was validated at parity, compilation was flipped on by default and
|
||||
AOT images (`aot.janet`) landed. Done before 3–4 because it's the runtime
|
||||
payoff and only needed the hybrid path to be correct, not self-hosting.
|
||||
3. **Self-host the compiler** (`jolt-lcn`) — *open*. Rewrite `compiler.janet` as
|
||||
Clojure (`jolt.compiler`) that Jolt compiles. Now the compiler is part of the
|
||||
language it compiles.
|
||||
4. **Shrink the kernel / core-in-Clojure** (`jolt-uqi`) — *open*. Move
|
||||
`clojure.core` from Janet to Clojure incrementally, each piece compiled by the
|
||||
previous stage — the language building itself — leaving a minimal Janet kernel.
|
||||
|
||||
What remains (3 and 4) is the actual Clojure-in-Clojure rewrite: the largest part
|
||||
of the work and where the "language builds itself" payoff lives. The correctness
|
||||
and runtime foundations it needs — redefinable compiled code, an always-correct
|
||||
hybrid path, compile-by-default, and AOT — are now in place.
|
||||
|
|
@ -68,8 +68,9 @@ Behavioral questions are settled in this order: differential testing against
|
|||
the reference implementation → cross-dialect agreement in clojure-test-suite
|
||||
→ ClojureDocs community examples (verified before inclusion) → reference
|
||||
source (for intent). Conformance tests live in this repository
|
||||
(`test/integration/conformance-test.janet` runs each assertion through three
|
||||
independent execution paths) and in the cross-dialect clojure-test-suite.
|
||||
(the corpus `test/chez/corpus.edn`, run on Chez via `host/chez/run-corpus.ss`
|
||||
and certified against reference JVM Clojure by `test/conformance/certify.clj`)
|
||||
and in the cross-dialect clojure-test-suite.
|
||||
|
||||
## 5. Chapter plan
|
||||
|
||||
|
|
|
|||
|
|
@ -43,7 +43,10 @@ exponent := [eE] ['+'|'-'] digits
|
|||
- S5. Trailing `N` (BigInt) and `M` (BigDecimal) suffixes are part of the
|
||||
grammar; their value semantics are the §4 numeric-tower question.
|
||||
Implementations without those towers SHOULD read them as the nearest
|
||||
numeric type and MUST document the choice.
|
||||
numeric type and MUST document the choice. The Chez host carries the full
|
||||
tower: `N` reads as an exact integer (arbitrary precision) and `M` as a real
|
||||
BigDecimal — `1.5M`, `0.0M`, `3M` — with value equality ignoring scale
|
||||
(`1.0M = 1.00M`), `(class 1.5M)` ⇒ `java.math.BigDecimal`, and `decimal?` true.
|
||||
|
||||
### Symbols and keywords
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,17 @@ syntax is specified here, their behavior is host-defined.
|
|||
|
||||
Special-form head symbols are not shadowable: a binding named `if` does not
|
||||
change the meaning of `(if ...)` in operator position. ⚠ This matches the
|
||||
reference; it differs from Scheme.
|
||||
reference; it differs from Scheme. A local *may* legally be named like a special
|
||||
form and used in value position (`(let [if 5] if)` ⇒ `5`); only operator
|
||||
position is reserved. **Macros, unlike special forms, ARE shadowable** by a local
|
||||
(`(let [when (fn ...)] (when 1 2))` calls the local).
|
||||
|
||||
A list form in operator position is resolved in this order (the canonical
|
||||
read → **macroexpand** → analyze pipeline): a local binding shadows everything;
|
||||
otherwise a macro head is expanded and the result re-analyzed; otherwise a
|
||||
special-form head is parsed by rule; otherwise the form is a function
|
||||
application. Macroexpansion therefore happens *before* special-form dispatch, so
|
||||
a macro is never mistaken for a special form (and vice versa).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -135,10 +145,11 @@ S1–S3, E1 → jolt `forms-spec` let group; clojure-test-suite
|
|||
| `do` | empty `(do)` → nil; top-level `do` splices for compilation units (important and under-documented) |
|
||||
| `fn*` | arities, variadic `&`, closure capture, self-name, simple-symbol params only, recur target |
|
||||
| `loop*` | recur arity must match bindings; recur rebinds in place |
|
||||
| `letfn` | mutually-recursive local fns (`letrec*` semantics — a fn body sees every binding, not only earlier ones). jolt treats `letfn` as a primitive special, not the reference's `letfn` macro → `letfn*` indirection; behavior is identical |
|
||||
| `recur` | tail-position rule (normative definition of tail position needed), across `if`/`do`/`let*`/`try` interactions |
|
||||
| `quote` | self-evaluation table: which literals are self-evaluating unquoted |
|
||||
| `var` | `#'` reader sugar; resolution at compile time |
|
||||
| `throw` | any value vs Throwable — host question; jolt/cljs allow data, reference requires Throwable → classification needed |
|
||||
| `try/catch/finally` | catch dispatch order, `:default`-style catch-all is a dialect extension (⚠ divergence note), finally evaluation guarantees, value of try |
|
||||
| `set!` | host-dependent (dynamic vars + host fields) |
|
||||
| `set!` | three targets, all implemented: `(set! *var* val)` sets the var's innermost thread binding (else root); `(set! field val)` inside a `deftype` method mutates a `^:unsynchronized-mutable`/`^:volatile-mutable` field in place; `(set! (.-field obj) val)` does the same via interop syntax. Returns val |
|
||||
| `.` / `new` | syntax only; behavior host-defined |
|
||||
|
|
|
|||
|
|
@ -38,10 +38,13 @@ Of the 694 `clojure.core` vars in the ClojureDocs inventory:
|
|||
|
||||
## How this connects to the test suites
|
||||
|
||||
- `test/integration/conformance-test.janet` — 302 assertions, each run
|
||||
through three independent execution paths (interpreter, bootstrap
|
||||
compiler, self-hosted compiler) that must agree. Spec entries cite these.
|
||||
- `test/spec/*.janet` — ~1,500 behavioral cases organized by topic.
|
||||
- `test/chez/corpus.edn` — the host-neutral behavioral corpus, one row per
|
||||
case (`{:suite :label :expected :actual}`). The Chez compiler evaluates each
|
||||
case via `host/chez/run-corpus.ss` (run with `make corpus`), and
|
||||
`test/conformance/certify.clj` certifies every `:expected` against reference
|
||||
JVM Clojure (run with `make certify`). Spec entries cite these cases.
|
||||
- `test/conformance/` — the certification tooling and classified divergences
|
||||
(`certify.clj`, `known-divergences.edn`); see its `README.md` and `SPEC.md`.
|
||||
- `vendor/clojure-test-suite` — the cross-dialect suite (≥4081 assertions
|
||||
passing); dialect splits there are classification evidence.
|
||||
- jank's per-construct corpus (`~/src/jank/compiler+runtime/test/jank`) is
|
||||
|
|
|
|||
|
|
@ -9,91 +9,57 @@ Scope, decided up front:
|
|||
- **pure `clj`/`cljc`** — anything needing the JVM won't load or run; expected.
|
||||
- **no classpath abstraction** — `require` just needs to find a dep's namespaces;
|
||||
"the classpath" is an ordered list of source directories.
|
||||
- **piggyback on jpm** — reuse jpm's git fetch + cache; don't write a package
|
||||
manager.
|
||||
- **own resolver, own reader** — `deps.edn` is read by jolt's own reader, and git
|
||||
fetch/cache is a thin shell-out to `git`; no external package manager.
|
||||
- **deps-agnostic runtime core** — resolution is a CLI front-end concern, not a
|
||||
runtime one. The `jolt` *runtime* knows nothing about deps.edn; it only reads
|
||||
source roots from `JOLT_PATH`. The `jolt` *CLI* resolves a deps.edn into that
|
||||
env var before running, in a module (`deps.janet`) that loads `jpm` lazily.
|
||||
(This was a separate `jolt-deps` binary originally; it was folded into `jolt`
|
||||
for a single-binary UX — the code boundary stayed, only the executable merged.
|
||||
A back-compat `jolt-deps` shim still ships and forwards to `jolt`.)
|
||||
runtime one. The runtime knows nothing about `deps.edn`; it only consumes a
|
||||
list of source roots. The CLI resolves a `deps.edn` into those roots before
|
||||
running.
|
||||
|
||||
## How jpm handles dependencies
|
||||
## How resolution works
|
||||
|
||||
jpm's package code (`jpm/pm.janet`) splits into a fetch half and a build half,
|
||||
and we use only the first:
|
||||
`jolt.deps` (`jolt-core/jolt/deps.clj`) reads `deps.edn` (jolt's own reader
|
||||
parses the EDN), then walks `:deps`:
|
||||
|
||||
- **`resolve-bundle`** normalizes a dep spec to `{:url :tag :type :shallow}`,
|
||||
accepting `:url`/`:repo` + `:tag`/`:sha`/`:commit`/`:ref`. A deps.edn
|
||||
`{:git/url … :git/sha …}` maps straight onto it.
|
||||
- **`download-bundle url :git tag shallow`** clones into a content-addressed cache
|
||||
(`<modpath>/.cache/git_<tag>_<sanitized-url>`) and returns the path —
|
||||
`git init` + `remote add` + fetch + reset, plus submodules. No build step.
|
||||
- **`bundle-install`** is the half we skip: it then runs `project.janet` build
|
||||
rules, which a Clojure lib doesn't have. It's cleanly separable from the clone.
|
||||
|
||||
So jpm gives us git resolution and a cache for free; calling `download-bundle`
|
||||
needs `jpm/config/load-default` first (it sets `gitpath` and the cache dyns).
|
||||
|
||||
## How it works
|
||||
|
||||
`src/jolt/deps.janet` reads `deps.edn` (Janet parses it directly — EDN and Janet
|
||||
syntax overlap for the `:deps`/`:paths` subset), then walks `:deps`:
|
||||
|
||||
- `:git/url` (+ `:git/sha` or `:git/tag`) → `resolve-bundle` + `download-bundle`
|
||||
into `jpm_tree/.cache`;
|
||||
- `:git/url` + `:git/sha` (+ optional `:deps/root`) → clone the sha into the git
|
||||
cache and contribute the checkout (or its `:deps/root` subdir);
|
||||
- `:local/root` → the path as-is;
|
||||
- `:mvn/*` and anything else → ignored.
|
||||
- `:mvn/*` → skipped with a warning;
|
||||
- anything else → ignored.
|
||||
|
||||
git resolution shells out to `git` through `jolt.host/sh` — `git init` + remote
|
||||
add + fetch + reset at the requested sha. Clones land in a global, sha-immutable
|
||||
cache (`$JOLT_GITLIBS`, else `~/.jolt/gitlibs`) shared across projects, the
|
||||
`tools.gitlibs` `~/.gitlibs` model.
|
||||
|
||||
Each resolved dependency contributes its own `:paths` (default `["src"]`) as
|
||||
source roots; the walk is **breadth-first** so every top-level coordinate
|
||||
registers before any transitive one — a top-level pin always wins, matching
|
||||
tools.deps, and a coordinate conflict warns on stderr naming both. The result
|
||||
is a de-duplicated, ordered list of directories. `resolve-deps-cached` memoizes
|
||||
that list in the project-local `.cpcache/jolt-deps.jdn`, keyed on a hash of the
|
||||
project `deps.edn` + the user-level `deps.edn` + the selected aliases. jpm is
|
||||
loaded lazily (`require`, not `import`) so it's pulled in only when resolving —
|
||||
never embedded in a built binary.
|
||||
tools.deps. The result is a de-duplicated, ordered list of directories.
|
||||
|
||||
Three tools.deps features are mirrored in reduced form. **Aliases**: `:aliases`
|
||||
Two tools.deps features are mirrored in reduced form. **Aliases**: `:aliases`
|
||||
entries supply `:extra-paths`/`:extra-deps` (accumulate across the aliases
|
||||
selected with `-A:a:b`) and `:main-opts` (last-wins, run with `-M:alias`).
|
||||
**User config**: a `deps.edn` under `$JOLT_CONFIG` (else
|
||||
`$XDG_CONFIG_HOME/jolt`, else `~/.jolt`) merges beneath the project file,
|
||||
per key, project wins. **Tasks**: the honest subset of babashka's — a string
|
||||
task is a shell command, a map task is `{:main-opts […] :doc "…"}`; bare
|
||||
Clojure expressions aren't supported because the reader hands back parsed
|
||||
data, and round-tripping it to source isn't worth the fragility.
|
||||
**Tasks**: the honest subset of babashka's — a string task is a shell command, a
|
||||
map task is `{:main-opts […]}`; bare Clojure expressions aren't a separate task
|
||||
form.
|
||||
|
||||
Clones default to a global sha-immutable cache (`$JOLT_GITLIBS`, else
|
||||
`<config-dir>/gitlibs`) shared across projects, the `tools.gitlibs`
|
||||
`~/.gitlibs` model; per-project trees remain available by passing `tree`
|
||||
explicitly.
|
||||
## How the CLI ties it together
|
||||
|
||||
The loader (`evaluator.janet/find-ns-file`) resolves a namespace by searching the
|
||||
context's `:source-paths` in order (the stdlib `src/jolt` first), trying `<ns>.clj`
|
||||
then `<ns>.cljc`. Extra roots come from `JOLT_PATH` or `init`'s `:paths` option.
|
||||
`jolt.main` (`jolt-core/jolt/main.clj`) is the CLI dispatch. Driven by `cli.ss`,
|
||||
it resolves the project (`jolt.deps/resolve-project`), prepends the resolved
|
||||
roots, and de-sugars the argv into a run:
|
||||
|
||||
The `jolt` CLI (`src/jolt/main.janet`, `resolve-deps-argv`) ties it together: on
|
||||
a deps subcommand — or any runnable command in a directory that has a `deps.edn`
|
||||
— it resolves the roots, sets `JOLT_PATH`/`JOLT_APP_PATHS`, and de-sugars the
|
||||
argv into a plain runtime command (`-M:alias` → the alias `:main-opts`, `run
|
||||
FILE` → `FILE`, …) that the normal dispatch then runs. `main.janet` imports
|
||||
`deps.janet`, so the resolver ships in the `jolt` binary; but `deps.janet` loads
|
||||
`jpm` lazily, and the runtime modules (`api`/`backend`/RT) never import it, so an
|
||||
app baked from its own `jolt/api` entry doesn't link it. The runtime's only
|
||||
dependency interface remains that one env var.
|
||||
- `run -m NS args` → load `NS`, call its `-main`;
|
||||
- `run FILE` → load the file;
|
||||
- `-M:alias` → run the alias's `:main-opts`;
|
||||
- `-A:alias` → add the alias's paths/deps, then run the rest;
|
||||
- `repl` → a line REPL;
|
||||
- `path` → print the resolved roots;
|
||||
- `<task>` → run a `deps.edn` `:tasks` entry.
|
||||
|
||||
`jolt uberscript` bundles a namespace and everything it requires into one
|
||||
standalone `.clj`. It requires the entry namespace and uses the order in which
|
||||
the loader finishes loading files — a dependency finishes before the file that
|
||||
required it, so the order is topological — then concatenates that source. The
|
||||
baked-in stdlib is excluded (it's part of the runtime, not bundled).
|
||||
|
||||
Gotcha worth remembering: the `jolt` CLI's context is built into its image at
|
||||
build time, so `JOLT_PATH` is applied at runtime in `main`, not in `init` (whose
|
||||
env read would be frozen at build).
|
||||
The resolver lives in the overlay alongside the runtime, but the runtime's only
|
||||
dependency interface is the list of source roots it's handed.
|
||||
|
||||
## Limitations
|
||||
|
||||
|
|
@ -105,35 +71,9 @@ env read would be frozen at build).
|
|||
|
||||
## Conformance
|
||||
|
||||
`test/integration/deps-conformance-test.janet` resolves a few real pure-`cljc`
|
||||
git libraries and reports whether their namespaces load and a sample call works.
|
||||
It's network-gated behind `JOLT_CONFORMANCE=1` so CI stays offline. Use it to
|
||||
check a library against the current interpreter, and to drive fixes for whatever
|
||||
gap a failure points at (the same loop as the clojure-test-suite battery). A
|
||||
library fails when it relies on something Jolt doesn't provide — JVM interop, or
|
||||
a regex feature like Unicode property classes (`\p{…}`).
|
||||
|
||||
## Not yet
|
||||
|
||||
- **Compiling deps into a binary image.** `uberscript` already produces a
|
||||
standalone `.clj`; baking a project's dependencies directly into a custom
|
||||
executable image is a heavier variant that isn't implemented.
|
||||
|
||||
## Janet dependencies: `:jpm/module`
|
||||
|
||||
A jolt project can depend on janet libraries. jpm owns their installation;
|
||||
`deps.edn` declares the requirement and `jolt` verifies it at resolve time:
|
||||
|
||||
```clojure
|
||||
:deps {janet/spork-http {:jpm/module "spork/http"
|
||||
:jpm/install "spork"}}
|
||||
```
|
||||
|
||||
- `:jpm/module` — the janet module path that must be importable.
|
||||
- `:jpm/install` (optional) — the jpm package to install when it isn't;
|
||||
`jolt` runs `jpm install <name>` once, then re-checks. Without it the resolve
|
||||
fails with the install hint.
|
||||
|
||||
A `:jpm/module` dep contributes no source roots. At runtime the `janet.*`
|
||||
interop bridge autoloads the module on first reference
|
||||
(`janet.spork.http/server`, …), so nothing else is needed.
|
||||
The known-working libraries (see [libraries.md](libraries.md)) and the
|
||||
[examples](https://github.com/jolt-lang/examples) exercise real pure-`cljc` git
|
||||
libraries end to end — resolving them from git, loading their namespaces, and
|
||||
running sample calls. A library fails when it relies on something Jolt doesn't
|
||||
provide — JVM interop, or a regex feature like Unicode property classes
|
||||
(`\p{…}`).
|
||||
|
|
|
|||
216
host/chez/async.ss
Normal file
216
host/chez/async.ss
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
;; async.ss (jolt-byjr) — clojure.core.async on real OS threads for the Chez host.
|
||||
;;
|
||||
;; No mature Chez fibers library exists, and this Chez is a threaded build, so a
|
||||
;; `go` block is just an OS thread and a channel is a mutex+condition blocking
|
||||
;; queue: <! / >! are the blocking <!! / >!! (they "park" by blocking the thread).
|
||||
;; <! / >! work ANYWHERE (no CPS transform) —
|
||||
;; here because they are ordinary blocking calls. Real parallelism, shared heap.
|
||||
;; Trade-off: one OS thread per go block (fine for typical use / conformance, not
|
||||
;; for thousands of simultaneous go blocks).
|
||||
;;
|
||||
;; Channel: an unbuffered channel is a rendezvous (the putter blocks until its
|
||||
;; value is taken); a buffered (chan n) put blocks only when full; dropping/sliding
|
||||
;; buffers never block the putter. A transducer is applied on the put side.
|
||||
;;
|
||||
;; The fns are def-var!'d into clojure.core.async; go/go-loop/thread are macros
|
||||
;; (mark-macro!) expanding to go-spawn. Loaded after
|
||||
;; concurrency.ss (reuses ms->duration). Requires a threaded Chez build.
|
||||
|
||||
;; --- buffers ----------------------------------------------------------------
|
||||
(define-record-type async-buffer (fields n kind) (nongenerative async-buffer-v1))
|
||||
(define (jolt-async-buffer n) (make-async-buffer n 'fixed))
|
||||
(define (jolt-async-dropping-buffer n) (make-async-buffer n 'dropping))
|
||||
(define (jolt-async-sliding-buffer n) (make-async-buffer n 'sliding))
|
||||
|
||||
;; --- channels ---------------------------------------------------------------
|
||||
;; items: a FIFO list of (value . box); box is #f for a buffered value or a 1-slot
|
||||
;; vector for an unbuffered rendezvous put (set #t when taken, waking the putter).
|
||||
;; cap 0 + kind 'unbuffered = rendezvous; cap>0 with kind fixed/dropping/sliding.
|
||||
(define-record-type async-chan
|
||||
(fields mu cv (mutable items) cap kind (mutable closed?) (mutable xrf))
|
||||
(nongenerative async-chan-v1))
|
||||
|
||||
(define (ac-qlen ch) (length (async-chan-items ch)))
|
||||
(define (ac-qempty? ch) (null? (async-chan-items ch)))
|
||||
(define (ac-qpush! ch entry) (async-chan-items-set! ch (append (async-chan-items ch) (list entry))))
|
||||
(define (ac-qpop! ch)
|
||||
(let ((e (car (async-chan-items ch))))
|
||||
(async-chan-items-set! ch (cdr (async-chan-items ch))) e))
|
||||
(define (ac-qdrop-oldest! ch) (async-chan-items-set! ch (cdr (async-chan-items ch))))
|
||||
|
||||
;; enqueue honoring the buffer kind (used by the transducer step + buffered puts).
|
||||
(define (ac-buf-give! ch v)
|
||||
(case (async-chan-kind ch)
|
||||
((dropping) (when (< (ac-qlen ch) (async-chan-cap ch)) (ac-qpush! ch (cons v #f))))
|
||||
((sliding) (when (>= (ac-qlen ch) (async-chan-cap ch)) (ac-qdrop-oldest! ch))
|
||||
(ac-qpush! ch (cons v #f)))
|
||||
(else (ac-qpush! ch (cons v #f)))) ; fixed: caller ensured room
|
||||
(condition-broadcast (async-chan-cv ch)))
|
||||
|
||||
;; A transducer is a jolt fn (xform); (xform add-rf) yields the channel's reducing
|
||||
;; fn. add-rf: 0-arg init, 1-arg completion, 2-arg step (enqueue the output). A
|
||||
;; `reduced` step result closes the channel.
|
||||
(define (ac-make-add-rf ch)
|
||||
(lambda args
|
||||
(cond ((null? args) ch) ; init
|
||||
((null? (cdr args)) (car args)) ; completion
|
||||
(else (ac-buf-give! ch (cadr args)) (car args))))) ; step
|
||||
|
||||
(define (ac-make cap kind xrf) (make-async-chan (make-mutex) (make-condition) '() cap kind #f xrf))
|
||||
|
||||
;; (chan) | (chan n) | (chan buf) | (chan n|buf xform)
|
||||
(define (jolt-async-chan . args)
|
||||
(let ((buf (if (pair? args) (car args) jolt-nil))
|
||||
(xform (if (and (pair? args) (pair? (cdr args))) (cadr args) jolt-nil)))
|
||||
(let-values (((cap kind)
|
||||
(cond ((async-buffer? buf) (values (async-buffer-n buf) (async-buffer-kind buf)))
|
||||
((and (number? buf) (> buf 0)) (values buf 'fixed))
|
||||
(else (values 0 'unbuffered)))))
|
||||
(let ((ch (ac-make cap kind #f)))
|
||||
(unless (jolt-nil? xform)
|
||||
(async-chan-xrf-set! ch (jolt-invoke xform (ac-make-add-rf ch))))
|
||||
ch))))
|
||||
|
||||
;; close! (idempotent): mark closed, flush a stateful transducer's completion, and
|
||||
;; wake everyone. ac-close! assumes the lock is held; the public form takes it.
|
||||
(define (ac-close! ch)
|
||||
(unless (async-chan-closed? ch)
|
||||
(async-chan-closed?-set! ch #t)
|
||||
(when (async-chan-xrf ch) (guard (e (#t #f)) (jolt-invoke (async-chan-xrf ch) ch)))
|
||||
(condition-broadcast (async-chan-cv ch)))
|
||||
jolt-nil)
|
||||
(define (jolt-async-close! ch) (with-mutex (async-chan-mu ch) (ac-close! ch)))
|
||||
|
||||
;; >! / >!! — put, blocking. false if closed; nil may not be put. With a
|
||||
;; transducer the value is run through it (one put -> zero or more channel values);
|
||||
;; a `reduced` result closes the channel.
|
||||
(define (jolt-async-give ch v)
|
||||
(when (jolt-nil? v) (jolt-throw (jolt-ex-info "Can't put nil on a channel" (jolt-hash-map))))
|
||||
(with-mutex (async-chan-mu ch)
|
||||
(cond
|
||||
((async-chan-closed? ch) #f)
|
||||
((async-chan-xrf ch)
|
||||
(let ((r (jolt-invoke (async-chan-xrf ch) ch v)))
|
||||
(when (jolt-reduced? r) (ac-close! ch))
|
||||
#t))
|
||||
(else
|
||||
(case (async-chan-kind ch)
|
||||
((dropping sliding) (ac-buf-give! ch v) #t)
|
||||
(else
|
||||
(if (> (async-chan-cap ch) 0)
|
||||
(let loop () ; buffered fixed: wait for room
|
||||
(cond ((async-chan-closed? ch) #f)
|
||||
((< (ac-qlen ch) (async-chan-cap ch))
|
||||
(ac-qpush! ch (cons v #f)) (condition-broadcast (async-chan-cv ch)) #t)
|
||||
(else (condition-wait (async-chan-cv ch) (async-chan-mu ch)) (loop))))
|
||||
(let ((box (vector #f))) ; unbuffered: rendezvous
|
||||
(ac-qpush! ch (cons v box))
|
||||
(condition-broadcast (async-chan-cv ch))
|
||||
(let loop ()
|
||||
(cond ((vector-ref box 0) #t)
|
||||
((async-chan-closed? ch) #f)
|
||||
(else (condition-wait (async-chan-cv ch) (async-chan-mu ch)) (loop))))))))))))
|
||||
|
||||
;; remove + return the head value, waking a parked rendezvous putter.
|
||||
(define (ac-take-head! ch)
|
||||
(let* ((entry (ac-qpop! ch)) (v (car entry)) (box (cdr entry)))
|
||||
(when box (vector-set! box 0 #t))
|
||||
(condition-broadcast (async-chan-cv ch))
|
||||
v))
|
||||
|
||||
;; <! / <!! — take, blocking. Drains buffered values, then nil once closed + empty.
|
||||
(define (jolt-async-take ch)
|
||||
(with-mutex (async-chan-mu ch)
|
||||
(let loop ()
|
||||
(cond ((not (ac-qempty? ch)) (ac-take-head! ch))
|
||||
((async-chan-closed? ch) jolt-nil)
|
||||
(else (condition-wait (async-chan-cv ch) (async-chan-mu ch)) (loop))))))
|
||||
|
||||
;; non-blocking take for alts!: a value, jolt-nil (closed+empty), or ac-poll-empty.
|
||||
(define ac-poll-empty (list 'empty))
|
||||
(define (ac-poll! ch)
|
||||
(with-mutex (async-chan-mu ch)
|
||||
(cond ((not (ac-qempty? ch)) (ac-take-head! ch))
|
||||
((async-chan-closed? ch) jolt-nil)
|
||||
(else ac-poll-empty))))
|
||||
|
||||
;; (alts! [ch ...]) — take from whichever channel is ready first; returns
|
||||
;; [value channel] (value nil if that channel closed). Take-only.
|
||||
;; Polls with a 1ms backoff — no cross-channel wait-set yet.
|
||||
(define ac-1ms (make-time 'time-duration 1000000 0))
|
||||
(define (jolt-async-alts chans)
|
||||
(let ((cs (seq->list (jolt-seq chans))))
|
||||
(let loop ()
|
||||
(let try ((rest cs))
|
||||
(if (null? rest)
|
||||
(begin (sleep ac-1ms) (loop))
|
||||
(let ((r (ac-poll! (car rest))))
|
||||
(if (eq? r ac-poll-empty)
|
||||
(try (cdr rest))
|
||||
(jolt-vector r (car rest)))))))))
|
||||
|
||||
;; (timeout ms) — a channel that closes after ms milliseconds.
|
||||
(define (jolt-async-timeout ms)
|
||||
(let ((w (ac-make 0 'unbuffered #f)))
|
||||
(fork-thread (lambda () (sleep (ms->duration ms)) (jolt-async-close! w)))
|
||||
w))
|
||||
|
||||
;; (put! ch v [cb]) / (take! ch cb) — async put/take on a thread, optional callback.
|
||||
(define (jolt-async-put! ch v . cb)
|
||||
(fork-thread (lambda ()
|
||||
(let ((ok (jolt-async-give ch v)))
|
||||
(when (and (pair? cb) (not (jolt-nil? (car cb)))) (jolt-invoke (car cb) ok)))))
|
||||
jolt-nil)
|
||||
(define (jolt-async-take! ch cb)
|
||||
(fork-thread (lambda ()
|
||||
(let ((v (jolt-async-take ch)))
|
||||
(unless (jolt-nil? cb) (jolt-invoke cb v)))))
|
||||
jolt-nil)
|
||||
|
||||
;; (go-spawn thunk) — run thunk on a thread; return a buffered(1) channel that
|
||||
;; conveys its value once then closes (a nil result just closes). Dynamic bindings
|
||||
;; are conveyed (Chez inherits the thread-parameter at fork; we install explicitly).
|
||||
(define (async-go-spawn thunk)
|
||||
(let ((w (ac-make 1 'fixed #f)) (snap (dyn-binding-stack)))
|
||||
(fork-thread
|
||||
(lambda ()
|
||||
(dyn-binding-stack snap)
|
||||
(let ((r (guard (e (#t (cons #f e))) (cons #t (jolt-invoke thunk)))))
|
||||
(when (and (car r) (not (jolt-nil? (cdr r)))) (jolt-async-give w (cdr r)))
|
||||
(jolt-async-close! w))))
|
||||
w))
|
||||
|
||||
;; --- macros (expander fns over the reader forms) ----------------------------
|
||||
(define cca-go-spawn-sym (jolt-symbol "clojure.core.async" "go-spawn"))
|
||||
(define cca-go-sym (jolt-symbol "clojure.core.async" "go"))
|
||||
(define cca-fn*-sym (jolt-symbol #f "fn*"))
|
||||
(define cca-loop-sym (jolt-symbol #f "loop"))
|
||||
|
||||
;; (go body...) -> (clojure.core.async/go-spawn (fn* [] body...))
|
||||
(define (cca-go-macro . body)
|
||||
(jolt-list cca-go-spawn-sym (apply jolt-list cca-fn*-sym empty-pvec body)))
|
||||
;; (go-loop bindings body...) -> (go (loop bindings body...))
|
||||
(define (cca-go-loop-macro bindings . body)
|
||||
(jolt-list cca-go-sym (apply jolt-list cca-loop-sym bindings body)))
|
||||
;; (thread body...) — a real OS thread (same shape as go here).
|
||||
(define (cca-thread-macro . body)
|
||||
(jolt-list cca-go-spawn-sym (apply jolt-list cca-fn*-sym empty-pvec body)))
|
||||
|
||||
;; --- install clojure.core.async ---------------------------------------------
|
||||
(define (cca-def! name v) (def-var! "clojure.core.async" name v))
|
||||
(cca-def! "chan" jolt-async-chan)
|
||||
(cca-def! "chan?" async-chan?)
|
||||
(cca-def! "buffer" jolt-async-buffer)
|
||||
(cca-def! "dropping-buffer" jolt-async-dropping-buffer)
|
||||
(cca-def! "sliding-buffer" jolt-async-sliding-buffer)
|
||||
(cca-def! "close!" jolt-async-close!)
|
||||
(cca-def! "<!" jolt-async-take) (cca-def! "<!!" jolt-async-take)
|
||||
(cca-def! ">!" jolt-async-give) (cca-def! ">!!" jolt-async-give)
|
||||
(cca-def! "alts!" jolt-async-alts) (cca-def! "alts!!" jolt-async-alts)
|
||||
(cca-def! "timeout" jolt-async-timeout)
|
||||
(cca-def! "put!" jolt-async-put!)
|
||||
(cca-def! "take!" jolt-async-take!)
|
||||
(cca-def! "go-spawn" async-go-spawn)
|
||||
(cca-def! "go" cca-go-macro) (mark-macro! "clojure.core.async" "go")
|
||||
(cca-def! "go-loop" cca-go-loop-macro) (mark-macro! "clojure.core.async" "go-loop")
|
||||
(cca-def! "thread" cca-thread-macro) (mark-macro! "clojure.core.async" "thread")
|
||||
146
host/chez/atoms.ss
Normal file
146
host/chez/atoms.ss
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
;; atoms (jolt-9ziu) — host-coupled mutable reference cells for the Chez host.
|
||||
;;
|
||||
;; atom/deref/swap!/reset! are host primitives (not the clojure.core overlay),
|
||||
;; so the Chez runtime provides native shims, def-var!'d into clojure.core. They
|
||||
;; lower to var-deref in prelude mode. The hierarchy machinery
|
||||
;; (global-hierarchy = (atom (make-hierarchy))) calls `atom` at the prelude's
|
||||
;; LOAD time, so without this shim the whole prelude fails to load.
|
||||
;;
|
||||
;; compare-and-set!/swap-vals!/reset-vals! are overlay fns over the native kernel
|
||||
;; in the live system; provided here natively too so the Chez host is
|
||||
;; self-sufficient for atoms without the full prelude (the overlay versions, when
|
||||
;; the full prelude loads, override these but compose the same native kernel).
|
||||
|
||||
;; watches is an alist of (key . watch-fn); validator is a jolt fn or jolt-nil.
|
||||
;; The overlay's add-watch/set-validator! drive these via jolt.host/ref-put! on a
|
||||
;; Janet table, which a Chez atom record is not — so the peripheral ops + the
|
||||
;; notify/validate behaviour live natively here, and post-prelude.ss re-asserts
|
||||
;; them over the overlay's def-var! (jolt-mn9o).
|
||||
;; `lock` (jolt-byjr) is a per-atom mutex guarding the read-modify-write critical
|
||||
;; sections, so swap!/reset!/compare-and-set! are atomic under real OS threads
|
||||
;; (futures/go blocks share the heap on Chez). The user fn in swap! runs OUTSIDE
|
||||
;; the lock (a CAS retry loop, like the JVM) so it never deadlocks on re-entrant
|
||||
;; access and a watch/validator can deref the same atom.
|
||||
(define-record-type jolt-atom
|
||||
(fields (mutable val) (mutable watches) (mutable validator) lock)
|
||||
(nongenerative jolt-atom-v3))
|
||||
|
||||
;; (atom init) / (atom init :validator f :meta m): scan the trailing keyword opts
|
||||
;; for :validator (the only one with runtime behaviour; :meta is accepted/ignored).
|
||||
(define (jolt-atom-new v . opts)
|
||||
(let loop ((o opts) (validator jolt-nil))
|
||||
(cond
|
||||
((or (null? o) (null? (cdr o))) (make-jolt-atom v '() validator (make-mutex)))
|
||||
((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "validator"))
|
||||
(loop (cddr o) (cadr o)))
|
||||
(else (loop (cddr o) validator)))))
|
||||
|
||||
;; validate a candidate value: a non-nil validator that returns falsey rejects.
|
||||
(define (jolt-atom-validate a v)
|
||||
(let ((vf (jolt-atom-validator a)))
|
||||
(when (and (not (jolt-nil? vf)) (jolt-not (jolt-invoke vf v)))
|
||||
(error #f "Invalid reference state"))))
|
||||
|
||||
;; notify each watch (k ref old new), in insertion order (alist is reverse-built,
|
||||
;; so walk it reversed to match add order).
|
||||
(define (jolt-atom-notify a old new)
|
||||
(for-each (lambda (kv) (jolt-invoke (cdr kv) (car kv) a old new))
|
||||
(reverse (jolt-atom-watches a))))
|
||||
|
||||
;; deref reads an atom; it also unwraps a `reduced` (Clojure @(reduced x) => x,
|
||||
;; which the overlay's `unreduced` relies on). The reduced record is in seq.ss.
|
||||
(define (jolt-deref x)
|
||||
(cond
|
||||
((jolt-atom? x) (jolt-atom-val x))
|
||||
((jolt-reduced? x) (jolt-reduced-val x))
|
||||
(else (error #f "deref: unsupported reference type" x))))
|
||||
|
||||
;; CAS the val from `old` to `nv` by identity (eq?), atomically. Returns #t on
|
||||
;; success. The compute step (f) runs outside this, so we re-check under the lock.
|
||||
(define (jolt-atom-cas! a old nv)
|
||||
(with-mutex (jolt-atom-lock a)
|
||||
(if (eq? (jolt-atom-val a) old)
|
||||
(begin (jolt-atom-val-set! a nv) #t)
|
||||
#f)))
|
||||
|
||||
;; (swap! a f arg*): JVM-style CAS loop — read, compute f OUTSIDE the lock, then
|
||||
;; atomically compare-and-set; retry if another thread changed it. Validate the
|
||||
;; new value before storing, notify watches after.
|
||||
(define (jolt-swap! a f . args)
|
||||
(let retry ()
|
||||
(let* ((old (jolt-atom-val a))
|
||||
(nv (apply jolt-invoke f old args)))
|
||||
(jolt-atom-validate a nv)
|
||||
(if (jolt-atom-cas! a old nv)
|
||||
(begin (jolt-atom-notify a old nv) nv)
|
||||
(retry)))))
|
||||
|
||||
(define (jolt-reset! a v)
|
||||
(jolt-atom-validate a v)
|
||||
(let ((old (with-mutex (jolt-atom-lock a)
|
||||
(let ((o (jolt-atom-val a))) (jolt-atom-val-set! a v) o))))
|
||||
(jolt-atom-notify a old v)
|
||||
v))
|
||||
|
||||
;; compare-and-set! keeps jolt= (value) semantics, done atomically under the lock.
|
||||
(define (jolt-compare-and-set! a oldv newv)
|
||||
(jolt-atom-validate a newv)
|
||||
(let ((swapped (with-mutex (jolt-atom-lock a)
|
||||
(if (jolt= (jolt-atom-val a) oldv)
|
||||
(begin (jolt-atom-val-set! a newv) #t)
|
||||
#f))))
|
||||
(when swapped (jolt-atom-notify a oldv newv))
|
||||
swapped))
|
||||
|
||||
(define (jolt-swap-vals! a f . args)
|
||||
(let retry ()
|
||||
(let* ((old (jolt-atom-val a))
|
||||
(nv (apply jolt-invoke f old args)))
|
||||
(jolt-atom-validate a nv)
|
||||
(if (jolt-atom-cas! a old nv)
|
||||
(begin (jolt-atom-notify a old nv) (jolt-vector old nv))
|
||||
(retry)))))
|
||||
|
||||
(define (jolt-reset-vals! a v)
|
||||
(jolt-atom-validate a v)
|
||||
(let ((old (with-mutex (jolt-atom-lock a)
|
||||
(let ((o (jolt-atom-val a))) (jolt-atom-val-set! a v) o))))
|
||||
(jolt-atom-notify a old v)
|
||||
(jolt-vector old v)))
|
||||
|
||||
;; --- watches / validators (jolt-mn9o) ---------------------------------------
|
||||
;; add-watch interns (key . fn) (replacing any existing key, keeping order);
|
||||
;; remove-watch drops it; both return the atom. set-validator! installs a
|
||||
;; validator and validates the CURRENT value immediately (Clojure throws if it's
|
||||
;; already invalid); get-validator reads the slot.
|
||||
(define (jolt-add-watch a key f)
|
||||
(jolt-atom-watches-set! a
|
||||
(cons (cons key f)
|
||||
(remp (lambda (kv) (jolt=2 (car kv) key)) (jolt-atom-watches a))))
|
||||
a)
|
||||
(define (jolt-remove-watch a key)
|
||||
(jolt-atom-watches-set! a
|
||||
(remp (lambda (kv) (jolt=2 (car kv) key)) (jolt-atom-watches a)))
|
||||
a)
|
||||
(define (jolt-set-validator! a f)
|
||||
(let ((vf (if (jolt-nil? f) jolt-nil f)))
|
||||
(when (and (not (jolt-nil? vf)) (jolt-not (jolt-invoke vf (jolt-atom-val a))))
|
||||
(error #f "Invalid reference state"))
|
||||
(jolt-atom-validator-set! a vf)
|
||||
jolt-nil))
|
||||
(define (jolt-get-validator a) (jolt-atom-validator a))
|
||||
|
||||
(def-var! "clojure.core" "atom" jolt-atom-new)
|
||||
(def-var! "clojure.core" "deref" jolt-deref)
|
||||
(def-var! "clojure.core" "swap!" jolt-swap!)
|
||||
(def-var! "clojure.core" "reset!" jolt-reset!)
|
||||
(def-var! "clojure.core" "compare-and-set!" jolt-compare-and-set!)
|
||||
(def-var! "clojure.core" "swap-vals!" jolt-swap-vals!)
|
||||
(def-var! "clojure.core" "reset-vals!" jolt-reset-vals!)
|
||||
(def-var! "clojure.core" "atom?" jolt-atom?)
|
||||
;; peripheral ops: the overlay (20-coll) re-defs these over jolt.host/ref-put!,
|
||||
;; which fails on a Chez atom record — post-prelude.ss re-asserts the natives.
|
||||
(def-var! "clojure.core" "add-watch" jolt-add-watch)
|
||||
(def-var! "clojure.core" "remove-watch" jolt-remove-watch)
|
||||
(def-var! "clojure.core" "set-validator!" jolt-set-validator!)
|
||||
(def-var! "clojure.core" "get-validator" jolt-get-validator)
|
||||
83
host/chez/bigdec.ss
Normal file
83
host/chez/bigdec.ss
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
;; BigDecimal (jolt-i2jm). A jbigdec is {unscaled, scale} over Chez arbitrary-
|
||||
;; precision exact integers; its value is unscaled * 10^-scale (1.5M = {15,1},
|
||||
;; 1.00M = {100,2}, 3M = {3,0}). M-suffix literals read to a :bigdec form that the
|
||||
;; back end lowers to jolt-bigdec-from-string; bigdec coerces a number/string.
|
||||
;; Equality is by value (1.0M = 1.00M), str drops the M, pr keeps it, class is
|
||||
;; java.math.BigDecimal. Arithmetic contagion is not modelled (jolt-i2jm scope).
|
||||
|
||||
(define-record-type jbigdec (fields unscaled scale) (nongenerative chez-jbigdec-v1))
|
||||
|
||||
(define (bd-index-char s ch)
|
||||
(let loop ((i 0))
|
||||
(cond ((>= i (string-length s)) #f)
|
||||
((char=? (string-ref s i) ch) i)
|
||||
(else (loop (+ i 1))))))
|
||||
|
||||
;; "1.50" -> {150,2}; "3" -> {3,0}; "-0.0" -> {0,1}; ".5" -> {5,1}.
|
||||
(define (jolt-bigdec-from-string s)
|
||||
(let* ((neg (and (> (string-length s) 0) (char=? (string-ref s 0) #\-)))
|
||||
(sgn (and (> (string-length s) 0) (or neg (char=? (string-ref s 0) #\+))))
|
||||
(s1 (if sgn (substring s 1 (string-length s)) s))
|
||||
(sign (if neg -1 1))
|
||||
(dot (bd-index-char s1 #\.)))
|
||||
(if dot
|
||||
(let* ((intp (substring s1 0 dot))
|
||||
(fracp (substring s1 (+ dot 1) (string-length s1)))
|
||||
(digs (string-append intp fracp))
|
||||
(unscaled (if (= 0 (string-length digs)) 0 (string->number digs))))
|
||||
(make-jbigdec (* sign unscaled) (string-length fracp)))
|
||||
(make-jbigdec (* sign (string->number s1)) 0))))
|
||||
|
||||
;; bigdec coercion: a bigdec is itself; an exact integer keeps scale 0; a string
|
||||
;; or any other number routes through its decimal text.
|
||||
(define (jolt-bigdec x)
|
||||
(cond
|
||||
((jbigdec? x) x)
|
||||
((and (number? x) (exact? x) (integer? x)) (make-jbigdec x 0))
|
||||
((string? x) (jolt-bigdec-from-string x))
|
||||
((number? x) (jolt-bigdec-from-string (jolt-num->string x)))
|
||||
(else (error #f "bigdec: cannot coerce" x))))
|
||||
|
||||
;; value equality: unscaled_a * 10^scale_b == unscaled_b * 10^scale_a.
|
||||
(define (jbigdec=? a b)
|
||||
(= (* (jbigdec-unscaled a) (expt 10 (jbigdec-scale b)))
|
||||
(* (jbigdec-unscaled b) (expt 10 (jbigdec-scale a)))))
|
||||
|
||||
;; render the decimal text (no M): insert the point `scale` digits from the right.
|
||||
(define (jbigdec->string bd)
|
||||
(let* ((u (jbigdec-unscaled bd)) (sc (jbigdec-scale bd))
|
||||
(neg (< u 0)) (digs (number->string (abs u))))
|
||||
(string-append
|
||||
(if neg "-" "")
|
||||
(if (<= sc 0)
|
||||
digs
|
||||
(let* ((padded (if (<= (string-length digs) sc)
|
||||
(string-append (make-string (- (+ sc 1) (string-length digs)) #\0) digs)
|
||||
digs))
|
||||
(pl (string-length padded)))
|
||||
(string-append (substring padded 0 (- pl sc)) "." (substring padded (- pl sc) pl)))))))
|
||||
|
||||
;; --- wire into the value model ----------------------------------------------
|
||||
(def-var! "clojure.core" "bigdec" jolt-bigdec)
|
||||
|
||||
;; equality: a bigdec equals only another bigdec, by value (matching (= 3M 3) = false).
|
||||
(define %bd-jolt=2 jolt=2)
|
||||
(set! jolt=2 (lambda (a b)
|
||||
(cond ((and (jbigdec? a) (jbigdec? b)) (jbigdec=? a b))
|
||||
((or (jbigdec? a) (jbigdec? b)) #f)
|
||||
(else (%bd-jolt=2 a b)))))
|
||||
|
||||
;; str drops the M; pr/pr-str keep it.
|
||||
(define %bd-str-render jolt-str-render-one)
|
||||
(set! jolt-str-render-one (lambda (x) (if (jbigdec? x) (jbigdec->string x) (%bd-str-render x))))
|
||||
(define %bd-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (jbigdec? x) (string-append (jbigdec->string x) "M") (%bd-pr-str x))))
|
||||
(define %bd-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (jbigdec? x) (string-append (jbigdec->string x) "M") (%bd-pr-readable x))))
|
||||
|
||||
;; class / decimal?
|
||||
(define %bd-class jolt-class)
|
||||
(set! jolt-class (lambda (x) (if (jbigdec? x) "java.math.BigDecimal" (%bd-class x))))
|
||||
(def-var! "clojure.core" "class" jolt-class)
|
||||
(set! jolt-decimal? (lambda (x) (jbigdec? x)))
|
||||
(def-var! "clojure.core" "decimal?" jolt-decimal?)
|
||||
42
host/chez/bootstrap.ss
Normal file
42
host/chez/bootstrap.ss
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
;; bootstrap.ss (jolt-9phg, Phase 3 inc9a) — the pure-Chez self-build.
|
||||
;;
|
||||
;; This is the zero-Janet build step. Given a SEED (prelude, image) pair — the
|
||||
;; bootstrap compiler, minted once via the inc8 fixpoint and checked in under
|
||||
;; host/chez/seed/ — it loads them, then rebuilds the clojure.core prelude AND the
|
||||
;; compiler image from the .clj/.ss sources using the ON-CHEZ compiler (emit-image.ss),
|
||||
;; writing fresh artifacts. No Janet is invoked: read -> analyze -> emit all run on
|
||||
;; Chez. The seed is a JOINT fixpoint, so a rebuild from an up-to-date seed
|
||||
;; reproduces it byte-for-byte (`make selfhost` checks this); when
|
||||
;; the sources change, run it twice to reconverge and re-mint the seed.
|
||||
;;
|
||||
;; Run from the repo root:
|
||||
;; chez --script host/chez/bootstrap.ss SEED-PRELUDE SEED-IMAGE OUT-PRELUDE OUT-IMAGE
|
||||
(import (chezscheme))
|
||||
|
||||
(define bs-args (cdr (command-line))) ; drop the script name
|
||||
(when (< (length bs-args) 4)
|
||||
(display "usage: bootstrap.ss SEED-PRELUDE SEED-IMAGE OUT-PRELUDE OUT-IMAGE\n")
|
||||
(exit 2))
|
||||
(define bs-seed-prelude (list-ref bs-args 0))
|
||||
(define bs-seed-image (list-ref bs-args 1))
|
||||
(define bs-out-prelude (list-ref bs-args 2))
|
||||
(define bs-out-image (list-ref bs-args 3))
|
||||
|
||||
;; Load the runtime + the SEED compiler (prelude for macros, image for the
|
||||
;; analyzer/emitter), exactly as the zero-Janet spine assembles a program.
|
||||
(load "host/chez/rt.ss")
|
||||
(set-chez-ns! "clojure.core")
|
||||
(load bs-seed-prelude)
|
||||
(load "host/chez/post-prelude.ss")
|
||||
(set-chez-ns! "user")
|
||||
(load "host/chez/host-contract.ss")
|
||||
(load bs-seed-image)
|
||||
(load "host/chez/compile-eval.ss")
|
||||
(load "host/chez/emit-image.ss")
|
||||
|
||||
;; Rebuild both artifacts from source ON CHEZ and write them out.
|
||||
(let ((p (open-output-file bs-out-prelude 'replace)))
|
||||
(put-string p (jolt-emit-prelude)) (close-port p))
|
||||
(let ((p (open-output-file bs-out-image 'replace)))
|
||||
(put-string p (jolt-emit-image)) (close-port p))
|
||||
(display "bootstrap: rebuilt prelude + compiler image on Chez (no Janet)\n")
|
||||
70
host/chez/cli.ss
Normal file
70
host/chez/cli.ss
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
;; cli.ss (jolt-9phg / jolt-90sp) — the pure-Chez jolt runtime. NO Janet.
|
||||
;;
|
||||
;; Loads the checked-in seed (host/chez/seed/{prelude,image}.ss — the bootstrap
|
||||
;; compiler) and the zero-Janet spine, then either evaluates a -e expression or
|
||||
;; dispatches a CLI command (run/-M/repl/path/task) through jolt.main. The loader
|
||||
;; (loader.ss) turns `require` into real file loading off the source roots, so a
|
||||
;; multi-file project with deps.edn dependencies runs end to end.
|
||||
;;
|
||||
;; Run from the repo root (bin/joltc cd's there); the project dir is JOLT_PWD.
|
||||
(import (chezscheme))
|
||||
|
||||
(define cli-args (cdr (command-line))) ; drop the script name
|
||||
|
||||
(load "host/chez/rt.ss")
|
||||
(set-chez-ns! "clojure.core")
|
||||
(load "host/chez/seed/prelude.ss")
|
||||
(load "host/chez/post-prelude.ss")
|
||||
(set-chez-ns! "user")
|
||||
(load "host/chez/host-contract.ss")
|
||||
(load "host/chez/seed/image.ss")
|
||||
(load "host/chez/compile-eval.ss")
|
||||
(load "host/chez/png.ss") ; jolt.png — a baked namespace before the snapshot
|
||||
(load "host/chez/http-client.ss") ; jolt.http-client (libcurl)
|
||||
(load "host/chez/sqlite.ss") ; jolt.sqlite + jdbc.core (libsqlite3)
|
||||
(load "host/chez/http-server.ss") ; jolt.http.server + ring-janet.adapter (BSD sockets)
|
||||
(load "host/chez/loader.ss")
|
||||
|
||||
;; jolt.main + jolt.deps live under jolt-core; keep them (and src/jolt) on the
|
||||
;; roots so the CLI's own namespaces — and any jolt.* an app pulls in — resolve.
|
||||
;; A project's resolved deps roots are prepended to these by jolt.main.
|
||||
(set-source-roots! (list "jolt-core" "src/jolt"))
|
||||
|
||||
;; Render an uncaught jolt throw (any value, not just a Chez condition) to stderr
|
||||
;; and exit non-zero, instead of Chez's opaque "non-condition value" dump. An
|
||||
;; ex-info shows its message + ex-data; anything else is pr-str'd.
|
||||
(define (jolt-report-uncaught v)
|
||||
(let ((port (current-error-port)))
|
||||
(if (and (jolt=2 (jolt-get v jolt-kw-ex-type jolt-nil) jolt-kw-ex-info))
|
||||
(begin
|
||||
(display "Unhandled exception: " port)
|
||||
(display (jolt-str-render-one (jolt-get v jolt-kw-message jolt-nil)) port)
|
||||
(newline port)
|
||||
(let ((data (jolt-get v jolt-kw-data jolt-nil)))
|
||||
(unless (jolt-nil? data)
|
||||
(display " ex-data: " port) (display (jolt-pr-str data) port) (newline port)))
|
||||
(let ((cause (jolt-get v jolt-kw-cause jolt-nil)))
|
||||
(when (condition? cause)
|
||||
(display " cause: " port)
|
||||
(display (with-output-to-string (lambda () (display-condition cause))) port)
|
||||
(newline port))))
|
||||
(begin
|
||||
(display "Unhandled exception: " port)
|
||||
(display (if (condition? v) (with-output-to-string (lambda () (display-condition v))) (jolt-pr-str v)) port)
|
||||
(newline port)))
|
||||
(exit 1)))
|
||||
|
||||
(guard (v (#t (jolt-report-uncaught v)))
|
||||
(cond
|
||||
;; -e EXPR — evaluate one expression and print it (blank for nil). Wrapped in
|
||||
;; (do …) so a multi-form string evaluates every form and returns the last.
|
||||
((and (= (length cli-args) 2) (string=? (car cli-args) "-e"))
|
||||
(let ((result (jolt-final-str
|
||||
(jolt-compile-eval (string-append "(do " (cadr cli-args) ")") "user"))))
|
||||
(unless (string=? result "")
|
||||
(display result) (newline))))
|
||||
;; otherwise dispatch the argv through jolt.main/-main
|
||||
(else
|
||||
(load-namespace "jolt.main")
|
||||
(let ((mainv (var-deref "jolt.main" "-main")))
|
||||
(apply jolt-invoke mainv cli-args)))))
|
||||
345
host/chez/collections.ss
Normal file
345
host/chez/collections.ss
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
;; Phase 1 (jolt-cf1q.2, inc 3a) — persistent collections on the Chez RT.
|
||||
;;
|
||||
;; The vector / map / set the emitted programs construct from literals and
|
||||
;; operate on via the lowered leaf ops (conj/get/nth/count/assoc/...). Loaded by
|
||||
;; rt.ss after values.ss; jolt=2 / jolt-hash (values.ss) call into the
|
||||
;; jolt-coll? / jolt-coll=? / jolt-coll-hash hooks defined here (forward refs,
|
||||
;; resolved at run time — nothing is CALLED during load).
|
||||
;;
|
||||
;; Phase note: the persistent vector is a copy-on-write Scheme vector and the
|
||||
;; map/set are a bitmap HAMT (the structure 0c measured self-hostable). They live
|
||||
;; in Scheme for the Phase-1 bootstrap; the 0c decision is to SELF-HOST them in
|
||||
;; Clojure once core is up on Chez (Phase 3 shim shrink). Correctness, not perf,
|
||||
;; is the Phase-1 gate.
|
||||
|
||||
;; ============================================================================
|
||||
;; small immutable-vector helpers (manual; avoid stdlib arg-order ambiguity)
|
||||
;; ============================================================================
|
||||
(define (vec-copy-range v start end)
|
||||
(let ((out (make-vector (fx- end start))))
|
||||
(let loop ((i start))
|
||||
(when (fx<? i end) (vector-set! out (fx- i start) (vector-ref v i)) (loop (fx+ i 1))))
|
||||
out))
|
||||
(define (vec-insert v i x) ; copy of v with x spliced in at index i
|
||||
(let* ((n (vector-length v)) (out (make-vector (fx+ n 1))))
|
||||
(let loop ((j 0)) (when (fx<? j i) (vector-set! out j (vector-ref v j)) (loop (fx+ j 1))))
|
||||
(vector-set! out i x)
|
||||
(let loop ((j i)) (when (fx<? j n) (vector-set! out (fx+ j 1) (vector-ref v j)) (loop (fx+ j 1))))
|
||||
out))
|
||||
(define (vec-set v i x) ; functional update at index i
|
||||
(let ((out (vec-copy-range v 0 (vector-length v)))) (vector-set! out i x) out))
|
||||
(define (vec-remove v i) ; copy of v with index i dropped
|
||||
(let* ((n (vector-length v)) (out (make-vector (fx- n 1))))
|
||||
(let loop ((j 0)) (when (fx<? j i) (vector-set! out j (vector-ref v j)) (loop (fx+ j 1))))
|
||||
(let loop ((j (fx+ i 1))) (when (fx<? j n) (vector-set! out (fx- j 1) (vector-ref v j)) (loop (fx+ j 1))))
|
||||
out))
|
||||
|
||||
;; ============================================================================
|
||||
;; persistent vector — copy-on-write over a Scheme vector
|
||||
;; ============================================================================
|
||||
;; A pvec carries an `ent` flag: #t marks a MAP ENTRY (the [k v] pair seq'd out
|
||||
;; of a map). A map entry equals its [k v] vector and walks like one (nth/count/
|
||||
;; seq/=/hash/print all read only `v`), but is NOT `vector?` and IS `map-entry?`
|
||||
;; — matching Clojure's MapEntry (jolt-agw6). The flag defaults #f, so every
|
||||
;; existing `(make-pvec v)` builds a plain vector; modifying an entry (conj/assoc)
|
||||
;; likewise yields a plain vector.
|
||||
(define-record-type pvec
|
||||
(fields v ent)
|
||||
(protocol (lambda (new) (case-lambda ((v) (new v #f)) ((v e) (new v e)))))
|
||||
(nongenerative chez-pvec-v1))
|
||||
(define empty-pvec (make-pvec (vector)))
|
||||
(define (jolt-vector . xs) (make-pvec (list->vector xs)))
|
||||
(define (make-map-entry k v) (make-pvec (vector k v) #t))
|
||||
(define (jolt-map-entry? x) (and (pvec? x) (pvec-ent x) #t))
|
||||
(define (pvec-count p) (vector-length (pvec-v p)))
|
||||
;; jolt models every number as a double, so vector indices arrive as flonums —
|
||||
;; coerce an integer-valued index to a Scheme fixnum before bounds math.
|
||||
(define (->idx i) (if (fixnum? i) i (if (flonum? i) (exact (floor i)) i)))
|
||||
(define (pvec-nth-d p i d)
|
||||
(let ((v (pvec-v p)) (i (->idx i)))
|
||||
(if (and (fixnum? i) (fx>=? i 0) (fx<? i (vector-length v))) (vector-ref v i) d)))
|
||||
(define (pvec-conj p x)
|
||||
(let* ((v (pvec-v p)) (n (vector-length v)) (out (make-vector (fx+ n 1))))
|
||||
(let loop ((i 0)) (when (fx<? i n) (vector-set! out i (vector-ref v i)) (loop (fx+ i 1))))
|
||||
(vector-set! out n x)
|
||||
(make-pvec out)))
|
||||
(define (pvec-assoc p i x) ; i in [0,count]; =count appends
|
||||
(let* ((v (pvec-v p)) (n (vector-length v)) (i (->idx i)))
|
||||
(cond ((and (fx>=? i 0) (fx<? i n)) (make-pvec (vec-set v i x)))
|
||||
((fx=? i n) (pvec-conj p x))
|
||||
(else (error 'assoc "vector index out of bounds")))))
|
||||
(define (pvec-peek p)
|
||||
(let ((n (pvec-count p))) (if (fx=? n 0) jolt-nil (vector-ref (pvec-v p) (fx- n 1)))))
|
||||
(define (pvec-pop p)
|
||||
(let ((n (pvec-count p)))
|
||||
(if (fx=? n 0) (error 'pop "can't pop empty vector")
|
||||
(make-pvec (vec-copy-range (pvec-v p) 0 (fx- n 1))))))
|
||||
|
||||
;; ============================================================================
|
||||
;; bitmap HAMT — keys hashed by jolt-hash, leaves compared by jolt=
|
||||
;; arr slot is one of: leaf (cons k v) | hnode (branch) | hcoll (hash bucket)
|
||||
;; ============================================================================
|
||||
(define-record-type hnode (fields bm arr) (nongenerative chez-hnode-v1))
|
||||
(define-record-type hcoll (fields hash alist) (nongenerative chez-hcoll-v1))
|
||||
(define empty-hnode (make-hnode 0 (vector)))
|
||||
(define hmask #x3FFFFFFFFFFFFFF) ; 58-bit non-negative hash window
|
||||
(define max-shift 55)
|
||||
;; bitwise-and (not fxand): jolt-hash is set!-decorated per type (records/inst/
|
||||
;; sorted return their own hash) and Chez's equal-hash can yield a BIGNUM, so a
|
||||
;; key's hash isn't guaranteed to be a fixnum. Masking with the 58-bit window via
|
||||
;; the generic bitwise-and always lands in fixnum range for the HAMT's fx slicing.
|
||||
(define (key-hash k) (bitwise-and (jolt-hash k) hmask))
|
||||
(define (chunk h shift) (fxand (fxsra h shift) 31))
|
||||
(define (bitpos h shift) (fxsll 1 (chunk h shift)))
|
||||
(define (popcount n) (let loop ((n n) (c 0)) (if (fx=? n 0) c (loop (fxand n (fx- n 1)) (fx+ c 1)))))
|
||||
(define (arr-index bm bit) (popcount (fxand bm (fx- bit 1))))
|
||||
|
||||
;; jolt= alist ops (for hash-collision buckets)
|
||||
(define (assoc-jolt k al) (cond ((null? al) #f) ((jolt= (caar al) k) (car al)) (else (assoc-jolt k (cdr al)))))
|
||||
(define (alist-replace k v al) (if (jolt= (caar al) k) (cons (cons k v) (cdr al)) (cons (car al) (alist-replace k v (cdr al)))))
|
||||
(define (alist-remove k al) (cond ((null? al) '()) ((jolt= (caar al) k) (cdr al)) (else (cons (car al) (alist-remove k (cdr al))))))
|
||||
|
||||
;; split two leaves that collided at `shift` into a subtree (or hcoll if the
|
||||
;; full hashes are equal / the hash is exhausted).
|
||||
(define (split-leaf shift ek ev h k v)
|
||||
(let ((eh (key-hash ek)))
|
||||
(if (or (fx>? shift max-shift) (fx=? eh h))
|
||||
(make-hcoll h (list (cons ek ev) (cons k v)))
|
||||
(let ((ei (chunk eh shift)) (ni (chunk h shift)))
|
||||
(if (fx=? ei ni)
|
||||
(make-hnode (fxsll 1 ei) (vector (split-leaf (fx+ shift 5) ek ev h k v)))
|
||||
(let ((eb (fxsll 1 ei)) (nb (fxsll 1 ni)))
|
||||
(if (fx<? ei ni)
|
||||
(make-hnode (fxior eb nb) (vector (cons ek ev) (cons k v)))
|
||||
(make-hnode (fxior eb nb) (vector (cons k v) (cons ek ev))))))))))
|
||||
|
||||
(define (node-assoc node shift h k v added)
|
||||
(let* ((bit (bitpos h shift)) (bm (hnode-bm node)) (arr (hnode-arr node)))
|
||||
(if (fx=? 0 (fxand bm bit))
|
||||
(begin (set-box! added #t)
|
||||
(make-hnode (fxior bm bit) (vec-insert arr (arr-index bm bit) (cons k v))))
|
||||
(let* ((i (arr-index bm bit)) (child (vector-ref arr i)))
|
||||
(cond
|
||||
((hnode? child) (make-hnode bm (vec-set arr i (node-assoc child (fx+ shift 5) h k v added))))
|
||||
((hcoll? child)
|
||||
(let ((al (hcoll-alist child)))
|
||||
(if (assoc-jolt k al)
|
||||
(make-hnode bm (vec-set arr i (make-hcoll (hcoll-hash child) (alist-replace k v al))))
|
||||
(begin (set-box! added #t)
|
||||
(make-hnode bm (vec-set arr i (make-hcoll (hcoll-hash child) (cons (cons k v) al))))))))
|
||||
((jolt= (car child) k) (make-hnode bm (vec-set arr i (cons k v)))) ; replace
|
||||
(else (set-box! added #t)
|
||||
(make-hnode bm (vec-set arr i (split-leaf (fx+ shift 5) (car child) (cdr child) h k v)))))))))
|
||||
|
||||
(define (node-get node shift h k default)
|
||||
(let* ((bit (bitpos h shift)) (bm (hnode-bm node)))
|
||||
(if (fx=? 0 (fxand bm bit)) default
|
||||
(let ((child (vector-ref (hnode-arr node) (arr-index bm bit))))
|
||||
(cond ((hnode? child) (node-get child (fx+ shift 5) h k default))
|
||||
((hcoll? child) (let ((p (assoc-jolt k (hcoll-alist child)))) (if p (cdr p) default)))
|
||||
((jolt= (car child) k) (cdr child))
|
||||
(else default))))))
|
||||
|
||||
(define (node-dissoc node shift h k removed)
|
||||
(let* ((bit (bitpos h shift)) (bm (hnode-bm node)) (arr (hnode-arr node)))
|
||||
(if (fx=? 0 (fxand bm bit)) node
|
||||
(let* ((i (arr-index bm bit)) (child (vector-ref arr i)))
|
||||
(cond
|
||||
((hnode? child) (make-hnode bm (vec-set arr i (node-dissoc child (fx+ shift 5) h k removed))))
|
||||
((hcoll? child)
|
||||
(if (assoc-jolt k (hcoll-alist child))
|
||||
(begin (set-box! removed #t)
|
||||
(let ((nal (alist-remove k (hcoll-alist child))))
|
||||
(cond ((null? nal) (make-hnode (fxand bm (fxnot bit)) (vec-remove arr i)))
|
||||
((null? (cdr nal)) (make-hnode bm (vec-set arr i (car nal)))) ; collapse to leaf
|
||||
(else (make-hnode bm (vec-set arr i (make-hcoll (hcoll-hash child) nal)))))))
|
||||
node))
|
||||
((jolt= (car child) k)
|
||||
(set-box! removed #t) (make-hnode (fxand bm (fxnot bit)) (vec-remove arr i)))
|
||||
(else node))))))
|
||||
|
||||
(define (node-fold node proc acc) ; (proc k v acc) over every leaf
|
||||
(let ((arr (hnode-arr node)))
|
||||
(let loop ((i 0) (acc acc))
|
||||
(if (fx<? i (vector-length arr))
|
||||
(let ((child (vector-ref arr i)))
|
||||
(loop (fx+ i 1)
|
||||
(cond ((hnode? child) (node-fold child proc acc))
|
||||
((hcoll? child)
|
||||
(let cl ((al (hcoll-alist child)) (a acc))
|
||||
(if (null? al) a (cl (cdr al) (proc (caar al) (cdar al) a)))))
|
||||
(else (proc (car child) (cdr child) acc)))))
|
||||
acc))))
|
||||
|
||||
;; ============================================================================
|
||||
;; persistent map / set over the HAMT
|
||||
;; ============================================================================
|
||||
(define-record-type pmap (fields root cnt) (nongenerative chez-pmap-v1))
|
||||
(define empty-pmap (make-pmap empty-hnode 0))
|
||||
(define pmap-absent (list 'absent)) ; unique missing-key sentinel
|
||||
(define (pmap-assoc m k v)
|
||||
(let* ((added (box #f)) (r (node-assoc (pmap-root m) 0 (key-hash k) k v added)))
|
||||
(make-pmap r (if (unbox added) (fx+ (pmap-cnt m) 1) (pmap-cnt m)))))
|
||||
(define (pmap-dissoc m k)
|
||||
(let* ((removed (box #f)) (r (node-dissoc (pmap-root m) 0 (key-hash k) k removed)))
|
||||
(make-pmap r (if (unbox removed) (fx- (pmap-cnt m) 1) (pmap-cnt m)))))
|
||||
(define (pmap-get m k default) (node-get (pmap-root m) 0 (key-hash k) k default))
|
||||
(define (pmap-contains? m k) (not (eq? pmap-absent (node-get (pmap-root m) 0 (key-hash k) k pmap-absent))))
|
||||
(define (pmap-fold m proc acc) (node-fold (pmap-root m) proc acc))
|
||||
(define (jolt-hash-map . kvs)
|
||||
(let loop ((m empty-pmap) (kvs kvs))
|
||||
(cond ((null? kvs) m)
|
||||
((null? (cdr kvs)) (error 'hash-map "odd number of map literal entries"))
|
||||
(else (loop (pmap-assoc m (car kvs) (cadr kvs)) (cddr kvs))))))
|
||||
|
||||
(define-record-type pset (fields m) (nongenerative chez-pset-v1))
|
||||
(define empty-pset (make-pset empty-pmap))
|
||||
(define (pset-conj s e) (if (pmap-contains? (pset-m s) e) s (make-pset (pmap-assoc (pset-m s) e e))))
|
||||
(define (pset-disj s e) (make-pset (pmap-dissoc (pset-m s) e)))
|
||||
(define (pset-contains? s e) (pmap-contains? (pset-m s) e))
|
||||
(define (pset-count s) (pmap-cnt (pset-m s)))
|
||||
(define (pset-fold s proc acc) (pmap-fold (pset-m s) (lambda (k v a) (proc k a)) acc))
|
||||
(define (jolt-hash-set . xs) (let loop ((s empty-pset) (xs xs)) (if (null? xs) s (loop (pset-conj s (car xs)) (cdr xs)))))
|
||||
|
||||
;; ============================================================================
|
||||
;; leaf ops the emitter lowers core/clojure fns to (mirrors native-ops)
|
||||
;; ============================================================================
|
||||
(define (jolt-conj1 coll x)
|
||||
(cond ((pvec? coll) (pvec-conj coll x)) ; nil is a valid vector/set element
|
||||
((pset? coll) (pset-conj coll x))
|
||||
;; a list/seq conjs by PREPENDING (seq.ss: cseq / empty-list). conj onto a
|
||||
;; list stays a list, conj onto a lazy/realized seq yields a seq cell (a
|
||||
;; Cons) — list?-preserving.
|
||||
((cseq? coll) (if (cseq-list? coll) (cseq-list x coll) (cseq-realized x coll)))
|
||||
((empty-list-t? coll) (cseq-list x jolt-nil))
|
||||
((pmap? coll)
|
||||
(cond ((jolt-nil? x) coll) ; (conj m nil) = m
|
||||
((pmap? x) (pmap-fold x (lambda (k v m) (pmap-assoc m k v)) coll)) ; merge
|
||||
((and (pvec? x) (fx=? 2 (pvec-count x)))
|
||||
(pmap-assoc coll (pvec-nth-d x 0 jolt-nil) (pvec-nth-d x 1 jolt-nil)))
|
||||
(else (error 'conj "conj on a map expects a [k v] pair or a map"))))
|
||||
(else (error 'conj "unsupported collection"))))
|
||||
;; (conj) -> []; (conj nil a b ...) builds a list (conj prepending -> (b a)).
|
||||
(define (jolt-conj . args)
|
||||
(if (null? args)
|
||||
(jolt-vector)
|
||||
(let ((coll (car args)) (xs (cdr args)))
|
||||
(if (jolt-nil? coll)
|
||||
(fold-left jolt-conj1 jolt-empty-list xs)
|
||||
(fold-left jolt-conj1 coll xs)))))
|
||||
|
||||
(define jolt-get
|
||||
(case-lambda
|
||||
((coll k) (jolt-get coll k jolt-nil))
|
||||
((coll k d)
|
||||
(cond ((pmap? coll) (pmap-get coll k d))
|
||||
((pset? coll) (if (pset-contains? coll k) k d))
|
||||
((pvec? coll) (pvec-nth-d coll k d))
|
||||
((string? coll) (let ((i (->idx k)))
|
||||
(if (and (fixnum? i) (fx>=? i 0) (fx<? i (string-length coll))) (string-ref coll i) d)))
|
||||
(else d)))))
|
||||
|
||||
(define jolt-nth
|
||||
(case-lambda
|
||||
((coll i)
|
||||
(let ((i (->idx i)))
|
||||
(cond ((pvec? coll) (let ((v (pvec-v coll)))
|
||||
(if (and (fx>=? i 0) (fx<? i (vector-length v))) (vector-ref v i)
|
||||
(error 'nth "index out of bounds"))))
|
||||
((string? coll) (string-ref coll i))
|
||||
((or (cseq? coll) (empty-list-t? coll)) (seq-nth coll i #f jolt-nil))
|
||||
(else (error 'nth "unsupported collection")))))
|
||||
((coll i d)
|
||||
(let ((i (->idx i)))
|
||||
(cond ((pvec? coll) (pvec-nth-d coll i d))
|
||||
((string? coll) (if (and (fx>=? i 0) (fx<? i (string-length coll))) (string-ref coll i) d))
|
||||
((or (cseq? coll) (empty-list-t? coll)) (seq-nth coll i #t d))
|
||||
(else d))))))
|
||||
|
||||
;; a count is an exact integer (JVM parity: count returns a long). jolt= is
|
||||
;; exactness-aware, so this must be exact to match an exact integer literal:
|
||||
;; (= 2 (count m)) -> 2 vs exact 2 -> true.
|
||||
(define (jolt-count coll)
|
||||
(begin
|
||||
(cond ((pvec? coll) (pvec-count coll))
|
||||
((pmap? coll) (pmap-cnt coll))
|
||||
((pset? coll) (pset-count coll))
|
||||
((string? coll) (string-length coll))
|
||||
((jolt-nil? coll) 0)
|
||||
((empty-list-t? coll) 0)
|
||||
((cseq? coll) (let loop ((s coll) (n 0)) ; walk (forces a finite seq)
|
||||
(if (jolt-nil? s) n (loop (jolt-seq (seq-more s)) (fx+ n 1)))))
|
||||
(else (error 'count "uncountable")))))
|
||||
|
||||
(define (jolt-assoc1 coll k v)
|
||||
(cond ((pmap? coll) (pmap-assoc coll k v))
|
||||
((pvec? coll) (pvec-assoc coll k v))
|
||||
((jolt-nil? coll) (pmap-assoc empty-pmap k v))
|
||||
(else (error 'assoc "unsupported collection"))))
|
||||
(define (jolt-assoc coll . kvs)
|
||||
(let loop ((coll coll) (kvs kvs))
|
||||
(cond ((null? kvs) coll)
|
||||
((null? (cdr kvs)) (error 'assoc "assoc expects an even number of key/vals"))
|
||||
(else (loop (jolt-assoc1 coll (car kvs) (cadr kvs)) (cddr kvs))))))
|
||||
|
||||
(define (jolt-dissoc coll . ks)
|
||||
(cond ((jolt-nil? coll) jolt-nil)
|
||||
((pmap? coll) (fold-left pmap-dissoc coll ks))
|
||||
(else (error 'dissoc "unsupported collection"))))
|
||||
|
||||
(define (jolt-contains? coll k)
|
||||
(cond ((pmap? coll) (pmap-contains? coll k))
|
||||
((pset? coll) (pset-contains? coll k))
|
||||
((pvec? coll) (let ((k (->idx k))) (and (fixnum? k) (fx>=? k 0) (fx<? k (pvec-count coll)))))
|
||||
((jolt-nil? coll) #f)
|
||||
(else #f)))
|
||||
|
||||
(define (jolt-empty? coll)
|
||||
(cond ((jolt-nil? coll) #t)
|
||||
((pvec? coll) (fx=? 0 (pvec-count coll)))
|
||||
((pmap? coll) (fx=? 0 (pmap-cnt coll)))
|
||||
((pset? coll) (fx=? 0 (pset-count coll)))
|
||||
((string? coll) (fx=? 0 (string-length coll)))
|
||||
((empty-list-t? coll) #t)
|
||||
((cseq? coll) #f) ; a cseq is non-empty by construction
|
||||
(else (error 'empty? "unsupported collection"))))
|
||||
|
||||
(define (jolt-peek coll)
|
||||
(cond ((pvec? coll) (pvec-peek coll))
|
||||
((or (cseq? coll) (empty-list-t? coll)) (jolt-first coll)) ; list peek = first
|
||||
((jolt-nil? coll) jolt-nil) (else (error 'peek "unsupported collection"))))
|
||||
(define (jolt-pop coll)
|
||||
(cond ((pvec? coll) (pvec-pop coll))
|
||||
((cseq? coll) (jolt-rest coll)) ; list pop = rest
|
||||
((empty-list-t? coll) (error 'pop "can't pop empty list"))
|
||||
(else (error 'pop "unsupported collection"))))
|
||||
|
||||
;; ============================================================================
|
||||
;; equality / hash hooks called from values.ss (jolt=2 / jolt-hash)
|
||||
;; ============================================================================
|
||||
(define (jolt-coll? x) (or (pvec? x) (pmap? x) (pset? x)))
|
||||
(define (jolt-coll=? a b)
|
||||
(cond
|
||||
((and (pvec? a) (pvec? b))
|
||||
(let ((va (pvec-v a)) (vb (pvec-v b)))
|
||||
(and (fx=? (vector-length va) (vector-length vb))
|
||||
(let loop ((i 0))
|
||||
(or (fx=? i (vector-length va))
|
||||
(and (jolt= (vector-ref va i) (vector-ref vb i)) (loop (fx+ i 1))))))))
|
||||
((and (pmap? a) (pmap? b))
|
||||
(and (fx=? (pmap-cnt a) (pmap-cnt b))
|
||||
(pmap-fold a (lambda (k v ok) (and ok (jolt= (pmap-get b k pmap-absent) v))) #t)))
|
||||
((and (pset? a) (pset? b))
|
||||
(and (fx=? (pset-count a) (pset-count b))
|
||||
(pset-fold a (lambda (e ok) (and ok (pset-contains? b e))) #t)))
|
||||
(else #f)))
|
||||
(define (jolt-coll-hash x)
|
||||
(cond
|
||||
((pvec? x)
|
||||
(let ((v (pvec-v x)))
|
||||
(let loop ((i 0) (h 1))
|
||||
(if (fx=? i (vector-length v)) (bitwise-and h hmask)
|
||||
(loop (fx+ i 1) (bitwise-and (+ (* 31 h) (key-hash (vector-ref v i))) hmask))))))
|
||||
;; maps/sets hash order-independently (sum), consistent with unordered =
|
||||
((pmap? x) (bitwise-and (pmap-fold x (lambda (k v a) (+ a (fxxor (key-hash k) (key-hash v)))) 0) hmask))
|
||||
((pset? x) (bitwise-and (pset-fold x (lambda (e a) (+ a (key-hash e))) 0) hmask))))
|
||||
149
host/chez/compile-eval.ss
Normal file
149
host/chez/compile-eval.ss
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
;; compile-eval.ss (jolt-hs9n, Phase 3 inc6) — the zero-Janet compile spine.
|
||||
;;
|
||||
;; Ties together the cross-compiled compiler image (jolt.ir + jolt.analyzer +
|
||||
;; jolt.backend-scheme, loaded as def-var! forms) and the host contract
|
||||
;; (host-contract.ss) into a runtime entry: a Clojure source string is read by the
|
||||
;; Chez data reader, analyzed by the ON-CHEZ analyzer to IR, emitted to Scheme by
|
||||
;; the ON-CHEZ emitter, and eval'd — no Janet in the loop. This is the spine the
|
||||
;; stage2==stage3 bootstrap fixpoint (later increments) closes over.
|
||||
;;
|
||||
;; Loaded after host-contract.ss + the compiler image.
|
||||
|
||||
(define jolt-ce-analyze (var-deref "jolt.analyzer" "analyze"))
|
||||
(define jolt-ce-emit (var-deref "jolt.backend-scheme" "emit"))
|
||||
(define jolt-ce-read (var-deref "clojure.core" "read-string"))
|
||||
|
||||
;; The zero-Janet spine ALWAYS runs with the full clojure.core prelude loaded, so a
|
||||
;; clojure.* ref must lower to var-deref (resolved from the prelude), not trip the
|
||||
;; emitter's "unsupported stdlib fn (no core on Chez yet)" out-of-subset guard —
|
||||
;; that guard is only for the bare -e subset with no prelude. Turn prelude mode on
|
||||
;; once, here, so every analyze->emit on this spine sees the full core (jolt-qjr0).
|
||||
((var-deref "jolt.backend-scheme" "set-prelude-mode!") #t)
|
||||
|
||||
;; (quote X) -> X, else x — unwraps a quoted require spec.
|
||||
(define (ce-unquote x)
|
||||
(if (and (cseq? x) (cseq-list? x))
|
||||
(let ((items (seq->list x)))
|
||||
(if (and (pair? items) (symbol-t? (car items))
|
||||
(string=? (symbol-t-name (car items)) "quote") (pair? (cdr items)))
|
||||
(cadr items) x))
|
||||
x))
|
||||
|
||||
;; Pre-register any (require ...)/(use ...) :as aliases under `ns` BEFORE analysis,
|
||||
;; so a qualified s/foo resolves while compiling (analysis precedes the runtime
|
||||
;; require). Walks the whole form (a require may be nested in a do/let). jolt-qjr0.
|
||||
(define (ce-clause-require? cl) ; (:require ...) / (:use ...) ns clause
|
||||
(and (pair? cl) (keyword? (car cl))
|
||||
(let ((kn (keyword-t-name (car cl)))) (or (string=? kn "require") (string=? kn "use")))))
|
||||
(define (ce-scan-requires! form ns)
|
||||
(when (and (cseq? form) (cseq-list? form))
|
||||
(let ((items (seq->list form)))
|
||||
(when (pair? items)
|
||||
(let* ((h (car items)) (hn (and (symbol-t? h) (symbol-t-name h))))
|
||||
(cond
|
||||
;; (require spec...) / (use spec...) — specs are quoted
|
||||
((and hn (or (string=? hn "require") (string=? hn "use")))
|
||||
(for-each (lambda (a) (chez-register-spec! ns (ce-unquote a))) (cdr items)))
|
||||
;; (ns name (:require [a :as x]) ...) — clause specs are literal
|
||||
((and hn (string=? hn "ns"))
|
||||
(for-each (lambda (clause)
|
||||
(when (and (cseq? clause) (cseq-list? clause))
|
||||
(let ((cl (seq->list clause)))
|
||||
(when (ce-clause-require? cl)
|
||||
(for-each (lambda (spec) (chez-register-spec! ns spec)) (cdr cl))))))
|
||||
(if (pair? (cdr items)) (cddr items) '())))
|
||||
(else (for-each (lambda (x) (ce-scan-requires! x ns)) items))))))))
|
||||
|
||||
;; Already-read FORM -> Scheme source string (analyze -> emit on Chez).
|
||||
;; `ns` is the compile namespace unqualified symbols resolve against.
|
||||
(define (jolt-analyze-emit-form form ns)
|
||||
(ce-scan-requires! form ns)
|
||||
(let* ((ctx (make-analyze-ctx ns))
|
||||
(ir (jolt-ce-analyze ctx form)))
|
||||
(jolt-ce-emit ir)))
|
||||
|
||||
;; Source string -> Scheme source string (read then analyze -> emit, all on Chez).
|
||||
(define (jolt-analyze-emit src ns)
|
||||
(jolt-analyze-emit-form (jolt-ce-read src) ns))
|
||||
|
||||
;; --- runtime defmacro (jolt-r8ku) -------------------------------------------
|
||||
;; Shared with emit-image.ss (loaded after this). A defmacro lowers to a def of
|
||||
;; its expander fn + a macro flag, exactly as the prelude emits build-time macros.
|
||||
|
||||
;; Is `f` a (defmacro ...) / (definline ...) form?
|
||||
(define (ce-macro-form? f)
|
||||
(and (cseq? f) (cseq-list? f)
|
||||
(let ((items (seq->list f)))
|
||||
(and (pair? items) (symbol-t? (car items))
|
||||
(let ((h (symbol-t-name (car items))))
|
||||
(or (string=? h "defmacro") (string=? h "definline")))))))
|
||||
|
||||
;; (defmacro NAME [docstring] [attr-map] params body...) -> (values "NAME" (fn ...)).
|
||||
;; Strips a leading docstring (native string) + attr-map (a non-symbol pmap), then
|
||||
;; re-heads the rest with `fn` so a destructured macro arglist desugars. Emits the
|
||||
;; BARE fn (the caller wraps it in def-var! + mark-macro!), never a (def NAME ...) —
|
||||
;; interning NAME would make require skip the real macro (jolt-r9lm).
|
||||
(define (ce-defmacro->fn f)
|
||||
(let* ((items (seq->list f))
|
||||
(name-sym (cadr items))
|
||||
(after-name (cddr items))
|
||||
(a1 (if (and (pair? after-name) (string? (car after-name)))
|
||||
(cdr after-name) after-name))
|
||||
(after-meta (if (and (pair? a1) (pmap? (car a1)))
|
||||
(cdr a1) a1))
|
||||
(fn-sym (jolt-symbol #f "fn")))
|
||||
(values (symbol-t-name name-sym)
|
||||
(apply jolt-list (cons fn-sym after-meta)))))
|
||||
|
||||
;; A bare top-level (do ...) form — head is the unqualified `do` symbol.
|
||||
(define (ce-top-do? form)
|
||||
(and (cseq? form) (cseq-list? form)
|
||||
(let ((h (seq-first form)))
|
||||
(and (symbol-t? h) (jolt-nil? (hc-sym-ns h))
|
||||
(string=? (symbol-t-name h) "do")))))
|
||||
|
||||
;; Compile + eval ONE already-read form in compile ns `ns`; returns the value.
|
||||
;; A top-level (do ...) is UNROLLED — each subform compiled+eval'd in turn, like
|
||||
;; Clojure's top-level do — so a runtime defmacro/def in an earlier subform is
|
||||
;; visible (macro flag set, var interned) before a later subform is analyzed.
|
||||
(define (jolt-compile-eval-form form ns)
|
||||
(cond
|
||||
;; thread the current ns: an earlier subform may switch it (ns/in-ns call
|
||||
;; set-chez-ns!), and the next subform must be ANALYZED in that ns so its defs
|
||||
;; land there and its refs resolve (cross-ns def/require in one program).
|
||||
((ce-top-do? form)
|
||||
(let loop ((fs (cdr (seq->list form))) (result jolt-nil) (cur ns))
|
||||
(if (null? fs)
|
||||
result
|
||||
(let ((r (jolt-compile-eval-form (car fs) cur)))
|
||||
(loop (cdr fs) r (chez-current-ns))))))
|
||||
;; defmacro is compiled like any other form — the analyzer lowers it to a def
|
||||
;; of the expander fn + (mark-macro! …) so subsequent forms expand it. One
|
||||
;; macro-expansion path (no separate spine interception).
|
||||
(else
|
||||
(eval (read (open-input-string (jolt-analyze-emit-form form ns)))
|
||||
(interaction-environment)))))
|
||||
|
||||
;; Source string -> value (read one form, compile + eval on Chez, in the
|
||||
;; top-level environment where rt.ss's runtime procedures live).
|
||||
(define (jolt-compile-eval src ns)
|
||||
(jolt-compile-eval-form (jolt-ce-read src) ns))
|
||||
|
||||
;; clojure.core/load-string: read every form from the source string and compile+
|
||||
;; eval each in the current ns, returning the last value (nil for blank input).
|
||||
;; jolt-r8ku.
|
||||
(define (jolt-load-string s)
|
||||
(let loop ((src s) (result jolt-nil))
|
||||
(let ((pn (jolt-parse-next src)))
|
||||
(if (jolt-nil? pn)
|
||||
result
|
||||
(loop (jolt-nth pn 1)
|
||||
(jolt-compile-eval-form (jolt-nth pn 0) (chez-current-ns)))))))
|
||||
|
||||
;; eval / load-string are FUNCTIONS on the spine (the compiler image is resident
|
||||
;; at runtime). eval takes an already-read FORM (e.g. from quote / list); it and
|
||||
;; load-string compile+eval in the current ns. eval is removed from the analyzer's
|
||||
;; special-symbol lists (host-contract.ss) so it resolves as an ordinary core var.
|
||||
(def-var! "clojure.core" "eval"
|
||||
(lambda (form) (jolt-compile-eval-form form (chez-current-ns))))
|
||||
(def-var! "clojure.core" "load-string" jolt-load-string)
|
||||
274
host/chez/concurrency.ss
Normal file
274
host/chez/concurrency.ss
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
;; concurrency.ss (jolt-byjr) — real OS-thread futures + promises for the Chez host.
|
||||
;;
|
||||
;; SHARED-HEAP semantics (JVM Clojure), NOT Janet's isolated-heap snapshot: a
|
||||
;; future body runs on a native thread (fork-thread) over the SAME heap, so a
|
||||
;; captured atom is shared and the body's mutations are visible to the parent —
|
||||
;; matching `clojure.core` on the JVM. deref blocks on a mutex+condition latch.
|
||||
;;
|
||||
;; future / future-call / future-cancel / future? / future-done? / future-cancelled?
|
||||
;; promise / deliver, and the deref extension for both, are bound here (some
|
||||
;; re-asserted in post-prelude.ss over the overlay's Janet-shaped versions).
|
||||
;;
|
||||
;; pmap / pcalls / pvalues live in the clojure.core overlay (40-lazy) expressed
|
||||
;; over `future`, so they light up for free once future-call exists.
|
||||
;;
|
||||
;; Loaded near the end of rt.ss — after atoms.ss (jolt-deref, the atom lock) and
|
||||
;; dyn-binding.ss (the thread-local binding stack we convey into the worker).
|
||||
;; Requires a threaded Chez build (fork-thread / make-mutex / make-condition).
|
||||
|
||||
;; --- time helpers -----------------------------------------------------------
|
||||
;; A relative duration / absolute deadline from a millisecond count (a jolt number).
|
||||
(define (ms->duration ms)
|
||||
(let* ((ms* (exact (floor ms)))
|
||||
(secs (quotient ms* 1000))
|
||||
(nanos (* (remainder ms* 1000) 1000000)))
|
||||
(make-time 'time-duration nanos secs)))
|
||||
(define (ms->deadline ms) (add-duration (current-time 'time-utc) (ms->duration ms)))
|
||||
|
||||
;; --- futures ----------------------------------------------------------------
|
||||
;; A future is a mutable cell guarded by `mu`; workers/derefs coordinate on `cv`.
|
||||
;; done? — result (or cancellation) is final; derefs may proceed
|
||||
;; cancelled? — future-cancel won before the body finished
|
||||
;; ok? — payload is a value (else payload is a raised condition/value)
|
||||
;; payload — the result value, or the captured throw
|
||||
(define-record-type jolt-future
|
||||
(fields (mutable done?) (mutable cancelled?) (mutable ok?) (mutable payload) mu cv)
|
||||
(nongenerative jolt-future-v1))
|
||||
|
||||
;; (future-call thunk): spawn a thread running (thunk). The dynamic bindings in
|
||||
;; effect now are conveyed into the worker (Chez inherits thread-parameters at
|
||||
;; fork; we also install an explicit snapshot for certainty). The result — value
|
||||
;; or thrown condition — is latched and broadcast; a cancel that already finalized
|
||||
;; the future makes the late result a no-op.
|
||||
(define (jolt-future-call thunk)
|
||||
(let ((f (make-jolt-future #f #f #f jolt-nil (make-mutex) (make-condition)))
|
||||
(snap (dyn-binding-stack)))
|
||||
(fork-thread
|
||||
(lambda ()
|
||||
(dyn-binding-stack snap)
|
||||
(let ((r (guard (e (#t (cons #f e))) (cons #t (jolt-invoke thunk)))))
|
||||
(with-mutex (jolt-future-mu f)
|
||||
(unless (jolt-future-done? f) ; not already cancelled
|
||||
(jolt-future-ok?-set! f (car r))
|
||||
(jolt-future-payload-set! f (cdr r))
|
||||
(jolt-future-done?-set! f #t))
|
||||
(condition-broadcast (jolt-future-cv f))))))
|
||||
f))
|
||||
|
||||
;; Final value of a settled future (called OUTSIDE the lock): re-raise a captured
|
||||
;; throw, signal a cancellation, else the value.
|
||||
(define (jolt-future-finish f)
|
||||
(cond
|
||||
((jolt-future-cancelled? f)
|
||||
(jolt-throw (jolt-ex-info "Future cancelled" (jolt-hash-map))))
|
||||
((jolt-future-ok? f) (jolt-future-payload f))
|
||||
(else (raise (jolt-future-payload f)))))
|
||||
|
||||
(define (jolt-future-deref f)
|
||||
(with-mutex (jolt-future-mu f)
|
||||
(let loop ()
|
||||
(unless (jolt-future-done? f)
|
||||
(condition-wait (jolt-future-cv f) (jolt-future-mu f))
|
||||
(loop))))
|
||||
(jolt-future-finish f))
|
||||
|
||||
;; (deref f timeout-ms timeout-val): wait up to timeout-ms; return timeout-val if
|
||||
;; it has not settled by the absolute deadline.
|
||||
(define (jolt-future-deref-timed f ms timeout-val)
|
||||
(let* ((deadline (ms->deadline ms))
|
||||
(settled (with-mutex (jolt-future-mu f)
|
||||
(let loop ()
|
||||
(cond ((jolt-future-done? f) #t)
|
||||
((condition-wait (jolt-future-cv f) (jolt-future-mu f) deadline)
|
||||
(loop)) ; woken — recheck
|
||||
(else (jolt-future-done? f))))))) ; timed out: final check
|
||||
(if settled (jolt-future-finish f) timeout-val)))
|
||||
|
||||
;; future-cancel: the running thread can't be interrupted, but the future object
|
||||
;; reflects the cancellation — if not already settled, mark it cancelled+done so
|
||||
;; derefs raise and the predicates flip. Returns true iff this call cancelled it.
|
||||
(define (jolt-future-cancel f)
|
||||
(let ((cancelled (with-mutex (jolt-future-mu f)
|
||||
(if (jolt-future-done? f)
|
||||
#f
|
||||
(begin (jolt-future-cancelled?-set! f #t)
|
||||
(jolt-future-done?-set! f #t)
|
||||
(condition-broadcast (jolt-future-cv f))
|
||||
#t)))))
|
||||
cancelled))
|
||||
|
||||
(define (jolt-future-done?* f) (and (jolt-future? f) (jolt-future-done? f)))
|
||||
(define (jolt-native-future-done? x)
|
||||
(if (jolt-future? x) (jolt-future-done? x)
|
||||
(jolt-throw (jolt-ex-info "future-done? requires a future" (jolt-hash-map)))))
|
||||
(define (jolt-native-future-cancelled? x)
|
||||
(and (jolt-future? x) (jolt-future-cancelled? x)))
|
||||
|
||||
;; --- promises ---------------------------------------------------------------
|
||||
;; A blocking promise (JVM), not Janet's non-blocking atom shim: deref parks until
|
||||
;; deliver, then caches the value. deliver wins once; later delivers return nil.
|
||||
(define-record-type jolt-promise
|
||||
(fields (mutable delivered?) (mutable value) mu cv)
|
||||
(nongenerative jolt-promise-v1))
|
||||
|
||||
(define (jolt-promise-new) (make-jolt-promise #f jolt-nil (make-mutex) (make-condition)))
|
||||
|
||||
(define (jolt-deliver p v)
|
||||
(if (jolt-promise? p)
|
||||
(let ((won (with-mutex (jolt-promise-mu p)
|
||||
(if (jolt-promise-delivered? p)
|
||||
#f
|
||||
(begin (jolt-promise-value-set! p v)
|
||||
(jolt-promise-delivered?-set! p #t)
|
||||
(condition-broadcast (jolt-promise-cv p))
|
||||
#t)))))
|
||||
(if won p jolt-nil))
|
||||
(jolt-throw (jolt-ex-info "deliver requires a promise" (jolt-hash-map)))))
|
||||
|
||||
(define (jolt-promise-deref p)
|
||||
(with-mutex (jolt-promise-mu p)
|
||||
(let loop ()
|
||||
(unless (jolt-promise-delivered? p)
|
||||
(condition-wait (jolt-promise-cv p) (jolt-promise-mu p))
|
||||
(loop))))
|
||||
(jolt-promise-value p))
|
||||
|
||||
(define (jolt-promise-deref-timed p ms timeout-val)
|
||||
(let* ((deadline (ms->deadline ms))
|
||||
(got (with-mutex (jolt-promise-mu p)
|
||||
(let loop ()
|
||||
(cond ((jolt-promise-delivered? p) #t)
|
||||
((condition-wait (jolt-promise-cv p) (jolt-promise-mu p) deadline)
|
||||
(loop))
|
||||
(else (jolt-promise-delivered? p)))))))
|
||||
(if got (jolt-promise-value p) timeout-val)))
|
||||
|
||||
;; --- agents (async, per-agent serialized dispatch) --------------------------
|
||||
;; JVM semantics, not Janet's synchronous shim: send/send-off enqueue an action
|
||||
;; and a single worker thread applies them to the state IN ORDER; deref reads the
|
||||
;; (possibly not-yet-updated) state without blocking; await blocks until the queue
|
||||
;; drains. An action error is captured (agent-error) and stops the queue.
|
||||
(define-record-type jolt-agent
|
||||
(fields (mutable state) (mutable err) (mutable validator)
|
||||
(mutable queue) (mutable running?) mu cv)
|
||||
(nongenerative jolt-agent-v1))
|
||||
|
||||
;; (agent state) / (agent state :validator f :error-mode m :meta x): only :validator
|
||||
;; has runtime behaviour here; other opts are accepted/ignored.
|
||||
(define (jolt-agent-new state . opts)
|
||||
(let loop ((o opts) (validator jolt-nil))
|
||||
(cond
|
||||
((or (null? o) (null? (cdr o)))
|
||||
(make-jolt-agent state jolt-nil validator '() #f (make-mutex) (make-condition)))
|
||||
((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "validator"))
|
||||
(loop (cddr o) (cadr o)))
|
||||
(else (loop (cddr o) validator)))))
|
||||
|
||||
;; Drain the queue, applying each action (f state arg*) outside the lock (an action
|
||||
;; may send/deref the same agent). A validator rejection or a thrown action puts the
|
||||
;; agent in an error state and halts the queue (JVM :fail mode).
|
||||
(define (jolt-agent-worker a)
|
||||
(let loop ()
|
||||
(let ((act (with-mutex (jolt-agent-mu a)
|
||||
(if (or (not (jolt-nil? (jolt-agent-err a))) (null? (jolt-agent-queue a)))
|
||||
(begin (jolt-agent-running?-set! a #f)
|
||||
(condition-broadcast (jolt-agent-cv a)) #f)
|
||||
(let ((x (car (jolt-agent-queue a))))
|
||||
(jolt-agent-queue-set! a (cdr (jolt-agent-queue a))) x)))))
|
||||
(when act
|
||||
(guard (e (#t (with-mutex (jolt-agent-mu a)
|
||||
(jolt-agent-err-set! a e)
|
||||
(condition-broadcast (jolt-agent-cv a)))))
|
||||
(let ((nv (apply jolt-invoke (car act) (jolt-agent-state a) (cdr act))))
|
||||
(let ((vf (jolt-agent-validator a)))
|
||||
(when (and (not (jolt-nil? vf)) (jolt-not (jolt-invoke vf nv)))
|
||||
(error #f "Invalid reference state")))
|
||||
(jolt-agent-state-set! a nv)))
|
||||
(loop)))))
|
||||
|
||||
;; send / send-off: enqueue the action, start the worker if idle. (jolt treats them
|
||||
;; identically — one serialized worker per agent — which is observably a superset of
|
||||
;; the JVM's fixed/cached pool split.)
|
||||
(define (jolt-agent-send a f . args)
|
||||
(with-mutex (jolt-agent-mu a)
|
||||
(jolt-agent-queue-set! a (append (jolt-agent-queue a) (list (cons f args))))
|
||||
(unless (jolt-agent-running? a)
|
||||
(jolt-agent-running?-set! a #t)
|
||||
(fork-thread (lambda () (jolt-agent-worker a)))))
|
||||
a)
|
||||
|
||||
;; (await & agents): block until each agent's queue has drained.
|
||||
(define (jolt-agent-await . agents)
|
||||
(for-each
|
||||
(lambda (a)
|
||||
(with-mutex (jolt-agent-mu a)
|
||||
(let loop ()
|
||||
(when (or (jolt-agent-running? a) (pair? (jolt-agent-queue a)))
|
||||
(condition-wait (jolt-agent-cv a) (jolt-agent-mu a)) (loop)))))
|
||||
agents)
|
||||
jolt-nil)
|
||||
|
||||
(define (jolt-agent-error a) (jolt-agent-err a))
|
||||
(define (jolt-agent-restart a new-state . _opts)
|
||||
(jolt-agent-err-set! a jolt-nil)
|
||||
(jolt-agent-state-set! a new-state)
|
||||
a)
|
||||
|
||||
;; --- delay (lazy once-forced computation) -----------------------------------
|
||||
;; (delay body) -> (make-delay (fn [] body)) (overlay macro); force/deref run the
|
||||
;; thunk once under a lock and cache the value (JVM delays are thread-safe). force
|
||||
;; (overlay) is (if (delay? x) (deref x) x), so it works once delay?/deref do.
|
||||
(define-record-type jolt-delay (fields thunk (mutable realized?) (mutable value) mu)
|
||||
(nongenerative jolt-delay-v1))
|
||||
(define (jolt-make-delay thunk) (make-jolt-delay thunk #f jolt-nil (make-mutex)))
|
||||
(define (jolt-delay-force d)
|
||||
(with-mutex (jolt-delay-mu d)
|
||||
(unless (jolt-delay-realized? d)
|
||||
(jolt-delay-value-set! d (jolt-invoke (jolt-delay-thunk d)))
|
||||
(jolt-delay-realized?-set! d #t)))
|
||||
(jolt-delay-value d))
|
||||
|
||||
;; --- deref extension --------------------------------------------------------
|
||||
;; Chain the fully-built jolt-deref (atoms/vars/volatiles/reduced) with futures,
|
||||
;; promises, agents, and delays; accept the timed (deref ref ms val) arity for the
|
||||
;; blocking ref types.
|
||||
(define %pre-conc-deref jolt-deref)
|
||||
(set! jolt-deref
|
||||
(lambda (x . opts)
|
||||
(cond
|
||||
((jolt-future? x)
|
||||
(if (null? opts) (jolt-future-deref x)
|
||||
(jolt-future-deref-timed x (car opts) (cadr opts))))
|
||||
((jolt-promise? x)
|
||||
(if (null? opts) (jolt-promise-deref x)
|
||||
(jolt-promise-deref-timed x (car opts) (cadr opts))))
|
||||
((jolt-agent? x) (jolt-agent-state x))
|
||||
((jolt-delay? x) (jolt-delay-force x))
|
||||
(else (apply %pre-conc-deref x opts)))))
|
||||
|
||||
;; realized? for a Chez future/promise/delay (the overlay reads Janet map keys).
|
||||
;; Wrapped over the overlay version in post-prelude.ss.
|
||||
(define (jolt-conc-realized? x)
|
||||
(cond ((jolt-future? x) (jolt-future-done? x))
|
||||
((jolt-promise? x) (jolt-promise-delivered? x))
|
||||
((jolt-delay? x) (jolt-delay-realized? x))
|
||||
(else #f)))
|
||||
|
||||
;; --- bind into clojure.core -------------------------------------------------
|
||||
(def-var! "clojure.core" "future-call" jolt-future-call)
|
||||
(def-var! "clojure.core" "future-cancel" jolt-future-cancel)
|
||||
(def-var! "clojure.core" "future?" jolt-future?)
|
||||
(def-var! "clojure.core" "future-done?" jolt-native-future-done?)
|
||||
(def-var! "clojure.core" "future-cancelled?" jolt-native-future-cancelled?)
|
||||
(def-var! "clojure.core" "promise" jolt-promise-new)
|
||||
(def-var! "clojure.core" "deliver" jolt-deliver)
|
||||
(def-var! "clojure.core" "agent" jolt-agent-new)
|
||||
(def-var! "clojure.core" "agent?" jolt-agent?)
|
||||
(def-var! "clojure.core" "send" jolt-agent-send)
|
||||
(def-var! "clojure.core" "send-off" jolt-agent-send)
|
||||
(def-var! "clojure.core" "await" jolt-agent-await)
|
||||
(def-var! "clojure.core" "agent-error" jolt-agent-error)
|
||||
(def-var! "clojure.core" "restart-agent" jolt-agent-restart)
|
||||
(def-var! "clojure.core" "make-delay" jolt-make-delay)
|
||||
(def-var! "clojure.core" "delay?" jolt-delay?)
|
||||
(def-var! "clojure.core" "deref" jolt-deref)
|
||||
146
host/chez/converters.ss
Normal file
146
host/chez/converters.ss
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
;; converters + string ops — host-coupled natives def-var!'d into clojure.core,
|
||||
;; resolved in prelude mode. Loaded last (after jolt-pr-str), since `str` reuses
|
||||
;; the printer. int/long truncate toward zero to an exact integer; compare returns
|
||||
;; an exact -1/0/1; double yields a flonum.
|
||||
|
||||
;; str: nil -> "", string raw, char bare (not \c), regex -> raw source, else the
|
||||
;; printer (which renders collections with readable elements).
|
||||
(define (jolt-str-render-one v)
|
||||
(cond
|
||||
((jolt-nil? v) "")
|
||||
((string? v) v)
|
||||
((char? v) (string v))
|
||||
((regex-t? v) (regex-t-source v))
|
||||
;; str/print render the infinities and NaN long-form (Clojure .toString),
|
||||
;; unlike the -e printer's inf/-inf/nan.
|
||||
((and (flonum? v) (fl= v +inf.0)) "Infinity")
|
||||
((and (flonum? v) (fl= v -inf.0)) "-Infinity")
|
||||
((and (flonum? v) (not (fl= v v))) "NaN")
|
||||
(else (jolt-pr-str v))))
|
||||
(define (jolt-str . xs)
|
||||
(let loop ((xs xs) (acc '()))
|
||||
(if (null? xs)
|
||||
(apply string-append (reverse acc))
|
||||
(loop (cdr xs) (cons (jolt-str-render-one (car xs)) acc)))))
|
||||
|
||||
;; jolt indices are flonums; substring etc. need exact ints.
|
||||
(define (jolt->idx n) (exact (truncate n)))
|
||||
|
||||
(define (jolt-subs s start . end)
|
||||
(substring s (jolt->idx start)
|
||||
(if (null? end) (string-length s) (jolt->idx (car end)))))
|
||||
|
||||
;; vec: a pvec from any seqable (already-pvec returns itself).
|
||||
(define (jolt-vec coll)
|
||||
(cond
|
||||
((jolt-nil? coll) (jolt-vector))
|
||||
((pvec? coll) coll)
|
||||
((string? coll) (apply jolt-vector (string->list coll)))
|
||||
(else (apply jolt-vector (seq->list coll)))))
|
||||
|
||||
(define (jolt-keyword . args)
|
||||
(cond
|
||||
((= (length args) 1)
|
||||
(let ((a (car args)))
|
||||
(cond
|
||||
((jolt-nil? a) jolt-nil)
|
||||
((keyword? a) a)
|
||||
;; a 1-arg string splits on the FIRST "/" into ns/name:
|
||||
;; (keyword "x/y") => :x/y with ns "x" — destructure's {:keys [x/y]} builds
|
||||
;; the key this way, so without the split the namespaced key never matches.
|
||||
((string? a)
|
||||
(let ((si (let loop ((i 0))
|
||||
(cond ((>= i (string-length a)) #f)
|
||||
((char=? (string-ref a i) #\/) i)
|
||||
(else (loop (+ i 1)))))))
|
||||
(if (and si (> si 0) (< si (- (string-length a) 1)))
|
||||
(keyword (substring a 0 si) (substring a (+ si 1) (string-length a)))
|
||||
(keyword #f a))))
|
||||
((jolt-symbol? a)
|
||||
(let ((ns (symbol-t-ns a)))
|
||||
(keyword (if (or (jolt-nil? ns) (not ns) (eq? ns '())) #f ns) (symbol-t-name a))))
|
||||
(else (error #f "keyword: requires string/symbol/keyword" a)))))
|
||||
((= (length args) 2)
|
||||
(keyword (let ((ns (car args))) (if (jolt-nil? ns) #f ns)) (cadr args)))
|
||||
(else (error #f "keyword: wrong arity"))))
|
||||
|
||||
(define (jolt-symbol-new . args)
|
||||
(cond
|
||||
((= (length args) 1)
|
||||
(let ((a (car args)))
|
||||
(cond
|
||||
((jolt-symbol? a) a)
|
||||
;; no-ns sentinel is #f — matches emit's quoted-symbol lowering
|
||||
;; (jolt-symbol #f "x"), so (= 'x (symbol "x")) holds (jolt= compares ns
|
||||
;; with strict equal?; jolt-nil vs #f would otherwise differ).
|
||||
((string? a) (jolt-symbol #f a))
|
||||
((keyword? a) (jolt-symbol (keyword-t-ns a) (keyword-t-name a)))
|
||||
(else (error #f "symbol: requires string/symbol" a)))))
|
||||
((= (length args) 2) (jolt-symbol (car args) (cadr args)))
|
||||
(else (error #f "symbol: wrong arity"))))
|
||||
|
||||
;; gensym: per-process counter.
|
||||
(define jolt-gensym-counter 0)
|
||||
(define (jolt-gensym . prefix)
|
||||
(let ((p (if (null? prefix) "G__" (car prefix))))
|
||||
(set! jolt-gensym-counter (+ jolt-gensym-counter 1))
|
||||
(jolt-symbol #f
|
||||
(string-append (if (string? p) p (jolt-str-render-one p))
|
||||
(number->string jolt-gensym-counter)))))
|
||||
|
||||
;; int/long: truncate toward zero to an EXACT integer (= JVM long). char -> code
|
||||
;; point (exact). double: always a flonum (= JVM double).
|
||||
(define (jolt-int x) (if (char? x) (char->integer x) (exact (truncate x))))
|
||||
(define (jolt-double x) (if (char? x) (exact->inexact (char->integer x)) (exact->inexact x)))
|
||||
|
||||
;; compare: 3-way, returns an EXACT integer (= JVM compare -> int).
|
||||
(define (jolt-cmp3 x y) (cond ((< x y) -1) ((> x y) 1) (else 0)))
|
||||
(define (jolt-strcmp a b) (cond ((string<? a b) -1) ((string>? a b) 1) (else 0)))
|
||||
(define (jolt-kw->string k)
|
||||
(let ((ns (keyword-t-ns k))) (if ns (string-append ns "/" (keyword-t-name k)) (keyword-t-name k))))
|
||||
(define (jolt-sym-ns-string s)
|
||||
(let ((n (symbol-t-ns s))) (if (or (jolt-nil? n) (not n) (eq? n '())) "" n)))
|
||||
;; compare returns an EXACT integer -1/0/1 (= JVM compare -> int).
|
||||
(define (jolt-compare a b)
|
||||
(cond
|
||||
((and (jolt-nil? a) (jolt-nil? b)) 0)
|
||||
((jolt-nil? a) -1)
|
||||
((jolt-nil? b) 1)
|
||||
((and (number? a) (number? b)) (jolt-cmp3 a b))
|
||||
((and (string? a) (string? b)) (jolt-strcmp a b))
|
||||
((and (keyword? a) (keyword? b)) (jolt-strcmp (jolt-kw->string a) (jolt-kw->string b)))
|
||||
((and (jolt-symbol? a) (jolt-symbol? b))
|
||||
(let ((r (jolt-strcmp (jolt-sym-ns-string a) (jolt-sym-ns-string b))))
|
||||
(if (= r 0) (jolt-strcmp (symbol-t-name a) (symbol-t-name b)) r)))
|
||||
((and (boolean? a) (boolean? b)) (cond ((eq? a b) 0) ((eq? a #f) -1) (else 1)))
|
||||
((and (char? a) (char? b)) (jolt-cmp3 (char->integer a) (char->integer b)))
|
||||
((and (pvec? a) (pvec? b))
|
||||
(let ((la (pvec-count a)) (lb (pvec-count b)))
|
||||
(if (not (= la lb))
|
||||
(jolt-cmp3 la lb)
|
||||
(let loop ((i 0))
|
||||
(if (>= i la)
|
||||
0
|
||||
(let ((r (jolt-compare (pvec-nth-d a i jolt-nil) (pvec-nth-d b i jolt-nil))))
|
||||
(if (= r 0) (loop (+ i 1)) r)))))))
|
||||
(else (error #f "compare: cannot compare these types" a b))))
|
||||
|
||||
(def-var! "clojure.core" "str" jolt-str)
|
||||
(def-var! "clojure.core" "subs" jolt-subs)
|
||||
(def-var! "clojure.core" "vec" jolt-vec)
|
||||
(def-var! "clojure.core" "keyword" jolt-keyword)
|
||||
(def-var! "clojure.core" "symbol" jolt-symbol-new)
|
||||
(def-var! "clojure.core" "gensym" jolt-gensym)
|
||||
(def-var! "clojure.core" "int" jolt-int)
|
||||
;; char: coerce a code point (jolt's all-flonum number) to a Chez char; pass a
|
||||
;; char through. Inverse of int on chars. (Missing on Chez before jolt-hs9n — the
|
||||
;; cross-compiled emitter's chez-str-lit needs it for printable-ASCII escaping.)
|
||||
(define (jolt-char x) (if (char? x) x (integer->char (exact (round x)))))
|
||||
(def-var! "clojure.core" "char" jolt-char)
|
||||
;; long: same truncation as int in jolt's all-flonum model (seed core-long =
|
||||
;; math/trunc; char -> code point). Distinct cell so (long ...) resolves.
|
||||
(def-var! "clojure.core" "long" jolt-int)
|
||||
(def-var! "clojure.core" "double" jolt-double)
|
||||
;; float: Chez has no single-float type, so float coerces to a flonum like double.
|
||||
(def-var! "clojure.core" "float" jolt-double)
|
||||
(def-var! "clojure.core" "compare" jolt-compare)
|
||||
87
host/chez/dot-forms.ss
Normal file
87
host/chez/dot-forms.ss
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
;; dot-forms.ss — generic dispatch for the `.` special-form / `.-field` desugar
|
||||
;; (jolt-kuic). The analyzer lowers (. target member arg*) and (.-field target)
|
||||
;; to a :host-call; the Chez emit routes a non-shimmed :host-call through
|
||||
;; record-method-dispatch. This file extends that dispatcher with the collection
|
||||
;; arms the interpreter's dispatch-member covers but the record/string base does
|
||||
;; not, with this precedence:
|
||||
;;
|
||||
;; * collection interop wins first — count/seq/nth/get/valAt/containsKey on a
|
||||
;; vector/map/set/seq/record (so (. {:count 9} count) is the entry count, 1,
|
||||
;; NOT the :count field).
|
||||
;; * field access — a "-name" member reads the field (records and maps).
|
||||
;; * map member — a stored fn is a method (called with self + args); any
|
||||
;; other value is returned as a field.
|
||||
;;
|
||||
;; Anything not recognized falls through to the previous dispatcher (jhost /
|
||||
;; number / regex / jrec protocol / string). Loaded LAST (after host-static.ss).
|
||||
;; A record (jrec) is jolt-map? here (records.ss makes it so) and a collection,
|
||||
;; so its protocol method (no dash, not a coll method) lands in the base.
|
||||
|
||||
(define %dot-rmd record-method-dispatch)
|
||||
|
||||
;; Vectors / maps / sets only (records are jolt-map? here). Raw seqs are excluded:
|
||||
;; coll-interop accepts some seq representations and not others (a
|
||||
;; plain (seq v) returns nil from .count, a lazy-seq returns the count), an
|
||||
;; inconsistency Chez's normalized cseq can't mirror — so a raw seq target falls
|
||||
;; through to the base dispatcher rather than risk a divergence the corpus would
|
||||
;; never exercise but a future case might.
|
||||
(define (dot-coll? obj)
|
||||
(or (jolt-vector? obj) (jolt-map? obj) (pset? obj)))
|
||||
|
||||
;; Mirror coll-interop: return a one-element list boxing the result (so a jolt-nil
|
||||
;; result is still distinguishable from "not a collection method"), or #f.
|
||||
(define (dot-coll-method obj name args)
|
||||
(cond
|
||||
((string=? name "count") (list (jolt-count obj)))
|
||||
((string=? name "seq") (list (jolt-seq obj)))
|
||||
((string=? name "nth") (list (apply jolt-nth obj args)))
|
||||
((or (string=? name "get") (string=? name "valAt"))
|
||||
(list (apply jolt-get obj args)))
|
||||
((string=? name "containsKey") (list (jolt-contains? obj (car args))))
|
||||
;; (.iterator coll): a java.util.Iterator over the seq — for a map this is the
|
||||
;; entry iterator. Without this a map's .iterator falls into the map-as-object
|
||||
;; branch and is mis-read as a missing :iterator key (nil). Some libraries
|
||||
;; (e.g. malli's -vmap) iterate a map this way.
|
||||
((string=? name "iterator") (list (make-jiterator (jolt-seq obj))))
|
||||
(else #f)))
|
||||
|
||||
;; Universal object-methods: on a
|
||||
;; non-record map these win OVER a field lookup, like dispatch-member. getMessage
|
||||
;; on an ex-info reads its :message (the one the corpus exercises); getCause reads
|
||||
;; :cause; toString/hashCode/equals round out the set. Returns a boxed result or
|
||||
;; #f. Strings/numbers/records/jhost keep the base dispatcher (it shims them).
|
||||
(define (dot-object-method obj name args)
|
||||
(cond
|
||||
((string=? name "getMessage")
|
||||
(list (if (jolt=2 (jolt-get obj jolt-kw-ex-type jolt-nil) jolt-kw-ex-info)
|
||||
(jolt-get obj jolt-kw-message jolt-nil)
|
||||
(jolt-str-render-one obj))))
|
||||
((string=? name "getCause") (list (jolt-get obj jolt-kw-cause jolt-nil)))
|
||||
((string=? name "toString") (list (jolt-str-render-one obj)))
|
||||
((string=? name "hashCode") (list (jolt-hash obj)))
|
||||
((string=? name "equals") (list (if (jolt= obj (car args)) #t #f)))
|
||||
(else #f)))
|
||||
|
||||
(set! record-method-dispatch
|
||||
(lambda (obj method-name rest-args)
|
||||
(let* ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args)))
|
||||
(field? (and (> (string-length method-name) 0)
|
||||
(char=? (string-ref method-name 0) #\-)))
|
||||
(mname (if field?
|
||||
(substring method-name 1 (string-length method-name))
|
||||
method-name)))
|
||||
(cond
|
||||
;; collection interop first (entry count / seq / nth / get / containsKey).
|
||||
((and (dot-coll? obj) (dot-coll-method obj mname rest))
|
||||
=> (lambda (box) (car box)))
|
||||
;; (.-field obj) / (. obj -field): field read on a record or map.
|
||||
(field? (jolt-get obj (keyword #f mname) jolt-nil))
|
||||
;; non-record map: a universal object-method (getMessage/...) wins first,
|
||||
;; then a stored procedure is a method (call with self), else the field.
|
||||
((and (jolt-map? obj) (not (jrec? obj)))
|
||||
(cond
|
||||
((dot-object-method obj mname rest) => car)
|
||||
(else
|
||||
(let ((v (jolt-get obj (keyword #f mname) jolt-nil)))
|
||||
(if (procedure? v) (apply jolt-invoke v obj rest) v)))))
|
||||
(else (%dot-rmd obj method-name rest-args))))))
|
||||
143
host/chez/dyn-binding.ss
Normal file
143
host/chez/dyn-binding.ss
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
;; dynamic var binding (jolt-2o7x, Phase 2) — binding / with-bindings* / var-set /
|
||||
;; thread-bound? / with-local-vars / with-redefs / bound-fn* / get-thread-bindings.
|
||||
;;
|
||||
;; A per-thread dynamic-binding stack: a list of frames, innermost (most recently
|
||||
;; pushed) at the HEAD. Each frame is an alist of (var-cell . value) MUTABLE pairs
|
||||
;; — so var-set can update the innermost binding in place (set-cdr!), matching
|
||||
;; Clojure where var-set targets the current binding, not the root.
|
||||
;;
|
||||
;; The binding macro builds a frame as a jolt map (array-map of (var x) -> value);
|
||||
;; push-thread-bindings folds it into the alist. Lookups walk frames by cell
|
||||
;; IDENTITY (eq?) — vars are interned, so (var x) always yields the same cell, and
|
||||
;; this sidesteps a persistent-hash-map-can't-find-a-var-key quirk.
|
||||
;;
|
||||
;; var reads (var-deref in compiled code, jolt-var-get / deref on a cell) consult
|
||||
;; the stack before falling back to the cell root. Loaded LAST (after vars.ss and
|
||||
;; ns.ss) so it chains the fully-extended jolt-var-get and overrides rt.ss var-deref.
|
||||
|
||||
;; THREAD-LOCAL (jolt-byjr): a Chez thread parameter, so each OS thread (a future
|
||||
;; / go block) has its own binding stack. Chez initializes a new thread's parameter
|
||||
;; to the spawning thread's value at fork time, giving Clojure binding conveyance
|
||||
;; for free (the future shim also installs an explicit snapshot, belt-and-suspenders).
|
||||
(define dyn-binding-stack (make-thread-parameter '()))
|
||||
|
||||
;; find the innermost (cell . value) pair binding CELL, or #f.
|
||||
(define (dyn-find-binding cell)
|
||||
(let loop ((frames (dyn-binding-stack)))
|
||||
(and (pair? frames)
|
||||
(or (assq cell (car frames))
|
||||
(loop (cdr frames))))))
|
||||
|
||||
;; a unique sentinel: distinguishes "no thread binding" from a binding whose
|
||||
;; value happens to be jolt-nil.
|
||||
(define dyn-no-binding (list 'no-binding))
|
||||
(define (dyn-binding-value cell)
|
||||
(if (pair? (dyn-binding-stack))
|
||||
(let ((p (dyn-find-binding cell)))
|
||||
(if p
|
||||
(let ((val (cdr p)))
|
||||
(if (var-cell? val) (jolt-var-get val) val)) ; nested var deref (Clojure)
|
||||
dyn-no-binding))
|
||||
dyn-no-binding))
|
||||
|
||||
;; push-thread-bindings: frame is a jolt map of var-cell -> value. Fold it into an
|
||||
;; identity-keyed alist of mutable pairs and push.
|
||||
(define (jolt-push-thread-bindings frame)
|
||||
(dyn-binding-stack
|
||||
(cons (pmap-fold frame (lambda (k v acc) (cons (cons k v) acc)) '())
|
||||
(dyn-binding-stack)))
|
||||
jolt-nil)
|
||||
|
||||
(define (jolt-pop-thread-bindings)
|
||||
(when (pair? (dyn-binding-stack))
|
||||
(dyn-binding-stack (cdr (dyn-binding-stack))))
|
||||
jolt-nil)
|
||||
|
||||
;; get-thread-bindings: a jolt map of every currently-bound cell -> value,
|
||||
;; innermost wins. Merge oldest-frame-first (the stack head is innermost). The
|
||||
;; result can be re-pushed by with-bindings* / bound-fn*.
|
||||
(define (jolt-get-thread-bindings)
|
||||
(let loop ((frames (reverse (dyn-binding-stack))) (m (jolt-hash-map)))
|
||||
(if (null? frames)
|
||||
m
|
||||
(loop (cdr frames)
|
||||
(let frame-loop ((alist (car frames)) (m m))
|
||||
(if (null? alist)
|
||||
m
|
||||
(frame-loop (cdr alist)
|
||||
(pmap-assoc m (caar alist) (cdar alist)))))))))
|
||||
|
||||
;; __thread-bound? — single var; true iff it has a thread binding.
|
||||
(define (jolt-thread-bound? v)
|
||||
(and (var-cell? v) (dyn-find-binding v) #t))
|
||||
|
||||
;; var-set: update the innermost frame that binds v (in place); else set the root.
|
||||
(define (jolt-var-set v val)
|
||||
(if (var-cell? v)
|
||||
(let ((p (dyn-find-binding v)))
|
||||
(if p
|
||||
(begin (set-cdr! p val) val)
|
||||
(begin (var-cell-root-set! v val) (var-cell-defined?-set! v #t) val)))
|
||||
(error #f "var-set: not a var" v)))
|
||||
|
||||
;; alter-var-root: atomically apply f to the current root plus args.
|
||||
(define (jolt-alter-var-root v f . args)
|
||||
(let ((new (apply jolt-invoke f (var-cell-root v) args)))
|
||||
(var-cell-root-set! v new)
|
||||
(var-cell-defined?-set! v #t)
|
||||
new))
|
||||
|
||||
;; __local-var: a fresh free-standing var cell (not interned). with-local-vars
|
||||
;; binds these as lexical locals; var-get/var-set read/write the root. Each gets a
|
||||
;; unique name so two locals never compare/hash equal as map keys.
|
||||
(define local-var-counter 0)
|
||||
(define (jolt-local-var . args)
|
||||
(set! local-var-counter (fx+ local-var-counter 1))
|
||||
(make-var-cell "" (string-append "local-" (number->string local-var-counter))
|
||||
(if (pair? args) (car args) jolt-nil)
|
||||
#t))
|
||||
|
||||
;; --- chain the var-read paths onto the binding stack -------------------------
|
||||
|
||||
;; var-deref (rt.ss): the compiled-code read path for every clojure.core var
|
||||
;; reference. Consult the stack first; fall straight back to the root (NOT through
|
||||
;; jolt-var-get's unbound-error path) so undefined-var reads keep prior behaviour.
|
||||
(define %dyn-rt-var-deref var-deref)
|
||||
(set! var-deref
|
||||
(lambda (ns name)
|
||||
(let ((cell (jolt-var ns name)))
|
||||
(let ((bv (dyn-binding-value cell)))
|
||||
(if (eq? bv dyn-no-binding) (var-cell-root cell) bv)))))
|
||||
|
||||
;; jolt-var-get (vars.ss): the var-get fn + deref/@ on a cell. Stack first, then
|
||||
;; the original (which errors on an unbound root, matching Clojure).
|
||||
(define %dyn-var-get jolt-var-get)
|
||||
(set! jolt-var-get
|
||||
(lambda (v)
|
||||
(if (var-cell? v)
|
||||
(let ((bv (dyn-binding-value v)))
|
||||
(if (eq? bv dyn-no-binding) (%dyn-var-get v) bv))
|
||||
(%dyn-var-get v))))
|
||||
|
||||
;; var-cell keys hash/compare by ns/name (jolt=2 in vars.ss already compares
|
||||
;; ns/name) — stable under root mutation, so a var works as a map key (with-redefs
|
||||
;; builds (hash-map (var f) v); get-thread-bindings returns a var-keyed map).
|
||||
(define %dyn-hash jolt-hash)
|
||||
(set! jolt-hash
|
||||
(lambda (x)
|
||||
(if (var-cell? x)
|
||||
(equal-hash (cons (var-cell-ns x) (var-cell-name x)))
|
||||
(%dyn-hash x))))
|
||||
|
||||
;; --- bind the host seams the overlay references -----------------------------
|
||||
(def-var! "clojure.core" "push-thread-bindings" jolt-push-thread-bindings)
|
||||
(def-var! "clojure.core" "pop-thread-bindings" jolt-pop-thread-bindings)
|
||||
(def-var! "clojure.core" "get-thread-bindings" jolt-get-thread-bindings)
|
||||
(def-var! "clojure.core" "__thread-bound?" jolt-thread-bound?)
|
||||
(def-var! "clojure.core" "var-set" jolt-var-set)
|
||||
(def-var! "clojure.core" "alter-var-root" jolt-alter-var-root)
|
||||
(def-var! "clojure.core" "__local-var" jolt-local-var)
|
||||
;; re-assert var-get / deref to the new (stack-aware) closures (vars.ss captured
|
||||
;; the pre-chain values).
|
||||
(def-var! "clojure.core" "var-get" jolt-var-get)
|
||||
(def-var! "clojure.core" "deref" jolt-deref)
|
||||
18
host/chez/dynamic-vars.ss
Normal file
18
host/chez/dynamic-vars.ss
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
;; dynamic vars — the handful of clojure.core dynamic vars that aren't emitted into
|
||||
;; the prelude. These two are plain constants; *ns* (a namespace object) needs a
|
||||
;; value type with get-see-through and map?=false and is tracked separately. Loaded
|
||||
;; from rt.ss after the value model + def-var!.
|
||||
|
||||
;; *clojure-version* — a map {:major 1 :minor 11 :incremental 0 :qualifier nil}.
|
||||
(def-var! "clojure.core" "*clojure-version*"
|
||||
(jolt-hash-map (keyword #f "major") 1
|
||||
(keyword #f "minor") 11
|
||||
(keyword #f "incremental") 0
|
||||
(keyword #f "qualifier") jolt-nil))
|
||||
|
||||
;; *unchecked-math* — jolt does no unchecked-math elision; the var reads false.
|
||||
(def-var! "clojure.core" "*unchecked-math*" #f)
|
||||
|
||||
;; *warn-on-reflection* — jolt has no reflection, so the var reads false; (set!
|
||||
;; *warn-on-reflection* …) resolves and updates it (a no-op effect).
|
||||
(def-var! "clojure.core" "*warn-on-reflection*" #f)
|
||||
110
host/chez/emit-image.ss
Normal file
110
host/chez/emit-image.ss
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
;; emit-image.ss (jolt-cf1q.4 inc8) — the on-Chez compiler-image emitter.
|
||||
;;
|
||||
;; This is the stage2/stage3 half of the self-hosting fixpoint. The
|
||||
;; analyze->emit runs ON CHEZ (jolt-ce-analyze / jolt-ce-emit, loaded from a
|
||||
;; previously-built image): feed it stage1's image and it produces stage2; feed it
|
||||
;; stage2 and it produces stage3. stage2 == stage3 byte-for-byte proves the
|
||||
;; on-Chez compiler reproduces itself (self-hosting-bootstrap-research §4).
|
||||
;;
|
||||
;; Loaded after compile-eval.ss (needs jolt-ce-analyze/jolt-ce-emit/ce-scan-requires!,
|
||||
;; make-analyze-ctx) and rt.ss (read-file-string, the reader's rdr-read-form).
|
||||
|
||||
;; Read every top-level form from a source string (a Chez read-all).
|
||||
;; Uses the same reader the spine reads single forms with.
|
||||
(define (ei-read-all src)
|
||||
(let ((end (string-length src)))
|
||||
(let loop ((i 0) (acc '()))
|
||||
(let-values (((form j) (rdr-read-form src i end)))
|
||||
(if (rdr-eof? form)
|
||||
(reverse acc)
|
||||
(loop j (cons form acc)))))))
|
||||
|
||||
;; Is `f` an (ns ...) form? (Its only role in the image is alias registration; we
|
||||
;; never emit it — the def-var!s carry explicit ns names.)
|
||||
(define (ei-ns-form? f)
|
||||
(and (cseq? f) (cseq-list? f)
|
||||
(let ((items (seq->list f)))
|
||||
(and (pair? items) (symbol-t? (car items))
|
||||
(string=? (symbol-t-name (car items)) "ns")))))
|
||||
|
||||
;; ei-macro-form? / ei-defmacro->fn moved to compile-eval.ss (ce-macro-form? /
|
||||
;; ce-defmacro->fn, loaded before this) — shared with the runtime defmacro spine.
|
||||
|
||||
;; Cross-compile one namespace's source to a list of guard-wrapped Scheme strings.
|
||||
;; Each form is analyzed with a fresh ctx — resolution is via the runtime var-table
|
||||
;; + alias tables, not ctx-accumulated state, so this matches the spine's per-form
|
||||
;; analyze. A defmacro emits its expander fn as (def-var! ns name <fn>) +
|
||||
;; (mark-macro! ns name) so the on-Chez analyzer can expand it (jolt-r9lm).
|
||||
(define (ei-emit-ns ns-name src)
|
||||
(let loop ((forms (ei-read-all src)) (acc '()))
|
||||
(if (null? forms)
|
||||
(reverse acc)
|
||||
(let ((f (car forms)))
|
||||
(ce-scan-requires! f ns-name)
|
||||
(cond
|
||||
((ei-ns-form? f) (loop (cdr forms) acc))
|
||||
((ce-macro-form? f)
|
||||
(let-values (((nm fn-form) (ce-defmacro->fn f)))
|
||||
(let ((scm (guard (e (#t #f))
|
||||
(let ((ctx (make-analyze-ctx ns-name)))
|
||||
(jolt-ce-emit (jolt-ce-analyze ctx fn-form))))))
|
||||
(loop (cdr forms)
|
||||
(if scm
|
||||
(cons (string-append
|
||||
"(guard (e (#t #f))\n (def-var! "
|
||||
(ei-str-lit ns-name) " " (ei-str-lit nm) "\n "
|
||||
scm ")\n (mark-macro! "
|
||||
(ei-str-lit ns-name) " " (ei-str-lit nm) "))")
|
||||
acc)
|
||||
acc)))))
|
||||
(else
|
||||
(let* ((ctx (make-analyze-ctx ns-name))
|
||||
(scm (guard (e (#t #f)) (jolt-ce-emit (jolt-ce-analyze ctx f)))))
|
||||
(loop (cdr forms)
|
||||
(if scm
|
||||
(cons (string-append "(guard (e (#t #f))\n " scm ")") acc)
|
||||
acc)))))))))
|
||||
|
||||
;; Scheme string literal for a ns/name — uses the runtime's own writer
|
||||
;; (printable ASCII identifiers only here).
|
||||
(define (ei-str-lit s) (with-output-to-string (lambda () (write s))))
|
||||
|
||||
;; The compiler namespaces, in load order.
|
||||
(define ei-compiler-ns-files
|
||||
(list (cons "jolt.ir" "jolt-core/jolt/ir.clj")
|
||||
(cons "jolt.analyzer" "jolt-core/jolt/analyzer.clj")
|
||||
(cons "jolt.backend-scheme" "jolt-core/jolt/backend_scheme.clj")))
|
||||
|
||||
;; The clojure.core tiers + stdlib namespaces, in load order.
|
||||
;; Re-emitting these on Chez is the
|
||||
;; prelude half of the fixpoint (the whole emitted system reproducing itself).
|
||||
(define ei-prelude-ns-files
|
||||
(append
|
||||
(map (lambda (tf) (cons "clojure.core" (string-append "jolt-core/clojure/core/" tf ".clj")))
|
||||
'("00-syntax" "00-kernel" "10-seq" "20-coll" "25-sorted" "30-macros" "40-lazy" "50-io"))
|
||||
(list (cons "clojure.string" "src/jolt/clojure/string.clj")
|
||||
(cons "clojure.walk" "src/jolt/clojure/walk.clj")
|
||||
(cons "clojure.template" "src/jolt/clojure/template.clj")
|
||||
(cons "clojure.edn" "src/jolt/clojure/edn.clj")
|
||||
(cons "clojure.set" "src/jolt/clojure/set.clj")
|
||||
(cons "clojure.pprint" "src/jolt/clojure/pprint.clj"))))
|
||||
|
||||
;; Join a list of form strings with "\n", no trailing newline.
|
||||
(define (ei-join forms)
|
||||
(let join ((fs forms) (out ""))
|
||||
(cond
|
||||
((null? fs) out)
|
||||
((string=? out "") (join (cdr fs) (car fs)))
|
||||
(else (join (cdr fs) (string-append out "\n" (car fs)))))))
|
||||
|
||||
;; Re-emit the whole list of (ns . file) pairs ON CHEZ as one Scheme string.
|
||||
(define (ei-emit-ns-files nfs)
|
||||
(ei-join (apply append
|
||||
(map (lambda (nf) (ei-emit-ns (car nf) (read-file-string (cdr nf)))) nfs))))
|
||||
|
||||
;; Emit the compiler image (jolt.ir + jolt.analyzer + jolt.backend-scheme) on Chez.
|
||||
(define (jolt-emit-image) (ei-emit-ns-files ei-compiler-ns-files))
|
||||
|
||||
;; Emit the clojure.core prelude (all tiers + stdlib) on Chez — the prelude half of
|
||||
;; the self-hosting fixpoint.
|
||||
(define (jolt-emit-prelude) (ei-emit-ns-files ei-prelude-ns-files))
|
||||
77
host/chez/host-class.ss
Normal file
77
host/chez/host-class.ss
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
;; host class tokens (jolt-13zk) — a bare class name (String, Keyword, File...)
|
||||
;; evaluates to its JVM canonical-name STRING, the same value (class instance)
|
||||
;; returns, so (= String (class "x")) holds and a (defmethod m String ...) keys
|
||||
;; against a (class …) dispatch (ring.util.request does this).
|
||||
;; The analyzer resolves these names to clojure.core vars, so the back end emits
|
||||
;; (var-deref "clojure.core" "String") — def-var!'ing the canonical strings here is
|
||||
;; all that's needed at runtime.
|
||||
;;
|
||||
;; Loaded after natives-meta.ss (jolt-type) + the printer (jolt-str-render-one).
|
||||
|
||||
;; (class x) — Clojure's class of a value. Scalars map to their JVM class name,
|
||||
;; matching core-class. Collections/seqs have no JVM class on this host;
|
||||
;; (str (type x)) is the clean host taxonomy and
|
||||
;; is never compared against a class token in the corpus. Records yield their
|
||||
;; ns-qualified class name (= (str (type x))). Total — never crashes.
|
||||
(define (jolt-class x)
|
||||
(cond
|
||||
((jolt-nil? x) jolt-nil)
|
||||
((boolean? x) "java.lang.Boolean")
|
||||
;; per-type number classes, like the JVM: integer -> Long, flonum -> Double,
|
||||
;; exact non-integer -> Ratio.
|
||||
((and (number? x) (flonum? x)) "java.lang.Double")
|
||||
((and (number? x) (exact? x) (integer? x)) "java.lang.Long")
|
||||
((and (number? x) (exact? x) (rational? x)) "clojure.lang.Ratio")
|
||||
((number? x) "java.lang.Number")
|
||||
((string? x) "java.lang.String")
|
||||
((keyword? x) "clojure.lang.Keyword")
|
||||
((symbol-t? x) "clojure.lang.Symbol")
|
||||
((jolt-atom? x) "clojure.lang.Atom")
|
||||
((char? x) "java.lang.Character")
|
||||
((procedure? x) "clojure.lang.IFn")
|
||||
(else (jolt-str-render-one (jolt-type x)))))
|
||||
|
||||
(def-var! "clojure.core" "class" jolt-class)
|
||||
|
||||
;; bare class-name tokens -> canonical JVM class-name strings.
|
||||
(define class-token-alist
|
||||
'(("String" . "java.lang.String") ("Number" . "java.lang.Number")
|
||||
("Boolean" . "java.lang.Boolean") ("Long" . "java.lang.Long")
|
||||
("Integer" . "java.lang.Integer") ("Double" . "java.lang.Double")
|
||||
("Object" . "java.lang.Object") ("Character" . "java.lang.Character")
|
||||
("InputStream" . "java.io.InputStream") ("OutputStream" . "java.io.OutputStream")
|
||||
("File" . "java.io.File") ("Reader" . "java.io.Reader") ("Writer" . "java.io.Writer")
|
||||
("ISeq" . "clojure.lang.ISeq") ("Keyword" . "clojure.lang.Keyword")
|
||||
("Symbol" . "clojure.lang.Symbol") ("MapEntry" . "clojure.lang.MapEntry")
|
||||
("StringReader" . "java.io.StringReader") ("StringWriter" . "java.io.StringWriter")
|
||||
("StringBuilder" . "java.lang.StringBuilder")
|
||||
("StringTokenizer" . "java.util.StringTokenizer")
|
||||
("Charset" . "java.nio.charset.Charset") ("Base64" . "java.util.Base64")
|
||||
("Exception" . "java.lang.Exception")
|
||||
("IllegalArgumentException" . "java.lang.IllegalArgumentException")
|
||||
("InterruptedException" . "java.lang.InterruptedException")
|
||||
("Throwable" . "java.lang.Throwable")))
|
||||
(for-each
|
||||
(lambda (pair) (def-var! "clojure.core" (car pair) (cdr pair)))
|
||||
class-token-alist)
|
||||
|
||||
;; resolve a ^Type hint symbol-name to its canonical class name at def time
|
||||
;; (jolt-a1ir): "String" -> "java.lang.String", matching the JVM compiler. An
|
||||
;; already-canonical name maps to itself; an unknown name yields #f (left as-is).
|
||||
(define class-hint-table (make-hashtable string-hash string=?))
|
||||
(for-each (lambda (p) (hashtable-set! class-hint-table (car p) (cdr p))) class-token-alist)
|
||||
(for-each (lambda (p) (hashtable-set! class-hint-table (cdr p) (cdr p))) class-token-alist)
|
||||
(define (resolve-class-hint name) (hashtable-ref class-hint-table name #f))
|
||||
(def-var! "jolt.host" "resolve-class-hint" resolve-class-hint)
|
||||
|
||||
;; fully-qualified canonical class names self-evaluate to their own name string,
|
||||
;; so (= (class 1) java.lang.Long) and (instance? clojure.lang.Atom x) resolve the
|
||||
;; class token (= what jolt-class / instance-check key on).
|
||||
;; Value classes only — NOT the collection interfaces (ISeq/IPersistentMap/...),
|
||||
;; which downstream code (e.g. SCI) references as protocols/interfaces.
|
||||
(for-each
|
||||
(lambda (nm) (def-var! "clojure.core" nm nm))
|
||||
'("java.lang.Long" "java.lang.Integer" "java.lang.Double" "java.lang.Float"
|
||||
"java.lang.Number" "java.lang.String" "java.lang.Boolean" "java.lang.Character"
|
||||
"java.lang.Object"
|
||||
"clojure.lang.Keyword" "clojure.lang.Symbol" "clojure.lang.Ratio" "clojure.lang.Atom"))
|
||||
334
host/chez/host-contract.ss
Normal file
334
host/chez/host-contract.ss
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
;; host-contract.ss (jolt-hs9n, Phase 3 inc6) — the jolt.host contract on Chez.
|
||||
;;
|
||||
;; The portable seam between jolt-core (analyzer/IR/emitter, cross-compiled to
|
||||
;; Scheme) and the host. Every
|
||||
;; contract fn is def-var!'d into the "jolt.host" namespace so the cross-compiled
|
||||
;; jolt.analyzer / jolt.backend-scheme — whose unqualified form-*/resolve-global/
|
||||
;; ... refs lower to (var-deref "jolt.host" ...) — resolve here at runtime.
|
||||
;;
|
||||
;; This is what puts analyze->IR->emit ON CHEZ (the zero-Janet spine). It runs
|
||||
;; over the Chez data reader's forms (reader.ss): symbols are symbol-t, lists are
|
||||
;; cseq (list?), () is empty-list-t, vectors/maps are pvec/pmap, sets and #tag/
|
||||
;; regex/inst/uuid are pmaps tagged :jolt/type, chars are NATIVE Chez chars.
|
||||
;;
|
||||
;; Loaded after rt.ss + reader.ss + the core prelude; before the compiler image.
|
||||
|
||||
;; --- the analyze ctx --------------------------------------------------------
|
||||
;; ctx is opaque to the analyzer (only ever threaded to these contract fns); we
|
||||
;; make it a box carrying the compile namespace. The var/ns registry it consults
|
||||
;; is the global var-table (rt.ss).
|
||||
(define-record-type chez-actx (fields (mutable cns)) (nongenerative chez-actx-v1))
|
||||
(define (make-analyze-ctx ns) (make-chez-actx ns))
|
||||
|
||||
;; Interned keywords reused for form tags + resolve-global's result map.
|
||||
(define hc-kw-jolt-type (keyword "jolt" "type"))
|
||||
(define hc-kw-jolt-set (keyword "jolt" "set"))
|
||||
(define hc-kw-jolt-tagged (keyword "jolt" "tagged"))
|
||||
(define hc-kw-value (keyword #f "value"))
|
||||
(define hc-kw-tag (keyword #f "tag"))
|
||||
(define hc-kw-form (keyword #f "form"))
|
||||
(define hc-kw-kind (keyword #f "kind"))
|
||||
(define hc-kw-ns (keyword #f "ns"))
|
||||
(define hc-kw-name (keyword #f "name"))
|
||||
(define hc-kw-var (keyword #f "var"))
|
||||
(define hc-kw-unresolved (keyword #f "unresolved"))
|
||||
(define hc-kw-regex (keyword #f "regex"))
|
||||
(define hc-kw-inst (keyword #f "#inst"))
|
||||
(define hc-kw-uuid (keyword #f "#uuid"))
|
||||
(define hc-kw-bigdec (keyword #f "bigdec"))
|
||||
|
||||
;; --- form predicates --------------------------------------------------------
|
||||
(define (hc-sym? x) (symbol-t? x))
|
||||
;; ANY non-empty seq is a list form for analysis (a macro/eval form built via
|
||||
;; concat/map/cons is a lazy cseq with list?=#f, but evaluating it still means
|
||||
;; calling its head) — not just reader-built lists (jolt-cf1q.7).
|
||||
(define (hc-list? x) (or (empty-list-t? x) (cseq? x)))
|
||||
(define (hc-vec? x) (pvec? x))
|
||||
(define (hc-map? x) (and (pmap? x) (jolt-nil? (jolt-get x hc-kw-jolt-type))))
|
||||
;; A set form is the reader's tagged map {:jolt/type :jolt/set :value <pvec>} OR a
|
||||
;; real pset value — a macro template's #{...} expansion (syntax-quote.ss jolt-sqset)
|
||||
;; produces a pset, which the analyzer must still read as a set literal (jolt-r9lm).
|
||||
(define (hc-set? x)
|
||||
(or (pset? x)
|
||||
(and (pmap? x) (eq? (jolt-get x hc-kw-jolt-type) hc-kw-jolt-set))))
|
||||
(define (hc-char? x) (char? x))
|
||||
(define (hc-keyword? x) (keyword? x))
|
||||
(define (hc-literal? x)
|
||||
(or (jolt-nil? x) (boolean? x) (number? x) (string? x) (keyword-t? x) (char? x)))
|
||||
|
||||
(define (hc-tagged-of x tag)
|
||||
(and (pmap? x)
|
||||
(eq? (jolt-get x hc-kw-jolt-type) hc-kw-jolt-tagged)
|
||||
(eq? (jolt-get x hc-kw-tag) tag)))
|
||||
(define (hc-regex? x) (hc-tagged-of x hc-kw-regex))
|
||||
(define (hc-inst? x) (hc-tagged-of x hc-kw-inst))
|
||||
(define (hc-uuid? x) (hc-tagged-of x hc-kw-uuid))
|
||||
(define (hc-bigdec? x) (hc-tagged-of x hc-kw-bigdec))
|
||||
(define (hc-bigdec-source x) (jolt-get x hc-kw-form))
|
||||
;; A live namespace value spliced into a form (e.g. `(str ~*ns*) in a macro):
|
||||
;; the analyzer can't carry an opaque runtime value, so recognize a jns and
|
||||
;; reconstruct it by name at the call site (jolt-8sha).
|
||||
(define (hc-ns-value? x) (jns? x))
|
||||
(define (hc-ns-value-name x) (jns-name x))
|
||||
|
||||
;; --- form accessors ---------------------------------------------------------
|
||||
(define (hc-char-code x) (char->integer x)) ; native Chez char -> codepoint
|
||||
(define (hc-sym-name x) (symbol-t-name x))
|
||||
;; The reader stores an unqualified symbol's ns inconsistently (#f, '(), or
|
||||
;; jolt-nil — see converters.ss). The contract is jolt-nil for unqualified (the
|
||||
;; analyzer tests (nil? ns)), so normalize; a real ns string passes through.
|
||||
(define (hc-sym-ns x)
|
||||
(let ((ns (symbol-t-ns x)))
|
||||
(if (and ns (not (jolt-nil? ns)) (not (null? ns))) ns jolt-nil)))
|
||||
(define (hc-sym-meta x)
|
||||
(let ((m (symbol-t-meta x)))
|
||||
(if (and m (not (jolt-nil? m)) (not (null? m))) m jolt-nil)))
|
||||
|
||||
;; list items -> jolt vector (pvec); the analyzer mapv's over the result.
|
||||
(define (hc-elements x)
|
||||
(cond ((empty-list-t? x) empty-pvec)
|
||||
((cseq? x) (make-pvec (list->vector (seq->list x))))
|
||||
(else empty-pvec)))
|
||||
(define (hc-vec-items x) x) ; already a pvec
|
||||
(define (hc-set-items x)
|
||||
(if (pset? x)
|
||||
(apply jolt-vector (pset-fold x cons '()))
|
||||
(jolt-get x hc-kw-value)))
|
||||
(define (hc-map-pairs x)
|
||||
(let ((kv (hashtable-ref rdr-map-order x #f)))
|
||||
(if kv
|
||||
;; reader-built map literal: emit pairs in SOURCE order (kv = k1 v1 k2 v2 …)
|
||||
;; so the analyzer evaluates the values left-to-right (jolt-qjr0).
|
||||
(let loop ((kv kv) (acc '()))
|
||||
(if (null? kv) (apply jolt-vector (reverse acc))
|
||||
(loop (cddr kv) (cons (jolt-vector (car kv) (cadr kv)) acc))))
|
||||
;; a runtime/non-reader map: pmap iteration order
|
||||
(let loop ((ks (if (jolt-nil? (jolt-seq (jolt-keys x))) '()
|
||||
(seq->list (jolt-seq (jolt-keys x))))) (acc '()))
|
||||
(if (null? ks) (apply jolt-vector (reverse acc))
|
||||
(loop (cdr ks) (cons (jolt-vector (car ks) (jolt-get x (car ks))) acc)))))))
|
||||
(define (hc-regex-source x) (jolt-get x hc-kw-form))
|
||||
(define (hc-inst-source x) (jolt-get x hc-kw-form))
|
||||
(define (hc-uuid-source x) (jolt-get x hc-kw-form))
|
||||
|
||||
;; The Chez reader does not record source offsets yet (jolt-q2kg).
|
||||
(define (hc-form-position x) jolt-nil)
|
||||
|
||||
;; --- special forms ----------------------------------------------------------
|
||||
;; Mirrors host_iface special-names + interop-head? — forms the analyzer marks
|
||||
;; uncompilable (the handled specials are dispatched in analyze-list BEFORE this).
|
||||
;; `eval` is NOT here: it is a clojure.core FUNCTION on the spine (compile-eval.ss
|
||||
;; def-var!s it), so it must resolve as an ordinary var, not punt (jolt-r8ku).
|
||||
;; `defmacro` stays special — the spine intercepts it before analysis.
|
||||
(define hc-special-names
|
||||
'("quote" "syntax-quote" "unquote" "unquote-splicing" "do" "if" "def"
|
||||
"defmacro" "fn*" "let*" "loop*" "recur" "throw" "try" "set!" "new"
|
||||
"." "gen-class" "monitor-enter" "monitor-exit" "letfn"))
|
||||
(define (hc-interop-head? name)
|
||||
(let ((n (string-length name)))
|
||||
(and (> n 1)
|
||||
(not (string=? name "..")) ; the .. threading macro, not an interop form
|
||||
(or (char=? (string-ref name 0) #\.)
|
||||
(char=? (string-ref name (- n 1)) #\.)))))
|
||||
(define (hc-special? name)
|
||||
(if (or (member name hc-special-names) (hc-interop-head? name)) #t #f))
|
||||
|
||||
;; --- compile-time environment -----------------------------------------------
|
||||
(define (hc-current-ns ctx) (chez-actx-cns ctx))
|
||||
(define (hc-late-bind? ctx) #t) ; Chez has no interpreter to punt to
|
||||
|
||||
;; Resolve a global symbol to its var cell against the compile ns then clojure.core
|
||||
;; (a qualified ns wins). Shared by resolve-global / form-macro? / form-expand-1.
|
||||
;; Normalizes the reader's unqualified-ns sentinel (#f / '() / jolt-nil) like
|
||||
;; hc-sym-ns, so an unqualified symbol never looks up a bogus "#f" namespace.
|
||||
(define (hc-resolve-cell ctx sym)
|
||||
(let* ((nm (symbol-t-name sym))
|
||||
(sns (symbol-t-ns sym))
|
||||
(qualified (and sns (not (jolt-nil? sns)) (not (null? sns)) sns)))
|
||||
(if qualified
|
||||
;; a qualified ns may be a require :as alias (s/split -> clojure.string/split)
|
||||
(let ((target (or (chez-resolve-alias (chez-actx-cns ctx) qualified) qualified)))
|
||||
(var-cell-lookup target nm))
|
||||
(or (var-cell-lookup (chez-actx-cns ctx) nm)
|
||||
;; a :refer'd name resolves to its source ns
|
||||
(let ((ref (chez-resolve-refer (chez-actx-cns ctx) nm)))
|
||||
(and ref (var-cell-lookup ref nm)))
|
||||
(var-cell-lookup "clojure.core" nm)))))
|
||||
|
||||
;; Runtime macros (jolt-r9lm, inc6b): a defmacro is emitted into the prelude as a
|
||||
;; def-var! of its cross-compiled expander fn plus (mark-macro! ns name), so the
|
||||
;; var cell is flagged a macro (rt.ss var-macro-table). form-macro? checks the
|
||||
;; flag; form-expand-1 applies the expander to the unevaluated arg forms (the rest
|
||||
;; of the list), and the analyzer re-analyzes the returned form.
|
||||
(define (hc-macro? ctx sym)
|
||||
(macro-var? (hc-resolve-cell ctx sym)))
|
||||
(define (hc-expand-1 ctx form)
|
||||
(let* ((items (seq->list form))
|
||||
(head (car items))
|
||||
(args (cdr items))
|
||||
(expander (var-cell-root (hc-resolve-cell ctx head))))
|
||||
(apply jolt-invoke expander args)))
|
||||
|
||||
;; Classify a global (non-local) symbol reference against the var registry:
|
||||
;; {:kind :var :ns NS :name NAME} — a defined var (compile ns / clojure.core)
|
||||
;; {:kind :unresolved :name NAME} — not found (late-bind -> var-ref @ compile ns;
|
||||
;; a qualified one -> host-static in the analyzer)
|
||||
;; No :host branch: there is no Janet-style native-op env on Chez — the hot
|
||||
;; clojure.core primitives (+,-,map,...) are declared in clojure.core below so
|
||||
;; they classify as :var and the emitter's native-op path lowers them.
|
||||
(define (hc-resolve-global ctx sym)
|
||||
(let* ((nm (symbol-t-name sym))
|
||||
(cell (hc-resolve-cell ctx sym)))
|
||||
(if (and cell (var-cell-defined? cell))
|
||||
(jolt-hash-map hc-kw-kind hc-kw-var
|
||||
hc-kw-ns (var-cell-ns cell)
|
||||
hc-kw-name (var-cell-name cell))
|
||||
(jolt-hash-map hc-kw-kind hc-kw-unresolved hc-kw-name nm))))
|
||||
|
||||
(define (hc-intern! ctx ns-name nm) (declare-var! ns-name nm) jolt-nil)
|
||||
|
||||
;; --- syntax-quote lowering (jolt-qjr0, inc7) ---------------------------------
|
||||
;; Lowers a `form
|
||||
;; to CONSTRUCTION CODE — Chez reader forms calling __sqcat/__sqvec/__sqmap/
|
||||
;; __sqset/__sq1 + quote — that the analyzer re-analyzes, so a backtick compiles
|
||||
;; with zero runtime cost (read -> macroexpand -> compile). Symbols resolve to
|
||||
;; clojure.core / the compile ns; a foo# auto-gensym is stable within one `.
|
||||
(define hc-special-symbols
|
||||
'("quote" "syntax-quote" "unquote" "unquote-splicing" "do" "if" "def"
|
||||
"defmacro" "fn*" "let*" "loop*" "recur" "throw" "try" "set!" "var"
|
||||
"new" "."))
|
||||
(define (hc-special-symbol? nm) (and (member nm hc-special-symbols) #t))
|
||||
|
||||
(define hc-sq-gensym-counter 0)
|
||||
(define (hc-sq-gensym base)
|
||||
(set! hc-sq-gensym-counter (+ hc-sq-gensym-counter 1))
|
||||
(jolt-symbol #f (string-append base "__" (number->string hc-sq-gensym-counter) "__auto")))
|
||||
|
||||
(define (hc-sym nm) (jolt-symbol #f nm))
|
||||
;; is `x` a non-empty list FORM whose head is the unqualified symbol `nm`?
|
||||
(define (hc-head-is? x nm)
|
||||
(and (cseq? x) (cseq-list? x)
|
||||
(let ((h (seq-first x)))
|
||||
(and (symbol-t? h) (jolt-nil? (hc-sym-ns h)) (string=? (symbol-t-name h) nm)))))
|
||||
(define (hc-second x) (seq-first (jolt-seq (seq-more x))))
|
||||
|
||||
(define (hc-sq-symbol ctx form gsmap)
|
||||
(let ((sns (hc-sym-ns form)) (nm (symbol-t-name form)))
|
||||
(if (jolt-nil? sns)
|
||||
(cond
|
||||
;; foo# -> a stable per-` auto-gensym
|
||||
((and (> (string-length nm) 0)
|
||||
(char=? (string-ref nm (- (string-length nm) 1)) #\#))
|
||||
(or (hashtable-ref gsmap nm #f)
|
||||
(let ((g (hc-sq-gensym (substring nm 0 (- (string-length nm) 1)))))
|
||||
(hashtable-set! gsmap nm g) g)))
|
||||
((hc-special-symbol? nm) form) ; special form: leave bare
|
||||
((hc-interop-head? nm) form) ; interop (.method / Class. / .-field): bare
|
||||
((var-cell-lookup "clojure.core" nm) (jolt-symbol "clojure.core" nm))
|
||||
(else (jolt-symbol (chez-actx-cns ctx) nm))) ; else: qualify to compile ns
|
||||
;; qualified: if the ns part is an :as alias in the compile ns, resolve it
|
||||
;; to the target namespace — Clojure resolves the alias part of a qualified
|
||||
;; symbol in syntax-quote, so a macro's `impl/foo` expands to its real
|
||||
;; (clojure.tools.logging.impl/foo) name and stays unambiguous even when
|
||||
;; another loaded ns shares the alias's short name (jolt-qjr0). Otherwise
|
||||
;; leave it as written (a real ns or an interop class token).
|
||||
(let ((target (chez-resolve-alias (chez-actx-cns ctx) sns)))
|
||||
(if target (jolt-symbol target nm) form)))))
|
||||
|
||||
(define (hc-sq-lower ctx form gsmap)
|
||||
(cond
|
||||
((hc-head-is? form "unquote") (hc-second form))
|
||||
((hc-head-is? form "unquote-splicing")
|
||||
(jolt-throw (jolt-ex-info "~@ used outside of a list or vector in syntax-quote"
|
||||
(jolt-hash-map))))
|
||||
((hc-literal? form) form)
|
||||
((symbol-t? form) (jolt-list (hc-sym "quote") (hc-sq-symbol ctx form gsmap)))
|
||||
((hc-list? form)
|
||||
(apply jolt-list (hc-sym "__sqcat")
|
||||
(map (lambda (it) (hc-sq-lower-part ctx it gsmap)) (seq->list form))))
|
||||
((hc-vec? form)
|
||||
(apply jolt-list (hc-sym "__sqvec")
|
||||
(map (lambda (it) (hc-sq-lower-part ctx it gsmap)) (seq->list form))))
|
||||
((hc-set? form)
|
||||
(apply jolt-list (hc-sym "__sqset")
|
||||
(map (lambda (it) (hc-sq-lower-part ctx it gsmap)) (seq->list (hc-set-items form)))))
|
||||
((hc-map? form)
|
||||
(apply jolt-list (hc-sym "__sqmap")
|
||||
(let loop ((pairs (seq->list (hc-map-pairs form))) (acc '()))
|
||||
(if (null? pairs) (reverse acc)
|
||||
(let ((p (seq->list (car pairs))))
|
||||
(loop (cdr pairs)
|
||||
(cons (hc-sq-lower ctx (cadr p) gsmap)
|
||||
(cons (hc-sq-lower ctx (car p) gsmap) acc))))))))
|
||||
(else (jolt-list (hc-sym "quote") form)))) ; tagged (char/regex/...) etc.
|
||||
|
||||
;; a list/vector/set element: a ~@ splice passes through (its seq is spliced by
|
||||
;; __sqcat), any other item is wrapped (__sq1 <lowered>) so __sqcat flattens it.
|
||||
(define (hc-sq-lower-part ctx item gsmap)
|
||||
(if (hc-head-is? item "unquote-splicing")
|
||||
(hc-second item)
|
||||
(jolt-list (hc-sym "__sq1") (hc-sq-lower ctx item gsmap))))
|
||||
|
||||
(define (hc-syntax-quote-lower ctx inner)
|
||||
(hc-sq-lower ctx inner (make-hashtable string-hash string=?)))
|
||||
(define (hc-record-type? ctx name) #f)
|
||||
(define (hc-record-ctor-key ctx name) jolt-nil)
|
||||
(define (hc-record-shapes ctx) (jolt-hash-map))
|
||||
(define (hc-inline-enabled? ctx) #f)
|
||||
(define (hc-inline-ir ctx ns-name nm) jolt-nil)
|
||||
|
||||
;; --- declare the hot clojure.core primitives so resolve-global sees them ------
|
||||
;; (mirrors backend_scheme.clj native-ops keys — the emitter lowers these inline,
|
||||
;; so the declared cell's unbound root is never deref'd.)
|
||||
(for-each (lambda (nm) (declare-var! "clojure.core" nm))
|
||||
'("+" "-" "*" "/" "<" ">" "<=" ">=" "=" "inc" "dec" "not" "min" "max"
|
||||
"mod" "rem" "quot" "vector" "hash-map" "hash-set" "conj" "get" "nth" "count"
|
||||
"assoc" "dissoc" "contains?" "empty?" "peek" "pop" "first" "rest" "next" "seq"
|
||||
"cons" "list" "reverse" "last" "map" "filter" "remove" "reduce" "into" "concat"
|
||||
"apply" "range" "take" "drop" "keys" "vals" "even?" "odd?" "pos?" "neg?"
|
||||
"zero?" "identity" "ex-info"))
|
||||
|
||||
;; --- install: bind the contract into the jolt.host namespace -----------------
|
||||
(define (hc-install!)
|
||||
(def-var! "jolt.host" "form-sym?" hc-sym?)
|
||||
(def-var! "jolt.host" "form-sym-name" hc-sym-name)
|
||||
(def-var! "jolt.host" "form-sym-ns" hc-sym-ns)
|
||||
(def-var! "jolt.host" "form-sym-meta" hc-sym-meta)
|
||||
(def-var! "jolt.host" "form-list?" hc-list?)
|
||||
(def-var! "jolt.host" "form-vec?" hc-vec?)
|
||||
(def-var! "jolt.host" "form-map?" hc-map?)
|
||||
(def-var! "jolt.host" "form-set?" hc-set?)
|
||||
(def-var! "jolt.host" "form-char?" hc-char?)
|
||||
(def-var! "jolt.host" "form-char-code" hc-char-code)
|
||||
(def-var! "jolt.host" "form-literal?" hc-literal?)
|
||||
(def-var! "jolt.host" "form-keyword?" hc-keyword?)
|
||||
(def-var! "jolt.host" "form-regex?" hc-regex?)
|
||||
(def-var! "jolt.host" "form-inst?" hc-inst?)
|
||||
(def-var! "jolt.host" "form-uuid?" hc-uuid?)
|
||||
(def-var! "jolt.host" "form-ns-value?" hc-ns-value?)
|
||||
(def-var! "jolt.host" "form-ns-value-name" hc-ns-value-name)
|
||||
(def-var! "jolt.host" "form-bigdec?" hc-bigdec?)
|
||||
(def-var! "jolt.host" "form-bigdec-source" hc-bigdec-source)
|
||||
(def-var! "jolt.host" "form-elements" hc-elements)
|
||||
(def-var! "jolt.host" "form-vec-items" hc-vec-items)
|
||||
(def-var! "jolt.host" "form-set-items" hc-set-items)
|
||||
(def-var! "jolt.host" "form-map-pairs" hc-map-pairs)
|
||||
(def-var! "jolt.host" "form-regex-source" hc-regex-source)
|
||||
(def-var! "jolt.host" "form-inst-source" hc-inst-source)
|
||||
(def-var! "jolt.host" "form-uuid-source" hc-uuid-source)
|
||||
(def-var! "jolt.host" "form-position" hc-form-position)
|
||||
(def-var! "jolt.host" "form-special?" hc-special?)
|
||||
(def-var! "jolt.host" "compile-ns" hc-current-ns)
|
||||
(def-var! "jolt.host" "late-bind?" hc-late-bind?)
|
||||
(def-var! "jolt.host" "form-macro?" hc-macro?)
|
||||
(def-var! "jolt.host" "form-expand-1" hc-expand-1)
|
||||
(def-var! "jolt.host" "resolve-global" hc-resolve-global)
|
||||
(def-var! "jolt.host" "host-intern!" hc-intern!)
|
||||
(def-var! "jolt.host" "form-syntax-quote-lower" hc-syntax-quote-lower)
|
||||
(def-var! "jolt.host" "record-type?" hc-record-type?)
|
||||
(def-var! "jolt.host" "record-ctor-key" hc-record-ctor-key)
|
||||
(def-var! "jolt.host" "record-shapes" hc-record-shapes)
|
||||
(def-var! "jolt.host" "inline-enabled?" hc-inline-enabled?)
|
||||
(def-var! "jolt.host" "inline-ir" hc-inline-ir))
|
||||
|
||||
(hc-install!)
|
||||
647
host/chez/host-static.ss
Normal file
647
host/chez/host-static.ss
Normal file
|
|
@ -0,0 +1,647 @@
|
|||
;; host-static.ss (jolt-avt6) — host class statics + constructors on Chez.
|
||||
;;
|
||||
;; The analyzer lowers `Class/member` to a :host-static node and `(Class. ...)` /
|
||||
;; `(new Class ...)` to a :host-new node (jolt-core/jolt/analyzer.clj); the Chez
|
||||
;; emit lowers a value ref to (host-static-ref "Class" "member"), a
|
||||
;; call head to (host-static-call "Class" "member" args...), and a constructor to
|
||||
;; (host-new "Class" args...). This file is the runtime registry those three
|
||||
;; resolve against — the class-statics / class-ctors /
|
||||
;; tagged-methods registries,
|
||||
;; restricted to the java.lang/util/net/io surface portable cljc code calls.
|
||||
;; (java.time formatting is a separate increment.)
|
||||
;;
|
||||
;; Constructed host objects are `jhost` records (a tag + mutable state); their
|
||||
;; (.method ...) calls reach record-method-dispatch (records.ss), extended below
|
||||
;; with a jhost arm that dispatches through host-tagged-methods.
|
||||
;;
|
||||
;; Loaded from rt.ss LAST (after natives-str.ss / records.ss): it extends
|
||||
;; record-method-dispatch and reuses jolt-str-render-one / jolt-re-pattern.
|
||||
|
||||
;; ---- registries -------------------------------------------------------------
|
||||
(define class-statics-tbl (make-hashtable string-hash string=?)) ; "Class" -> (member-ht)
|
||||
(define class-ctors-tbl (make-hashtable string-hash string=?)) ; "Class" -> ctor proc
|
||||
(define host-methods-tbl (make-hashtable string-hash string=?)) ; tag -> (method-ht)
|
||||
|
||||
;; A class token may arrive fully qualified (java.io.StringReader) or short
|
||||
;; (StringReader). Register both; resolve by exact then by last dotted segment.
|
||||
(define (short-class-name s)
|
||||
(let loop ((i (- (string-length s) 1)))
|
||||
(cond ((< i 0) s)
|
||||
((char=? (string-ref s i) #\.) (substring s (+ i 1) (string-length s)))
|
||||
(else (loop (- i 1))))))
|
||||
|
||||
(define (register-class-statics! name members) ; members: list of (str . val/proc)
|
||||
(let ((h (or (hashtable-ref class-statics-tbl name #f)
|
||||
(let ((h (make-hashtable string-hash string=?)))
|
||||
(hashtable-set! class-statics-tbl name h) h))))
|
||||
(for-each (lambda (p) (hashtable-set! h (car p) (cdr p))) members)))
|
||||
|
||||
(define (register-class-ctor! name proc) (hashtable-set! class-ctors-tbl name proc))
|
||||
|
||||
(define (register-host-methods! tag members)
|
||||
(let ((h (or (hashtable-ref host-methods-tbl tag #f)
|
||||
(let ((h (make-hashtable string-hash string=?)))
|
||||
(hashtable-set! host-methods-tbl tag h) h))))
|
||||
(for-each (lambda (p) (hashtable-set! h (car p) (cdr p))) members)))
|
||||
|
||||
(define (lookup-class h-tbl name)
|
||||
(or (hashtable-ref h-tbl name #f)
|
||||
(hashtable-ref h-tbl (short-class-name name) #f)))
|
||||
|
||||
;; ---- host object ------------------------------------------------------------
|
||||
(define-record-type jhost (fields tag (mutable state)) (nongenerative chez-jhost-v1))
|
||||
|
||||
;; record-method-dispatch (records.ss) gets a jhost arm: dispatch (.method obj a*)
|
||||
;; through the tag's method table.
|
||||
(define %hs-record-method-dispatch record-method-dispatch)
|
||||
(set! record-method-dispatch
|
||||
(lambda (obj method-name rest-args)
|
||||
(cond
|
||||
((jhost? obj)
|
||||
(let ((mh (hashtable-ref host-methods-tbl (jhost-tag obj) #f)))
|
||||
(let ((f (and mh (hashtable-ref mh method-name #f))))
|
||||
(if f
|
||||
(apply f obj (if (jolt-nil? rest-args) '() (seq->list rest-args)))
|
||||
(error #f (string-append "No method " method-name " on host " (jhost-tag obj)))))))
|
||||
((number? obj) (number-method method-name obj))
|
||||
(else (%hs-record-method-dispatch obj method-name rest-args)))))
|
||||
|
||||
;; java.lang.Number method surface (the boxed-number methods cljc code calls). The
|
||||
;; integer projections wrap modulo their width (ring-codec relies on byteValue
|
||||
;; overflow: (.byteValue 255) => -1); the float projections are identity flonums.
|
||||
(define (number-method method n)
|
||||
(cond
|
||||
((string=? method "byteValue") (let ((b (modulo (jnum->exact n) 256))) (->num (if (>= b 128) (- b 256) b))))
|
||||
((string=? method "shortValue") (let ((b (modulo (jnum->exact n) 65536))) (->num (if (>= b 32768) (- b 65536) b))))
|
||||
((string=? method "intValue") (->num (jnum->exact n)))
|
||||
((string=? method "longValue") (->num (jnum->exact n)))
|
||||
((string=? method "doubleValue") (->num n))
|
||||
((string=? method "floatValue") (->num n))
|
||||
((string=? method "toString") (jolt-num->string n))
|
||||
((string=? method "hashCode") (->num (jnum->exact n)))
|
||||
(else (error #f (string-append "No method " method " for number")))))
|
||||
|
||||
;; ---- emit entry points ------------------------------------------------------
|
||||
(define (host-static-ref class member)
|
||||
(let ((h (lookup-class class-statics-tbl class)))
|
||||
(if h
|
||||
(let ((v (hashtable-ref h member #f)))
|
||||
(if v v (error #f (string-append "No static " class "/" member))))
|
||||
(error #f (string-append "Unknown class " class)))))
|
||||
|
||||
(define (host-static-call class member . args)
|
||||
(apply (host-static-ref class member) args))
|
||||
|
||||
(define (host-new class . args)
|
||||
(let ((ctor (lookup-class class-ctors-tbl class)))
|
||||
(cond
|
||||
(ctor (apply ctor args))
|
||||
;; deftype/defrecord (jolt-499t): the type name is bound as a VAR (the
|
||||
;; make-deftype-ctor closure) in its defining ns, not a registered host class.
|
||||
;; Resolve it in the current ns / clojure.core and invoke it — so (P. args)
|
||||
;; works the same as the ->P factory.
|
||||
(else
|
||||
(let ((cell (or (var-cell-lookup (chez-current-ns) class)
|
||||
(var-cell-lookup "clojure.core" class))))
|
||||
(if (and cell (var-cell-defined? cell) (procedure? (var-cell-root cell)))
|
||||
(apply (var-cell-root cell) args)
|
||||
(error #f (string-append "No constructor for class " class))))))))
|
||||
|
||||
;; ---- coercion helpers -------------------------------------------------------
|
||||
;; numeric tower (jolt-n6al): currentTimeMillis/nanoTime are exact longs (JVM).
|
||||
(define (->num x) x)
|
||||
(define (jnum->exact n) (exact (truncate n)))
|
||||
;; parse an integer string in radix; #f on failure
|
||||
(define (parse-int-str s radix)
|
||||
(let ((n (string->number (str-trim (if (string? s) s (jolt-str-render-one s))) radix)))
|
||||
(and n (integer? n) (->num n))))
|
||||
(define (parse-int-or-throw s radix what)
|
||||
(or (parse-int-str s radix)
|
||||
(error #f (string-append "NumberFormatException: For input string: \""
|
||||
(if (string? s) s (jolt-str-render-one s)) "\""))))
|
||||
(define (char-code c) (if (char? c) (char->integer c) (jnum->exact c)))
|
||||
|
||||
;; ---- java.lang statics ------------------------------------------------------
|
||||
;; java.lang.Math: sqrt/pow/floor/ceil/trig/log/exp always return a DOUBLE on the
|
||||
;; JVM (Chez's sqrt/expt return EXACT for exact args, e.g. (sqrt 9) -> 3), so coerce
|
||||
;; to flonum. round -> long (exact); abs/max/min preserve the argument's type.
|
||||
(define (->dbl x) (exact->inexact x))
|
||||
(register-class-statics! "Math"
|
||||
(list (cons "sqrt" (lambda (x) (->dbl (sqrt x))))
|
||||
(cons "pow" (lambda (a b) (->dbl (expt a b))))
|
||||
(cons "floor" (lambda (x) (->dbl (floor x))))
|
||||
(cons "ceil" (lambda (x) (->dbl (ceiling x))))
|
||||
(cons "round" (lambda (x) (exact (floor (+ x 1/2))))) ; JVM round-half-up -> long
|
||||
(cons "abs" (lambda (x) (abs x)))
|
||||
(cons "sin" (lambda (x) (->dbl (sin x)))) (cons "cos" (lambda (x) (->dbl (cos x))))
|
||||
(cons "tan" (lambda (x) (->dbl (tan x)))) (cons "asin" (lambda (x) (->dbl (asin x))))
|
||||
(cons "acos" (lambda (x) (->dbl (acos x)))) (cons "atan" (lambda (x) (->dbl (atan x))))
|
||||
(cons "log" (lambda (x) (->dbl (log x)))) (cons "log10" (lambda (x) (->dbl (/ (log x) (log 10)))))
|
||||
(cons "exp" (lambda (x) (->dbl (exp x))))
|
||||
(cons "max" (lambda (a b) (if (> a b) a b))) (cons "min" (lambda (a b) (if (< a b) a b)))
|
||||
(cons "signum" (lambda (x) (cond ((< x 0) -1.0) ((> x 0) 1.0) (else 0.0))))
|
||||
(cons "PI" (->dbl (* 4 (atan 1)))) (cons "E" (->dbl (exp 1)))
|
||||
(cons "random" (lambda args (random 1.0)))))
|
||||
|
||||
;; Thread: real OS threads back futures/promises (jolt-byjr), so sleep genuinely
|
||||
;; parks the calling thread for `ms` milliseconds (a worker sleeping doesn't block
|
||||
;; the parent). yield hands off the scheduler.
|
||||
(register-class-statics! "Thread"
|
||||
(list (cons "sleep" (lambda (ms . _)
|
||||
(let* ((ms* (exact (floor ms)))
|
||||
(secs (quotient ms* 1000))
|
||||
(nanos (* (remainder ms* 1000) 1000000)))
|
||||
(sleep (make-time 'time-duration nanos secs)))
|
||||
jolt-nil))
|
||||
(cons "yield" (lambda () jolt-nil))
|
||||
(cons "interrupted" (lambda () #f))
|
||||
(cons "currentThread" (lambda () (make-jhost "thread" '())))))
|
||||
(register-host-methods! "thread"
|
||||
(list (cons "getContextClassLoader" (lambda (self) (make-jhost "classloader" '())))))
|
||||
|
||||
;; clojure.lang.LockingTransaction: jolt has no STM (no refs/dosync), so a
|
||||
;; transaction is never running. isRunning -> false (jolt-0obq).
|
||||
(register-class-statics! "LockingTransaction" (list (cons "isRunning" (lambda () #f))))
|
||||
(register-class-statics! "clojure.lang.LockingTransaction" (list (cons "isRunning" (lambda () #f))))
|
||||
|
||||
;; clojure.lang.LazilyPersistentVector/createOwning: build a vector from an array
|
||||
;; (malli's -vmap fills an object-array then hands it over). jolt has no array
|
||||
;; ownership transfer, so copy the array's elements into a persistent vector.
|
||||
(define (lpv-create-owning arr) (apply jolt-vector (seq->list (jolt-seq arr))))
|
||||
(register-class-statics! "LazilyPersistentVector" (list (cons "createOwning" lpv-create-owning)))
|
||||
(register-class-statics! "clojure.lang.LazilyPersistentVector" (list (cons "createOwning" lpv-create-owning)))
|
||||
|
||||
;; clojure.lang.PersistentArrayMap/createWithCheck: build a map from a [k v k v…]
|
||||
;; array, throwing on a duplicate key. malli's eager entry parser relies on the
|
||||
;; throw to report ::duplicate-keys, so a missing class would mis-fire on every
|
||||
;; map. Build the map and signal if a key collapsed (count*2 < array length).
|
||||
(define (pam-create-with-check arr)
|
||||
(let ((items (seq->list (jolt-seq arr))))
|
||||
(let loop ((xs items) (m (jolt-hash-map)))
|
||||
(if (null? xs) m
|
||||
(if (null? (cdr xs)) (error #f "PersistentArrayMap: odd key/value count")
|
||||
(let ((k (car xs)))
|
||||
(if (jolt-contains? m k) (error #f "Duplicate key")
|
||||
(loop (cddr xs) (jolt-assoc m k (cadr xs))))))))))
|
||||
(register-class-statics! "PersistentArrayMap" (list (cons "createWithCheck" pam-create-with-check)))
|
||||
(register-class-statics! "clojure.lang.PersistentArrayMap" (list (cons "createWithCheck" pam-create-with-check)))
|
||||
|
||||
(define (now-millis)
|
||||
(let ((t (current-time 'time-utc)))
|
||||
(+ (* 1000 (time-second t)) (quotient (time-nanosecond t) 1000000))))
|
||||
|
||||
;; clojure.core/current-time-ms — epoch milliseconds; backs the `time` macro.
|
||||
(def-var! "clojure.core" "current-time-ms" (lambda () (->num (now-millis))))
|
||||
(register-class-statics! "System"
|
||||
(list (cons "currentTimeMillis" (lambda () (->num (now-millis))))
|
||||
(cons "nanoTime" (lambda () (->num (* 1000000 (now-millis)))))
|
||||
(cons "exit" (lambda args (exit (if (null? args) 0 (jnum->exact (car args))))))
|
||||
;; wrapped in lambdas: the helpers are defined below, resolved at call time.
|
||||
(cons "getProperty" (lambda (k . d) (apply sys-get-property k d)))
|
||||
(cons "getProperties" (lambda () (sys-properties-map)))
|
||||
(cons "getenv" (lambda k (apply sys-getenv k)))))
|
||||
|
||||
(register-class-statics! "Long"
|
||||
(list (cons "MAX_VALUE" (->num 9223372036854775807))
|
||||
(cons "MIN_VALUE" (->num -9223372036854775808))
|
||||
(cons "parseLong" (lambda (s . r) (parse-int-or-throw s (if (null? r) 10 (jnum->exact (car r))) "parseLong")))
|
||||
(cons "valueOf" (lambda (s . r) (parse-int-or-throw s (if (null? r) 10 (jnum->exact (car r))) "valueOf")))))
|
||||
|
||||
(register-class-statics! "Integer"
|
||||
(list (cons "MAX_VALUE" (->num 2147483647)) (cons "MIN_VALUE" (->num -2147483648))
|
||||
(cons "valueOf" (lambda (x . r)
|
||||
(if (number? x) (->num x)
|
||||
(parse-int-or-throw x (if (null? r) 10 (jnum->exact (car r))) "valueOf"))))
|
||||
(cons "parseInt" (lambda (x . r) (parse-int-or-throw x (if (null? r) 10 (jnum->exact (car r))) "parseInt")))))
|
||||
|
||||
(register-class-statics! "Boolean"
|
||||
(list (cons "parseBoolean" (lambda (s) (string=? "true" (ascii-string-down (if (string? s) s (jolt-str-render-one s))))))
|
||||
(cons "TRUE" #t) (cons "FALSE" #f)))
|
||||
|
||||
;; Character: ASCII predicates (the engine is byte/ASCII oriented).
|
||||
(register-class-statics! "Character"
|
||||
(list (cons "isUpperCase" (lambda (c) (let ((n (char-code c))) (and (>= n 65) (<= n 90)))))
|
||||
(cons "isLowerCase" (lambda (c) (let ((n (char-code c))) (and (>= n 97) (<= n 122)))))
|
||||
(cons "isDigit" (lambda (c) (let ((n (char-code c))) (and (>= n 48) (<= n 57)))))
|
||||
(cons "isWhitespace" (lambda (c) (char<=? (integer->char (char-code c)) #\space)))))
|
||||
|
||||
;; String/valueOf(Object): "null" for nil, else jolt's str semantics.
|
||||
(register-class-statics! "String"
|
||||
(list (cons "valueOf" (lambda (x . _) (if (jolt-nil? x) "null" (jolt-str-render-one x))))))
|
||||
|
||||
(register-class-statics! "Class"
|
||||
;; an array descriptor ("[C", "[I", …) is its own class token (so instance? and
|
||||
;; class compare equal); other names become a class jhost.
|
||||
(list (cons "forName" (lambda (nm)
|
||||
(if (and (> (string-length nm) 0) (char=? (string-ref nm 0) #\[))
|
||||
nm
|
||||
(make-jhost "class" (list (cons 'name nm))))))))
|
||||
|
||||
;; ---- System helpers (defined before use above via top-level order) ----------
|
||||
(define (sys-get-property k . dflt)
|
||||
(cond ((string=? k "os.name") "Mac OS X")
|
||||
((string=? k "line.separator") "\n")
|
||||
((string=? k "file.separator") "/")
|
||||
((string=? k "path.separator") ":")
|
||||
((string=? k "user.dir") (or (getenv "PWD") "."))
|
||||
((string=? k "user.home") (or (getenv "HOME") ""))
|
||||
((string=? k "java.io.tmpdir") (or (getenv "TMPDIR") "/tmp"))
|
||||
((pair? dflt) (car dflt))
|
||||
(else jolt-nil)))
|
||||
(define (sys-properties-map)
|
||||
(jolt-hash-map "os.name" "Mac OS X" "line.separator" "\n" "file.separator" "/"
|
||||
"user.dir" (or (getenv "PWD") ".") "user.home" (or (getenv "HOME") "")
|
||||
"java.io.tmpdir" (or (getenv "TMPDIR") "/tmp")))
|
||||
|
||||
;; full environment as an alist of (name . value), via spawning `env`.
|
||||
(define (all-env-pairs)
|
||||
(call-with-values
|
||||
(lambda () (open-process-ports "env" (buffer-mode block) (native-transcoder)))
|
||||
(lambda (stdin stdout stderr pid)
|
||||
(let loop ((acc '()))
|
||||
(let ((l (get-line stdout)))
|
||||
(if (eof-object? l) (reverse acc)
|
||||
(let ((eq (let scan ((i 0)) (cond ((= i (string-length l)) #f)
|
||||
((char=? (string-ref l i) #\=) i)
|
||||
(else (scan (+ i 1)))))))
|
||||
(loop (if eq (cons (cons (substring l 0 eq) (substring l (+ eq 1) (string-length l))) acc) acc)))))))))
|
||||
;; JOLT_BAKE_ENV_ALLOWLIST (jolt-s3j): when set, only the listed comma-separated
|
||||
;; names are served; unset (the normal case) reads are live and unfiltered.
|
||||
(define (env-allowlist)
|
||||
(let ((a (getenv "JOLT_BAKE_ENV_ALLOWLIST")))
|
||||
(and a (map str-trim (str-literal-split a ",")))))
|
||||
(define (sys-getenv . k)
|
||||
(let ((allow (env-allowlist)))
|
||||
(if (null? k)
|
||||
(apply jolt-hash-map
|
||||
(let loop ((ps (all-env-pairs)) (acc '()))
|
||||
(cond ((null? ps) (reverse acc))
|
||||
((and allow (not (member (caar ps) allow))) (loop (cdr ps) acc))
|
||||
(else (loop (cdr ps) (cons (cdar ps) (cons (caar ps) acc)))))))
|
||||
(let ((name (car k)))
|
||||
(if (and allow (not (member name allow))) jolt-nil
|
||||
(let ((v (getenv name))) (if v v jolt-nil)))))))
|
||||
|
||||
;; ---- StringBuilder ----------------------------------------------------------
|
||||
;; state: a box (1-vector) holding the accumulated string.
|
||||
(define (sb-str self) (vector-ref (jhost-state self) 0))
|
||||
(define (sb-set! self s) (vector-set! (jhost-state self) 0 s))
|
||||
(define (render-piece x)
|
||||
(cond ((jolt-nil? x) "null") ((char? x) (string x)) ((string? x) x)
|
||||
(else (jolt-str-render-one x))))
|
||||
;; (Object.) — a fresh value with distinct identity (libraries use it as a lock
|
||||
;; or a unique sentinel). Each call returns a new jhost so identical?/= separate.
|
||||
(register-class-ctor! "Object" (lambda _ (make-jhost "object" (vector))))
|
||||
|
||||
(register-class-ctor! "StringBuilder"
|
||||
(lambda args (make-jhost "string-builder"
|
||||
;; a numeric first arg is a CAPACITY hint, not content.
|
||||
(vector (if (and (pair? args) (not (number? (car args)))) (render-piece (car args)) "")))))
|
||||
(register-host-methods! "string-builder"
|
||||
(list (cons "append" (lambda (self x) (sb-set! self (string-append (sb-str self) (render-piece x))) self))
|
||||
(cons "toString" (lambda (self) (sb-str self)))
|
||||
(cons "length" (lambda (self) (->num (string-length (sb-str self)))))
|
||||
(cons "charAt" (lambda (self i) (string-ref (sb-str self) (jnum->exact i))))
|
||||
(cons "setLength" (lambda (self n)
|
||||
(let ((cur (sb-str self)) (n (jnum->exact n)))
|
||||
(sb-set! self (if (< n (string-length cur))
|
||||
(substring cur 0 n)
|
||||
(string-append cur (make-string (- n (string-length cur)) #\nul)))))
|
||||
jolt-nil))))
|
||||
|
||||
;; ---- StringWriter -----------------------------------------------------------
|
||||
;; Writer.write(int) writes the CHAR for that code; append(char) appends the char.
|
||||
(define (writer-piece x) (if (number? x) (string (integer->char (jnum->exact x))) (render-piece x)))
|
||||
(register-class-ctor! "StringWriter" (lambda args (make-jhost "writer" (vector ""))))
|
||||
(register-host-methods! "writer"
|
||||
(list (cons "write" (lambda (self x) (sb-set! self (string-append (sb-str self) (writer-piece x))) jolt-nil))
|
||||
(cons "append" (lambda (self x) (sb-set! self (string-append (sb-str self) (render-piece x))) self))
|
||||
(cons "flush" (lambda (self) jolt-nil))
|
||||
(cons "close" (lambda (self) jolt-nil))
|
||||
(cons "toString" (lambda (self) (sb-str self)))))
|
||||
|
||||
;; a file-backed writer (clojure.java.io/writer of a File/path): accumulates like
|
||||
;; StringWriter, then persists to the path on flush/close, so
|
||||
;; (with-open [w (io/writer "f")] (.write w …)) writes the file. State #(path buf).
|
||||
(define (fw-path self) (vector-ref (jhost-state self) 0))
|
||||
(define (fw-buf self) (vector-ref (jhost-state self) 1))
|
||||
(define (fw-append! self s) (vector-set! (jhost-state self) 1 (string-append (fw-buf self) s)))
|
||||
(define (fw-flush! self) (jolt-spit (fw-path self) (fw-buf self))) ; jolt-spit: io.ss
|
||||
(register-host-methods! "file-writer"
|
||||
(list (cons "write" (lambda (self x) (fw-append! self (writer-piece x)) jolt-nil))
|
||||
(cons "append" (lambda (self x) (fw-append! self (render-piece x)) self))
|
||||
(cons "flush" (lambda (self) (fw-flush! self) jolt-nil))
|
||||
(cons "close" (lambda (self) (fw-flush! self) jolt-nil))
|
||||
(cons "toString" (lambda (self) (fw-buf self)))))
|
||||
|
||||
;; a writer over a real Chez port — the values *out* / *err* hold. write/append
|
||||
;; push to the port (so (.write *out* s) and (binding [*out* *err*] …) work);
|
||||
;; it isn't a buffer, so toString is empty. Lets libraries that touch *out*/*err*
|
||||
;; (tools.logging, selmer) compile and run.
|
||||
(register-host-methods! "port-writer"
|
||||
(list (cons "write" (lambda (self x) (display (writer-piece x) (vector-ref (jhost-state self) 0)) jolt-nil))
|
||||
(cons "append" (lambda (self x) (display (render-piece x) (vector-ref (jhost-state self) 0)) self))
|
||||
(cons "flush" (lambda (self) (flush-output-port (vector-ref (jhost-state self) 0)) jolt-nil))
|
||||
(cons "close" (lambda (self) jolt-nil))
|
||||
(cons "toString" (lambda (self) ""))))
|
||||
(def-var! "clojure.core" "*out*" (make-jhost "port-writer" (vector (current-output-port))))
|
||||
(def-var! "clojure.core" "*err*" (make-jhost "port-writer" (vector (current-error-port))))
|
||||
|
||||
;; ---- java.util.HashMap ------------------------------------------------------
|
||||
;; A mutable map keyed by jolt values (jolt-hash / jolt=2). State #(chez-hashtable).
|
||||
;; Constructors: () | (capacity) | (capacity load-factor) [sizing args ignored] |
|
||||
;; (Map m) [copy]. Enough of the Map surface for libraries that build a fast lookup
|
||||
;; (malli's fast-registry: (doto (HashMap. 1024 0.25) (.putAll m)) then .get).
|
||||
(define (hm-hash k) (let ((h (jolt-hash k)))
|
||||
(bitwise-and (if (and (integer? h) (exact? h)) (abs h) 0) #x3FFFFFFF)))
|
||||
(define (hm-tbl self) (vector-ref (jhost-state self) 0))
|
||||
(define (hm-hashmap? x) (and (jhost? x) (string=? (jhost-tag x) "hashmap")))
|
||||
(define (hm-copy-into! ht src) ; src: a jolt map or another hashmap
|
||||
(if (hm-hashmap? src)
|
||||
(vector-for-each (lambda (k) (hashtable-set! ht k (hashtable-ref (hm-tbl src) k jolt-nil)))
|
||||
(hashtable-keys (hm-tbl src)))
|
||||
(for-each (lambda (e) (hashtable-set! ht (jolt-nth e 0) (jolt-nth e 1)))
|
||||
(seq->list (jolt-seq src)))))
|
||||
(register-class-ctor! "HashMap"
|
||||
(lambda args
|
||||
(let ((ht (make-hashtable hm-hash jolt=2)))
|
||||
(when (and (pair? args) (or (pmap? (car args)) (hm-hashmap? (car args))))
|
||||
(hm-copy-into! ht (car args)))
|
||||
(make-jhost "hashmap" (vector ht)))))
|
||||
(define (hm->pmap self)
|
||||
(let ((m (jolt-hash-map)))
|
||||
(vector-for-each (lambda (k) (set! m (jolt-assoc m k (hashtable-ref (hm-tbl self) k jolt-nil))))
|
||||
(hashtable-keys (hm-tbl self)))
|
||||
m))
|
||||
(register-host-methods! "hashmap"
|
||||
(list (cons "put" (lambda (self k v) (let ((old (hashtable-ref (hm-tbl self) k jolt-nil)))
|
||||
(hashtable-set! (hm-tbl self) k v) old)))
|
||||
(cons "get" (lambda (self k) (hashtable-ref (hm-tbl self) k jolt-nil)))
|
||||
(cons "getOrDefault" (lambda (self k d) (hashtable-ref (hm-tbl self) k d)))
|
||||
(cons "containsKey" (lambda (self k) (if (hashtable-contains? (hm-tbl self) k) #t #f)))
|
||||
(cons "containsValue" (lambda (self v)
|
||||
(let ((found #f))
|
||||
(vector-for-each (lambda (k) (when (jolt=2 v (hashtable-ref (hm-tbl self) k jolt-nil)) (set! found #t)))
|
||||
(hashtable-keys (hm-tbl self))) found)))
|
||||
(cons "size" (lambda (self) (hashtable-size (hm-tbl self))))
|
||||
(cons "isEmpty" (lambda (self) (= 0 (hashtable-size (hm-tbl self)))))
|
||||
(cons "remove" (lambda (self k) (let ((old (hashtable-ref (hm-tbl self) k jolt-nil)))
|
||||
(hashtable-delete! (hm-tbl self) k) old)))
|
||||
(cons "clear" (lambda (self) (hashtable-clear! (hm-tbl self)) jolt-nil))
|
||||
(cons "putAll" (lambda (self m) (hm-copy-into! (hm-tbl self) m) jolt-nil))
|
||||
(cons "keySet" (lambda (self) (apply jolt-hash-set (vector->list (hashtable-keys (hm-tbl self))))))
|
||||
(cons "values" (lambda (self) (apply jolt-vector
|
||||
(map (lambda (k) (hashtable-ref (hm-tbl self) k jolt-nil))
|
||||
(vector->list (hashtable-keys (hm-tbl self)))))))
|
||||
(cons "entrySet" (lambda (self) (jolt-seq (hm->pmap self))))
|
||||
(cons "toString" (lambda (self) (jolt-pr-str (hm->pmap self))))))
|
||||
|
||||
;; ---- StringReader -----------------------------------------------------------
|
||||
;; state: a vector #(string pos marked).
|
||||
(register-class-ctor! "StringReader"
|
||||
;; src is a String or a char[] ((StringReader. (char-array s)) — selmer's parser
|
||||
;; reads templates this way); a char-array becomes the string of its chars.
|
||||
(lambda (src . _)
|
||||
(make-jhost "string-reader"
|
||||
(vector (cond ((string? src) src)
|
||||
((jolt-array? src) (apply string-append (map jolt-str-render-one (seq->list (jolt-seq src)))))
|
||||
(else (jolt-str-render-one src)))
|
||||
0 0))))
|
||||
(define (sr-s self) (vector-ref (jhost-state self) 0))
|
||||
(define (sr-pos self) (vector-ref (jhost-state self) 1))
|
||||
(define (sr-pos! self p) (vector-set! (jhost-state self) 1 p))
|
||||
(register-host-methods! "string-reader"
|
||||
(list (cons "read" (lambda (self)
|
||||
(let ((s (sr-s self)) (p (sr-pos self)))
|
||||
(if (>= p (string-length s)) -1 ; EOF -> exact int -1 (= JVM)
|
||||
(begin (sr-pos! self (+ p 1)) (->num (char->integer (string-ref s p))))))))
|
||||
(cons "mark" (lambda (self . _) (vector-set! (jhost-state self) 2 (sr-pos self)) jolt-nil))
|
||||
(cons "reset" (lambda (self) (sr-pos! self (vector-ref (jhost-state self) 2)) jolt-nil))
|
||||
(cons "skip" (lambda (self n) (let ((n (jnum->exact n)))
|
||||
(sr-pos! self (min (string-length (sr-s self)) (+ (sr-pos self) n))) (->num n))))
|
||||
;; readLine: the next line without its terminator (\n or \r\n), nil at EOF —
|
||||
;; what line-seq drives over a BufferedReader.
|
||||
(cons "readLine"
|
||||
(lambda (self)
|
||||
(let ((s (sr-s self)) (p (sr-pos self)) (len (string-length (sr-s self))))
|
||||
(if (>= p len) jolt-nil
|
||||
(let scan ((i p))
|
||||
(cond
|
||||
((>= i len) (sr-pos! self len) (substring s p len))
|
||||
((char=? (string-ref s i) #\newline)
|
||||
(sr-pos! self (+ i 1))
|
||||
(substring s p (if (and (> i p) (char=? (string-ref s (- i 1)) #\return)) (- i 1) i)))
|
||||
(else (scan (+ i 1)))))))))
|
||||
(cons "close" (lambda (self) jolt-nil))))
|
||||
|
||||
;; ---- PushbackReader ---------------------------------------------------------
|
||||
;; state: a vector #(wrapped-reader pushed-list)
|
||||
(register-class-ctor! "PushbackReader"
|
||||
(lambda (rdr . _) (make-jhost "pushback-reader" (vector rdr '()))))
|
||||
(define (read-unit r) ; read one code unit (flonum) from any reader, -1 at EOF
|
||||
(record-method-dispatch r "read" jolt-nil))
|
||||
(register-host-methods! "pushback-reader"
|
||||
(list (cons "read" (lambda (self)
|
||||
(let ((pushed (vector-ref (jhost-state self) 1)))
|
||||
(if (pair? pushed)
|
||||
(begin (vector-set! (jhost-state self) 1 (cdr pushed)) (car pushed))
|
||||
(read-unit (vector-ref (jhost-state self) 0))))))
|
||||
(cons "unread" (lambda (self ch)
|
||||
(vector-set! (jhost-state self) 1
|
||||
(cons (if (char? ch) (->num (char->integer ch)) ch) (vector-ref (jhost-state self) 1)))
|
||||
jolt-nil))
|
||||
(cons "close" (lambda (self) jolt-nil))))
|
||||
|
||||
;; ---- HashMap ----------------------------------------------------------------
|
||||
;; state: a box holding an alist of (k . v), jolt= keyed.
|
||||
(define (hm-alist self) (vector-ref (jhost-state self) 0))
|
||||
(define (hm-set! self al) (vector-set! (jhost-state self) 0 al))
|
||||
(define (hm-assoc al k v)
|
||||
(let loop ((ps al) (acc '()) (hit #f))
|
||||
(cond ((null? ps) (reverse (if hit acc (cons (cons k v) acc))))
|
||||
((jolt=2 (caar ps) k) (loop (cdr ps) (cons (cons k v) acc) #t))
|
||||
(else (loop (cdr ps) (cons (car ps) acc) hit)))))
|
||||
(define (hm-get al k) (let loop ((ps al)) (cond ((null? ps) jolt-nil) ((jolt=2 (caar ps) k) (cdar ps)) (else (loop (cdr ps))))))
|
||||
(define (coll->pairs m)
|
||||
(if (jolt-nil? m) '()
|
||||
(let loop ((s (jolt-seq m)) (acc '()))
|
||||
(if (jolt-nil? s) (reverse acc)
|
||||
(let ((e (seq-first s))) (loop (jolt-seq (seq-more s)) (cons (cons (jolt-nth e 0) (jolt-nth e 1)) acc)))))))
|
||||
(register-class-ctor! "HashMap"
|
||||
(lambda args
|
||||
(let ((init (and (pair? args) (car args))))
|
||||
(make-jhost "hashmap" (vector (if (and init (not (number? init))) (coll->pairs init) '()))))))
|
||||
(register-host-methods! "hashmap"
|
||||
(list (cons "get" (lambda (self k) (hm-get (hm-alist self) k)))
|
||||
(cons "put" (lambda (self k v) (hm-set! self (hm-assoc (hm-alist self) k v)) v))
|
||||
(cons "putAll" (lambda (self m) (for-each (lambda (p) (hm-set! self (hm-assoc (hm-alist self) (car p) (cdr p)))) (coll->pairs m)) jolt-nil))
|
||||
(cons "containsKey" (lambda (self k) (not (jolt-nil? (hm-get (hm-alist self) k)))))
|
||||
(cons "size" (lambda (self) (->num (length (hm-alist self)))))))
|
||||
|
||||
;; ---- StringTokenizer --------------------------------------------------------
|
||||
;; state: a vector #(tokens-list pos)
|
||||
(define (tokenize s delims)
|
||||
(let ((dset (string->list delims)))
|
||||
(let loop ((chars (string->list s)) (cur '()) (toks '()))
|
||||
(cond ((null? chars) (reverse (if (null? cur) toks (cons (list->string (reverse cur)) toks))))
|
||||
((memv (car chars) dset)
|
||||
(loop (cdr chars) '() (if (null? cur) toks (cons (list->string (reverse cur)) toks))))
|
||||
(else (loop (cdr chars) (cons (car chars) cur) toks))))))
|
||||
(register-class-ctor! "StringTokenizer"
|
||||
(lambda (s . delims) (make-jhost "string-tokenizer"
|
||||
(vector (tokenize (if (string? s) s (jolt-str-render-one s))
|
||||
(if (null? delims) " \t\n\r\f" (car delims))) 0))))
|
||||
(register-host-methods! "string-tokenizer"
|
||||
(list (cons "hasMoreTokens" (lambda (self) (< (vector-ref (jhost-state self) 1) (length (vector-ref (jhost-state self) 0)))))
|
||||
(cons "countTokens" (lambda (self) (->num (- (length (vector-ref (jhost-state self) 0)) (vector-ref (jhost-state self) 1)))))
|
||||
(cons "nextToken" (lambda (self)
|
||||
(let ((toks (vector-ref (jhost-state self) 0)) (p (vector-ref (jhost-state self) 1)))
|
||||
(if (< p (length toks))
|
||||
(begin (vector-set! (jhost-state self) 1 (+ p 1)) (list-ref toks p))
|
||||
(error #f "NoSuchElementException")))))))
|
||||
|
||||
;; ---- String / BigInteger / MapEntry constructors ----------------------------
|
||||
;; (String. x) / (String. bytes): a bytevector decodes UTF-8; else stringify.
|
||||
(register-class-ctor! "String"
|
||||
(lambda (x . _) (cond ((bytevector? x) (utf8->string x)) ((string? x) x) (else (jolt-str-render-one x)))))
|
||||
(register-class-ctor! "BigInteger"
|
||||
(lambda (v) (parse-int-or-throw v 10 "BigInteger")))
|
||||
(register-class-ctor! "MapEntry" (lambda (k v) (make-map-entry k v)))
|
||||
;; JVM exception ctors: keep the message string (so getMessage / ex-message work).
|
||||
(for-each (lambda (nm) (register-class-ctor! nm (lambda (msg . _) (if (string? msg) msg (jolt-str-render-one msg)))))
|
||||
'("Exception" "RuntimeException" "IllegalArgumentException" "IllegalStateException"
|
||||
"InterruptedException" "UnsupportedOperationException" "IOException"))
|
||||
|
||||
;; ---- URLEncoder / URLDecoder (www-form-urlencoded) --------------------------
|
||||
(define (url-unreserved? b)
|
||||
(or (and (>= b 48) (<= b 57)) (and (>= b 65) (<= b 90)) (and (>= b 97) (<= b 122))
|
||||
(= b 46) (= b 42) (= b 95) (= b 45)))
|
||||
(define hex-digits "0123456789ABCDEF")
|
||||
(define (url-encode s . _)
|
||||
(let ((bs (string->utf8 (if (string? s) s (jolt-str-render-one s)))) (out '()))
|
||||
(let loop ((i 0))
|
||||
(if (= i (bytevector-length bs)) (list->string (reverse out))
|
||||
(let ((b (bytevector-u8-ref bs i)))
|
||||
(cond ((url-unreserved? b) (set! out (cons (integer->char b) out)))
|
||||
((= b 32) (set! out (cons #\+ out)))
|
||||
(else (set! out (cons (string-ref hex-digits (bitwise-and b 15))
|
||||
(cons (string-ref hex-digits (bitwise-arithmetic-shift-right b 4))
|
||||
(cons #\% out))))))
|
||||
(loop (+ i 1)))))))
|
||||
(define (hexv c)
|
||||
(cond ((and (char<=? #\0 c) (char<=? c #\9)) (- (char->integer c) 48))
|
||||
((and (char<=? #\A c) (char<=? c #\F)) (- (char->integer c) 55))
|
||||
((and (char<=? #\a c) (char<=? c #\f)) (- (char->integer c) 87))
|
||||
(else (error #f "URLDecoder: malformed escape"))))
|
||||
(define (url-decode s . _)
|
||||
(let* ((str (if (string? s) s (jolt-str-render-one s))) (n (string-length str)) (out '()))
|
||||
(let loop ((i 0))
|
||||
(if (>= i n) (utf8->string (u8-list->bytevector (reverse out)))
|
||||
(let ((c (string-ref str i)))
|
||||
(cond ((char=? c #\+) (set! out (cons 32 out)) (loop (+ i 1)))
|
||||
((char=? c #\%)
|
||||
(set! out (cons (+ (* 16 (hexv (string-ref str (+ i 1)))) (hexv (string-ref str (+ i 2)))) out))
|
||||
(loop (+ i 3)))
|
||||
(else (set! out (cons (char->integer c) out)) (loop (+ i 1)))))))))
|
||||
(define (u8-list->bytevector lst)
|
||||
(let ((bv (make-bytevector (length lst))))
|
||||
(let loop ((l lst) (i 0)) (if (null? l) bv (begin (bytevector-u8-set! bv i (car l)) (loop (cdr l) (+ i 1)))))))
|
||||
(register-class-statics! "URLEncoder" (list (cons "encode" url-encode)))
|
||||
(register-class-statics! "URLDecoder" (list (cons "decode" url-decode)))
|
||||
(register-class-statics! "Charset" (list (cons "forName" (lambda (nm) (make-jhost "charset" (list (cons 'name nm)))))))
|
||||
|
||||
;; ---- Base64 (RFC 4648) ------------------------------------------------------
|
||||
(define b64-alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
|
||||
(define (->bytevector x) (cond ((bytevector? x) x) ((string? x) (string->utf8 x)) (else (string->utf8 (jolt-str-render-one x)))))
|
||||
(define (b64-encode x)
|
||||
(let* ((bs (->bytevector x)) (n (bytevector-length bs)) (out '()))
|
||||
(let loop ((i 0))
|
||||
(if (>= i n) (list->string (reverse out))
|
||||
(let* ((b0 (bytevector-u8-ref bs i))
|
||||
(b1 (if (< (+ i 1) n) (bytevector-u8-ref bs (+ i 1)) #f))
|
||||
(b2 (if (< (+ i 2) n) (bytevector-u8-ref bs (+ i 2)) #f)))
|
||||
(set! out (cons (string-ref b64-alphabet (bitwise-arithmetic-shift-right b0 2)) out))
|
||||
(set! out (cons (string-ref b64-alphabet (bitwise-ior (bitwise-arithmetic-shift-left (bitwise-and b0 3) 4)
|
||||
(bitwise-arithmetic-shift-right (or b1 0) 4))) out))
|
||||
(set! out (cons (if b1 (string-ref b64-alphabet (bitwise-ior (bitwise-arithmetic-shift-left (bitwise-and b1 15) 2)
|
||||
(bitwise-arithmetic-shift-right (or b2 0) 6))) #\=) out))
|
||||
(set! out (cons (if b2 (string-ref b64-alphabet (bitwise-and b2 63)) #\=) out))
|
||||
(loop (+ i 3)))))))
|
||||
(define (b64-char-val c)
|
||||
(let loop ((i 0)) (cond ((= i 64) (error #f "Base64: illegal character")) ((char=? (string-ref b64-alphabet i) c) i) (else (loop (+ i 1))))))
|
||||
(define (b64-decode x)
|
||||
(let* ((str (let ((s (if (string? x) x (utf8->string (->bytevector x)))))
|
||||
(list->string (filter (lambda (c) (not (char=? c #\=))) (string->list s)))))
|
||||
(out '()) (acc 0) (bits 0))
|
||||
(for-each (lambda (c)
|
||||
(set! acc (bitwise-ior (bitwise-arithmetic-shift-left acc 6) (b64-char-val c)))
|
||||
(set! bits (+ bits 6))
|
||||
(when (>= bits 8)
|
||||
(set! bits (- bits 8))
|
||||
(set! out (cons (bitwise-and (bitwise-arithmetic-shift-right acc bits) 255) out))))
|
||||
(string->list str))
|
||||
(u8-list->bytevector (reverse out))))
|
||||
(register-host-methods! "b64-encoder"
|
||||
(list (cons "encode" (lambda (self bs) (string->utf8 (b64-encode bs))))
|
||||
(cons "encodeToString" (lambda (self bs) (b64-encode bs)))))
|
||||
(register-host-methods! "b64-decoder"
|
||||
(list (cons "decode" (lambda (self s) (b64-decode s)))))
|
||||
(register-class-statics! "Base64"
|
||||
(list (cons "getEncoder" (lambda () (make-jhost "b64-encoder" '())))
|
||||
(cons "getDecoder" (lambda () (make-jhost "b64-decoder" '())))))
|
||||
|
||||
;; ---- java.util.regex.Pattern ------------------------------------------------
|
||||
;; Pattern/compile returns a jolt-regex value (regex-t), so str/replace, re-find,
|
||||
;; .split etc. accept it transparently.
|
||||
(define pattern-multiline 8.0)
|
||||
(define (pattern-quote s)
|
||||
(let ((meta "\\.[]{}()*+-?^$|&") (s (if (string? s) s (jolt-str-render-one s))) (out '()))
|
||||
(let loop ((i 0))
|
||||
(if (= i (string-length s)) (list->string (reverse out))
|
||||
(let ((c (string-ref s i)))
|
||||
(when (memv c (string->list meta)) (set! out (cons #\\ out)))
|
||||
(set! out (cons c out))
|
||||
(loop (+ i 1)))))))
|
||||
(register-class-statics! "Pattern"
|
||||
(list (cons "compile" (lambda (s . flags)
|
||||
(if (and (pair? flags) (= (bitwise-and (jnum->exact (car flags)) 8) 8))
|
||||
(jolt-regex (string-append "(?m)" s))
|
||||
(jolt-regex s))))
|
||||
(cons "quote" (lambda (s) (pattern-quote s)))
|
||||
(cons "MULTILINE" pattern-multiline)))
|
||||
;; record-method-dispatch already routes string? -> jolt-string-method. Add a
|
||||
;; regex-t arm (Pattern .split / .matcher-less surface used by corpus) by wrapping
|
||||
;; once more — a regex-t isn't a jhost.
|
||||
(define %hs-rmd2 record-method-dispatch)
|
||||
(set! record-method-dispatch
|
||||
(lambda (obj method-name rest-args)
|
||||
(if (regex-t? obj)
|
||||
(let ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args))))
|
||||
(cond ((string=? method-name "split")
|
||||
;; .split returns a String[] — a seq (prints
|
||||
;; (a b c), not a vector). re-split with no limit; drop trailing
|
||||
;; empties (JVM default).
|
||||
(let ((parts (re-split (regex-t-irx obj) (car rest) #f)))
|
||||
(list->cseq (str-split-drop-trailing parts))))
|
||||
((string=? method-name "pattern") (regex-t-source obj))
|
||||
(else (error #f (string-append "No method " method-name " on Pattern")))))
|
||||
(%hs-rmd2 obj method-name rest-args))))
|
||||
|
||||
;; ---- def-var! the registry entry points so emit can also reach them ---------
|
||||
(def-var! "clojure.core" "host-static-ref" host-static-ref)
|
||||
(def-var! "clojure.core" "host-static-call" (lambda (c m . a) (apply host-static-call c m a)))
|
||||
(def-var! "clojure.core" "host-new" (lambda (c . a) (apply host-new c a)))
|
||||
|
||||
;; Clojure-visible class-registration hooks. A host shim (e.g. reitit.trie-jolt,
|
||||
;; which mirrors the reitit.Trie Java class) registers a constructor proc or a
|
||||
;; map of static members against a class token so (Class. args) / (Class/member
|
||||
;; args) resolve to it. The statics argument is a jolt map {member-name -> val}.
|
||||
(define (jmap->static-alist m)
|
||||
(let loop ((s (jolt-seq m)) (acc '()))
|
||||
(if (jolt-nil? s) acc
|
||||
(let ((e (jolt-first s)))
|
||||
(loop (jolt-seq (jolt-rest s)) (cons (cons (jolt-nth e 0) (jolt-nth e 1)) acc))))))
|
||||
(def-var! "clojure.core" "__register-class-ctor!"
|
||||
(lambda (name proc) (register-class-ctor! name proc) jolt-nil))
|
||||
(def-var! "clojure.core" "__register-class-statics!"
|
||||
(lambda (name members) (register-class-statics! name (jmap->static-alist members)) jolt-nil))
|
||||
178
host/chez/host-table.ss
Normal file
178
host/chez/host-table.ss
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
;; host tables + sorted collections (jolt-cf1q.3, jolt-0zoy) — the jolt.host
|
||||
;; value primitives and the 25-sorted tier's runtime.
|
||||
;;
|
||||
;; jolt.host/tagged-table + ref-put! + ref-get resolved to jolt-nil on the Chez
|
||||
;; prelude, so the whole sorted tier (sorted-map/sorted-set/subseq/rsubseq) AND
|
||||
;; every overlay fn that calls (sorted? x) — empty, ifn?, reversible?, map?, set?,
|
||||
;; coll? — hit the apply-jolt-nil crash bucket. This provides:
|
||||
;; 1. tagged-table / ref-put! / ref-get over a Chez mutable tagged-table type
|
||||
;; (a string-keyed hashtable wrapped in an `htable` record), def-var!'d into
|
||||
;; the jolt.host ns. The sorted tier (25-sorted.clj) mints its wrapper with
|
||||
;; these — a red-black tree + :ops table travel inside the htable.
|
||||
;; 2. a sorted-coll arm on the collection dispatchers, set!-extended the same
|
||||
;; way records.ss extends them for jrec: each op routes through the value's
|
||||
;; own :ops table (the dispatch pattern). first/rest/
|
||||
;; next/last fall out free once jolt-seq has a sorted arm (they seq first).
|
||||
;;
|
||||
;; Loaded LAST (after records.ss / transients.ss / natives-meta.ss): it wraps the
|
||||
;; jrec-extended dispatchers + value-host-tags, delegating to the captured prior.
|
||||
|
||||
;; --- jolt.host primitives ----------------------------------------------------
|
||||
;; A tagged-table: a string-keyed hashtable (keyword field -> value). Keyword
|
||||
;; keys collapse to their ns/name string so interning isn't relied on.
|
||||
(define-record-type htable (fields (immutable h)) (nongenerative chez-htable-v1))
|
||||
(define (kw->key k)
|
||||
(let ((ns (keyword-t-ns k)))
|
||||
(if (and ns (not (jolt-nil? ns))) (string-append ns "/" (keyword-t-name k)) (keyword-t-name k))))
|
||||
(define (jolt-tagged-table tag)
|
||||
(let ((h (make-hashtable string-hash string=?)))
|
||||
(hashtable-set! h "jolt/type" tag)
|
||||
(make-htable h)))
|
||||
;; ref-put! threads the table back; a nil value REMOVES the key (Janet table
|
||||
;; semantics — h-ref-put!). Errors on a non-htable so the atom-watch / volatile
|
||||
;; uses (which pass a different ref type and have no Chez table yet) stay a crash
|
||||
;; rather than silently diverging.
|
||||
(define (jolt-ref-put! t k v)
|
||||
(unless (htable? t) (error #f "ref-put!: not a host table" t))
|
||||
(if (jolt-nil? v)
|
||||
(hashtable-delete! (htable-h t) (kw->key k))
|
||||
(hashtable-set! (htable-h t) (kw->key k) v))
|
||||
t)
|
||||
(define (jolt-ref-get t k)
|
||||
(if (htable? t) (hashtable-ref (htable-h t) (kw->key k) jolt-nil) jolt-nil))
|
||||
|
||||
(def-var! "jolt.host" "tagged-table" jolt-tagged-table)
|
||||
(def-var! "jolt.host" "ref-put!" jolt-ref-put!)
|
||||
(def-var! "jolt.host" "ref-get" jolt-ref-get)
|
||||
;; map-entry constructor: a 2-elem entry-flagged pvec (map-entry? true, vector?
|
||||
;; false), so sorted-map seq/first produce real map entries that key/val accept.
|
||||
(def-var! "jolt.host" "map-entry" make-map-entry)
|
||||
|
||||
;; --- sorted-coll recognition + ops access ------------------------------------
|
||||
(define kw-jtype (keyword "jolt" "type"))
|
||||
(define kw-sorted-map (keyword "jolt" "sorted-map"))
|
||||
(define kw-sorted-set (keyword "jolt" "sorted-set"))
|
||||
(define kw-ops (keyword #f "ops"))
|
||||
(define kw-op-count (keyword #f "count"))
|
||||
(define kw-op-seq (keyword #f "seq"))
|
||||
(define kw-op-get (keyword #f "get"))
|
||||
(define kw-op-contains (keyword #f "contains"))
|
||||
(define kw-op-assoc (keyword #f "assoc"))
|
||||
(define kw-op-dissoc (keyword #f "dissoc"))
|
||||
(define kw-op-conj (keyword #f "conj"))
|
||||
(define kw-op-disj (keyword #f "disj"))
|
||||
|
||||
(define (htable-sorted-map? x) (and (htable? x) (jolt=2 (jolt-ref-get x kw-jtype) kw-sorted-map)))
|
||||
(define (htable-sorted-set? x) (and (htable? x) (jolt=2 (jolt-ref-get x kw-jtype) kw-sorted-set)))
|
||||
(define (htable-sorted? x) (or (htable-sorted-map? x) (htable-sorted-set? x)))
|
||||
;; the op fn for `op-kw` from the value's attached :ops map, then invoke it on sc.
|
||||
(define (sc-op sc op-kw) (jolt-get (jolt-ref-get sc kw-ops) op-kw jolt-nil))
|
||||
(define (sc-call sc op-kw . args) (apply jolt-invoke (sc-op sc op-kw) sc args))
|
||||
|
||||
;; --- extend the collection dispatchers with a sorted arm ---------------------
|
||||
(define %h-seq jolt-seq)
|
||||
(set! jolt-seq (lambda (x) (if (htable-sorted? x) (sc-call x kw-op-seq) (%h-seq x))))
|
||||
(define %h-count jolt-count)
|
||||
(set! jolt-count (lambda (coll) (if (htable-sorted? coll) (sc-call coll kw-op-count) (%h-count coll))))
|
||||
(define %h-get jolt-get)
|
||||
(set! jolt-get (case-lambda
|
||||
((coll k) (if (htable-sorted? coll) (sc-call coll kw-op-get k jolt-nil) (%h-get coll k)))
|
||||
((coll k d) (if (htable-sorted? coll) (sc-call coll kw-op-get k d) (%h-get coll k d)))))
|
||||
(define %h-contains? jolt-contains?)
|
||||
(set! jolt-contains? (lambda (coll k)
|
||||
(if (htable-sorted? coll) (if (jolt-truthy? (sc-call coll kw-op-contains k)) #t #f) (%h-contains? coll k))))
|
||||
(define %h-assoc1 jolt-assoc1)
|
||||
(set! jolt-assoc1 (lambda (coll k v)
|
||||
(if (htable-sorted-map? coll) (sc-call coll kw-op-assoc (jolt-vector k v)) (%h-assoc1 coll k v))))
|
||||
(define %h-dissoc jolt-dissoc)
|
||||
(set! jolt-dissoc (lambda (coll . ks)
|
||||
(if (htable-sorted-map? coll) (sc-call coll kw-op-dissoc (apply jolt-vector ks)) (apply %h-dissoc coll ks))))
|
||||
(define %h-conj1 jolt-conj1)
|
||||
(set! jolt-conj1 (lambda (coll x)
|
||||
(if (htable-sorted? coll) (sc-call coll kw-op-conj (jolt-vector x)) (%h-conj1 coll x))))
|
||||
(define %h-disj jolt-disj)
|
||||
(set! jolt-disj (lambda (s . xs)
|
||||
(if (htable-sorted-set? s) (sc-call s kw-op-disj (apply jolt-vector xs)) (apply %h-disj s xs))))
|
||||
(def-var! "clojure.core" "disj" jolt-disj)
|
||||
(define %h-empty? jolt-empty?)
|
||||
(set! jolt-empty? (lambda (coll) (if (htable-sorted? coll) (zero? (sc-call coll kw-op-count)) (%h-empty? coll))))
|
||||
(define %h-keys jolt-keys)
|
||||
(set! jolt-keys (lambda (m)
|
||||
(if (htable-sorted-map? m)
|
||||
(list->cseq (map (lambda (e) (jolt-nth e 0)) (seq->list (sc-call m kw-op-seq))))
|
||||
(%h-keys m))))
|
||||
(define %h-vals jolt-vals)
|
||||
(set! jolt-vals (lambda (m)
|
||||
(if (htable-sorted-map? m)
|
||||
(list->cseq (map (lambda (e) (jolt-nth e 1)) (seq->list (sc-call m kw-op-seq))))
|
||||
(%h-vals m))))
|
||||
;; sorted colls are collections (callable as fns via jolt-invoke, conj-able).
|
||||
(define %h-coll? jolt-coll?)
|
||||
(set! jolt-coll? (lambda (x) (or (htable-sorted? x) (%h-coll? x))))
|
||||
|
||||
;; public predicates: a sorted-map is map?, a sorted-set is set?, both coll?.
|
||||
;; predicates.ss/records.ss def-var!'d a snapshot, so re-def-var! after set!.
|
||||
(define %h-map? jolt-map?)
|
||||
(set! jolt-map? (lambda (x) (or (htable-sorted-map? x) (%h-map? x))))
|
||||
(def-var! "clojure.core" "map?" jolt-map?)
|
||||
(define %h-set? jolt-set?)
|
||||
(set! jolt-set? (lambda (x) (or (htable-sorted-set? x) (%h-set? x))))
|
||||
(def-var! "clojure.core" "set?" jolt-set?)
|
||||
(def-var! "clojure.core" "coll?" (lambda (x) (or (htable-sorted? x) (jrec? x) (jolt-coll-pred? x))))
|
||||
|
||||
;; --- equality / hash ---------------------------------------------------------
|
||||
;; A sorted coll canonicalizes like its unordered counterpart:
|
||||
;; a sorted-map equals ANY map (hash or sorted) with the same entries, a
|
||||
;; sorted-set ANY set with the same elements — the comparator is irrelevant to =.
|
||||
;; Convert to the plain persistent coll and delegate to the prior jolt=2 / hash.
|
||||
;; (htable-sorted? short-circuits on a non-htable BEFORE any jolt=2, so extending
|
||||
;; jolt=2 here doesn't recurse: the inner tag compare gets two keywords.)
|
||||
(define (sorted-map->pmap sc)
|
||||
(fold-left (lambda (m e) (pmap-assoc m (jolt-nth e 0) (jolt-nth e 1)))
|
||||
empty-pmap (seq->list (sc-call sc kw-op-seq))))
|
||||
(define (sorted-set->pset sc)
|
||||
(fold-left (lambda (s x) (pset-conj s x)) empty-pset (seq->list (sc-call sc kw-op-seq))))
|
||||
(define (sorted->plain x) (if (htable-sorted-map? x) (sorted-map->pmap x) (sorted-set->pset x)))
|
||||
(define %h-jolt=2 jolt=2)
|
||||
(set! jolt=2 (lambda (a b)
|
||||
(cond ((htable-sorted? a) (%h-jolt=2 (sorted->plain a) (if (htable-sorted? b) (sorted->plain b) b)))
|
||||
((htable-sorted? b) (%h-jolt=2 a (sorted->plain b)))
|
||||
(else (%h-jolt=2 a b)))))
|
||||
(define %h-jolt-hash jolt-hash)
|
||||
(set! jolt-hash (lambda (x) (if (htable-sorted? x) (%h-jolt-hash (sorted->plain x)) (%h-jolt-hash x))))
|
||||
|
||||
;; --- printing ----------------------------------------------------------------
|
||||
;; sorted colls render in SORTED order (the value's :seq), not HAMT order — and
|
||||
;; a sorted-map prints "{k v, k v}" (", " between pairs),
|
||||
;; NOT the space-only form the unordered pmap arm uses.
|
||||
(define (sorted-map-render sc render)
|
||||
(string-append "{"
|
||||
(let loop ((es (seq->list (sc-call sc kw-op-seq))) (first #t) (acc ""))
|
||||
(if (null? es) acc
|
||||
(loop (cdr es) #f
|
||||
(string-append acc (if first "" ", ")
|
||||
(render (jolt-nth (car es) 0)) " " (render (jolt-nth (car es) 1))))))
|
||||
"}"))
|
||||
(define (sorted-set-render sc render)
|
||||
(string-append "#{" (jolt-str-join (map render (seq->list (sc-call sc kw-op-seq)))) "}"))
|
||||
(define (sorted-render x render)
|
||||
(if (htable-sorted-map? x) (sorted-map-render x render) (sorted-set-render x render)))
|
||||
|
||||
(define %h-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (htable-sorted? x) (sorted-render x jolt-pr-readable) (%h-pr-readable x))))
|
||||
(define %h-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (htable-sorted? x) (sorted-render x jolt-pr-str) (%h-pr-str x))))
|
||||
(define %h-str-render-one jolt-str-render-one)
|
||||
(set! jolt-str-render-one (lambda (x) (if (htable-sorted? x) (sorted-render x jolt-str-render-one) (%h-str-render-one x))))
|
||||
|
||||
;; --- protocol dispatch over builtins (extend-protocol Map/Set on sorted) ------
|
||||
;; value-host-tags (records.ss) drives extend-protocol on host values; a
|
||||
;; sorted-map must answer to "Map", a sorted-set to "Set"/"Collection".
|
||||
(define %h-value-host-tags value-host-tags)
|
||||
(set! value-host-tags (lambda (obj)
|
||||
(cond
|
||||
((htable-sorted-map? obj) '("PersistentTreeMap" "Sorted" "IPersistentMap" "Associative"
|
||||
"Map" "java.util.Map" "IPersistentCollection" "Object"))
|
||||
((htable-sorted-set? obj) '("PersistentTreeSet" "Sorted" "IPersistentSet"
|
||||
"Set" "java.util.Set" "Collection" "IPersistentCollection" "Object"))
|
||||
(else (%h-value-host-tags obj)))))
|
||||
160
host/chez/http-client.ss
Normal file
160
host/chez/http-client.ss
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
;; http-client.ss (jolt-90sp) — jolt.http-client: a synchronous HTTP client.
|
||||
;;
|
||||
;; Backed by the system `curl` binary rather than a direct libcurl FFI: on Apple
|
||||
;; Silicon curl_easy_setopt is variadic and its value arg goes on the stack, where
|
||||
;; Chez's fixed-signature foreign-procedure can't place it (it would need a
|
||||
;; compiled C shim per platform). Shelling to curl uses the same mature native
|
||||
;; library — TLS, redirects, gzip and all — with no build step and identical
|
||||
;; behavior across platforms. Returns a Ring-ish {:status :headers :body}.
|
||||
;;
|
||||
;; def-var!'d into the jolt.http-client namespace; loaded by the CLI before the
|
||||
;; loader snapshot, so (require '[jolt.http-client]) resolves with no source file.
|
||||
|
||||
;; single-quote an argument for the outer `sh -c` (loader.ss's sh-quote isn't
|
||||
;; loaded yet at this point).
|
||||
(define (hc-shq s)
|
||||
(string-append "'"
|
||||
(apply string-append
|
||||
(map (lambda (c) (if (char=? c #\') "'\\''" (string c))) (string->list s)))
|
||||
"'"))
|
||||
|
||||
(define hc-status-sentinel "\nJOLTHTTPSTATUS:")
|
||||
|
||||
(define kw-method (keyword #f "method"))
|
||||
(define kw-url (keyword #f "url"))
|
||||
(define kw-headers (keyword #f "headers"))
|
||||
(define kw-body (keyword #f "body"))
|
||||
(define kw-insecure (keyword #f "insecure?"))
|
||||
(define kw-follow (keyword #f "follow?"))
|
||||
(define kw-timeout (keyword #f "timeout-ms"))
|
||||
(define kw-status (keyword #f "status"))
|
||||
(define kw-query (keyword #f "query-params"))
|
||||
(define kw-ctype (keyword #f "content-type"))
|
||||
|
||||
;; :content-type :json -> "application/json"; a string passes through.
|
||||
(define (hc-ctype->str ct)
|
||||
(cond ((keyword? ct)
|
||||
(let ((n (keyword-t-name ct)))
|
||||
(cond ((string=? n "json") "application/json")
|
||||
((string=? n "xml") "application/xml")
|
||||
((string=? n "form") "application/x-www-form-urlencoded")
|
||||
(else n))))
|
||||
(else (jolt-str-render-one ct))))
|
||||
|
||||
;; A per-request header file path, unique across processes (PID) and threads (a
|
||||
;; mutex-guarded monotonic counter). The previous unguarded `set!` + `mod 90000`
|
||||
;; raced: concurrent callers could compute the same path and clobber each other's
|
||||
;; -D header dump. getpid is a fast, non-blocking foreign call.
|
||||
(define c-getpid (begin (load-shared-object #f) (foreign-procedure "getpid" () int)))
|
||||
(define hc-tmp-mutex (make-mutex))
|
||||
(define hc-tmp-counter 0)
|
||||
(define (hc-tmp-path)
|
||||
(let ((n (with-mutex hc-tmp-mutex (set! hc-tmp-counter (+ hc-tmp-counter 1)) hc-tmp-counter)))
|
||||
(string-append (or (getenv "TMPDIR") "/tmp") "/jolt-http-"
|
||||
(number->string (c-getpid)) "-" (number->string n) ".hdr")))
|
||||
|
||||
(define (hc-trim s)
|
||||
(let* ((n (string-length s))
|
||||
(a (let lp ((i 0)) (if (and (< i n) (char-whitespace? (string-ref s i))) (lp (+ i 1)) i)))
|
||||
(b (let lp ((i n)) (if (and (> i a) (char-whitespace? (string-ref s (- i 1)))) (lp (- i 1)) i))))
|
||||
(substring s a b)))
|
||||
(define (hc-lines s)
|
||||
(let loop ((i 0) (start 0) (acc '()))
|
||||
(cond ((>= i (string-length s)) (reverse (if (> i start) (cons (substring s start i) acc) acc)))
|
||||
((char=? (string-ref s i) #\newline)
|
||||
(loop (+ i 1) (+ i 1) (if (> i start) (cons (substring s start i) acc) acc)))
|
||||
(else (loop (+ i 1) start acc)))))
|
||||
;; raw header dump (curl -D) -> a jolt map {lowercased-name -> value}. With
|
||||
;; redirects there are several blocks; the LAST status line resets the map so the
|
||||
;; final response's headers win.
|
||||
(define (hc-parse-headers text)
|
||||
(let ((m (jolt-hash-map)))
|
||||
(for-each
|
||||
(lambda (raw)
|
||||
(let ((line (hc-trim raw)))
|
||||
(cond
|
||||
((= 0 (string-length line)) #t)
|
||||
((and (>= (string-length line) 5) (string=? (substring line 0 5) "HTTP/"))
|
||||
(set! m (jolt-hash-map))) ; new response block
|
||||
(else
|
||||
(let ((ci (let scan ((i 0)) (cond ((>= i (string-length line)) #f)
|
||||
((char=? (string-ref line i) #\:) i)
|
||||
(else (scan (+ i 1)))))))
|
||||
(when (and ci (> ci 0))
|
||||
(set! m (jolt-assoc m (ascii-string-down (hc-trim (substring line 0 ci)))
|
||||
(hc-trim (substring line (+ ci 1) (string-length line)))))))))))
|
||||
(hc-lines text))
|
||||
m))
|
||||
|
||||
(define (hc-split-status out)
|
||||
;; out ends with "\nJOLTHTTPSTATUS:<code>"; return (values body code-int).
|
||||
(let ((idx (let ((sl (string-length hc-status-sentinel)) (ol (string-length out)))
|
||||
(let scan ((i (- ol sl)))
|
||||
(cond ((< i 0) #f)
|
||||
((string=? (substring out i (+ i sl)) hc-status-sentinel) i)
|
||||
(else (scan (- i 1))))))))
|
||||
(if idx
|
||||
(values (substring out 0 idx)
|
||||
(or (string->number (hc-trim (substring out (+ idx (string-length hc-status-sentinel))
|
||||
(string-length out)))) 0))
|
||||
(values out 0))))
|
||||
|
||||
(define (hc-request method url opts)
|
||||
(when (or (not url) (jolt-nil? url)) (error #f "jolt.http-client: missing :url"))
|
||||
(let* ((headers (jolt-get opts kw-headers))
|
||||
(body (let ((x (jolt-get opts kw-body))) (and (not (jolt-nil? x)) x)))
|
||||
(insecure? (jolt-truthy? (jolt-get opts kw-insecure)))
|
||||
(follow? (let ((x (jolt-get opts kw-follow))) (or (jolt-nil? x) (jolt-truthy? x))))
|
||||
(timeout (let ((x (jolt-get opts kw-timeout))) (if (jolt-nil? x) 30 (quotient (jnum->exact x) 1000))))
|
||||
(hdrfile (hc-tmp-path))
|
||||
(parts (list "curl -sS"
|
||||
(if follow? "-L" "")
|
||||
(if insecure? "-k" "")
|
||||
"--max-time" (number->string (max 1 timeout))
|
||||
"-D" (hc-shq hdrfile)
|
||||
"-X" (hc-shq (string-upcase method))
|
||||
"-w" (hc-shq (string-append hc-status-sentinel "%{http_code}"))
|
||||
"--compressed"))
|
||||
(ctype (let ((x (jolt-get opts kw-ctype))) (and (not (jolt-nil? x)) (hc-ctype->str x))))
|
||||
(parts (if ctype (append parts (list "-H" (hc-shq (string-append "Content-Type: " ctype)))) parts))
|
||||
(parts (if (pmap? headers)
|
||||
(append parts (pmap-fold headers
|
||||
(lambda (k v acc)
|
||||
(cons "-H" (cons (hc-shq (string-append (jolt-str-render-one k) ": "
|
||||
(jolt-str-render-one v))) acc)))
|
||||
'()))
|
||||
parts))
|
||||
;; query-params: let curl URL-encode them onto the URL (-G appends as the
|
||||
;; query string for a GET).
|
||||
(qp (let ((x (jolt-get opts kw-query))) (and (pmap? x) x)))
|
||||
(parts (if qp
|
||||
(append parts
|
||||
(cons "-G"
|
||||
(pmap-fold qp (lambda (k v acc)
|
||||
(cons "--data-urlencode"
|
||||
(cons (hc-shq (string-append (jolt-str-render-one k) "="
|
||||
(jolt-str-render-one v))) acc)))
|
||||
'())))
|
||||
parts))
|
||||
(parts (if body (append parts (list "--data-binary" (hc-shq (jolt-str-render-one body)))) parts))
|
||||
(parts (append parts (list (hc-shq (jolt-str-render-one url)))))
|
||||
(cmd (let join ((xs parts) (s "")) (if (null? xs) s
|
||||
(join (cdr xs) (if (string=? (car xs) "") s (string-append s (if (string=? s "") "" " ") (car xs)))))))
|
||||
(out (jolt-sh-out cmd)))
|
||||
(let-values (((bdy code) (hc-split-status out)))
|
||||
(let ((hdr-text (guard (e (#t "")) (read-file-string hdrfile))))
|
||||
(guard (e (#t #f)) (delete-file hdrfile))
|
||||
(jolt-hash-map kw-status code
|
||||
kw-headers (hc-parse-headers hdr-text)
|
||||
kw-body bdy)))))
|
||||
|
||||
;; --- public jolt.http-client API --------------------------------------------
|
||||
(define (hc-verb method) (lambda (url . opt) (hc-request method url (if (pair? opt) (car opt) (jolt-hash-map)))))
|
||||
(def-var! "jolt.http-client" "request"
|
||||
(lambda (opts) (hc-request (let ((m (jolt-get opts kw-method))) (if (jolt-nil? m) "GET" (jolt-str-render-one m)))
|
||||
(jolt-get opts kw-url) opts)))
|
||||
(def-var! "jolt.http-client" "get" (hc-verb "GET"))
|
||||
(def-var! "jolt.http-client" "head" (hc-verb "HEAD"))
|
||||
(def-var! "jolt.http-client" "post" (hc-verb "POST"))
|
||||
(def-var! "jolt.http-client" "put" (hc-verb "PUT"))
|
||||
(def-var! "jolt.http-client" "delete" (hc-verb "DELETE"))
|
||||
229
host/chez/http-server.ss
Normal file
229
host/chez/http-server.ss
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
;; http-server.ss (jolt-90sp) — a minimal HTTP/1.1 server over BSD sockets via
|
||||
;; Chez's FFI (the socket calls are non-variadic, so they bind directly). One
|
||||
;; connection handled at a time on a background accept thread; synchronous Ring
|
||||
;; handlers. Enough to serve a small web app.
|
||||
;;
|
||||
;; Exposed as jolt.http.server/run-server + stop-server — a baked namespace an
|
||||
;; app requires for a Ring-style adapter (run a handler, stop the server).
|
||||
|
||||
(load-shared-object #f) ; resolve socket/bind/listen/accept/recv/send in the process
|
||||
|
||||
(define c-socket (foreign-procedure "socket" (int int int) int))
|
||||
(define c-bind (foreign-procedure "bind" (int void* int) int))
|
||||
(define c-listen (foreign-procedure "listen" (int int) int))
|
||||
(define c-setsockopt (foreign-procedure "setsockopt" (int int int void* int) int))
|
||||
(define c-close (foreign-procedure "close" (int) int))
|
||||
;; accept/recv/send can BLOCK (accept indefinitely while idle). A thread inside a
|
||||
;; plain foreign call stays "active" and stalls the stop-the-world collector for
|
||||
;; every thread, so the accept loop would freeze GC process-wide whenever a future
|
||||
;; or async block allocates while no request is in flight. __collect_safe
|
||||
;; deactivates the calling thread for the call's duration so collection proceeds.
|
||||
;; Safe here: the only arguments are an fd and foreign-alloc'd buffers (outside the
|
||||
;; Scheme heap), so a collection during the call has nothing to move.
|
||||
(define c-accept (foreign-procedure __collect_safe "accept" (int void* void*) int))
|
||||
(define c-recv (foreign-procedure __collect_safe "recv" (int void* size_t int) ssize_t))
|
||||
(define c-send (foreign-procedure __collect_safe "send" (int void* size_t int) ssize_t))
|
||||
|
||||
(define AF_INET 2) (define SOCK_STREAM 1)
|
||||
;; SOL_SOCKET / SO_REUSEADDR differ by platform: macOS uses 0xffff / 4, Linux 1 / 2.
|
||||
(define on-macos?
|
||||
(let ((m (symbol->string (machine-type))))
|
||||
(let loop ((i 0)) (cond ((> (+ i 3) (string-length m)) #f)
|
||||
((string=? (substring m i (+ i 3)) "osx") #t)
|
||||
(else (loop (+ i 1)))))))
|
||||
(define sock-level (if on-macos? #xffff 1))
|
||||
(define sock-reuse (if on-macos? 4 2))
|
||||
|
||||
;; sockaddr_in for host:port. macOS: byte0=len(16), byte1=family; Linux: bytes0-1=family.
|
||||
(define (make-sockaddr host port)
|
||||
(let ((sa (foreign-alloc 16)))
|
||||
(do ((i 0 (+ i 1))) ((= i 16)) (foreign-set! 'unsigned-8 sa i 0))
|
||||
(if (= sock-level #xffff)
|
||||
(begin (foreign-set! 'unsigned-8 sa 0 16) (foreign-set! 'unsigned-8 sa 1 AF_INET))
|
||||
(foreign-set! 'unsigned-8 sa 0 AF_INET))
|
||||
(foreign-set! 'unsigned-8 sa 2 (bitwise-and (bitwise-arithmetic-shift-right port 8) #xff))
|
||||
(foreign-set! 'unsigned-8 sa 3 (bitwise-and port #xff))
|
||||
;; sin_addr: 127.0.0.1 (loopback) — the example serves locally
|
||||
(foreign-set! 'unsigned-8 sa 4 127) (foreign-set! 'unsigned-8 sa 5 0)
|
||||
(foreign-set! 'unsigned-8 sa 6 0) (foreign-set! 'unsigned-8 sa 7 1)
|
||||
sa))
|
||||
|
||||
(define (listen-socket host port)
|
||||
(let ((fd (c-socket AF_INET SOCK_STREAM 0)))
|
||||
(when (< fd 0) (error #f "socket() failed"))
|
||||
(let ((opt (foreign-alloc 4)))
|
||||
(foreign-set! 'int opt 0 1)
|
||||
(c-setsockopt fd sock-level sock-reuse opt 4)
|
||||
(foreign-free opt))
|
||||
(let ((sa (make-sockaddr host port)))
|
||||
(when (< (c-bind fd sa 16) 0) (c-close fd) (foreign-free sa) (error #f (string-append "bind() failed on port " (number->string port))))
|
||||
(foreign-free sa))
|
||||
(when (< (c-listen fd 64) 0) (c-close fd) (error #f "listen() failed"))
|
||||
fd))
|
||||
|
||||
;; --- request reading --------------------------------------------------------
|
||||
(define hs-bufsize 65536)
|
||||
;; index just past the "\r\n\r\n" header/body separator, or #f.
|
||||
(define (bv-find-crlfcrlf bv)
|
||||
(let ((len (bytevector-length bv)))
|
||||
(let loop ((i 0))
|
||||
(cond ((> (+ i 4) len) #f)
|
||||
((and (= (bytevector-u8-ref bv i) 13) (= (bytevector-u8-ref bv (+ i 1)) 10)
|
||||
(= (bytevector-u8-ref bv (+ i 2)) 13) (= (bytevector-u8-ref bv (+ i 3)) 10))
|
||||
(+ i 4))
|
||||
(else (loop (+ i 1)))))))
|
||||
|
||||
;; read the whole request (headers + Content-Length body). Returns a string, or #f.
|
||||
(define (read-request conn)
|
||||
(let ((buf (foreign-alloc hs-bufsize)))
|
||||
(let loop ((acc (make-bytevector 0)))
|
||||
(let ((n (c-recv conn buf hs-bufsize 0)))
|
||||
(if (<= n 0)
|
||||
(begin (foreign-free buf) (if (> (bytevector-length acc) 0) (utf8->safe acc) #f))
|
||||
(let ((chunk (make-bytevector n)))
|
||||
(do ((i 0 (+ i 1))) ((= i n)) (bytevector-u8-set! chunk i (foreign-ref 'unsigned-8 buf i)))
|
||||
(let* ((acc2 (bv-append acc chunk))
|
||||
(hdr-end (bv-find-crlfcrlf acc2)))
|
||||
(if (not hdr-end)
|
||||
(loop acc2)
|
||||
(let ((clen (content-length acc2 hdr-end)))
|
||||
(if (>= (- (bytevector-length acc2) hdr-end) clen)
|
||||
(begin (foreign-free buf) (utf8->safe acc2))
|
||||
(loop acc2)))))))))))
|
||||
(define (bv-append a b)
|
||||
(let ((out (make-bytevector (+ (bytevector-length a) (bytevector-length b)))))
|
||||
(bytevector-copy! a 0 out 0 (bytevector-length a))
|
||||
(bytevector-copy! b 0 out (bytevector-length a) (bytevector-length b))
|
||||
out))
|
||||
(define (utf8->safe bv) (guard (e (#t (bytes->latin1 bv))) (utf8->string bv)))
|
||||
(define (bytes->latin1 bv) (list->string (map integer->char (bytevector->u8-list bv))))
|
||||
(define (content-length bv hdr-end)
|
||||
(let* ((hdrs (ascii-string-down (utf8->safe (let ((b (make-bytevector hdr-end)))
|
||||
(bytevector-copy! bv 0 b 0 hdr-end) b))))
|
||||
(idx (string-search hdrs "content-length:")))
|
||||
(if (not idx) 0
|
||||
(let* ((s (+ idx (string-length "content-length:")))
|
||||
(e (let scan ((i s)) (if (or (>= i (string-length hdrs))
|
||||
(char=? (string-ref hdrs i) #\return)
|
||||
(char=? (string-ref hdrs i) #\newline)) i (scan (+ i 1))))))
|
||||
(or (string->number (string-trim-ws (substring hdrs s e))) 0)))))
|
||||
(define (string-search hay needle)
|
||||
(let ((hl (string-length hay)) (nl (string-length needle)))
|
||||
(let loop ((i 0)) (cond ((> (+ i nl) hl) #f)
|
||||
((string=? (substring hay i (+ i nl)) needle) i)
|
||||
(else (loop (+ i 1)))))))
|
||||
(define (string-trim-ws s)
|
||||
(let* ((n (string-length s))
|
||||
(a (let lp ((i 0)) (if (and (< i n) (char-whitespace? (string-ref s i))) (lp (+ i 1)) i)))
|
||||
(b (let lp ((i n)) (if (and (> i a) (char-whitespace? (string-ref s (- i 1)))) (lp (- i 1)) i))))
|
||||
(substring s a b)))
|
||||
|
||||
;; --- request -> Ring map ----------------------------------------------------
|
||||
(define (split-once s ch)
|
||||
(let scan ((i 0)) (cond ((>= i (string-length s)) (values s #f))
|
||||
((char=? (string-ref s i) ch) (values (substring s 0 i) (substring s (+ i 1) (string-length s))))
|
||||
(else (scan (+ i 1))))))
|
||||
(define (req-lines s)
|
||||
(let loop ((i 0) (start 0) (acc '()))
|
||||
(cond ((>= i (string-length s)) (reverse (cons (substring s start i) acc)))
|
||||
((char=? (string-ref s i) #\newline)
|
||||
(let ((line (if (and (> i start) (char=? (string-ref s (- i 1)) #\return)) (substring s start (- i 1)) (substring s start i))))
|
||||
(loop (+ i 1) (+ i 1) (cons line acc))))
|
||||
(else (loop (+ i 1) start acc)))))
|
||||
(define (request->ring text port)
|
||||
(let* ((blank (string-search text "\r\n\r\n"))
|
||||
(head (if blank (substring text 0 blank) text))
|
||||
(body (if blank (substring text (+ blank 4) (string-length text)) ""))
|
||||
(lines (req-lines head))
|
||||
(reqline (if (pair? lines) (car lines) "GET / HTTP/1.1"))
|
||||
(parts (let lp ((i 0) (start 0) (acc '()))
|
||||
(cond ((>= i (string-length reqline)) (reverse (cons (substring reqline start i) acc)))
|
||||
((char=? (string-ref reqline i) #\space)
|
||||
(lp (+ i 1) (+ i 1) (cons (substring reqline start i) acc)))
|
||||
(else (lp (+ i 1) start acc)))))
|
||||
(method (if (pair? parts) (car parts) "GET"))
|
||||
(target (if (and (pair? parts) (pair? (cdr parts))) (cadr parts) "/"))
|
||||
(hdrs (let loop ((ls (if (pair? lines) (cdr lines) '())) (m (jolt-hash-map)))
|
||||
(if (null? ls) m
|
||||
(let-values (((k v) (split-once (car ls) #\:)))
|
||||
(if v (loop (cdr ls) (jolt-assoc m (ascii-string-down (string-trim-ws k)) (string-trim-ws v)))
|
||||
(loop (cdr ls) m)))))))
|
||||
(let-values (((uri qs) (split-once target #\?)))
|
||||
(jolt-hash-map
|
||||
(keyword #f "server-port") port
|
||||
(keyword #f "server-name") "127.0.0.1"
|
||||
(keyword #f "remote-addr") "127.0.0.1"
|
||||
(keyword #f "uri") uri
|
||||
(keyword #f "query-string") (if qs qs jolt-nil)
|
||||
(keyword #f "scheme") (keyword #f "http")
|
||||
(keyword #f "request-method") (keyword #f (ascii-string-down method))
|
||||
(keyword #f "protocol") "HTTP/1.1"
|
||||
(keyword #f "headers") hdrs
|
||||
(keyword #f "body") (if (> (string-length body) 0) (host-new "StringReader" body) jolt-nil)))))
|
||||
|
||||
;; --- Ring response -> bytes -------------------------------------------------
|
||||
(define (status-text code)
|
||||
(cond ((= code 200) "OK") ((= code 201) "Created") ((= code 204) "No Content")
|
||||
((= code 303) "See Other") ((= code 302) "Found") ((= code 304) "Not Modified")
|
||||
((= code 400) "Bad Request") ((= code 401) "Unauthorized") ((= code 403) "Forbidden")
|
||||
((= code 404) "Not Found") ((= code 405) "Method Not Allowed") ((= code 500) "Internal Server Error")
|
||||
(else "OK")))
|
||||
(define (body->string b)
|
||||
(cond ((jolt-nil? b) "")
|
||||
((string? b) b)
|
||||
((or (cseq? b) (empty-list-t? b) (pvec? b)) (apply string-append (map jolt-str-render-one (seq->list (jolt-seq b)))))
|
||||
(else (jolt-str-render-one b))))
|
||||
(define (response->bytes resp)
|
||||
(let* ((status (let ((s (jolt-get resp (keyword #f "status")))) (if (jolt-nil? s) 200 (jnum->exact s))))
|
||||
(headers (jolt-get resp (keyword #f "headers")))
|
||||
(body (body->string (jolt-get resp (keyword #f "body"))))
|
||||
(body-bv (string->utf8 body))
|
||||
(out (open-output-string)))
|
||||
(display (string-append "HTTP/1.1 " (number->string status) " " (status-text status) "\r\n") out)
|
||||
(when (pmap? headers)
|
||||
(pmap-fold headers (lambda (k v acc)
|
||||
(display (string-append (jolt-str-render-one k) ": " (jolt-str-render-one v) "\r\n") out) acc) 0))
|
||||
(display (string-append "Content-Length: " (number->string (bytevector-length body-bv)) "\r\n") out)
|
||||
(display "Connection: close\r\n\r\n" out)
|
||||
(bv-append (string->utf8 (get-output-string out)) body-bv)))
|
||||
|
||||
(define (send-all conn bv)
|
||||
(let ((len (bytevector-length bv)) (buf (foreign-alloc (max 1 (bytevector-length bv)))))
|
||||
(do ((i 0 (+ i 1))) ((= i len)) (foreign-set! 'unsigned-8 buf i (bytevector-u8-ref bv i)))
|
||||
(let loop ((off 0))
|
||||
(when (< off len)
|
||||
(let ((n (c-send conn (+ buf off) (- len off) 0)))
|
||||
(if (<= n 0) (set! off len) (loop (+ off n))))))
|
||||
(foreign-free buf)))
|
||||
|
||||
;; --- the server -------------------------------------------------------------
|
||||
(define (serve-loop listen-fd handler port)
|
||||
(let loop ()
|
||||
(let ((conn (c-accept listen-fd 0 0)))
|
||||
(when (>= conn 0)
|
||||
(guard (e (#t (guard (e2 (#t #f))
|
||||
(send-all conn (response->bytes
|
||||
(jolt-hash-map (keyword #f "status") 500
|
||||
(keyword #f "body") "Internal Server Error"))))))
|
||||
(let ((text (read-request conn)))
|
||||
(when text
|
||||
(let* ((req (request->ring text port))
|
||||
(resp (jolt-invoke handler req)))
|
||||
(send-all conn (response->bytes resp))))))
|
||||
(c-close conn))
|
||||
(loop))))
|
||||
|
||||
;; run-server: bind+listen, spawn the accept loop on a background thread, return a
|
||||
;; handle {:port :socket}. opts is a map with :port (default 3000).
|
||||
(define (http-run-server handler opts)
|
||||
(let* ((port (let ((p (and (pmap? opts) (jolt-get opts (keyword #f "port"))))) (if (or (not p) (jolt-nil? p)) 3000 (jnum->exact p))))
|
||||
(fd (listen-socket "127.0.0.1" port)))
|
||||
(fork-thread (lambda () (serve-loop fd handler port)))
|
||||
(jolt-hash-map (keyword #f "port") port (keyword #f "socket") fd)))
|
||||
(define (http-stop-server server)
|
||||
(when (pmap? server)
|
||||
(let ((fd (jolt-get server (keyword #f "socket")))) (when (number? fd) (c-close (jnum->exact fd)))))
|
||||
jolt-nil)
|
||||
|
||||
(def-var! "jolt.http.server" "run-server" (lambda (handler . opt) (http-run-server handler (if (pair? opt) (car opt) (jolt-hash-map)))))
|
||||
(def-var! "jolt.http.server" "stop-server" http-stop-server)
|
||||
318
host/chez/inst-time.ss
Normal file
318
host/chez/inst-time.ss
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
;; #inst values + a java.time formatting shim (jolt-at0a, inc X).
|
||||
;;
|
||||
;; A #inst literal lowers (analyzer :inst node -> emit) to (jolt-inst-from-string
|
||||
;; "…"); this file parses the RFC3339 string to epoch-ms and models the value as a
|
||||
;; `jinst` record (one flonum field, ms). Equality / map-key hashing are by the
|
||||
;; INSTANT (offset-normalized). The overlay inst?/inst-ms read (get x :jolt/type)/(get x :ms),
|
||||
;; so jolt-get answers those off a jinst — the overlay fns then work unchanged.
|
||||
;;
|
||||
;; The java.time surface (DateTimeFormatter/Instant/ZoneId/LocalDateTime/
|
||||
;; FormatStyle/Locale + the .format/.atZone/.toInstant/… methods) is
|
||||
;; registered through host-static.ss's class-statics / host-
|
||||
;; methods registries — so this loads LAST in rt.ss, after host-static.ss and io.ss.
|
||||
|
||||
;; --- civil <-> days since the Unix epoch (Howard Hinnant's algorithms) -------
|
||||
;; No portable UTC mktime on Chez, so compute epoch days directly from y/m/d.
|
||||
(define (days-from-civil y m d)
|
||||
(let* ((y2 (if (<= m 2) (- y 1) y))
|
||||
(era (quotient (if (>= y2 0) y2 (- y2 399)) 400))
|
||||
(yoe (- y2 (* era 400)))
|
||||
(doy (+ (quotient (+ (* 153 (+ m (if (> m 2) -3 9))) 2) 5) (- d 1)))
|
||||
(doe (+ (* yoe 365) (quotient yoe 4) (- (quotient yoe 100)) doy)))
|
||||
(+ (* era 146097) doe -719468)))
|
||||
|
||||
(define (civil-from-days z) ; -> (values year month day)
|
||||
(let* ((z2 (+ z 719468))
|
||||
(era (quotient (if (>= z2 0) z2 (- z2 146096)) 146097))
|
||||
(doe (- z2 (* era 146097)))
|
||||
(yoe (quotient (+ doe (- (quotient doe 1460)) (quotient doe 36524) (- (quotient doe 146096))) 365))
|
||||
(y (+ yoe (* era 400)))
|
||||
(doy (- doe (+ (* 365 yoe) (quotient yoe 4) (- (quotient yoe 100)))))
|
||||
(mp (quotient (+ (* 5 doy) 2) 153))
|
||||
(d (+ (- doy (quotient (+ (* 153 mp) 2) 5)) 1))
|
||||
(m (+ mp (if (< mp 10) 3 -9))))
|
||||
(values (if (<= m 2) (+ y 1) y) m d)))
|
||||
|
||||
;; --- RFC3339 parse: yyyy[-MM[-dd[Thh[:mm[:ss[.fff]]]]]][Z|±hh:mm] -> ms -------
|
||||
(define-record-type jinst (fields ms) (nongenerative chez-jinst-v1))
|
||||
|
||||
(define (digit? c) (and (char>=? c #\0) (char<=? c #\9)))
|
||||
(define (digits-at s i n) ; n digits from i -> integer, or #f
|
||||
(and (<= (+ i n) (string-length s))
|
||||
(let loop ((j i) (acc 0))
|
||||
(if (= j (+ i n))
|
||||
acc
|
||||
(and (digit? (string-ref s j))
|
||||
(loop (+ j 1) (+ (* acc 10) (- (char->integer (string-ref s j)) 48))))))))
|
||||
|
||||
(define (jolt-inst-from-string ts)
|
||||
(define len (string-length ts))
|
||||
(define (fail) (error #f (string-append "Unrecognized #inst timestamp: " ts)))
|
||||
(let* ((year (or (digits-at ts 0 4) (fail)))
|
||||
(i 4) (month 1) (day 1) (hh 0) (mm 0) (ss 0) (frac-ms 0) (off-s 0))
|
||||
;; -MM
|
||||
(when (and (< i len) (char=? (string-ref ts i) #\-) (digits-at ts (+ i 1) 2))
|
||||
(set! month (digits-at ts (+ i 1) 2)) (set! i (+ i 3)))
|
||||
;; -dd
|
||||
(when (and (< i len) (char=? (string-ref ts i) #\-) (digits-at ts (+ i 1) 2))
|
||||
(set! day (digits-at ts (+ i 1) 2)) (set! i (+ i 3)))
|
||||
;; Thh
|
||||
(when (and (< i len) (or (char=? (string-ref ts i) #\T) (char=? (string-ref ts i) #\t))
|
||||
(digits-at ts (+ i 1) 2))
|
||||
(set! hh (digits-at ts (+ i 1) 2)) (set! i (+ i 3))
|
||||
;; :mm
|
||||
(when (and (< i len) (char=? (string-ref ts i) #\:) (digits-at ts (+ i 1) 2))
|
||||
(set! mm (digits-at ts (+ i 1) 2)) (set! i (+ i 3))
|
||||
;; :ss
|
||||
(when (and (< i len) (char=? (string-ref ts i) #\:) (digits-at ts (+ i 1) 2))
|
||||
(set! ss (digits-at ts (+ i 1) 2)) (set! i (+ i 3))
|
||||
;; .fff (truncate beyond 3)
|
||||
(when (and (< i len) (char=? (string-ref ts i) #\.))
|
||||
(let loop ((j (+ i 1)) (k 0) (acc 0))
|
||||
(if (and (< j len) (digit? (string-ref ts j)))
|
||||
(loop (+ j 1) (+ k 1) (if (< k 3) (+ (* acc 10) (- (char->integer (string-ref ts j)) 48)) acc))
|
||||
(begin
|
||||
(set! frac-ms (* acc (expt 10 (max 0 (- 3 k)))))
|
||||
(set! i j))))))))
|
||||
;; offset Z | ±hh:mm
|
||||
(when (< i len)
|
||||
(let ((c (string-ref ts i)))
|
||||
(cond
|
||||
((or (char=? c #\Z) (char=? c #\z)) (set! i (+ i 1)))
|
||||
((or (char=? c #\+) (char=? c #\-))
|
||||
(let ((oh (digits-at ts (+ i 1) 2)) (om (digits-at ts (+ i 4) 2)))
|
||||
(unless (and oh om (char=? (string-ref ts (+ i 3)) #\:)) (fail))
|
||||
(set! off-s (* (if (char=? c #\-) -1 1) (+ (* oh 3600) (* om 60))))
|
||||
(set! i (+ i 6))))
|
||||
(else (fail)))))
|
||||
(unless (= i len) (fail))
|
||||
(let ((base-s (+ (* (days-from-civil year month day) 86400) (* hh 3600) (* mm 60) ss)))
|
||||
(make-jinst (- (+ (* base-s 1000) frac-ms) (* off-s 1000))))))
|
||||
|
||||
;; --- canonical print form: yyyy-MM-ddThh:mm:ss.fff-00:00 (UTC) ---------------
|
||||
(define (pad2 n) (if (< n 10) (string-append "0" (number->string n)) (number->string n)))
|
||||
(define (pad4 n) (let ((s (number->string n))) (string-append (make-string (max 0 (- 4 (string-length s))) #\0) s)))
|
||||
(define (pad3 n) (let ((s (number->string n))) (string-append (make-string (max 0 (- 3 (string-length s))) #\0) s)))
|
||||
(define (floor-div a b) (let ((q (quotient a b)) (r (remainder a b))) (if (and (not (= r 0)) (< (* a b) 0)) (- q 1) q)))
|
||||
(define (floor-mod a b) (- a (* (floor-div a b) b)))
|
||||
|
||||
(define (inst-fields ms) ; -> list (y mo d hh mm ss frac dow)
|
||||
(let* ((total-s (floor-div (exact (truncate ms)) 1000))
|
||||
(frac (- (exact (truncate ms)) (* total-s 1000)))
|
||||
(days (floor-div total-s 86400))
|
||||
(sod (floor-mod total-s 86400))
|
||||
(hh (quotient sod 3600)) (mm (quotient (remainder sod 3600) 60)) (ss (remainder sod 60))
|
||||
(dow (floor-mod (+ days 4) 7))) ; 1970-01-01 = Thursday; 0=Sunday
|
||||
(call-with-values (lambda () (civil-from-days days))
|
||||
(lambda (y mo d) (list y mo d hh mm ss frac dow)))))
|
||||
|
||||
(define (inst-rfc3339 inst)
|
||||
(let ((f (inst-fields (jinst-ms inst))))
|
||||
(string-append (pad4 (list-ref f 0)) "-" (pad2 (list-ref f 1)) "-" (pad2 (list-ref f 2))
|
||||
"T" (pad2 (list-ref f 3)) ":" (pad2 (list-ref f 4)) ":" (pad2 (list-ref f 5))
|
||||
"." (pad3 (list-ref f 6)) "-00:00")))
|
||||
|
||||
;; --- DateTimeFormatter pattern engine -----
|
||||
(define month-names (vector "January" "February" "March" "April" "May" "June" "July"
|
||||
"August" "September" "October" "November" "December"))
|
||||
(define day-names (vector "Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"))
|
||||
|
||||
(define (format-ms pattern ms)
|
||||
(let ((f (inst-fields ms)) (n (string-length pattern)) (out (open-output-string)))
|
||||
(let ((y (list-ref f 0)) (mo (list-ref f 1)) (d (list-ref f 2))
|
||||
(hh (list-ref f 3)) (mi (list-ref f 4)) (se (list-ref f 5)) (dow (list-ref f 7)))
|
||||
(define (run-len i c) (let loop ((j i)) (if (and (< j n) (char=? (string-ref pattern j) c)) (loop (+ j 1)) (- j i))))
|
||||
(let loop ((i 0))
|
||||
(when (< i n)
|
||||
(let* ((c (string-ref pattern i)) (k (run-len i c)))
|
||||
(cond
|
||||
((char=? c #\')
|
||||
(if (and (< (+ i 1) n) (char=? (string-ref pattern (+ i 1)) #\'))
|
||||
(begin (write-char #\' out) (loop (+ i 2)))
|
||||
(let close ((j (+ i 1)))
|
||||
(cond ((>= j n) (loop j))
|
||||
((char=? (string-ref pattern j) #\') (loop (+ j 1)))
|
||||
(else (write-char (string-ref pattern j) out) (close (+ j 1)))))))
|
||||
((char=? c #\y) (display (if (>= k 4) (number->string y) (pad2 (modulo y 100))) out) (loop (+ i k)))
|
||||
((char=? c #\M)
|
||||
(display (cond ((= k 1) (number->string mo)) ((= k 2) (pad2 mo))
|
||||
((= k 3) (substring (vector-ref month-names (- mo 1)) 0 3))
|
||||
(else (vector-ref month-names (- mo 1)))) out)
|
||||
(loop (+ i k)))
|
||||
((char=? c #\d) (display (if (= k 1) (number->string d) (pad2 d)) out) (loop (+ i k)))
|
||||
((char=? c #\E)
|
||||
(display (if (>= k 4) (vector-ref day-names dow) (substring (vector-ref day-names dow) 0 3)) out)
|
||||
(loop (+ i k)))
|
||||
((char=? c #\H) (display (if (= k 1) (number->string hh) (pad2 hh)) out) (loop (+ i k)))
|
||||
((char=? c #\h)
|
||||
(let ((h12 (let ((h (modulo hh 12))) (if (= h 0) 12 h))))
|
||||
(display (if (= k 1) (number->string h12) (pad2 h12)) out)) (loop (+ i k)))
|
||||
((char=? c #\m) (display (if (= k 1) (number->string mi) (pad2 mi)) out) (loop (+ i k)))
|
||||
((char=? c #\s) (display (if (= k 1) (number->string se) (pad2 se)) out) (loop (+ i k)))
|
||||
((char=? c #\a) (display (if (< hh 12) "AM" "PM") out) (loop (+ i k)))
|
||||
(else (write-char c out) (loop (+ i 1)))))))
|
||||
(get-output-string out))))
|
||||
|
||||
;; --- value integration: get / = / hash / pr / type / instance? --------------
|
||||
(define kw-jolt-type (keyword "jolt" "type"))
|
||||
(define kw-ms (keyword #f "ms"))
|
||||
(define inst-type-kw (keyword "jolt" "inst"))
|
||||
|
||||
(define %it-get jolt-get)
|
||||
(set! jolt-get (case-lambda
|
||||
((coll k) (jolt-get coll k jolt-nil))
|
||||
((coll k d) (if (jinst? coll)
|
||||
(cond ((jolt=2 k kw-jolt-type) inst-type-kw)
|
||||
((jolt=2 k kw-ms) (jinst-ms coll))
|
||||
(else d))
|
||||
(%it-get coll k d)))))
|
||||
|
||||
(define %it-=2 jolt=2)
|
||||
(set! jolt=2 (lambda (a b)
|
||||
(cond ((jinst? a) (and (jinst? b) (= (jinst-ms a) (jinst-ms b))))
|
||||
((jinst? b) #f)
|
||||
(else (%it-=2 a b)))))
|
||||
|
||||
(define %it-hash jolt-hash)
|
||||
(set! jolt-hash (lambda (x) (if (jinst? x) (jolt-hash (jinst-ms x)) (%it-hash x))))
|
||||
|
||||
(define (inst-pr i) (string-append "#inst \"" (inst-rfc3339 i) "\""))
|
||||
(define %it-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (jinst? x) (inst-pr x) (%it-pr-str x))))
|
||||
(define %it-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (jinst? x) (inst-pr x) (%it-pr-readable x))))
|
||||
(define %it-str-render jolt-str-render-one)
|
||||
(set! jolt-str-render-one (lambda (x) (if (jinst? x) (inst-rfc3339 x) (%it-str-render x))))
|
||||
|
||||
(define %it-type jolt-type)
|
||||
(set! jolt-type (lambda (x) (if (jinst? x) inst-type-kw (%it-type x))))
|
||||
(def-var! "clojure.core" "type" jolt-type)
|
||||
|
||||
;; instance? java.util.Date -> a jinst; java.time.Instant/LocalDateTime -> the
|
||||
;; matching jhost tag. The instance? macro passes the class-name symbol.
|
||||
(define (class-short tn) (let loop ((i (- (string-length tn) 1)))
|
||||
(cond ((< i 0) tn) ((char=? (string-ref tn i) #\.) (substring tn (+ i 1) (string-length tn))) (else (loop (- i 1))))))
|
||||
(define %it-instance-check instance-check)
|
||||
(set! instance-check
|
||||
(lambda (type-sym val)
|
||||
(let ((tn (class-short (symbol-t-name type-sym))))
|
||||
(cond
|
||||
;; a #inst / (Date.) is a java.util.Date; it is NOT a java.sql.Timestamp
|
||||
;; (on the JVM a Date is not a Timestamp), so answer Timestamp explicitly #f.
|
||||
((jinst? val) (cond ((string=? tn "Date") #t)
|
||||
((string=? tn "Timestamp") #f)
|
||||
(else (%it-instance-check type-sym val))))
|
||||
((and (jhost? val) (string=? (jhost-tag val) "instant")) (if (string=? tn "Instant") #t (%it-instance-check type-sym val)))
|
||||
((and (jhost? val) (string=? (jhost-tag val) "local-dt")) (if (string=? tn "LocalDateTime") #t (%it-instance-check type-sym val)))
|
||||
(else (%it-instance-check type-sym val))))))
|
||||
(def-var! "clojure.core" "instance-check" instance-check)
|
||||
|
||||
;; inst-ms* is a seed native (the overlay inst-ms reads (get x :ms), now answered).
|
||||
(def-var! "clojure.core" "inst-ms*" (lambda (i) (jinst-ms i)))
|
||||
|
||||
;; --- java.time shim values (jhost objects over host-static.ss registries) -----
|
||||
(define (ms-of d)
|
||||
(cond ((number? d) d)
|
||||
((jinst? d) (jinst-ms d))
|
||||
((and (jhost? d) (member (jhost-tag d) '("instant" "zoned-dt" "local-dt")))
|
||||
(vector-ref (jhost-state d) 0))
|
||||
(else (error #f "not a date value" d))))
|
||||
(define (mk-instant ms) (make-jhost "instant" (vector ms)))
|
||||
(define (mk-zoned ms) (make-jhost "zoned-dt" (vector ms)))
|
||||
(define (mk-local ms) (make-jhost "local-dt" (vector ms)))
|
||||
(define (mk-formatter pat) (make-jhost "dt-formatter" (vector pat)))
|
||||
(define (fmt-pat f) (vector-ref (jhost-state f) 0))
|
||||
(define (now-ms) (now-millis)) ; exact ms (= JVM long); now-millis from host-static.ss
|
||||
;; coerce a user-supplied ms (exact or flonum) to an exact integer for storage.
|
||||
(define (ms->exact ms) (exact (round ms)))
|
||||
|
||||
(register-host-methods! "instant"
|
||||
(list (cons "atZone" (lambda (self zone) (mk-zoned (ms-of self))))
|
||||
(cons "toEpochMilli" (lambda (self) (ms-of self)))
|
||||
(cons "toString" (lambda (self) (inst-rfc3339 (make-jinst (ms-of self)))))))
|
||||
(register-host-methods! "zoned-dt"
|
||||
(list (cons "toLocalDateTime" (lambda (self) (mk-local (ms-of self))))
|
||||
(cons "toInstant" (lambda (self) (mk-instant (ms-of self))))))
|
||||
(register-host-methods! "local-dt"
|
||||
(list (cons "atZone" (lambda (self zone) (mk-zoned (ms-of self))))))
|
||||
(register-host-methods! "dt-formatter"
|
||||
(list (cons "withLocale" (lambda (self locale) (mk-formatter (fmt-pat self))))
|
||||
(cons "format" (lambda (self d) (format-ms (fmt-pat self) (ms-of d))))))
|
||||
|
||||
;; FormatStyle approximations (no locale DB on this host).
|
||||
(define style-patterns
|
||||
'((date . ((short . "M/d/yy") (medium . "MMM d, yyyy") (long . "MMMM d, yyyy") (full . "EEEE, MMMM d, yyyy")))
|
||||
(time . ((short . "h:mm a") (medium . "h:mm:ss a") (long . "h:mm:ss a") (full . "h:mm:ss a")))
|
||||
(datetime . ((short . "M/d/yy, h:mm a") (medium . "MMM d, yyyy, h:mm:ss a")
|
||||
(long . "MMMM d, yyyy, h:mm:ss a") (full . "EEEE, MMMM d, yyyy, h:mm:ss a")))))
|
||||
(define (style-of fs) (vector-ref (jhost-state fs) 0)) ; a symbol: short/medium/long/full
|
||||
(define (style-fmt kind fs)
|
||||
(mk-formatter (or (let ((row (assq kind style-patterns))) (and row (let ((e (assq (style-of fs) (cdr row)))) (and e (cdr e)))))
|
||||
"yyyy-MM-dd HH:mm:ss")))
|
||||
|
||||
(register-class-statics! "FormatStyle"
|
||||
(list (cons "SHORT" (make-jhost "format-style" (vector 'short)))
|
||||
(cons "MEDIUM" (make-jhost "format-style" (vector 'medium)))
|
||||
(cons "LONG" (make-jhost "format-style" (vector 'long)))
|
||||
(cons "FULL" (make-jhost "format-style" (vector 'full)))))
|
||||
(register-class-statics! "DateTimeFormatter"
|
||||
(list (cons "ofPattern" (lambda (p . _) (mk-formatter p)))
|
||||
(cons "ISO_LOCAL_DATE" (mk-formatter "yyyy-MM-dd"))
|
||||
(cons "ISO_LOCAL_DATE_TIME" (mk-formatter "yyyy-MM-dd'T'HH:mm:ss"))
|
||||
(cons "ofLocalizedDate" (lambda (fs) (style-fmt 'date fs)))
|
||||
(cons "ofLocalizedTime" (lambda (fs) (style-fmt 'time fs)))
|
||||
(cons "ofLocalizedDateTime" (lambda (fs) (style-fmt 'datetime fs)))))
|
||||
(register-class-statics! "Instant"
|
||||
(list (cons "ofEpochMilli" (lambda (ms) (mk-instant (ms->exact ms))))
|
||||
(cons "now" (lambda () (mk-instant (now-ms))))))
|
||||
(register-class-statics! "ZoneId"
|
||||
(list (cons "systemDefault" (lambda () (make-jhost "zone-id" (vector "system"))))
|
||||
(cons "of" (lambda (id) (make-jhost "zone-id" (vector id))))))
|
||||
(register-class-statics! "LocalDateTime"
|
||||
(list (cons "ofInstant" (lambda (inst zone) (mk-local (ms-of inst))))
|
||||
(cons "now" (lambda () (mk-local (now-ms))))))
|
||||
(let ((locale-ctor (lambda (id . _) (make-jhost "locale" (vector (if (string? id) id (jolt-str-render-one id)))))))
|
||||
(register-class-ctor! "Locale" locale-ctor)
|
||||
(register-class-ctor! "java.util.Locale" locale-ctor))
|
||||
(register-class-statics! "Locale"
|
||||
(list (cons "getDefault" (lambda () (make-jhost "locale" (vector "default"))))
|
||||
(cons "ENGLISH" (make-jhost "locale" (vector "en")))
|
||||
(cons "US" (make-jhost "locale" (vector "en-US")))
|
||||
(cons "ROOT" (make-jhost "locale" (vector "root")))))
|
||||
|
||||
;; java.util.Date / java.sql.Timestamp: #inst's classes. (Date.) = now, (Date. ms)
|
||||
;; or (Date. another-date) -> a jinst (ms-of accepts a number / jinst / instant), so
|
||||
;; .getTime / inst? / instance? Date|Timestamp work. (jolt-dcmm)
|
||||
(define (date-ctor . args)
|
||||
(make-jinst (if (null? args) (now-ms) (ms->exact (ms-of (car args))))))
|
||||
(register-class-ctor! "Date" date-ctor)
|
||||
(register-class-ctor! "java.util.Date" date-ctor)
|
||||
(register-class-ctor! "Timestamp" date-ctor)
|
||||
(register-class-ctor! "java.sql.Timestamp" date-ctor)
|
||||
|
||||
;; java.util.TimeZone: an opaque id holder (format-ms is UTC, so a non-UTC zone is
|
||||
;; not honored — only the UTC case the corpus uses is exercised).
|
||||
(define (timezone-of id) (make-jhost "timezone" (vector (if (string? id) id (jolt-str-render-one id)))))
|
||||
(register-class-statics! "TimeZone" (list (cons "getTimeZone" timezone-of)))
|
||||
(register-class-statics! "java.util.TimeZone" (list (cons "getTimeZone" timezone-of)))
|
||||
|
||||
;; java.text.SimpleDateFormat: holds a pattern; .setTimeZone is accepted (format-ms
|
||||
;; is UTC); .format(date) renders the date per the pattern via the format-ms engine.
|
||||
(define (sdf-ctor pat . _) (make-jhost "sdf" (vector (if (string? pat) pat (jolt-str-render-one pat)))))
|
||||
(register-class-ctor! "SimpleDateFormat" sdf-ctor)
|
||||
(register-class-ctor! "java.text.SimpleDateFormat" sdf-ctor)
|
||||
(register-host-methods! "sdf"
|
||||
(list (cons "setTimeZone" (lambda (self tz) jolt-nil))
|
||||
(cons "format" (lambda (self d) (format-ms (vector-ref (jhost-state self) 0) (ms-of d))))))
|
||||
|
||||
;; a jinst's java.util.Date method surface (record-method-dispatch arm).
|
||||
(define %it-rmd record-method-dispatch)
|
||||
(set! record-method-dispatch
|
||||
(lambda (obj method-name rest-args)
|
||||
(cond
|
||||
((jinst? obj)
|
||||
(cond ((string=? method-name "getTime") (jinst-ms obj))
|
||||
((string=? method-name "toInstant") (mk-instant (jinst-ms obj)))
|
||||
((string=? method-name "toString") (inst-rfc3339 obj))
|
||||
(else (error #f (string-append "No method " method-name " on Date")))))
|
||||
(else (%it-rmd obj method-name rest-args)))))
|
||||
287
host/chez/io.ss
Normal file
287
host/chez/io.ss
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
;; java.io.File + host file I/O (jolt-yyud). A
|
||||
;; Chez-native implementation over Chez's filesystem primitives. A File is a
|
||||
;; path-backed jfile record: (instance? java.io.File f) is true, str/slurp coerce
|
||||
;; it to its path, and the File method surface (getName/getPath/exists/
|
||||
;; isDirectory/isFile/listFiles) dispatches through record-method-dispatch.
|
||||
;;
|
||||
;; Provides make-file/file?/slurp/spit/flush/dir?/
|
||||
;; list-dir for the overlay file-seq (20-coll.clj), which calls __file?/__dir?/
|
||||
;; __list-dir + the .isDirectory/.listFiles/.isFile method surface.
|
||||
;;
|
||||
;; Reader/StringReader-coupled io (io/reader, line-seq over a file, .toURL,
|
||||
;; slurp over a reader) is deferred to jolt-at0a. Loaded LAST in rt.ss, after
|
||||
;; dot-forms.ss (so the jfile method arm wraps the fully-built dispatch) and
|
||||
;; natives-meta.ss / records.ss / printing.ss (jolt-type / instance-check /
|
||||
;; jolt-str-render-one, which it extends).
|
||||
|
||||
(define-record-type jfile (fields path) (nongenerative jolt-jfile-v1))
|
||||
(define (jolt-file? x) (jfile? x))
|
||||
|
||||
;; path string of any value: a jfile -> its path, else its str rendering.
|
||||
(define (file-path-of x) (if (jfile? x) (jfile-path x) (jolt-str-render-one x)))
|
||||
|
||||
;; A user-facing relative path resolves against JOLT_PWD — the user's cwd before
|
||||
;; the launcher cd'd to the jolt repo root — matching the JVM, where io/file is
|
||||
;; cwd-relative. (io/resource builds jfiles from the source roots directly, so it
|
||||
;; isn't routed through here.)
|
||||
(define (project-relative p)
|
||||
(if (or (= (string-length p) 0) (char=? (string-ref p 0) #\/))
|
||||
p
|
||||
(let ((pwd (getenv "JOLT_PWD")))
|
||||
(if (and pwd (> (string-length pwd) 0)) (string-append pwd "/" p) p))))
|
||||
|
||||
;; (io/file path) / (io/file parent child) — join children with "/".
|
||||
(define (jolt-make-file path . rest)
|
||||
(let loop ((p (project-relative (file-path-of path))) (cs rest))
|
||||
(if (null? cs) (make-jfile p)
|
||||
(loop (string-append p "/" (file-path-of (car cs))) (cdr cs)))))
|
||||
|
||||
(define (path-last-segment p)
|
||||
(let loop ((i (- (string-length p) 1)))
|
||||
(cond ((< i 0) p)
|
||||
((char=? (string-ref p i) #\/) (substring p (+ i 1) (string-length p)))
|
||||
(else (loop (- i 1))))))
|
||||
|
||||
;; directory children as full paths, sorted (the __list-dir seed primitive).
|
||||
(define (jolt-list-dir path)
|
||||
(let ((p (file-path-of path)))
|
||||
(map (lambda (e) (string-append p "/" e))
|
||||
(sort string<? (directory-list p)))))
|
||||
(define (jolt-dir? path) (if (file-directory? (file-path-of path)) #t #f))
|
||||
|
||||
;; absolute path string (cwd-relative paths resolved against current-directory).
|
||||
(define (jfile-abs p)
|
||||
(if (and (> (string-length p) 0) (char=? (string-ref p 0) #\/)) p
|
||||
(string-append (current-directory) "/" p)))
|
||||
|
||||
;; --- java.net.URL (a jhost "url", state #(spec)) ----------------------------
|
||||
;; A File.toURL value: .toString / .toExternalForm give the spec, .getPath /
|
||||
;; .getFile strip the "file:" scheme.
|
||||
(define (make-url spec) (make-jhost "url" (vector spec)))
|
||||
(define (url-spec u) (vector-ref (jhost-state u) 0))
|
||||
(define (url-strip-scheme spec)
|
||||
(if (and (>= (string-length spec) 5) (string=? (substring spec 0 5) "file:"))
|
||||
(substring spec 5 (string-length spec)) spec))
|
||||
(register-host-methods! "url"
|
||||
(list (cons "toString" (lambda (self) (url-spec self)))
|
||||
(cons "toExternalForm" (lambda (self) (url-spec self)))
|
||||
(cons "getPath" (lambda (self) (url-strip-scheme (url-spec self))))
|
||||
(cons "getFile" (lambda (self) (url-strip-scheme (url-spec self))))))
|
||||
|
||||
;; --- File method surface (record-method-dispatch arm) -----------------------
|
||||
(define (jfile-method f name args) ; -> boxed result, or #f to fall through
|
||||
(let ((p (jfile-path f)))
|
||||
(cond
|
||||
((string=? name "getPath") (list p))
|
||||
((string=? name "getName") (list (path-last-segment p)))
|
||||
((string=? name "toString") (list p))
|
||||
((string=? name "getAbsolutePath")(list (jfile-abs p)))
|
||||
((string=? name "getCanonicalPath")(list (jfile-abs p)))
|
||||
((string=? name "toURI") (list (string-append "file:" (jfile-abs p))))
|
||||
((string=? name "toURL") (list (make-url (string-append "file:" (jfile-abs p)))))
|
||||
((string=? name "exists") (list (if (file-exists? p) #t #f)))
|
||||
((string=? name "isDirectory") (list (if (file-directory? p) #t #f)))
|
||||
((string=? name "isFile") (list (if (and (file-exists? p) (not (file-directory? p))) #t #f)))
|
||||
((string=? name "listFiles") (list (list->cseq (map make-jfile (jolt-list-dir p)))))
|
||||
((string=? name "getParent")
|
||||
(let loop ((i (- (string-length p) 1)))
|
||||
(cond ((< i 0) (list jolt-nil))
|
||||
((char=? (string-ref p i) #\/) (list (if (= i 0) "/" (substring p 0 i))))
|
||||
(else (loop (- i 1))))))
|
||||
(else #f))))
|
||||
|
||||
(define %io-rmd record-method-dispatch)
|
||||
(set! record-method-dispatch
|
||||
(lambda (obj method-name rest-args)
|
||||
(if (jfile? obj)
|
||||
(let* ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args)))
|
||||
(r (jfile-method obj method-name rest)))
|
||||
(if r (car r) (error #f "no File method" method-name)))
|
||||
(%io-rmd obj method-name rest-args))))
|
||||
|
||||
;; .isDirectory / .listFiles emit to jolt-host-call (rt.ss), not record-method-
|
||||
;; dispatch — the Phase-1 shims there assume a
|
||||
;; path STRING target. Make them jfile-aware so file-seq's File branch works.
|
||||
(define %io-host-call jolt-host-call)
|
||||
(set! jolt-host-call
|
||||
(lambda (method target . args)
|
||||
(cond
|
||||
((and (jfile? target) (string=? method "isDirectory"))
|
||||
(if (file-directory? (jfile-path target)) #t #f))
|
||||
((and (jfile? target) (string=? method "listFiles"))
|
||||
(list->cseq (map make-jfile (jolt-list-dir target))))
|
||||
(else (apply %io-host-call method target args)))))
|
||||
|
||||
;; --- slurp / spit / flush ---------------------------------------------------
|
||||
(define (read-file-string path)
|
||||
(let ((p (open-input-file path)))
|
||||
(let ((s (get-string-all p))) (close-port p) (if (eof-object? s) "" s))))
|
||||
|
||||
;; Drain a jhost reader (StringReader / PushbackReader): read code units from the
|
||||
;; current position to EOF (-1) and assemble the string. Used by slurp; advances
|
||||
;; the reader, as on the JVM.
|
||||
(define (drain-reader r)
|
||||
(let loop ((acc '()))
|
||||
(let ((u (record-method-dispatch r "read" jolt-nil)))
|
||||
(if (or (jolt-nil? u) (and (number? u) (< u 0)))
|
||||
(list->string (reverse acc))
|
||||
(loop (cons (integer->char (exact (truncate u))) acc))))))
|
||||
|
||||
(define (reader-jhost? x)
|
||||
(and (jhost? x) (member (jhost-tag x) '("string-reader" "pushback-reader"))))
|
||||
|
||||
;; clojure.edn/read over a reader (jolt-uicd): the overlay edn.clj's drain-reader is
|
||||
;; janet/type-coupled, so on Chez we drain the jhost reader to a string and read the
|
||||
;; first EDN form (read-string). Re-asserted over the prelude in post-prelude.ss.
|
||||
(define (chez-edn-read reader)
|
||||
(jolt-invoke (var-deref "clojure.core" "read-string")
|
||||
(if (reader-jhost? reader) (drain-reader reader) (jolt-str-render-one reader))))
|
||||
|
||||
;; line-seq (jolt-0obq): the overlay line-seq reads via a Janet map-reader's
|
||||
;; :read-line-fn, but a Chez io/reader is a jhost StringReader. Drain it (or take a
|
||||
;; string) and split on newline; a trailing newline does NOT yield a final empty
|
||||
;; line (like readLine -> nil at EOF). Re-asserted in post-prelude.ss.
|
||||
(define (chez-lines s)
|
||||
(let loop ((cs (string->list s)) (cur '()) (acc '()))
|
||||
(cond ((null? cs) (reverse (if (null? cur) acc (cons (list->string (reverse cur)) acc))))
|
||||
((char=? (car cs) #\newline) (loop (cdr cs) '() (cons (list->string (reverse cur)) acc)))
|
||||
(else (loop (cdr cs) (cons (car cs) cur) acc)))))
|
||||
(define (chez-line-seq rdr)
|
||||
(list->cseq (chez-lines (cond ((string? rdr) rdr)
|
||||
((reader-jhost? rdr) (drain-reader rdr))
|
||||
(else (jolt-str-render-one rdr))))))
|
||||
|
||||
(define (jolt-slurp src . opts)
|
||||
(cond
|
||||
((jfile? src) (read-file-string (jfile-path src)))
|
||||
((reader-jhost? src) (drain-reader src))
|
||||
((string? src) (read-file-string src))
|
||||
(else (error #f "slurp: unsupported source" src))))
|
||||
|
||||
(define (spit-append? opts)
|
||||
(let loop ((o opts))
|
||||
(cond ((or (null? o) (null? (cdr o))) #f)
|
||||
((and (keyword-t? (car o)) (string=? (keyword-t-name (car o)) "append")
|
||||
(jolt-truthy? (cadr o))) #t)
|
||||
(else (loop (cddr o))))))
|
||||
|
||||
(define (jolt-spit path content . opts)
|
||||
(let* ((p (file-path-of path))
|
||||
(port (open-output-file p (if (spit-append? opts) 'append 'truncate))))
|
||||
(put-string port (jolt-str-render-one content))
|
||||
(close-port port)
|
||||
jolt-nil))
|
||||
|
||||
(define (jolt-flush) (flush-output-port (current-output-port)) jolt-nil)
|
||||
|
||||
;; --- str / type / instance? integration ------------------------------------
|
||||
;; str of a jfile is its path (Clojure's File.toString).
|
||||
(define %io-str-render jolt-str-render-one)
|
||||
(set! jolt-str-render-one
|
||||
(lambda (v) (if (jfile? v) (jfile-path v) (%io-str-render v))))
|
||||
|
||||
;; (type f) -> :jolt/file (the tagged-file :jolt/type). Re-def-var!
|
||||
;; "type": natives-meta.ss already bound the var to the old jolt-type value, so the
|
||||
;; set! alone (which updates the symbol for internal callers) wouldn't reach it.
|
||||
(define io-kw-file (keyword "jolt" "file"))
|
||||
(define %io-type jolt-type)
|
||||
(set! jolt-type (lambda (x) (if (jfile? x) io-kw-file (%io-type x))))
|
||||
(def-var! "clojure.core" "type" jolt-type)
|
||||
|
||||
;; (instance? java.io.File f): the instance? macro passes the class-name symbol;
|
||||
;; match "File" / "java.io.File" (and any *.File) against a jfile.
|
||||
(define %io-instance-check instance-check)
|
||||
(set! instance-check
|
||||
(lambda (type-sym val)
|
||||
(let ((tname (symbol-t-name type-sym)))
|
||||
(if (and (jfile? val)
|
||||
(or (string=? tname "File") (string=? tname "java.io.File")
|
||||
(string=? (path-last-segment tname) "File")))
|
||||
#t
|
||||
(%io-instance-check type-sym val)))))
|
||||
(def-var! "clojure.core" "instance-check" instance-check)
|
||||
|
||||
;; --- def-var! the native names the overlay file-seq + str/slurp use ----
|
||||
(def-var! "clojure.core" "__make-file" jolt-make-file)
|
||||
(def-var! "clojure.core" "__file?" jolt-file?)
|
||||
(def-var! "clojure.core" "__dir?" jolt-dir?)
|
||||
(def-var! "clojure.core" "__list-dir" (lambda (p) (list->cseq (jolt-list-dir p))))
|
||||
(def-var! "clojure.core" "slurp" jolt-slurp)
|
||||
(def-var! "clojure.core" "spit" jolt-spit)
|
||||
(def-var! "clojure.core" "flush" jolt-flush)
|
||||
|
||||
;; --- char-array: a seq of chars over a string (the JVM char[]). io/reader's
|
||||
;; char[] branch + selmer's (char-array template) feed on this.
|
||||
;; char-array (string -> chars). A leaf array native; lives here as io/reader
|
||||
;; is its only Chez consumer so far.
|
||||
(define (jolt-char-array a . rest)
|
||||
(cond
|
||||
((string? a) (list->cseq (string->list a)))
|
||||
((number? a) (list->cseq (make-list (exact (truncate a)) #\nul)))
|
||||
(else (list->cseq (map (lambda (c) (if (char? c) c (integer->char (exact (truncate c)))))
|
||||
(seq->list a))))))
|
||||
(def-var! "clojure.core" "char-array" jolt-char-array)
|
||||
|
||||
;; --- with-open's close seam (__close): a map-like value closes via its :close
|
||||
;; fn; a jhost reader/writer/file via its .close method (a no-op here); anything
|
||||
;; else is an error.
|
||||
(define (jolt-close x)
|
||||
(cond
|
||||
((jolt-nil? x) jolt-nil)
|
||||
((and (jhost? x) (member (jhost-tag x) '("string-reader" "pushback-reader" "writer")))
|
||||
(record-method-dispatch x "close" jolt-nil) jolt-nil)
|
||||
((jfile? x) jolt-nil)
|
||||
(else
|
||||
(let ((closef (jolt-get x (keyword #f "close") jolt-nil)))
|
||||
(if (and (not (jolt-nil? closef)) (procedure? closef))
|
||||
(begin (jolt-invoke closef) jolt-nil)
|
||||
(error #f "with-open: don't know how to close" x))))))
|
||||
(def-var! "clojure.core" "__close" jolt-close)
|
||||
|
||||
;; --- clojure.java.io/reader: an in-memory java.io.Reader over the source. An
|
||||
;; existing reader passes through; a File / path / URL is slurped; a char[] (or
|
||||
;; any seq) becomes a reader over (apply str …). Mirrors io.clj's reader. Returns
|
||||
;; a StringReader (host-static.ss jhost) so .read/.mark/.reset and slurp work.
|
||||
(define (seq-source->string x)
|
||||
(apply string-append (map jolt-str-render-one (seq->list x))))
|
||||
(define (jolt-io-reader x)
|
||||
(cond
|
||||
((reader-jhost? x) x)
|
||||
((jfile? x) (host-new "StringReader" (read-file-string (jfile-path x))))
|
||||
((and (jhost? x) (string=? (jhost-tag x) "url"))
|
||||
(host-new "StringReader" (read-file-string (url-strip-scheme (url-spec x)))))
|
||||
((string? x) (host-new "StringReader" (read-file-string x)))
|
||||
((or (cseq? x) (empty-list-t? x) (pvec? x))
|
||||
(host-new "StringReader" (seq-source->string x)))
|
||||
(else (host-new "StringReader" (jolt-str-render-one x)))))
|
||||
|
||||
;; --- clojure.java.io/writer: an existing writer passes through; a File / path
|
||||
;; gets a file-backed writer (host-static.ss "file-writer") that persists on
|
||||
;; flush/close. Mirrors io.clj's writer over the host's StringWriter/file ports.
|
||||
(define (jolt-io-writer x)
|
||||
(cond
|
||||
((and (jhost? x) (string=? (jhost-tag x) "writer")) x)
|
||||
((and (jhost? x) (string=? (jhost-tag x) "file-writer")) x)
|
||||
((jfile? x) (make-jhost "file-writer" (vector (jfile-path x) "")))
|
||||
((string? x) (make-jhost "file-writer" (vector x "")))
|
||||
(else (error #f "io/writer: don't know how to create a writer from" x))))
|
||||
|
||||
;; --- clojure.java.io ns -----------------------------------------------------
|
||||
(def-var! "clojure.java.io" "file" jolt-make-file)
|
||||
(def-var! "clojure.java.io" "as-file" (lambda (x) (if (jfile? x) x (make-jfile (file-path-of x)))))
|
||||
(def-var! "clojure.java.io" "reader" jolt-io-reader)
|
||||
(def-var! "clojure.java.io" "writer" jolt-io-writer)
|
||||
(def-var! "clojure.java.io" "input-stream" jolt-io-reader)
|
||||
(def-var! "clojure.java.io" "output-stream" jolt-io-writer)
|
||||
;; resource: jolt has no classpath, so a named resource is resolved against the
|
||||
;; loader's source roots (a project's :paths, e.g. "resources"). Returns a File
|
||||
;; (slurp/reader-able) for the first match, else nil. get-source-roots is the
|
||||
;; loader's accessor (loader.ss), resolved at call time — the runtime CLI loads it.
|
||||
(define (jolt-io-resource name)
|
||||
(let ((nm (jolt-str-render-one name)))
|
||||
(let loop ((roots (get-source-roots)))
|
||||
(cond ((null? roots) jolt-nil)
|
||||
((file-exists? (string-append (car roots) "/" nm)) (make-jfile (string-append (car roots) "/" nm)))
|
||||
(else (loop (cdr roots)))))))
|
||||
(def-var! "clojure.java.io" "resource" jolt-io-resource)
|
||||
(def-var! "clojure.java.io" "as-url" (lambda (x) (if (and (jhost? x) (string=? (jhost-tag x) "url")) x (make-url (jolt-str-render-one x)))))
|
||||
87
host/chez/lazy-bridge.ss
Normal file
87
host/chez/lazy-bridge.ss
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
;; lazy-seq bridge (jolt-cf1q.3, jolt-dmw9) — make-lazy-seq / coll->cells.
|
||||
;;
|
||||
;; The `lazy-seq` macro (00-syntax.clj) expands to
|
||||
;; (make-lazy-seq (fn* [] (coll->cells (do body))))
|
||||
;; and `lazy-cat` to (concat (lazy-seq c) ...). make-lazy-seq / coll->cells had
|
||||
;; no Chez shim, so EVERY overlay fn
|
||||
;; built on lazy-seq — repeat / iterate / cycle / dedupe / take-nth / keep /
|
||||
;; interpose / reductions / tree-seq (-> flatten) / lazy-cat — resolved the call
|
||||
;; to jolt-nil and hit the apply-jolt-nil crash bucket.
|
||||
;;
|
||||
;; Bridge to the cseq model (seq.ss): a `jolt-lazyseq` is a deferred seq — a 0-arg
|
||||
;; thunk that, when forced once, yields a seq (cseq | nil). coll->cells coerces the
|
||||
;; body result to a seq (= jolt-seq), so the thunk already returns a seq; jolt-seq
|
||||
;; is extended to force a lazyseq. The one trap: (cons x (a-lazy-seq)) must NOT
|
||||
;; force the tail (else (repeat x) = (lazy-seq (cons x (repeat x))) loops forever),
|
||||
;; so jolt-cons defers a lazyseq tail into a lazy cseq cell.
|
||||
;;
|
||||
;; Loaded LAST (after host-table.ss): %ls-seq then captures the fully-extended
|
||||
;; jolt-seq (sorted-aware), so a lazy body returning a sorted coll still seqs.
|
||||
|
||||
(define-record-type jolt-lazyseq
|
||||
(fields (mutable thunk) (mutable val) (mutable realized?))
|
||||
(nongenerative jolt-lazyseq-v1))
|
||||
|
||||
(define (jolt-make-lazy-seq thunk) (make-jolt-lazyseq thunk jolt-nil #f))
|
||||
|
||||
;; force once and memoize. The thunk is (fn [] (coll->cells body)); coll->cells
|
||||
;; already coerced the body to a seq (cseq | nil) via the live jolt-seq, so the
|
||||
;; result needs no further coercion (a nested lazyseq was forced by coll->cells).
|
||||
(define (force-lazyseq x)
|
||||
(if (jolt-lazyseq-realized? x)
|
||||
(jolt-lazyseq-val x)
|
||||
(let ((r (jolt-invoke (jolt-lazyseq-thunk x))))
|
||||
(jolt-lazyseq-val-set! x r)
|
||||
(jolt-lazyseq-realized?-set! x #t)
|
||||
(jolt-lazyseq-thunk-set! x #f)
|
||||
r)))
|
||||
|
||||
;; coll->cells: coerce the body result to the cell representation = a seq | nil.
|
||||
(define (jolt-coll->cells c) (jolt-seq c))
|
||||
|
||||
;; extend jolt-seq to force a lazyseq (a lazyseq is seqable -> its realized seq).
|
||||
(define %ls-seq jolt-seq)
|
||||
(set! jolt-seq (lambda (x) (if (jolt-lazyseq? x) (force-lazyseq x) (%ls-seq x))))
|
||||
|
||||
;; (cons x lazyseq): keep the tail lazy — force it only when the cseq cell is
|
||||
;; walked, so an infinite (repeat/iterate/cycle) stays productive.
|
||||
(define %ls-cons jolt-cons)
|
||||
(set! jolt-cons (lambda (x coll)
|
||||
(if (jolt-lazyseq? coll)
|
||||
(cseq-lazy x (lambda () (force-lazyseq coll)))
|
||||
(%ls-cons x coll))))
|
||||
|
||||
;; A lazyseq is a NEW value type, so the dispatchers that DON'T route through
|
||||
;; jolt-seq must learn it or a raw (unrealized) lazyseq escapes — e.g. the corpus
|
||||
;; compares (= [1 3 5] (take-nth 2 …)) against the raw lazyseq, and jolt=2 would
|
||||
;; see an unknown type and return false. Recognizing it as sequential is enough
|
||||
;; for equality + hash (seq=? / seq-hash coerce via jolt-seq); count / empty? /
|
||||
;; nth / the printers don't, so coerce those explicitly.
|
||||
(define %ls-sequential? jolt-sequential?)
|
||||
(set! jolt-sequential? (lambda (x) (or (jolt-lazyseq? x) (%ls-sequential? x))))
|
||||
(define %ls-count jolt-count)
|
||||
(set! jolt-count (lambda (x) (if (jolt-lazyseq? x) (%ls-count (jolt-seq x)) (%ls-count x))))
|
||||
(define %ls-empty? jolt-empty?)
|
||||
(set! jolt-empty? (lambda (x) (if (jolt-lazyseq? x) (%ls-empty? (jolt-seq x)) (%ls-empty? x))))
|
||||
(define %ls-nth jolt-nth)
|
||||
(set! jolt-nth (case-lambda
|
||||
((coll i) (if (jolt-lazyseq? coll) (%ls-nth (jolt-seq coll) i) (%ls-nth coll i)))
|
||||
((coll i d) (if (jolt-lazyseq? coll) (%ls-nth (jolt-seq coll) i d) (%ls-nth coll i d)))))
|
||||
(define %ls-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (jolt-lazyseq? x) (%ls-pr-str (jolt-seq x)) (%ls-pr-str x))))
|
||||
(define %ls-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (jolt-lazyseq? x) (%ls-pr-readable (jolt-seq x)) (%ls-pr-readable x))))
|
||||
(define %ls-str-render-one jolt-str-render-one)
|
||||
(set! jolt-str-render-one (lambda (x) (if (jolt-lazyseq? x) (%ls-str-render-one (jolt-seq x)) (%ls-str-render-one x))))
|
||||
|
||||
;; seq? — a lazy seq IS a seq (predicates.ss's jolt-seq? predates the lazyseq
|
||||
;; record). Unlike the native-op dispatchers above (called via a direct top-level
|
||||
;; reference, so the set! is enough), seq? is reached through var-deref, which
|
||||
;; reads the var-cell root — so the patched closure must be re-def-var!'d, not just
|
||||
;; set!. (Exposed once dynamic binding let with-in-str/line-seq reach seq?.)
|
||||
(define %ls-seq? jolt-seq?)
|
||||
(set! jolt-seq? (lambda (x) (or (jolt-lazyseq? x) (%ls-seq? x))))
|
||||
(def-var! "clojure.core" "seq?" jolt-seq?)
|
||||
|
||||
(def-var! "clojure.core" "make-lazy-seq" jolt-make-lazy-seq)
|
||||
(def-var! "clojure.core" "coll->cells" jolt-coll->cells)
|
||||
194
host/chez/loader.ss
Normal file
194
host/chez/loader.ss
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
;; loader.ss (jolt-90sp) — file-based namespace loading + a shell primitive.
|
||||
;;
|
||||
;; The corpus/CLI spine compiles one program at a time; namespaces declared in
|
||||
;; that program see each other because a top-level (do …) unrolls. A real project
|
||||
;; spans many FILES, so `require` must locate a namespace's source on the search
|
||||
;; roots and load it — transitively, once each. This is the piece the Phase-3
|
||||
;; "cross-ns load is deferred" note left open (ns.ss).
|
||||
;;
|
||||
;; Loaded by cli.ss AFTER compile-eval.ss (it calls jolt-compile-eval-form). The
|
||||
;; gates load compile-eval.ss but NOT this file, so the corpus/unit/sci runners
|
||||
;; keep their alias-only `require` and are unaffected.
|
||||
|
||||
;; --- search roots -----------------------------------------------------------
|
||||
;; An ordered list of directory strings. `require` searches them left to right.
|
||||
;; The CLI seeds this with the project's resolved deps roots (jolt.deps) plus the
|
||||
;; jolt-core roots so jolt.main/jolt.deps themselves load.
|
||||
(define source-roots '("."))
|
||||
(define (set-source-roots! roots) (set! source-roots roots))
|
||||
(define (get-source-roots) source-roots)
|
||||
|
||||
;; --- namespace -> file path -------------------------------------------------
|
||||
;; "app.commonmark-test" -> "app/commonmark_test": split on '.', munge '-'->'_'
|
||||
;; per segment, join with '/'. Matches Clojure's ns->file munging.
|
||||
(define (ns-seg-munge seg)
|
||||
(list->string (map (lambda (c) (if (char=? c #\-) #\_ c)) (string->list seg))))
|
||||
(define (ns-name->rel name)
|
||||
(let loop ((cs (string->list name)) (seg '()) (segs '()))
|
||||
(cond
|
||||
((null? cs)
|
||||
(let ((all (reverse (cons (list->string (reverse seg)) segs))))
|
||||
(let join ((xs all) (acc ""))
|
||||
(cond ((null? xs) acc)
|
||||
((string=? acc "") (join (cdr xs) (ns-seg-munge (car xs))))
|
||||
(else (join (cdr xs) (string-append acc "/" (ns-seg-munge (car xs)))))))))
|
||||
((char=? (car cs) #\.)
|
||||
(loop (cdr cs) '() (cons (list->string (reverse seg)) segs)))
|
||||
(else (loop (cdr cs) (cons (car cs) seg) segs)))))
|
||||
|
||||
(define (find-ns-file name)
|
||||
(let ((rel (ns-name->rel name)))
|
||||
(let loop ((roots source-roots))
|
||||
(if (null? roots) #f
|
||||
(let ((clj (string-append (car roots) "/" rel ".clj"))
|
||||
(cljc (string-append (car roots) "/" rel ".cljc")))
|
||||
(cond ((file-exists? clj) clj)
|
||||
((file-exists? cljc) cljc)
|
||||
(else (loop (cdr roots)))))))))
|
||||
|
||||
;; --- the loaded set ---------------------------------------------------------
|
||||
;; Seeded with every namespace that already has vars at load time — the baked
|
||||
;; prelude/image (clojure.core, clojure.string, jolt.analyzer, …). A `require` of
|
||||
;; one of those then no-ops instead of hunting for a (nonexistent) source file.
|
||||
(define loaded-ns (make-hashtable string-hash string=?))
|
||||
(vector-for-each (lambda (c) (hashtable-set! loaded-ns (var-cell-ns c) #t))
|
||||
(hashtable-values var-table))
|
||||
|
||||
;; Read every form from a file and compile+eval it in turn. The first form is
|
||||
;; normally (ns …), which expands to (in-ns …) and switches the current ns, so
|
||||
;; later forms compile in that namespace — (chez-current-ns) is re-read each step.
|
||||
;;
|
||||
;; Reads by POSITION rather than via __parse-next: a top-level form that reads as
|
||||
;; nothing — a :cljs-only #? with no matching branch, a #_ discard, a trailing
|
||||
;; comment — yields rdr-eof but still advances. parse-next collapses that to "no
|
||||
;; more forms", which would silently drop the entire rest of the file; here we
|
||||
;; skip the no-op form and continue to true end-of-string.
|
||||
(define (load-jolt-file path)
|
||||
(let* ((src (read-file-string path)) (end (string-length src)))
|
||||
(let loop ((i 0))
|
||||
(when (< i end)
|
||||
(let-values (((form j) (rdr-read-form src i end)))
|
||||
(when (> j i)
|
||||
(unless (rdr-eof? form)
|
||||
(when (getenv "JOLT_TRACE_LOAD")
|
||||
(display " [load-form] " (current-error-port))
|
||||
(display (jolt-pr-str form) (current-error-port)) (newline (current-error-port)))
|
||||
(jolt-compile-eval-form form (chez-current-ns)))
|
||||
(loop j)))))))
|
||||
|
||||
;; load-namespace: load `name`'s source once. Marked loaded BEFORE eval so a
|
||||
;; dependency cycle terminates (Clojure's behavior). The caller's current ns is
|
||||
;; restored afterward, since loading the file switched it.
|
||||
(define (load-namespace name)
|
||||
(unless (hashtable-ref loaded-ns name #f)
|
||||
(hashtable-set! loaded-ns name #t)
|
||||
(let ((file (find-ns-file name)))
|
||||
(if (not file)
|
||||
(begin
|
||||
(hashtable-delete! loaded-ns name)
|
||||
(error #f (string-append "Could not locate " (ns-name->rel name)
|
||||
".clj (or .cljc) on the source roots") name))
|
||||
(let ((saved (chez-current-ns)))
|
||||
(load-jolt-file file)
|
||||
(set-chez-ns! saved)
|
||||
(def-var! "clojure.core" "*ns*" (intern-ns! saved)))))))
|
||||
|
||||
;; load-file: load an explicit path (a `run FILE`), in the current ns.
|
||||
(define (jolt-load-file path)
|
||||
(load-jolt-file path)
|
||||
jolt-nil)
|
||||
|
||||
;; The target ns name of a require/use spec ([ns …] / (ns …) / bare ns).
|
||||
(define (spec-target-name spec)
|
||||
(let ((items (cond ((pvec? spec) (seq->list spec))
|
||||
((or (cseq? spec) (empty-list-t? spec)) (seq->list spec))
|
||||
((symbol-t? spec) (list spec))
|
||||
(else '()))))
|
||||
(and (pair? items) (symbol-t? (car items)) (symbol-t-name (car items)))))
|
||||
|
||||
;; --- require/use that LOAD ---------------------------------------------------
|
||||
;; Override the alias-only versions from natives-str.ss. Load each spec's target
|
||||
;; (no-op if baked/already loaded), THEN register its :as/:refer under the caller
|
||||
;; ns (chez-register-spec! reads the current ns, restored by load-namespace).
|
||||
(define (loader-require . specs)
|
||||
(for-each
|
||||
(lambda (s)
|
||||
(let ((target (spec-target-name s)))
|
||||
(when target (load-namespace target)))
|
||||
(chez-register-spec! (chez-current-ns) s))
|
||||
specs)
|
||||
jolt-nil)
|
||||
(def-var! "clojure.core" "require" loader-require)
|
||||
|
||||
(define (loader-use . specs)
|
||||
(for-each
|
||||
(lambda (spec)
|
||||
(let ((target (spec-target-name spec)))
|
||||
(when target (load-namespace target)))
|
||||
(chez-register-spec! (chez-current-ns) spec)
|
||||
(let* ((items (cond ((pvec? spec) (seq->list spec))
|
||||
((or (cseq? spec) (empty-list-t? spec)) (seq->list spec))
|
||||
((symbol-t? spec) (list spec))
|
||||
(else '())))
|
||||
(target (and (pair? items) (symbol-t? (car items)) (symbol-t-name (car items))))
|
||||
(filtered (let scan ((xs (if (pair? items) (cdr items) '())))
|
||||
(cond ((null? xs) #f)
|
||||
((and (keyword? (car xs))
|
||||
(member (keyword-t-name (car xs)) '("only" "refer"))) #t)
|
||||
(else (scan (cdr xs)))))))
|
||||
(when (and target (not filtered))
|
||||
(chez-register-refer-all! (chez-current-ns) target))))
|
||||
specs)
|
||||
jolt-nil)
|
||||
(def-var! "clojure.core" "use" loader-use)
|
||||
|
||||
(def-var! "clojure.core" "load-file" jolt-load-file)
|
||||
;; load: each arg is a "/"-rooted resource path like "/app/extra"; load the file
|
||||
;; for it relative to the search roots (strip the leading slash, try .clj/.cljc).
|
||||
(define (jolt-load . paths)
|
||||
(for-each
|
||||
(lambda (p)
|
||||
(let* ((rel (if (and (> (string-length p) 0) (char=? (string-ref p 0) #\/))
|
||||
(substring p 1 (string-length p)) p)))
|
||||
(let loop ((roots source-roots))
|
||||
(if (null? roots)
|
||||
(error #f "Could not locate resource on source roots" p)
|
||||
(let ((clj (string-append (car roots) "/" rel ".clj"))
|
||||
(cljc (string-append (car roots) "/" rel ".cljc")))
|
||||
(cond ((file-exists? clj) (load-jolt-file clj))
|
||||
((file-exists? cljc) (load-jolt-file cljc))
|
||||
(else (loop (cdr roots)))))))))
|
||||
paths)
|
||||
jolt-nil)
|
||||
(def-var! "clojure.core" "load" jolt-load)
|
||||
|
||||
;; --- shell primitive (jolt.host/sh, sh-out) ---------------------------------
|
||||
;; `sh` runs `sh -c CMD`, inheriting stdout/stderr (so git progress shows), and
|
||||
;; returns the exit code. `sh-out` captures stdout to a string (exit ignored) for
|
||||
;; commands whose output we parse (git rev-parse). Used by jolt.deps for git.
|
||||
(define (jolt-sh cmd) (system cmd))
|
||||
(def-var! "jolt.host" "sh" jolt-sh)
|
||||
|
||||
(define (jolt-sh-out cmd)
|
||||
(call-with-values
|
||||
(lambda () (open-process-ports (string-append "exec sh -c " (sh-quote cmd))
|
||||
(buffer-mode block) (native-transcoder)))
|
||||
(lambda (stdin stdout stderr pid)
|
||||
(close-port stdin)
|
||||
(let ((out (get-string-all stdout)))
|
||||
(close-port stdout) (close-port stderr)
|
||||
(if (eof-object? out) "" out)))))
|
||||
(define (sh-quote s) ; single-quote for the outer sh -c
|
||||
(string-append "'"
|
||||
(apply string-append
|
||||
(map (lambda (c) (if (char=? c #\') "'\\''" (string c))) (string->list s)))
|
||||
"'"))
|
||||
(def-var! "jolt.host" "sh-out" jolt-sh-out)
|
||||
|
||||
;; Expose source-root control + ns loading to Clojure (jolt.main / jolt.deps).
|
||||
(def-var! "jolt.host" "set-source-roots!"
|
||||
(lambda (roots) (set-source-roots! (seq->list roots)) jolt-nil))
|
||||
(def-var! "jolt.host" "source-roots" (lambda () (list->cseq source-roots)))
|
||||
(def-var! "jolt.host" "load-namespace" (lambda (n) (load-namespace n) jolt-nil))
|
||||
(def-var! "jolt.host" "file-exists?" (lambda (p) (if (file-exists? p) #t #f)))
|
||||
(def-var! "jolt.host" "getenv" (lambda (n) (let ((v (getenv n))) (if v v jolt-nil))))
|
||||
67
host/chez/math.ss
Normal file
67
host/chez/math.ss
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
;; clojure.math (jolt-22vo) — Chez host shim over native flonum math.
|
||||
;;
|
||||
;; clojure.math is registered as native bindings (jolt-h79), NOT a .clj file — so
|
||||
;; there's no source tier to emit. Chez provides its own def-var! shims here, one per
|
||||
;; clojure.math fn, over Chez's native procedures. The analyzer knows the
|
||||
;; clojure.math ns exists, so a ref
|
||||
;; like clojure.math/sqrt lowers to a var-deref; these cells back it at runtime.
|
||||
;;
|
||||
;; jolt is all-flonum, so every result is a flonum (inputs arrive as flonums; Chez
|
||||
;; sqrt/sin/expt/... return flonums for flonum args). Semantics match
|
||||
;; Clojure 1.11 clojure.math: round = floor(x+0.5), rint = round-half-even,
|
||||
;; floor/ceil/floor-div return doubles, to-degrees/to-radians via PI.
|
||||
|
||||
(define jolt-math-pi (acos -1.0))
|
||||
(define jolt-math-e (exp 1.0))
|
||||
|
||||
(define (jolt-math-cbrt x)
|
||||
;; sign-aware so negative inputs stay real (expt of a negative flonum to a
|
||||
;; fractional power goes complex).
|
||||
(if (< x 0.0)
|
||||
(- (expt (- x) (/ 1.0 3.0)))
|
||||
(expt x (/ 1.0 3.0))))
|
||||
|
||||
;; clojure.math/round returns a long (exact); floor/ceil/signum/rint return doubles.
|
||||
(define (jolt-math-round x) (exact (floor (+ x 0.5))))
|
||||
(define (jolt-math-signum x) (cond ((< x 0.0) -1.0) ((> x 0.0) 1.0) (else 0.0)))
|
||||
(define (jolt-math-to-degrees r) (/ (* r 180.0) jolt-math-pi))
|
||||
(define (jolt-math-to-radians d) (/ (* d jolt-math-pi) 180.0))
|
||||
(define (jolt-math-hypot a b) (sqrt (+ (* a a) (* b b))))
|
||||
(define (jolt-math-floor-div a b) (floor (/ a b)))
|
||||
(define (jolt-math-floor-mod a b) (- a (* b (floor (/ a b)))))
|
||||
|
||||
;; clojure.math fns always return a DOUBLE; Chez's sqrt/expt/sin/floor/... return
|
||||
;; EXACT for exact args ((sqrt 9) -> 3, (sin 0) -> 0), so coerce.
|
||||
(define (m1 f) (lambda (x) (exact->inexact (f x))))
|
||||
(define (m2 f) (lambda (a b) (exact->inexact (f a b))))
|
||||
(def-var! "clojure.math" "sqrt" (m1 sqrt))
|
||||
(def-var! "clojure.math" "cbrt" jolt-math-cbrt)
|
||||
(def-var! "clojure.math" "pow" (m2 expt))
|
||||
(def-var! "clojure.math" "exp" (m1 exp))
|
||||
(def-var! "clojure.math" "expm1" (lambda (x) (- (exp x) 1.0)))
|
||||
(def-var! "clojure.math" "log" (m1 log))
|
||||
(def-var! "clojure.math" "log10" (lambda (x) (exact->inexact (log x 10.0))))
|
||||
(def-var! "clojure.math" "log1p" (lambda (x) (log (+ 1.0 x))))
|
||||
(def-var! "clojure.math" "sin" (m1 sin))
|
||||
(def-var! "clojure.math" "cos" (m1 cos))
|
||||
(def-var! "clojure.math" "tan" (m1 tan))
|
||||
(def-var! "clojure.math" "asin" (m1 asin))
|
||||
(def-var! "clojure.math" "acos" (m1 acos))
|
||||
(def-var! "clojure.math" "atan" (m1 atan))
|
||||
;; clojure.math/atan2 is atan2(y, x); Chez's 2-arg atan is (atan y x).
|
||||
(def-var! "clojure.math" "atan2" (lambda (y x) (exact->inexact (atan y x))))
|
||||
(def-var! "clojure.math" "sinh" (m1 sinh))
|
||||
(def-var! "clojure.math" "cosh" (m1 cosh))
|
||||
(def-var! "clojure.math" "tanh" (m1 tanh))
|
||||
(def-var! "clojure.math" "floor" (m1 floor))
|
||||
(def-var! "clojure.math" "ceil" (m1 ceiling))
|
||||
(def-var! "clojure.math" "rint" (m1 round))
|
||||
(def-var! "clojure.math" "round" jolt-math-round)
|
||||
(def-var! "clojure.math" "signum" jolt-math-signum)
|
||||
(def-var! "clojure.math" "to-degrees" jolt-math-to-degrees)
|
||||
(def-var! "clojure.math" "to-radians" jolt-math-to-radians)
|
||||
(def-var! "clojure.math" "hypot" jolt-math-hypot)
|
||||
(def-var! "clojure.math" "floor-div" jolt-math-floor-div)
|
||||
(def-var! "clojure.math" "floor-mod" jolt-math-floor-mod)
|
||||
(def-var! "clojure.math" "E" jolt-math-e)
|
||||
(def-var! "clojure.math" "PI" jolt-math-pi)
|
||||
196
host/chez/multimethods.ss
Normal file
196
host/chez/multimethods.ss
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
;; multimethods (jolt-9ls5) — the multimethod dispatch runtime on the Chez host.
|
||||
;;
|
||||
;; defmulti/defmethod are macros that expand to ctx-capturing setup CALLS
|
||||
;; (defmulti-setup / defmethod-setup, + the table ops get-method/methods/
|
||||
;; remove-method/prefer-method/prefers), implemented here against
|
||||
;; the runtime's ns/var machinery.
|
||||
;;
|
||||
;; A multimethod VALUE is a jolt-multifn record carrying its dispatch fn and a
|
||||
;; mutable method table (dispatch-val -> method fn, keyed with jolt= so keyword/
|
||||
;; vector/number dispatch values match by value). jolt-invoke dispatches it:
|
||||
;; an exact method, else an isa?/hierarchy match (resolved through prefer-method
|
||||
;; and the overlay's isa?/derive/hierarchy), else the :default method.
|
||||
;;
|
||||
;; NS resolution: defmulti expands to (defmulti-setup (quote name) ...) with a
|
||||
;; BARE symbol — the Chez RT has no compile-time current ns at the call site, so a
|
||||
;; runtime `chez-current-ns` box names where to def-var! the multifn. It defaults
|
||||
;; to "user" (matching the analyzer's ns for -e user code); the assembled prelude
|
||||
;; sets it to "clojure.core" around its own load (program-with-prelude), so the
|
||||
;; print-method/print-dup defmultis land in clojure.core. defmethod-setup and the
|
||||
;; symbol-taking table ops resolve the multifn via (var-deref (chez-current-ns) …),
|
||||
;; so they agree with defmulti. Loaded from rt.ss after seq.ss (jolt-invoke),
|
||||
;; collections.ss (jolt=/key-hash/jolt-hash-map) and the var-cell machinery.
|
||||
|
||||
(define chez-current-ns-box (vector "user"))
|
||||
(define (chez-current-ns) (vector-ref chez-current-ns-box 0))
|
||||
(define (set-chez-ns! ns) (vector-set! chez-current-ns-box 0 ns))
|
||||
|
||||
(define-record-type jolt-multifn
|
||||
(fields name dispatch-fn methods default hierarchy prefers)
|
||||
(nongenerative jolt-multifn-v1))
|
||||
|
||||
(define kw-default (keyword #f "default"))
|
||||
(define (new-mm-table) (make-hashtable key-hash jolt=))
|
||||
|
||||
;; (defmulti-setup 'name dispatch & opts) — opts is a flat :default/:hierarchy plist.
|
||||
(define (parse-mm-opts opts)
|
||||
(let loop ((o opts) (dk kw-default) (h #f))
|
||||
(if (or (null? o) (null? (cdr o)))
|
||||
(values dk h)
|
||||
(let ((k (car o)) (v (cadr o)))
|
||||
(cond
|
||||
((and (keyword? k) (not (keyword-t-ns k)) (string=? (keyword-t-name k) "default"))
|
||||
(loop (cddr o) v h))
|
||||
((and (keyword? k) (not (keyword-t-ns k)) (string=? (keyword-t-name k) "hierarchy"))
|
||||
(loop (cddr o) dk v))
|
||||
(else (loop (cddr o) dk h)))))))
|
||||
|
||||
(define (jolt-defmulti-setup name-sym dispatch . opts)
|
||||
(let-values (((dk h) (parse-mm-opts opts)))
|
||||
(let ((mf (make-jolt-multifn (symbol-t-name name-sym) dispatch
|
||||
(new-mm-table) dk h (new-mm-table))))
|
||||
(def-var! (chez-current-ns) (symbol-t-name name-sym) mf)
|
||||
mf)))
|
||||
|
||||
;; (defmethod-setup 'mm dispatch-val impl) — add a method. Auto-creates the multifn
|
||||
;; if absent (defmethod before defmulti — rare; identity dispatch as a fallback).
|
||||
(define (jolt-defmethod-setup mm-sym dval impl)
|
||||
(let* ((nm (symbol-t-name mm-sym))
|
||||
(sns (symbol-t-ns mm-sym))
|
||||
(qns (and sns (not (jolt-nil? sns)) (not (null? sns)) sns))
|
||||
;; qualified (cf.mm/ext) resolves in its own ns (cross-ns defmethod);
|
||||
;; unqualified stays in the current ns (a shadow, as before).
|
||||
(mns (if qns (or (chez-resolve-alias (chez-current-ns) qns) qns) (chez-current-ns)))
|
||||
(cur (var-deref mns nm))
|
||||
(mf (if (jolt-multifn? cur) cur
|
||||
;; auto-create: copy the dispatch fn + default from a same-named
|
||||
;; clojure.core multifn (e.g. print-method's 2-arg dispatch) so a
|
||||
;; (defmethod print-method ...) before naming clojure.core's still
|
||||
;; dispatches right — the old 1-arg identity fallback crashed.
|
||||
(let* ((core (var-deref "clojure.core" nm))
|
||||
(disp (if (jolt-multifn? core)
|
||||
(jolt-multifn-dispatch-fn core)
|
||||
(var-deref "clojure.core" "identity")))
|
||||
(deft (if (jolt-multifn? core) (jolt-multifn-default core) kw-default))
|
||||
(m (make-jolt-multifn nm disp (new-mm-table) deft #f (new-mm-table))))
|
||||
(def-var! mns nm m) m))))
|
||||
(hashtable-set! (jolt-multifn-methods mf) dval impl)
|
||||
mf))
|
||||
|
||||
;; --- dispatch ----------------------------------------------------------------
|
||||
(define (mm-isa? mf)
|
||||
;; the overlay's isa? (the hierarchy system is pure Clojure); a per-mm :hierarchy
|
||||
;; is an atom (deref each dispatch, like a Clojure var) or a plain map.
|
||||
(let* ((isa (var-deref "clojure.core" "isa?"))
|
||||
(h (jolt-multifn-hierarchy mf))
|
||||
(hval (and h (if (jolt-atom? h) (jolt-atom-val h) h))))
|
||||
(lambda (x y) (jolt-truthy? (if hval (jolt-invoke isa hval x y) (jolt-invoke isa x y))))))
|
||||
|
||||
(define (mm-find-isa mf dv)
|
||||
(let* ((methods (jolt-multifn-methods mf))
|
||||
(isa? (mm-isa? mf))
|
||||
(default (jolt-multifn-default mf))
|
||||
(keys (filter (lambda (k) (not (jolt= k default)))
|
||||
(vector->list (hashtable-keys methods))))
|
||||
(matches (filter (lambda (k) (isa? dv k)) keys)))
|
||||
(cond
|
||||
((null? matches) #f)
|
||||
((null? (cdr matches)) (hashtable-ref methods (car matches) #f))
|
||||
(else
|
||||
;; >1 isa-match: pick the dominant key (x dominates y when x is
|
||||
;; prefer-method'd over y, or (isa? x y)); ambiguity with no dominant is an
|
||||
;; error, as in Clojure.
|
||||
(let* ((prefers (jolt-multifn-prefers mf))
|
||||
(pref? (lambda (x y)
|
||||
(let ((px (hashtable-ref prefers x #f)))
|
||||
(and px (hashtable-ref px y #f) #t))))
|
||||
(dom? (lambda (x y) (or (pref? x y) (isa? x y))))
|
||||
(best (fold-left (lambda (b k) (if (dom? k b) k b)) (car matches) (cdr matches))))
|
||||
(for-each
|
||||
(lambda (k)
|
||||
(when (and (not (jolt= k best)) (not (dom? best k)))
|
||||
(error #f (string-append "Multiple methods in multimethod '" (jolt-multifn-name mf)
|
||||
"' match dispatch value - and neither is preferred"))))
|
||||
matches)
|
||||
(hashtable-ref methods best #f))))))
|
||||
|
||||
(define (multifn-dispatch mf . args)
|
||||
(let* ((dv (apply jolt-invoke (jolt-multifn-dispatch-fn mf) args))
|
||||
(methods (jolt-multifn-methods mf))
|
||||
(direct (hashtable-ref methods dv #f)))
|
||||
(cond
|
||||
(direct (apply jolt-invoke direct args))
|
||||
((mm-find-isa mf dv) => (lambda (m) (apply jolt-invoke m args)))
|
||||
((hashtable-ref methods (jolt-multifn-default mf) #f)
|
||||
=> (lambda (m) (apply jolt-invoke m args)))
|
||||
(else (error #f (string-append "No method in multimethod '" (jolt-multifn-name mf)
|
||||
"' for dispatch value: " (jolt-pr-str dv)))))))
|
||||
|
||||
;; jolt-invoke dispatches a multifn (otherwise falls through to the prior logic).
|
||||
(define %prev-jolt-invoke jolt-invoke)
|
||||
(set! jolt-invoke
|
||||
(lambda (f . args)
|
||||
(if (jolt-multifn? f)
|
||||
(apply multifn-dispatch f args)
|
||||
(apply %prev-jolt-invoke f args))))
|
||||
|
||||
;; --- table ops ---------------------------------------------------------------
|
||||
;; prefer-method/remove-method/remove-all-methods/prefers take the name QUOTED;
|
||||
;; get-method/methods take the multifn VALUE (Clojure semantics).
|
||||
(define (mm-of-sym sym) (let ((v (var-deref (chez-current-ns) (symbol-t-name sym))))
|
||||
(and (jolt-multifn? v) v)))
|
||||
|
||||
(define (jolt-prefer-method-setup mm-sym dval-a dval-b)
|
||||
(let ((mf (mm-of-sym mm-sym)))
|
||||
(when mf
|
||||
(let ((sub (or (hashtable-ref (jolt-multifn-prefers mf) dval-a #f)
|
||||
(let ((h (new-mm-table)))
|
||||
(hashtable-set! (jolt-multifn-prefers mf) dval-a h) h))))
|
||||
(hashtable-set! sub dval-b #t)))
|
||||
mf))
|
||||
|
||||
(define (jolt-remove-method-setup mm-sym dval)
|
||||
(let ((mf (mm-of-sym mm-sym)))
|
||||
(when mf (hashtable-delete! (jolt-multifn-methods mf) dval))
|
||||
mf))
|
||||
|
||||
(define (jolt-remove-all-methods-setup mm-sym)
|
||||
(let ((mf (mm-of-sym mm-sym)))
|
||||
(when mf (hashtable-clear! (jolt-multifn-methods mf)))
|
||||
mf))
|
||||
|
||||
(define (jolt-get-method-setup mf dval)
|
||||
(if (jolt-multifn? mf)
|
||||
(or (hashtable-ref (jolt-multifn-methods mf) dval #f)
|
||||
(hashtable-ref (jolt-multifn-methods mf) (jolt-multifn-default mf) #f)
|
||||
jolt-nil)
|
||||
jolt-nil))
|
||||
|
||||
(define (jolt-methods-setup mf)
|
||||
(if (jolt-multifn? mf)
|
||||
(let-values (((ks vs) (hashtable-entries (jolt-multifn-methods mf))))
|
||||
(let loop ((i 0) (m (jolt-hash-map)))
|
||||
(if (fx>=? i (vector-length ks)) m
|
||||
(loop (fx+ i 1) (jolt-assoc m (vector-ref ks i) (vector-ref vs i))))))
|
||||
jolt-nil))
|
||||
|
||||
(define (jolt-prefers-setup mm-sym)
|
||||
(let ((mf (mm-of-sym mm-sym)))
|
||||
(if (not mf) (jolt-hash-map)
|
||||
(let-values (((ks vs) (hashtable-entries (jolt-multifn-prefers mf))))
|
||||
(let loop ((i 0) (m (jolt-hash-map)))
|
||||
(if (fx>=? i (vector-length ks)) m
|
||||
;; each value is an inner set of preferred-over keys -> a jolt set
|
||||
(loop (fx+ i 1)
|
||||
(jolt-assoc m (vector-ref ks i)
|
||||
(apply jolt-hash-set
|
||||
(vector->list (hashtable-keys (vector-ref vs i))))))))))))
|
||||
|
||||
(def-var! "clojure.core" "defmulti-setup" jolt-defmulti-setup)
|
||||
(def-var! "clojure.core" "defmethod-setup" jolt-defmethod-setup)
|
||||
(def-var! "clojure.core" "prefer-method-setup" jolt-prefer-method-setup)
|
||||
(def-var! "clojure.core" "remove-method-setup" jolt-remove-method-setup)
|
||||
(def-var! "clojure.core" "remove-all-methods-setup" jolt-remove-all-methods-setup)
|
||||
(def-var! "clojure.core" "get-method-setup" jolt-get-method-setup)
|
||||
(def-var! "clojure.core" "methods-setup" jolt-methods-setup)
|
||||
(def-var! "clojure.core" "prefers-setup" jolt-prefers-setup)
|
||||
197
host/chez/natives-array.ss
Normal file
197
host/chez/natives-array.ss
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
;; natives-array.ss (jolt-cf1q.7) — Java-style mutable arrays for the Chez host.
|
||||
;;
|
||||
;; A jolt-array wraps a Chez mutable vector + a `kind` tag (for bytes?). The array
|
||||
;; CONSTRUCTORS are native (they build the backing); the overlay's aget/aset/alength
|
||||
;; are pure over count / nth / jolt.host/ref-put!, so we extend those dispatchers
|
||||
;; to see a jolt-array (backed by a Chez vector). Loaded after host-table.ss (ref-put!),
|
||||
;; transients.ss, seq.ss (the dispatchers it chains).
|
||||
|
||||
(define-record-type jolt-array (fields (mutable vec) kind) (nongenerative jolt-array-v1))
|
||||
|
||||
;; JVM array class name per element kind ((class (int-array 3)) -> "[I", like the
|
||||
;; JVM's Class.getName for arrays). Object arrays use the descriptor form.
|
||||
(define (na-array-class-name arr)
|
||||
(case (jolt-array-kind arr)
|
||||
((int) "[I") ((long) "[J") ((short) "[S") ((double) "[D")
|
||||
((float) "[F") ((boolean) "[Z") ((byte) "[B") ((char) "[C")
|
||||
(else "[Ljava.lang.Object;")))
|
||||
|
||||
(define (na-idx i) (if (and (number? i) (not (exact? i))) (exact (floor i)) i))
|
||||
(define (na-from-seq x kind) (make-jolt-array (list->vector (seq->list (jolt-seq x))) kind))
|
||||
;; (T-array size) | (T-array size init) | (T-array seq)
|
||||
(define (na-num-array a rest init kind)
|
||||
(if (number? a)
|
||||
(make-jolt-array (make-vector (exact (na-idx a)) (if (pair? rest) (car rest) init)) kind)
|
||||
(na-from-seq a kind)))
|
||||
|
||||
;; numeric tower (jolt-n6al): array element defaults / masked bytes / count are
|
||||
;; EXACT integers (= JVM byte/short/int), matching exact integer literals.
|
||||
(define (na-byte-of v) (bitwise-and (exact (floor v)) #xff))
|
||||
|
||||
;; --- constructors -----------------------------------------------------------
|
||||
(define (na-object-array a . rest) (na-num-array a rest jolt-nil 'object))
|
||||
;; integer kinds default to exact 0 (JVM int/long/short 0 -> "0", not "0.0").
|
||||
(define (na-int-array a . rest) (na-num-array a rest 0 'int))
|
||||
(define (na-long-array a . rest) (na-num-array a rest 0 'long))
|
||||
(define (na-short-array a . rest) (na-num-array a rest 0 'short))
|
||||
(define (na-double-array a . rest) (na-num-array a rest 0.0 'double))
|
||||
(define (na-float-array a . rest) (na-num-array a rest 0.0 'float))
|
||||
(define (na-boolean-array a . rest) (na-num-array a rest #f 'boolean))
|
||||
;; char-array is a real 'char array (instance? "[C"), seqing as chars via the
|
||||
;; dispatchers below — io/reader (extended here) and str/slurp consume the seq.
|
||||
(define (na-char-array a . rest)
|
||||
(cond
|
||||
((string? a) (make-jolt-array (list->vector (string->list a)) 'char))
|
||||
((number? a) (make-jolt-array (make-vector (exact (na-idx a)) #\nul) 'char))
|
||||
(else (make-jolt-array
|
||||
(list->vector (map (lambda (c) (if (char? c) c (integer->char (exact (truncate c)))))
|
||||
(seq->list (jolt-seq a)))) 'char))))
|
||||
(define (na-byte-array a . rest)
|
||||
(if (number? a)
|
||||
(make-jolt-array (make-vector (exact (na-idx a)) (na-byte-of (if (pair? rest) (car rest) 0))) 'byte)
|
||||
(make-jolt-array (list->vector (map na-byte-of (seq->list (jolt-seq a)))) 'byte)))
|
||||
(define (na-make-array a . rest) ; (make-array len) | (make-array type len ...)
|
||||
(make-jolt-array (make-vector (exact (na-idx (if (number? a) a (car rest)))) jolt-nil) 'object))
|
||||
(define (na-into-array a . rest) (na-from-seq (if (pair? rest) (car rest) a) 'object))
|
||||
(define (na-to-array coll) (na-from-seq coll 'object))
|
||||
(define (na-aclone arr)
|
||||
(if (jolt-array? arr)
|
||||
(make-jolt-array (vector-copy (jolt-array-vec arr)) (jolt-array-kind arr))
|
||||
(na-from-seq arr 'object)))
|
||||
|
||||
;; --- typed aset (return the stored value) -----------------------------------
|
||||
(define (na-aset! arr i v) (vector-set! (jolt-array-vec arr) (exact (na-idx i)) v) v)
|
||||
(define (na-aset-int arr i v) (na-aset! arr i v))
|
||||
(define (na-aset-long arr i v) (na-aset! arr i v))
|
||||
(define (na-aset-short arr i v) (na-aset! arr i v))
|
||||
(define (na-aset-double arr i v) (na-aset! arr i v))
|
||||
(define (na-aset-float arr i v) (na-aset! arr i v))
|
||||
(define (na-aset-char arr i v) (na-aset! arr i v))
|
||||
(define (na-aset-boolean arr i v) (na-aset! arr i v))
|
||||
(define (na-aset-byte arr i v)
|
||||
(vector-set! (jolt-array-vec arr) (exact (na-idx i)) (na-byte-of v)) v)
|
||||
|
||||
;; --- coercions (identity on arrays; byte/short are masked scalar casts) ------
|
||||
(define (na-bytes x) (if (and (jolt-array? x) (eq? (jolt-array-kind x) 'byte)) x (na-byte-array x)))
|
||||
(define (na-bytes? x) (and (jolt-array? x) (eq? (jolt-array-kind x) 'byte)))
|
||||
(define (na-identity x) x)
|
||||
(define (na-byte x)
|
||||
(let ((b (bitwise-and (exact (floor x)) #xff))) (if (>= b 128) (- b 256) b)))
|
||||
(define (na-short x)
|
||||
(let ((s (bitwise-and (exact (floor x)) #xffff))) (if (>= s #x8000) (- s #x10000) s)))
|
||||
|
||||
;; --- chunked seqs -----------------------------------------------------------
|
||||
;; A vector's seq is a REAL chunked-seq: (seq v) carries its backing vector +
|
||||
;; element index (seq.ss cseq-vec), so chunked-seq? is true and chunk-first hands
|
||||
;; out a 32-element block (a pvec slice) while chunk-rest is the seq at the next
|
||||
;; block boundary — the Clojure/CLJS ChunkedSeq contract (chunk-first ++
|
||||
;; chunk-rest == the seq). The eager buffer model (chunk-buffer/chunk-append/
|
||||
;; chunk) builds a plain cseq; chunk-cons/first/rest fall back to seq ops over it.
|
||||
(define na-chunk-size 32)
|
||||
(define-record-type jolt-chunkbuf (fields (mutable items)) (nongenerative jolt-chunkbuf-v1))
|
||||
(define (na-chunk-buffer cap) (make-jolt-chunkbuf '()))
|
||||
(define (na-chunk-append b x) (jolt-chunkbuf-items-set! b (append (jolt-chunkbuf-items b) (list x))) b)
|
||||
(define (na-chunk b) (list->cseq (jolt-chunkbuf-items b)))
|
||||
(define (na-chunk-cons chunk rest) (jolt-concat chunk rest))
|
||||
;; backing (vector . end-of-block index) for a vector-seq cell, or #f.
|
||||
(define (na-vblock s)
|
||||
(and (cseq? s) (cseq-cvec s)
|
||||
(let* ((v (cseq-cvec s)) (i (cseq-ci s)))
|
||||
(cons v (fxmin (fx+ i na-chunk-size) (pvec-count v))))))
|
||||
(define (na-chunked-seq? x) (and (na-vblock x) #t))
|
||||
(define (na-chunk-first s)
|
||||
(let ((vb (na-vblock s)))
|
||||
(if vb (make-pvec (vec-copy-range (pvec-v (car vb)) (cseq-ci s) (cdr vb)))
|
||||
(jolt-first s)))) ; eager-buffer fallback
|
||||
(define (na-chunk-rest s)
|
||||
(let ((vb (na-vblock s)))
|
||||
(if vb (if (fx>=? (cdr vb) (pvec-count (car vb))) jolt-empty-list (vec->seq (car vb) (cdr vb)))
|
||||
(jolt-rest s))))
|
||||
(define (na-chunk-next s)
|
||||
(let ((vb (na-vblock s)))
|
||||
(if vb (if (fx>=? (cdr vb) (pvec-count (car vb))) jolt-nil (vec->seq (car vb) (cdr vb)))
|
||||
(jolt-next s))))
|
||||
|
||||
;; --- extend the collection dispatchers to see a jolt-array ------------------
|
||||
(define %na-count jolt-count)
|
||||
(set! jolt-count (lambda (c) (if (jolt-array? c) (vector-length (jolt-array-vec c)) (%na-count c))))
|
||||
(define %na-seq jolt-seq)
|
||||
(set! jolt-seq (lambda (c) (if (jolt-array? c) (list->cseq (vector->list (jolt-array-vec c))) (%na-seq c))))
|
||||
(define %na-nth jolt-nth)
|
||||
(set! jolt-nth
|
||||
(case-lambda
|
||||
((c i) (if (jolt-array? c) (vector-ref (jolt-array-vec c) (exact (na-idx i))) (%na-nth c i)))
|
||||
((c i d) (if (jolt-array? c)
|
||||
(let ((v (jolt-array-vec c)) (j (exact (na-idx i))))
|
||||
(if (and (>= j 0) (< j (vector-length v))) (vector-ref v j) d))
|
||||
(%na-nth c i d)))))
|
||||
(define %na-get jolt-get)
|
||||
(set! jolt-get
|
||||
(case-lambda
|
||||
((c k) (if (jolt-array? c) (jolt-nth c k) (%na-get c k)))
|
||||
((c k d) (if (jolt-array? c) (jolt-nth c k d) (%na-get c k d)))))
|
||||
;; aset (overlay) writes through jolt.host/ref-put! — mutate the slot, return arr.
|
||||
;; count/nth/seq/get above are NATIVE-OPS (inlined at call sites), so aget/alength/
|
||||
;; array-seq/vec already use the set!-extended globals; ref-put! is a host var
|
||||
;; (var-deref'd), so re-assert its cell to the array-aware closure.
|
||||
(define %na-ref-put! jolt-ref-put!)
|
||||
(set! jolt-ref-put!
|
||||
(lambda (t k v)
|
||||
(if (jolt-array? t) (begin (vector-set! (jolt-array-vec t) (exact (na-idx k)) v) t)
|
||||
(%na-ref-put! t k v))))
|
||||
(def-var! "jolt.host" "ref-put!" jolt-ref-put!)
|
||||
|
||||
;; --- array identity: type / class / instance? recognize arrays ---------------
|
||||
;; (type arr) / (class arr) -> the JVM array class name; (class …) delegates to
|
||||
;; (jolt-type …) for arrays, so extending jolt-type covers both.
|
||||
(define %na-type jolt-type)
|
||||
(set! jolt-type (lambda (x) (if (jolt-array? x) (na-array-class-name x) (%na-type x))))
|
||||
(def-var! "clojure.core" "type" jolt-type)
|
||||
|
||||
;; instance? over an array class token ([I, [C, …). The token reaches us as a
|
||||
;; string (Class/forName "[C") or symbol; normalize, and pass a non-array string
|
||||
;; token on as a symbol so the inner wrappers' symbol-t-name doesn't choke.
|
||||
(define %na-instance-check instance-check)
|
||||
(set! instance-check
|
||||
(lambda (type-sym val)
|
||||
(let ((tname (cond ((string? type-sym) type-sym)
|
||||
((symbol-t? type-sym) (symbol-t-name type-sym))
|
||||
(else #f))))
|
||||
(cond
|
||||
((and tname (> (string-length tname) 0) (char=? (string-ref tname 0) #\[))
|
||||
(and (jolt-array? val) (string=? (na-array-class-name val) tname)))
|
||||
((string? type-sym) (%na-instance-check (jolt-symbol #f type-sym) val))
|
||||
(else (%na-instance-check type-sym val))))))
|
||||
(def-var! "clojure.core" "instance-check" instance-check)
|
||||
|
||||
;; clojure.java.io/reader over a char-array reads its chars (the JVM char[] branch).
|
||||
(def-var! "clojure.java.io" "reader"
|
||||
(lambda (x)
|
||||
(if (jolt-array? x)
|
||||
(host-new "StringReader"
|
||||
(apply string-append (map jolt-str-render-one (seq->list (jolt-seq x)))))
|
||||
(jolt-io-reader x))))
|
||||
|
||||
;; --- bind into clojure.core -------------------------------------------------
|
||||
(for-each (lambda (p) (def-var! "clojure.core" (car p) (cdr p)))
|
||||
(list
|
||||
(cons "object-array" na-object-array) (cons "int-array" na-int-array)
|
||||
(cons "long-array" na-long-array) (cons "short-array" na-short-array)
|
||||
(cons "double-array" na-double-array) (cons "float-array" na-float-array)
|
||||
(cons "boolean-array" na-boolean-array)
|
||||
(cons "byte-array" na-byte-array) (cons "char-array" na-char-array)
|
||||
(cons "array?" (lambda (x) (jolt-array? x)))
|
||||
(cons "make-array" na-make-array)
|
||||
(cons "into-array" na-into-array) (cons "to-array" na-to-array) (cons "aclone" na-aclone)
|
||||
(cons "aset-int" na-aset-int) (cons "aset-long" na-aset-long)
|
||||
(cons "aset-short" na-aset-short) (cons "aset-double" na-aset-double)
|
||||
(cons "aset-float" na-aset-float) (cons "aset-char" na-aset-char)
|
||||
(cons "aset-boolean" na-aset-boolean) (cons "aset-byte" na-aset-byte)
|
||||
(cons "bytes" na-bytes) (cons "bytes?" na-bytes?)
|
||||
(cons "booleans" na-identity) (cons "ints" na-identity) (cons "longs" na-identity)
|
||||
(cons "shorts" na-identity) (cons "doubles" na-identity) (cons "floats" na-identity)
|
||||
(cons "chars" na-identity) (cons "byte" na-byte) (cons "short" na-short)
|
||||
(cons "chunk-buffer" na-chunk-buffer) (cons "chunk-append" na-chunk-append)
|
||||
(cons "chunk" na-chunk) (cons "chunk-cons" na-chunk-cons)
|
||||
(cons "chunk-first" na-chunk-first) (cons "chunk-rest" na-chunk-rest)
|
||||
(cons "chunk-next" na-chunk-next) (cons "chunked-seq?" na-chunked-seq?)))
|
||||
30
host/chez/natives-coll.ss
Normal file
30
host/chez/natives-coll.ss
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
;; Collection constructors + rand (jolt-cf1q.3 Phase 2 inc A) — host-coupled
|
||||
;; natives the overlay assumes as bare clojure.core vars but which were never
|
||||
;; def-var!'d, so they resolved to jolt-nil and any call hit the apply-jolt-nil
|
||||
;; crash bucket. The persistent-collection constructors already exist in
|
||||
;; collections.ss (jolt-hash-map / jolt-hash-set / jolt-vector); this just binds
|
||||
;; the public clojure.core names to them. Loaded after def-var! (rt.ss) + the
|
||||
;; collections + seq tiers. hash-map/array-map/hash-set/set/rand semantics.
|
||||
|
||||
;; hash-map / hash-set: variadic kvs / elems straight onto the existing ctors.
|
||||
;; array-map: Clojure preserves insertion order, but jolt's `=` is structural and
|
||||
;; the parity corpus compares by value, so a pmap is observationally equal for
|
||||
;; the tested cases; keys-ordering is a separate (untested-here) concern.
|
||||
(define (jolt-array-map . kvs) (apply jolt-hash-map kvs))
|
||||
|
||||
;; set: realize any seqable to a list, then dedup through the set ctor. nil -> #{}.
|
||||
(define (jolt-set coll)
|
||||
(if (jolt-nil? coll) (jolt-hash-set) (apply jolt-hash-set (seq->list coll))))
|
||||
|
||||
;; rand: a flonum in [0, n) (n defaults to 1.0) — jolt is all-flonum, so the
|
||||
;; result is a double like every other number.
|
||||
(define (jolt-rand . n)
|
||||
(let ((r (random 1.0)))
|
||||
(if (null? n) r (* r (exact->inexact (car n))))))
|
||||
|
||||
(def-var! "clojure.core" "hash-map" jolt-hash-map)
|
||||
(def-var! "clojure.core" "hash-set" jolt-hash-set)
|
||||
(def-var! "clojure.core" "array-map" jolt-array-map)
|
||||
(def-var! "clojure.core" "set" jolt-set)
|
||||
(def-var! "clojure.core" "rand" jolt-rand)
|
||||
(def-var! "clojure.core" "map-entry?" jolt-map-entry?)
|
||||
112
host/chez/natives-meta.ss
Normal file
112
host/chez/natives-meta.ss
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
;; metadata (jolt-cf1q.3 Phase 2 inc E) — meta / with-meta. Chez values don't
|
||||
;; carry metadata, so collections use an identity-keyed side-table: with-meta
|
||||
;; returns a fresh COPY of the value (new identity) and records its meta there, so
|
||||
;; the original is unchanged (Clojure's immutable-with-meta) and a copy made by a
|
||||
;; later op (conj/assoc) drops the meta. Symbols carry meta in their own field.
|
||||
;; meta on a non-metadatable value (number/string/keyword) is nil.
|
||||
;;
|
||||
;; Loaded after records.ss (jrec) + collections/seq/values (the ctors it copies).
|
||||
|
||||
(define meta-table (make-eq-hashtable))
|
||||
|
||||
(define (jolt-meta x)
|
||||
(cond
|
||||
((symbol-t? x) (let ((m (symbol-t-meta x))) (if (jolt-nil? m) jolt-nil m)))
|
||||
;; a var's meta is {:ns :name} (derived from the cell) + any def-time user
|
||||
;; meta from rt.ss's var-meta-table (jolt-zikh).
|
||||
((var-cell? x)
|
||||
(let ((user (hashtable-ref var-meta-table x #f)))
|
||||
(jolt-assoc (if user user (jolt-hash-map))
|
||||
jolt-kw-var-ns (var-cell-ns x)
|
||||
jolt-kw-var-name (var-cell-name x))))
|
||||
((or (pvec? x) (pmap? x) (pset? x) (cseq? x) (empty-list-t? x) (jrec? x) (procedure? x))
|
||||
(hashtable-ref meta-table x jolt-nil))
|
||||
(else jolt-nil)))
|
||||
|
||||
;; fresh-identity copy of a metadatable value (so attaching meta doesn't mutate
|
||||
;; the original). cseq/procedure can't be copied meaningfully — keyed in place.
|
||||
(define (meta-copy x)
|
||||
(cond
|
||||
((pvec? x) (make-pvec (pvec-v x) (pvec-ent x)))
|
||||
((pmap? x) (make-pmap (pmap-root x) (pmap-cnt x)))
|
||||
((pset? x) (make-pset (pset-m x)))
|
||||
((jrec? x) (make-jrec (jrec-tag x) (jrec-pairs x)))
|
||||
(else x))) ; cseq / empty-list / procedure
|
||||
|
||||
(define (jolt-with-meta x m)
|
||||
(cond
|
||||
((symbol-t? x) (make-symbol-t (symbol-t-ns x) (symbol-t-name x) m))
|
||||
((or (pvec? x) (pmap? x) (pset? x) (cseq? x) (empty-list-t? x) (jrec? x) (procedure? x))
|
||||
(let ((c (meta-copy x)))
|
||||
(if (jolt-nil? m) (hashtable-delete! meta-table c) (hashtable-set! meta-table c m))
|
||||
c))
|
||||
(else (error #f "with-meta: value does not support metadata" x))))
|
||||
|
||||
(def-var! "clojure.core" "meta" jolt-meta)
|
||||
(def-var! "clojure.core" "with-meta" jolt-with-meta)
|
||||
|
||||
;; (type x) — Clojure's (or (:type (meta x)) (class x)). With no JVM classes the
|
||||
;; "class" is a host taxonomy: a record yields its ns-qualified class-name SYMBOL
|
||||
;; (user.TyR), everything else a keyword (:number/:vector/:seq/…).
|
||||
;; MUST be total — a non-record value
|
||||
;; falling through to a crash would read as a divergence, not the right keyword.
|
||||
;; Forward refs (jolt-lazyseq?, the sorted-htable / wrapper predicates) all bind by
|
||||
;; call time (every host .ss loads before any user expr runs).
|
||||
(define ty-kw-type (keyword #f "type")) ; the :type meta key
|
||||
(define ty-kw-jtype (keyword "jolt" "type")) ; tagged-map discriminator (ex-info)
|
||||
(define ty-number (keyword #f "number"))
|
||||
(define ty-string (keyword #f "string"))
|
||||
(define ty-keyword (keyword #f "keyword"))
|
||||
(define ty-symbol (keyword #f "symbol"))
|
||||
(define ty-boolean (keyword #f "boolean"))
|
||||
(define ty-char (keyword #f "char"))
|
||||
(define ty-vector (keyword #f "vector"))
|
||||
(define ty-map (keyword #f "map"))
|
||||
(define ty-set (keyword #f "set"))
|
||||
(define ty-seq (keyword #f "seq"))
|
||||
(define ty-fn (keyword #f "fn"))
|
||||
(define ty-atom (keyword "jolt" "atom"))
|
||||
(define ty-volatile (keyword "jolt" "volatile"))
|
||||
(define ty-regex (keyword "jolt" "regex"))
|
||||
(define ty-var (keyword "jolt" "var"))
|
||||
(define ty-transient (keyword "jolt" "transient"))
|
||||
(define ty-uuid (keyword "jolt" "uuid"))
|
||||
(define ty-sorted-set (keyword "jolt" "sorted-set"))
|
||||
(define ty-object (keyword #f "object"))
|
||||
|
||||
(define (jolt-type x)
|
||||
(let* ((m (jolt-meta x))
|
||||
(override (if (jolt-nil? m) jolt-nil (jolt-get m ty-kw-type jolt-nil))))
|
||||
(cond
|
||||
((not (jolt-nil? override)) override) ; :type meta wins
|
||||
;; record -> its ns-qualified class-name STRING (= (class x)). jolt models
|
||||
;; classes as strings, so (symbol (str (type r))) is NOT (type r) — as on the
|
||||
;; JVM where type is a Class, not a Symbol.
|
||||
((jrec? x) (jrec-tag x))
|
||||
((jolt-nil? x) jolt-nil)
|
||||
((boolean? x) ty-boolean)
|
||||
((number? x) ty-number)
|
||||
((string? x) ty-string)
|
||||
((keyword? x) ty-keyword)
|
||||
((symbol-t? x) ty-symbol)
|
||||
((char? x) ty-char)
|
||||
;; host wrappers — keyed by their :jolt/* tags (checked before the
|
||||
;; collection arms; none of these are pvec/pmap/pset).
|
||||
((jolt-atom? x) ty-atom)
|
||||
((jvol? x) ty-volatile)
|
||||
((jolt-regex? x) ty-regex)
|
||||
((var-cell? x) ty-var)
|
||||
((jolt-transient? x) ty-transient)
|
||||
((juuid? x) ty-uuid)
|
||||
((htable-sorted-set? x) ty-sorted-set)
|
||||
((htable-sorted-map? x) ty-map)
|
||||
;; collections — pvec INCLUDES map entries (:vector).
|
||||
((pvec? x) ty-vector)
|
||||
((pmap? x) ; a :jolt/type-tagged map (ex-info) -> its tag
|
||||
(let ((t (jolt-get x ty-kw-jtype jolt-nil))) (if (jolt-nil? t) ty-map t)))
|
||||
((pset? x) ty-set)
|
||||
((or (cseq? x) (empty-list-t? x) (jolt-lazyseq? x)) ty-seq)
|
||||
((procedure? x) ty-fn)
|
||||
(else ty-object))))
|
||||
|
||||
(def-var! "clojure.core" "type" jolt-type)
|
||||
160
host/chez/natives-misc.ss
Normal file
160
host/chez/natives-misc.ss
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
;; misc scalar natives (jolt-cf1q.3) — UUID, format/printf, tagged-literal,
|
||||
;; bigint. Seed natives that were jolt-nil on the prelude.
|
||||
;;
|
||||
;; Loaded after the printers (pr-str of a uuid is #uuid "…") and converters
|
||||
;; (jolt-str-render-one for %s / str of a uuid).
|
||||
|
||||
;; --- UUID --------------------------------------------------------------------
|
||||
;; A uuid is a record wrapping its canonical 36-char lowercase string. str -> the
|
||||
;; bare string; pr-str -> #uuid "…"; not map?/coll?.
|
||||
(define-record-type juuid (fields s) (nongenerative chez-juuid-v1))
|
||||
(define (jolt-uuid-pred? x) (juuid? x))
|
||||
|
||||
(define hexd "0123456789abcdef")
|
||||
(define (rand-hex) (string-ref hexd (random 16)))
|
||||
;; v4: 8-4-4-4-12, version nibble (index 14) = 4, variant nibble (index 19) in 8-b.
|
||||
(define (random-uuid-str)
|
||||
(let ((cs (make-string 36)))
|
||||
(let loop ((i 0))
|
||||
(if (fx=? i 36) cs
|
||||
(begin
|
||||
(string-set! cs i
|
||||
(cond ((or (fx=? i 8) (fx=? i 13) (fx=? i 18) (fx=? i 23)) #\-)
|
||||
((fx=? i 14) #\4)
|
||||
((fx=? i 19) (string-ref "89ab" (random 4)))
|
||||
(else (rand-hex))))
|
||||
(loop (fx+ i 1)))))))
|
||||
(define (jolt-random-uuid) (make-juuid (random-uuid-str)))
|
||||
|
||||
;; #uuid literal -> a uuid value (the emitter lowers the :uuid node to this). The
|
||||
;; reader already validated the shape; lowercase for value equality.
|
||||
(define (jolt-uuid-from-string s) (make-juuid (string-downcase s)))
|
||||
|
||||
;; parse-uuid: validate the canonical shape (8-4-4-4-12 hex), lowercase, -> uuid;
|
||||
;; nil if the string doesn't conform (Clojure parse-uuid), error on a non-string.
|
||||
(define (hex-char? c) (or (and (char>=? c #\0) (char<=? c #\9))
|
||||
(and (char>=? c #\a) (char<=? c #\f))
|
||||
(and (char>=? c #\A) (char<=? c #\F))))
|
||||
(define (uuid-shape? s)
|
||||
(and (string? s) (fx=? (string-length s) 36)
|
||||
(let loop ((i 0))
|
||||
(if (fx=? i 36) #t
|
||||
(let ((c (string-ref s i)))
|
||||
(cond ((or (fx=? i 8) (fx=? i 13) (fx=? i 18) (fx=? i 23)) (and (char=? c #\-) (loop (fx+ i 1))))
|
||||
((hex-char? c) (loop (fx+ i 1)))
|
||||
(else #f)))))))
|
||||
(define (jolt-parse-uuid s)
|
||||
(cond ((not (string? s)) (error #f "parse-uuid: not a string" s))
|
||||
((uuid-shape? s) (make-juuid (string-downcase s)))
|
||||
(else jolt-nil)))
|
||||
|
||||
;; uuid? / random-uuid / parse-uuid are OVERLAY fns (they read :jolt/type), so
|
||||
;; the prelude would clobber a def-var! here — they're asserted in post-prelude.ss.
|
||||
|
||||
;; str of a uuid -> the bare 36-char string; pr-str -> #uuid "…".
|
||||
(define %m-str-render-one jolt-str-render-one)
|
||||
(set! jolt-str-render-one (lambda (x) (if (juuid? x) (juuid-s x) (%m-str-render-one x))))
|
||||
(define (juuid-pr u) (string-append "#uuid \"" (juuid-s u) "\""))
|
||||
(define %m-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (juuid? x) (juuid-pr x) (%m-pr-str x))))
|
||||
(define %m-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (juuid? x) (juuid-pr x) (%m-pr-readable x))))
|
||||
;; two uuids are = iff same string.
|
||||
(define %m-=2 jolt=2)
|
||||
(set! jolt=2 (lambda (a b)
|
||||
(cond ((juuid? a) (and (juuid? b) (string=? (juuid-s a) (juuid-s b))))
|
||||
((juuid? b) #f)
|
||||
(else (%m-=2 a b)))))
|
||||
|
||||
;; --- bigint / biginteger -----------------------------------------------------
|
||||
;; jolt models every number as a double; an integer-valued double prints without
|
||||
;; a ".0" (jolt-num->string), so bigint is just the number for the corpus range.
|
||||
;; (Arbitrary-precision beyond 2^53 is a separate concern.)
|
||||
(define (jolt-bigint x) x)
|
||||
(def-var! "clojure.core" "bigint" jolt-bigint)
|
||||
(def-var! "clojure.core" "biginteger" jolt-bigint)
|
||||
|
||||
;; --- tagged-literal ----------------------------------------------------------
|
||||
;; (tagged-literal tag form): a tagged value with :tag / :form. tagged-literal? is
|
||||
;; overlay (reads :jolt/type) so it's overridden in post-prelude.ss.
|
||||
(define-record-type jtagged (fields tag form) (nongenerative chez-jtagged-v1))
|
||||
(define (jolt-tagged-literal tag form) (make-jtagged tag form))
|
||||
(define (jolt-tagged-literal-pred? x) (jtagged? x))
|
||||
(define kw-tl-tag (keyword #f "tag"))
|
||||
(define kw-tl-form (keyword #f "form"))
|
||||
(define %m-get jolt-get)
|
||||
(set! jolt-get (case-lambda
|
||||
((coll k) (if (jtagged? coll) (jolt-get coll k jolt-nil) (%m-get coll k)))
|
||||
((coll k d) (if (jtagged? coll)
|
||||
(cond ((jolt=2 k kw-tl-tag) (jtagged-tag coll))
|
||||
((jolt=2 k kw-tl-form) (jtagged-form coll))
|
||||
(else d))
|
||||
(%m-get coll k d)))))
|
||||
(define (jtagged-pr t) (string-append "#" (jolt-pr-str (jtagged-tag t)) " " (jolt-pr-readable (jtagged-form t))))
|
||||
(define %m2-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (jtagged? x) (jtagged-pr x) (%m2-pr-str x))))
|
||||
(define %m2-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (jtagged? x) (jtagged-pr x) (%m2-pr-readable x))))
|
||||
(def-var! "clojure.core" "tagged-literal" jolt-tagged-literal)
|
||||
;; tagged-literal? is OVERLAY (reads :jolt/type) — asserted in post-prelude.ss.
|
||||
|
||||
;; --- format / printf ---------------------------------------------------------
|
||||
;; A small %-format engine over the all-flonum number model: %d (integer), %s
|
||||
;; (str), %f / %.Nf (fixed-point), %x/%X (hex int), %o (octal), %c (char int),
|
||||
;; %b (boolean), %% (literal). Enough for the corpus; not the full Java spec.
|
||||
(define (->long x) (exact (truncate x)))
|
||||
(define (pad-left s n c) (if (fx>=? (string-length s) n) s (string-append (make-string (fx- n (string-length s)) c) s)))
|
||||
(define (fmt-float x prec)
|
||||
(let* ((neg (< x 0)) (ax (abs x))
|
||||
(scale (expt 10 prec))
|
||||
(scaled (round (* (inexact ax) scale)))
|
||||
(i (exact (truncate (/ scaled scale))))
|
||||
(frac (exact (truncate (- scaled (* i scale))))))
|
||||
(string-append (if neg "-" "")
|
||||
(number->string i)
|
||||
(if (fx>? prec 0) (string-append "." (pad-left (number->string frac) prec #\0)) ""))))
|
||||
(define (jolt-format fmt . args)
|
||||
(let ((out (open-output-string)))
|
||||
(let loop ((i 0) (as args))
|
||||
(if (fx>=? i (string-length fmt))
|
||||
(get-output-string out)
|
||||
(let ((c (string-ref fmt i)))
|
||||
(if (char=? c #\%)
|
||||
;; parse a directive: %[-][0][width][.prec]conv
|
||||
(let scan ((j (fx+ i 1)) (left #f) (zero #f) (width #f) (prec #f) (seen-dot #f))
|
||||
(let ((d (string-ref fmt j)))
|
||||
(cond
|
||||
((char=? d #\%) (write-char #\% out) (loop (fx+ j 1) as))
|
||||
((and (not seen-dot) (not width) (char=? d #\-))
|
||||
(scan (fx+ j 1) #t zero width prec seen-dot))
|
||||
((and (not seen-dot) (not width) (char=? d #\0))
|
||||
(scan (fx+ j 1) left #t width prec seen-dot))
|
||||
((char=? d #\.) (scan (fx+ j 1) left zero width 0 #t))
|
||||
((and (char>=? d #\0) (char<=? d #\9))
|
||||
(if seen-dot
|
||||
(scan (fx+ j 1) left zero width (fx+ (fx* (or prec 0) 10) (fx- (char->integer d) 48)) seen-dot)
|
||||
(scan (fx+ j 1) left zero (fx+ (fx* (or width 0) 10) (fx- (char->integer d) 48)) prec seen-dot)))
|
||||
(else
|
||||
(let* ((a (if (null? as) jolt-nil (car as)))
|
||||
(rest (if (null? as) '() (cdr as)))
|
||||
(s (case d
|
||||
((#\d) (number->string (->long a)))
|
||||
((#\s) (jolt-str-render-one a))
|
||||
((#\f) (fmt-float a (or prec 6)))
|
||||
((#\x) (number->string (->long a) 16))
|
||||
((#\X) (string-upcase (number->string (->long a) 16)))
|
||||
((#\o) (number->string (->long a) 8))
|
||||
((#\b) (if (jolt-truthy? a) "true" "false"))
|
||||
((#\c) (string (integer->char (->long a))))
|
||||
(else (string #\% d))))
|
||||
;; pad to width: left-justify with spaces, else right-justify
|
||||
;; (zero-pad only a right-justified number).
|
||||
(s (if (and width (fx<? (string-length s) width))
|
||||
(let ((p (fx- width (string-length s))))
|
||||
(if left (string-append s (make-string p #\space))
|
||||
(string-append (make-string p (if (and zero (memv d '(#\d #\f #\x #\X #\o))) #\0 #\space)) s)))
|
||||
s)))
|
||||
(display s out)
|
||||
(loop (fx+ j 1) rest))))))
|
||||
(begin (write-char c out) (loop (fx+ i 1) as))))))))
|
||||
(def-var! "clojure.core" "format" jolt-format)
|
||||
88
host/chez/natives-num.ss
Normal file
88
host/chez/natives-num.ss
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
;; bit ops + string->number parsers (jolt-cf1q.3 Phase 2 inc C) — host-coupled
|
||||
;; natives (bit family, parse-long/double) that
|
||||
;; resolved to jolt-nil. jolt models every number as a double, so bit ops coerce
|
||||
;; to an exact integer, operate, and return a flonum. parse-* use
|
||||
;; strict shapes (Clojure 1.11: nil on malformed, throw on a non-string).
|
||||
|
||||
;; bit ops return EXACT integers (= JVM long). ->int coerces the operand.
|
||||
(define (->int x) (exact (truncate x)))
|
||||
(define (jolt-bit-and a b) (bitwise-and (->int a) (->int b)))
|
||||
(define (jolt-bit-or a b) (bitwise-ior (->int a) (->int b)))
|
||||
(define (jolt-bit-xor a b) (bitwise-xor (->int a) (->int b)))
|
||||
(define (jolt-bit-and-not a b) (bitwise-and (->int a) (bitwise-not (->int b))))
|
||||
(define (jolt-bit-not a) (bitwise-not (->int a)))
|
||||
(define (jolt-bit-shift-left x n) (bitwise-arithmetic-shift-left (->int x) (->int n)))
|
||||
(define (jolt-bit-shift-right x n) (bitwise-arithmetic-shift-right (->int x) (->int n)))
|
||||
(define (bit-mask n) (bitwise-arithmetic-shift-left 1 (->int n)))
|
||||
(define (jolt-bit-set x n) (bitwise-ior (->int x) (bit-mask n)))
|
||||
(define (jolt-bit-clear x n) (bitwise-and (->int x) (bitwise-not (bit-mask n))))
|
||||
(define (jolt-bit-flip x n) (bitwise-xor (->int x) (bit-mask n)))
|
||||
(define (jolt-bit-test x n) (not (zero? (bitwise-and (->int x) (bit-mask n)))))
|
||||
;; unsigned-bit-shift-right: logical shift over 64-bit longs. For the common
|
||||
;; non-negative operand it equals the arithmetic shift; the negative-operand
|
||||
;; 64-bit-window case is not modeled.
|
||||
(define (jolt-unsigned-bit-shift-right x n)
|
||||
(bitwise-arithmetic-shift-right (->int x) (->int n)))
|
||||
|
||||
;; ---- string->scalar parsers -------------------------------------------------
|
||||
(define (ascii-digit? c) (and (char>=? c #\0) (char<=? c #\9)))
|
||||
(define (skip-digits s i n) (let loop ((i i)) (if (and (< i n) (ascii-digit? (string-ref s i))) (loop (+ i 1)) i)))
|
||||
(define (sign-at? s i n) (and (< i n) (let ((c (string-ref s i))) (or (char=? c #\+) (char=? c #\-)))))
|
||||
|
||||
(define (parse-long-shape? s)
|
||||
(let* ((n (string-length s)) (i0 (if (sign-at? s 0 n) 1 0)))
|
||||
(and (> n i0) (= (skip-digits s i0 n) n))))
|
||||
|
||||
(define (jolt-parse-long s)
|
||||
(if (not (string? s)) (error #f "parse-long requires a string" s)
|
||||
(if (parse-long-shape? s) (string->number s) jolt-nil))) ; exact long
|
||||
|
||||
;; strict float shape: [+-]? ( D+ (. D*)? | . D+ ) ([eE][+-]? D+)? fully anchored.
|
||||
(define (parse-double-shape? s)
|
||||
(let ((n (string-length s)))
|
||||
(and (> n 0)
|
||||
(call/cc
|
||||
(lambda (no)
|
||||
(let* ((i0 (if (sign-at? s 0 n) 1 0))
|
||||
(after-int (skip-digits s i0 n))
|
||||
(had-int (> after-int i0))
|
||||
;; mantissa end
|
||||
(jm (cond
|
||||
((and had-int (< after-int n) (char=? (string-ref s after-int) #\.))
|
||||
(skip-digits s (+ after-int 1) n)) ; D+ . D*
|
||||
((and (not had-int) (< i0 n) (char=? (string-ref s i0) #\.))
|
||||
(let ((k (skip-digits s (+ i0 1) n))) ; . D+
|
||||
(if (> k (+ i0 1)) k (no #f))))
|
||||
(had-int after-int)
|
||||
(else (no #f))))
|
||||
;; optional exponent
|
||||
(je (if (and (< jm n) (let ((c (string-ref s jm))) (or (char=? c #\e) (char=? c #\E))))
|
||||
(let* ((es (if (sign-at? s (+ jm 1) n) (+ jm 2) (+ jm 1)))
|
||||
(ee (skip-digits s es n)))
|
||||
(if (> ee es) ee (no #f)))
|
||||
jm)))
|
||||
(= je n)))))))
|
||||
|
||||
(define (jolt-parse-double s)
|
||||
(if (not (string? s)) (error #f "parse-double requires a string" s)
|
||||
(cond
|
||||
((string=? s "Infinity") +inf.0)
|
||||
((string=? s "-Infinity") -inf.0)
|
||||
((string=? s "NaN") +nan.0)
|
||||
((parse-double-shape? s) (exact->inexact (string->number s)))
|
||||
(else jolt-nil))))
|
||||
|
||||
(def-var! "clojure.core" "__bit-and" jolt-bit-and)
|
||||
(def-var! "clojure.core" "__bit-or" jolt-bit-or)
|
||||
(def-var! "clojure.core" "__bit-xor" jolt-bit-xor)
|
||||
(def-var! "clojure.core" "__bit-and-not" jolt-bit-and-not)
|
||||
(def-var! "clojure.core" "bit-not" jolt-bit-not)
|
||||
(def-var! "clojure.core" "bit-shift-left" jolt-bit-shift-left)
|
||||
(def-var! "clojure.core" "bit-shift-right" jolt-bit-shift-right)
|
||||
(def-var! "clojure.core" "bit-set" jolt-bit-set)
|
||||
(def-var! "clojure.core" "bit-clear" jolt-bit-clear)
|
||||
(def-var! "clojure.core" "bit-flip" jolt-bit-flip)
|
||||
(def-var! "clojure.core" "bit-test" jolt-bit-test)
|
||||
(def-var! "clojure.core" "unsigned-bit-shift-right" jolt-unsigned-bit-shift-right)
|
||||
(def-var! "clojure.core" "parse-long" jolt-parse-long)
|
||||
(def-var! "clojure.core" "parse-double" jolt-parse-double)
|
||||
91
host/chez/natives-parity.ss
Normal file
91
host/chez/natives-parity.ss
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
;; natives-parity.ss (jolt-cf1q.7) — native Chez shims for clojure.core fns that
|
||||
;; had no Chez shim, so they resolved to nil ("not a fn"). Pure-Chez, JVM-matching.
|
||||
;;
|
||||
;; Loaded after host-table.ss (htable-sorted?), transients.ss (jolt-transient?),
|
||||
;; values.ss (jolt-hash), seq.ss (jolt-seq/seq->list/list->cseq/jolt-invoke).
|
||||
|
||||
;; --- hash family (24-bit masked so int? holds) ------
|
||||
(define (np-h24 x) (bitwise-and (jolt-hash x) #xffffff))
|
||||
(define (np-hash x) (np-h24 x))
|
||||
(define (np-hash-combine a b)
|
||||
(bitwise-and (bitwise-xor (np-h24 a) (+ (np-h24 b) #x9e3779)) #xffffff))
|
||||
(define (np-hash-ordered-coll coll)
|
||||
(let loop ((xs (seq->list (jolt-seq coll))) (h 1))
|
||||
(if (null? xs) h (loop (cdr xs) (bitwise-and (+ (* 31 h) (np-h24 (car xs))) #xffffff)))))
|
||||
(define (np-hash-unordered-coll coll)
|
||||
(let loop ((xs (seq->list (jolt-seq coll))) (h 0))
|
||||
(if (null? xs) h (loop (cdr xs) (bitwise-and (+ h (np-h24 (car xs))) #xffffff)))))
|
||||
|
||||
;; --- transient? ---------------------------------------------------------------
|
||||
(define (np-transient? x) (jolt-transient? x))
|
||||
|
||||
;; --- rseq: vectors + sorted colls only (Clojure), reverse of the ascending seq.
|
||||
(define (np-rseq coll)
|
||||
(if (or (pvec? coll) (htable-sorted? coll))
|
||||
(list->cseq (reverse (seq->list (jolt-seq coll))))
|
||||
(jolt-throw (jolt-ex-info "rseq requires a vector or sorted collection" (jolt-hash-map)))))
|
||||
|
||||
;; --- cat transducer: each item of the input
|
||||
;; is itself a collection, concatenated into the downstream reducing fn.
|
||||
(define (np-cat rf)
|
||||
(lambda a
|
||||
(cond
|
||||
((null? a) (jolt-invoke rf))
|
||||
((null? (cdr a)) (jolt-invoke rf (car a)))
|
||||
(else
|
||||
(let loop ((xs (seq->list (jolt-seq (cadr a)))) (acc (car a)))
|
||||
(if (null? xs) acc (loop (cdr xs) (jolt-invoke rf acc (car xs)))))))))
|
||||
|
||||
;; --- reader feature set (for #?() conditionals) — mutable list of name strings,
|
||||
;; default jolt + default. __reader-features returns the strings; -set! replaces.
|
||||
(define np-reader-features (list "jolt" "default"))
|
||||
(define (np-reader-features-get) (list->cseq np-reader-features))
|
||||
(define (np-reader-features-set! names)
|
||||
(set! np-reader-features
|
||||
(map (lambda (n) (cond ((keyword-t? n) (keyword-t-name n)) ((string? n) n) (else (jolt-pr-str n))))
|
||||
(seq->list (jolt-seq names))))
|
||||
jolt-nil)
|
||||
|
||||
;; --- reader-conditional / re-matcher: tagged maps (reader-conditional? + the
|
||||
;; matcher consumers are overlay tagged-value predicates that read :jolt/type).
|
||||
(define np-kw-type (keyword "jolt" "type"))
|
||||
(define np-kw-rc (keyword "jolt" "reader-conditional"))
|
||||
(define np-kw-form (keyword #f "form"))
|
||||
(define np-kw-spl (keyword #f "splicing?"))
|
||||
(define np-kw-mat (keyword "jolt" "matcher"))
|
||||
(define np-kw-re (keyword #f "re"))
|
||||
(define np-kw-s (keyword #f "s"))
|
||||
(define np-kw-pos (keyword #f "pos"))
|
||||
(define (np-reader-conditional form splicing?)
|
||||
(jolt-hash-map np-kw-type np-kw-rc np-kw-form form np-kw-spl splicing?))
|
||||
(define (np-re-matcher re s)
|
||||
(jolt-hash-map np-kw-type np-kw-mat np-kw-re re np-kw-s s np-kw-pos 0.0))
|
||||
|
||||
;; (delay? / make-delay / force live in concurrency.ss with the real delay type.)
|
||||
|
||||
;; --- macroexpand-1 / macroexpand: expand a (quoted) call form via the runtime
|
||||
;; macro table (host-contract hc-macro?/hc-expand-1; forward-referenced, resolved
|
||||
;; at call time after the spine loads). macroexpand loops until the head is no
|
||||
;; longer a macro (subforms are not expanded, matching Clojure).
|
||||
(define (np-macroexpand-1 form)
|
||||
(if (and (cseq? form) (cseq-list? form) (symbol-t? (seq-first form)))
|
||||
(let ((ctx (make-analyze-ctx (chez-current-ns))))
|
||||
(if (hc-macro? ctx (seq-first form)) (hc-expand-1 ctx form) form))
|
||||
form))
|
||||
(define (np-macroexpand form)
|
||||
(let loop ((cur form))
|
||||
(let ((nxt (np-macroexpand-1 cur))) (if (eq? cur nxt) cur (loop nxt)))))
|
||||
|
||||
(def-var! "clojure.core" "hash" np-hash)
|
||||
(def-var! "clojure.core" "hash-combine" np-hash-combine)
|
||||
(def-var! "clojure.core" "hash-ordered-coll" np-hash-ordered-coll)
|
||||
(def-var! "clojure.core" "hash-unordered-coll" np-hash-unordered-coll)
|
||||
(def-var! "clojure.core" "transient?" np-transient?)
|
||||
(def-var! "clojure.core" "rseq" np-rseq)
|
||||
(def-var! "clojure.core" "cat" np-cat)
|
||||
(def-var! "clojure.core" "__reader-features" np-reader-features-get)
|
||||
(def-var! "clojure.core" "__reader-features-set!" np-reader-features-set!)
|
||||
(def-var! "clojure.core" "reader-conditional" np-reader-conditional)
|
||||
(def-var! "clojure.core" "re-matcher" np-re-matcher)
|
||||
(def-var! "clojure.core" "macroexpand-1" np-macroexpand-1)
|
||||
(def-var! "clojure.core" "macroexpand" np-macroexpand)
|
||||
218
host/chez/natives-seq.ss
Normal file
218
host/chez/natives-seq.ss
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
;; seq-native shims (jolt-y6mv) — native seq fns the overlay assumes are
|
||||
;; clojure.core natives but which have no def-var! in the assembled prelude and
|
||||
;; resolve to jolt-nil on
|
||||
;; Chez. This was the dominant prelude-parity crash bucket ('apply jolt-nil').
|
||||
;; Each is a pure fn over the existing seq layer (seq.ss) — collection arities
|
||||
;; only; the 1-arg transducer arities are jolt-kxsr. Loaded last (after
|
||||
;; converters.ss for jolt-compare and seq.ss for the reduced record).
|
||||
|
||||
;; reduced / reduced? — the box itself is the jolt-reduced record from seq.ss
|
||||
;; (so the reduce machinery there can see it); these just expose the constructor
|
||||
;; and predicate. (deref a-reduced) is handled in atoms.ss.
|
||||
(define (jolt-reduced-new x) (make-jolt-reduced x))
|
||||
(define (jolt-reduced-pred x) (jolt-reduced? x))
|
||||
(define (ensure-reduced x) (if (jolt-reduced? x) x (make-jolt-reduced x)))
|
||||
|
||||
;; ============================================================================
|
||||
;; transducers (jolt-kxsr) — the 1-arg arity of map/filter/take/... returns a
|
||||
;; transducer (fn [rf] rf') where rf' is a reducing fn with arities
|
||||
;; []=init, [acc]=complete, [acc x]=step. rf and the mapping/predicate fns are jolt values, so every
|
||||
;; call routes through jolt-invoke. A `reduced` step stops the fold — reduce-seq
|
||||
;; (seq.ss) already short-circuits on a jolt-reduced.
|
||||
;; ============================================================================
|
||||
(define (td-map f)
|
||||
(lambda (rf)
|
||||
(lambda a
|
||||
(case (length a)
|
||||
((0) (jolt-invoke rf))
|
||||
((1) (jolt-invoke rf (car a)))
|
||||
(else (jolt-invoke rf (car a) (jolt-invoke f (cadr a))))))))
|
||||
(define (td-filter pred)
|
||||
(lambda (rf)
|
||||
(lambda a
|
||||
(case (length a)
|
||||
((0) (jolt-invoke rf))
|
||||
((1) (jolt-invoke rf (car a)))
|
||||
(else (if (jolt-truthy? (jolt-invoke pred (cadr a)))
|
||||
(jolt-invoke rf (car a) (cadr a))
|
||||
(car a)))))))
|
||||
(define (td-remove pred) (td-filter (lambda (x) (jolt-not (jolt-invoke pred x)))))
|
||||
(define (td-take n)
|
||||
(lambda (rf)
|
||||
(let ((left n))
|
||||
(lambda a
|
||||
(case (length a)
|
||||
((0) (jolt-invoke rf))
|
||||
((1) (jolt-invoke rf (car a)))
|
||||
(else (if (<= left 0)
|
||||
(make-jolt-reduced (car a))
|
||||
(let ((r (jolt-invoke rf (car a) (cadr a))))
|
||||
(set! left (- left 1))
|
||||
(if (<= left 0) (ensure-reduced r) r)))))))))
|
||||
(define (td-drop n)
|
||||
(lambda (rf)
|
||||
(let ((left n))
|
||||
(lambda a
|
||||
(case (length a)
|
||||
((0) (jolt-invoke rf))
|
||||
((1) (jolt-invoke rf (car a)))
|
||||
(else (if (> left 0) (begin (set! left (- left 1)) (car a))
|
||||
(jolt-invoke rf (car a) (cadr a)))))))))
|
||||
(define (td-take-while pred)
|
||||
(lambda (rf)
|
||||
(lambda a
|
||||
(case (length a)
|
||||
((0) (jolt-invoke rf))
|
||||
((1) (jolt-invoke rf (car a)))
|
||||
(else (if (jolt-truthy? (jolt-invoke pred (cadr a)))
|
||||
(jolt-invoke rf (car a) (cadr a))
|
||||
(make-jolt-reduced (car a))))))))
|
||||
(define (td-drop-while pred)
|
||||
(lambda (rf)
|
||||
(let ((dropping #t))
|
||||
(lambda a
|
||||
(case (length a)
|
||||
((0) (jolt-invoke rf))
|
||||
((1) (jolt-invoke rf (car a)))
|
||||
(else (begin
|
||||
(when (and dropping (not (jolt-truthy? (jolt-invoke pred (cadr a)))))
|
||||
(set! dropping #f))
|
||||
(if dropping (car a) (jolt-invoke rf (car a) (cadr a))))))))))
|
||||
;; (mapcat f) transducer: map f, then splice (cat) f's result into rf, honoring a
|
||||
;; mid-splice `reduced`.
|
||||
(define (td-mapcat f)
|
||||
(lambda (rf)
|
||||
(lambda a
|
||||
(case (length a)
|
||||
((0) (jolt-invoke rf))
|
||||
((1) (jolt-invoke rf (car a)))
|
||||
(else (let loop ((acc (car a))
|
||||
(xs (seq->list (jolt-seq (jolt-invoke f (cadr a))))))
|
||||
(if (or (null? xs) (jolt-reduced? acc)) acc
|
||||
(loop (jolt-invoke rf acc (car xs)) (cdr xs)))))))))
|
||||
|
||||
;; (into to xform from): transduce `from` through `xform` with conj as the rf.
|
||||
(define (into-xform to xform from)
|
||||
(let* ((conj-rf (lambda a (if (fx=? (length a) 1) (car a) ; completion = identity
|
||||
(jolt-conj1 (car a) (cadr a)))))
|
||||
(xrf (jolt-invoke xform conj-rf))
|
||||
(res (reduce-seq xrf to (jolt-seq from))))
|
||||
(jolt-invoke xrf res)))
|
||||
|
||||
;; mapcat: (mapcat f) -> transducer; (mapcat f coll & colls) -> map f across the
|
||||
;; colls (stops at shortest), then concat the results.
|
||||
(define (jolt-mapcat f . colls)
|
||||
(if (null? colls)
|
||||
(td-mapcat f)
|
||||
(apply jolt-concat (seq->list (apply jolt-map f colls)))))
|
||||
|
||||
;; take-while / drop-while: 1-arg -> transducer; 2-arg -> a seq over the coll.
|
||||
(define (take-while-seq pred s)
|
||||
(if (jolt-nil? s) jolt-empty-list
|
||||
(let ((x (seq-first s)))
|
||||
(if (jolt-truthy? (jolt-invoke pred x))
|
||||
(cseq-lazy x (lambda () (take-while-seq pred (jolt-seq (seq-more s)))))
|
||||
jolt-empty-list))))
|
||||
(define jolt-take-while
|
||||
(case-lambda
|
||||
((pred) (td-take-while pred))
|
||||
((pred coll) (take-while-seq pred (jolt-seq coll)))))
|
||||
(define (drop-while-seq pred coll)
|
||||
(let loop ((s (jolt-seq coll)))
|
||||
(if (and (not (jolt-nil? s)) (jolt-truthy? (jolt-invoke pred (seq-first s))))
|
||||
(loop (jolt-seq (seq-more s)))
|
||||
(if (jolt-nil? s) jolt-empty-list s))))
|
||||
(define jolt-drop-while
|
||||
(case-lambda
|
||||
((pred) (td-drop-while pred))
|
||||
((pred coll) (drop-while-seq pred coll))))
|
||||
|
||||
;; partition: (partition n coll), (partition n step coll), or
|
||||
;; (partition n step pad coll). Only complete partitions of size n are kept;
|
||||
;; with pad, a short final partition is padded from pad (and may be < n if pad
|
||||
;; runs out). Each partition is a seq; the whole result is a lazy seq of seqs.
|
||||
(define jolt-partition
|
||||
(case-lambda
|
||||
((n coll) (partition* (->idx n) (->idx n) #f #f coll))
|
||||
((n step coll) (partition* (->idx n) (->idx step) #f #f coll))
|
||||
((n step pad coll) (partition* (->idx n) (->idx step) #t pad coll))))
|
||||
(define (take-n n s) ; -> (values list-of-first-n remaining-seq taken-count)
|
||||
(let loop ((n n) (s s) (acc '()))
|
||||
(if (or (fx<=? n 0) (jolt-nil? s))
|
||||
(values (reverse acc) s (length acc))
|
||||
(loop (fx- n 1) (jolt-seq (seq-more s)) (cons (seq-first s) acc)))))
|
||||
(define (partition* n step has-pad pad coll)
|
||||
(let loop ((s (jolt-seq coll)))
|
||||
(if (jolt-nil? s) jolt-empty-list
|
||||
(let-values (((part rest taken) (take-n n s)))
|
||||
(cond
|
||||
;; full partition: emit it, advance `step` from its START
|
||||
((fx=? taken n)
|
||||
(cseq-lazy (list->cseq part)
|
||||
(lambda () (loop (jolt-seq (advance-by step s))))))
|
||||
;; short final partition with pad: top up to n from pad, then stop
|
||||
((and has-pad (fx>? taken 0))
|
||||
(let ((padded (append part (take-list (- n taken) (jolt-seq pad)))))
|
||||
(cseq-lazy (list->cseq padded) (lambda () jolt-empty-list))))
|
||||
;; short final partition, no pad: dropped (Clojure keeps only full ones)
|
||||
(else jolt-empty-list))))))
|
||||
(define (advance-by step s) ; drop `step` elements from s (seq), returns a seq
|
||||
(let loop ((step step) (s s))
|
||||
(if (or (fx<=? step 0) (jolt-nil? s)) s
|
||||
(loop (fx- step 1) (jolt-seq (seq-more s))))))
|
||||
(define (take-list n s) ; up to n elements of seq s as a Scheme list
|
||||
(let loop ((n n) (s s) (acc '()))
|
||||
(if (or (fx<=? n 0) (jolt-nil? s)) (reverse acc)
|
||||
(loop (fx- n 1) (jolt-seq (seq-more s)) (cons (seq-first s) acc)))))
|
||||
|
||||
;; sort: (sort coll) uses compare; (sort cmp coll) uses cmp, whose result may be
|
||||
;; a 3-way number (<0 / 0 / >0) OR a boolean (a Clojure-style less-than pred).
|
||||
(define (cmp->less cmp)
|
||||
(lambda (a b)
|
||||
(let ((r (jolt-invoke cmp a b)))
|
||||
(if (number? r) (< r 0) (jolt-truthy? r)))))
|
||||
(define jolt-sort
|
||||
(case-lambda
|
||||
((coll) (jolt-sort* (cmp->less jolt-compare) coll))
|
||||
((cmp coll) (jolt-sort* (cmp->less cmp) coll))))
|
||||
(define (jolt-sort* less? coll)
|
||||
(let ((s (jolt-seq coll)))
|
||||
(if (jolt-nil? s) jolt-empty-list
|
||||
(list->cseq (list-sort less? (seq->list s))))))
|
||||
|
||||
;; identical?: jolt reference identity, defined as (= a b) over the
|
||||
;; value model, where interned keywords/small values compare equal.
|
||||
(define (jolt-identical? a b) (jolt= a b))
|
||||
|
||||
;; Give the seq.ss native procedures their transducer (1-arg) arity — the emitter
|
||||
;; lowers (map f)/(filter p)/(take n) at the wrong arity to the bare procedure
|
||||
;; (value-position path), so widening the procedures is what makes the 1-arg form
|
||||
;; work. Capture the originals (collection arities) first, then redefine.
|
||||
(define %prev-jolt-map jolt-map)
|
||||
(set! jolt-map (lambda (f . colls)
|
||||
(if (null? colls) (td-map f) (apply %prev-jolt-map f colls))))
|
||||
(define %prev-jolt-filter jolt-filter)
|
||||
(set! jolt-filter (case-lambda ((pred) (td-filter pred))
|
||||
((pred coll) (%prev-jolt-filter pred coll))))
|
||||
(define %prev-jolt-remove jolt-remove)
|
||||
(set! jolt-remove (case-lambda ((pred) (td-remove pred))
|
||||
((pred coll) (%prev-jolt-remove pred coll))))
|
||||
(define %prev-jolt-take jolt-take)
|
||||
(set! jolt-take (case-lambda ((n) (td-take n))
|
||||
((n coll) (%prev-jolt-take n coll))))
|
||||
(define %prev-jolt-drop jolt-drop)
|
||||
(set! jolt-drop (case-lambda ((n) (td-drop n))
|
||||
((n coll) (%prev-jolt-drop n coll))))
|
||||
;; into: add the 3-arg (into to xform from). The 2-arg stays the seq.ss fold.
|
||||
(define %prev-jolt-into jolt-into)
|
||||
(set! jolt-into (case-lambda ((to from) (%prev-jolt-into to from))
|
||||
((to xform from) (into-xform to xform from))))
|
||||
|
||||
(def-var! "clojure.core" "reduced" jolt-reduced-new)
|
||||
(def-var! "clojure.core" "reduced?" jolt-reduced-pred)
|
||||
(def-var! "clojure.core" "mapcat" jolt-mapcat)
|
||||
(def-var! "clojure.core" "take-while" jolt-take-while)
|
||||
(def-var! "clojure.core" "drop-while" jolt-drop-while)
|
||||
(def-var! "clojure.core" "partition" jolt-partition)
|
||||
(def-var! "clojure.core" "sort" jolt-sort)
|
||||
(def-var! "clojure.core" "identical?" jolt-identical?)
|
||||
333
host/chez/natives-str.ss
Normal file
333
host/chez/natives-str.ss
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
;; natives-str.ss (jolt-nfca) — java.lang.String method interop on Chez.
|
||||
;;
|
||||
;; (.method s arg*) on a string target lowers to record-method-dispatch (emit.ss),
|
||||
;; which falls through to jolt-string-method here when the target is a string.
|
||||
;; Covers the
|
||||
;; portable java.lang.String/CharSequence methods cljc libraries actually call.
|
||||
;; Case mapping is ASCII (the whole engine is byte-oriented), indexOf returns -1
|
||||
;; on miss as on the JVM, indices come in as flonums, char results are Scheme
|
||||
;; chars, and numeric results are flonums to match jolt's number model.
|
||||
;;
|
||||
;; Loaded from rt.ss AFTER regex.ss (the regex methods reuse jolt-re-pattern /
|
||||
;; regex-t-irx) and records.ss (which calls jolt-string-method).
|
||||
|
||||
;; --- ASCII case mapping (byte-oriented) -------
|
||||
(define (ascii-up-char c)
|
||||
(if (and (char<=? #\a c) (char<=? c #\z))
|
||||
(integer->char (fx- (char->integer c) 32)) c))
|
||||
(define (ascii-down-char c)
|
||||
(if (and (char<=? #\A c) (char<=? c #\Z))
|
||||
(integer->char (fx+ (char->integer c) 32)) c))
|
||||
(define (ascii-string-up s) (list->string (map ascii-up-char (string->list s))))
|
||||
(define (ascii-string-down s) (list->string (map ascii-down-char (string->list s))))
|
||||
|
||||
;; --- ASCII trim: drop leading/trailing chars with code <= space (JVM .trim) ---
|
||||
(define (str-trim s)
|
||||
(let ((len (string-length s)))
|
||||
(let scan-l ((i 0))
|
||||
(cond ((fx=? i len) "")
|
||||
((char<=? (string-ref s i) #\space) (scan-l (fx+ i 1)))
|
||||
(else (let scan-r ((j (fx- len 1)))
|
||||
(if (char<=? (string-ref s j) #\space)
|
||||
(scan-r (fx- j 1))
|
||||
(substring s i (fx+ j 1)))))))))
|
||||
(define (str-triml s)
|
||||
(let ((len (string-length s)))
|
||||
(let loop ((i 0))
|
||||
(cond ((fx=? i len) "")
|
||||
((char<=? (string-ref s i) #\space) (loop (fx+ i 1)))
|
||||
(else (substring s i len))))))
|
||||
(define (str-trimr s)
|
||||
(let loop ((j (fx- (string-length s) 1)))
|
||||
(cond ((fx<? j 0) "")
|
||||
((char<=? (string-ref s j) #\space) (loop (fx- j 1)))
|
||||
(else (substring s 0 (fx+ j 1))))))
|
||||
|
||||
;; --- substring search: first index of `needle` in `s` at/after `from`, or -1 --
|
||||
(define (str-index-of s needle from)
|
||||
(let ((nlen (string-length needle)) (slen (string-length s)))
|
||||
(let loop ((i (max 0 from)))
|
||||
(cond ((fx>? (fx+ i nlen) slen) -1)
|
||||
((string=? (substring s i (fx+ i nlen)) needle) i)
|
||||
(else (loop (fx+ i 1)))))))
|
||||
(define (str-last-index-of s needle)
|
||||
(let ((nlen (string-length needle)) (slen (string-length s)))
|
||||
(let loop ((i (fx- slen nlen)) (found -1))
|
||||
(cond ((fx<? i 0) found)
|
||||
((string=? (substring s i (fx+ i nlen)) needle) i)
|
||||
(else (loop (fx- i 1) found))))))
|
||||
|
||||
;; A needle arg: a char value -> its 1-char string; a number -> the char at that
|
||||
;; code point (JVM treats an int arg to indexOf as a char code); else a string.
|
||||
(define (str-needle x)
|
||||
(cond ((char? x) (string x))
|
||||
((number? x) (string (integer->char (exact (truncate x)))))
|
||||
((string? x) x)
|
||||
(else (jolt-str x))))
|
||||
|
||||
;; literal replace-all (JVM String.replace(CharSequence,CharSequence)).
|
||||
(define (str-replace-literal s a b)
|
||||
(let ((alen (string-length a)) (slen (string-length s)))
|
||||
(if (fx=? alen 0) s
|
||||
(let loop ((i 0) (acc '()))
|
||||
(cond ((fx>? (fx+ i alen) slen)
|
||||
(apply string-append (reverse (cons (substring s i slen) acc))))
|
||||
((string=? (substring s i (fx+ i alen)) a)
|
||||
(loop (fx+ i alen) (cons b acc)))
|
||||
(else (loop (fx+ i 1) (cons (substring s i (fx+ i 1)) acc))))))))
|
||||
|
||||
;; A compiled irregex for a plain-string Java-regex pattern (or a jolt-regex).
|
||||
(define (str-irx pat) (regex-t-irx (jolt-re-pattern pat)))
|
||||
|
||||
;; JVM String.split: split fully, then drop trailing empty strings.
|
||||
(define (str-split-drop-trailing parts)
|
||||
(let loop ((p (reverse parts)))
|
||||
(if (and (pair? p) (string=? (car p) "")) (loop (cdr p)) (reverse p))))
|
||||
|
||||
(define (jolt-string-method method s rest)
|
||||
(define (arg n) (list-ref rest n))
|
||||
(cond
|
||||
((string=? method "toString") s)
|
||||
((string=? method "toLowerCase") (ascii-string-down s))
|
||||
((string=? method "toUpperCase") (ascii-string-up s))
|
||||
((string=? method "trim") (str-trim s))
|
||||
((string=? method "length") (string-length s)) ; exact int (= JVM)
|
||||
((string=? method "isEmpty") (fx=? (string-length s) 0))
|
||||
((string=? method "charAt") (string-ref s (jolt->idx (arg 0))))
|
||||
((string=? method "substring")
|
||||
(substring s (jolt->idx (arg 0))
|
||||
(if (fx>? (length rest) 1) (jolt->idx (arg 1)) (string-length s))))
|
||||
((string=? method "indexOf")
|
||||
(str-index-of s (str-needle (arg 0))
|
||||
(if (fx>? (length rest) 1) (jolt->idx (arg 1)) 0)))
|
||||
((string=? method "lastIndexOf")
|
||||
(str-last-index-of s (str-needle (arg 0))))
|
||||
((string=? method "startsWith")
|
||||
(let ((p (arg 0))) (and (fx>=? (string-length s) (string-length p))
|
||||
(string=? (substring s 0 (string-length p)) p))))
|
||||
((string=? method "endsWith")
|
||||
(let ((p (arg 0)) (slen (string-length s)))
|
||||
(and (fx>=? slen (string-length p))
|
||||
(string=? (substring s (fx- slen (string-length p)) slen) p))))
|
||||
((string=? method "contains")
|
||||
(fx>=? (str-index-of s (str-needle (arg 0)) 0) 0))
|
||||
((string=? method "concat") (string-append s (arg 0)))
|
||||
((string=? method "replace") (str-replace-literal s (str-needle (arg 0)) (str-needle (arg 1))))
|
||||
((string=? method "equalsIgnoreCase")
|
||||
(string=? (ascii-string-down s) (ascii-string-down (arg 0))))
|
||||
((string=? method "compareTo")
|
||||
(let ((o (arg 0))) (cond ((string<? s o) -1.0) ((string>? s o) 1.0) (else 0.0))))
|
||||
((string=? method "getBytes") (string->utf8 s))
|
||||
((string=? method "matches") (if (irregex-match (str-irx (arg 0)) s) #t #f))
|
||||
((string=? method "replaceAll") (irregex-replace/all (str-irx (arg 0)) s (arg 1)))
|
||||
((string=? method "replaceFirst") (irregex-replace (str-irx (arg 0)) s (arg 1)))
|
||||
((string=? method "split")
|
||||
(apply jolt-vector (str-split-drop-trailing (irregex-split (str-irx (arg 0)) s))))
|
||||
;; universal object-methods that reach a string target (seed object-methods):
|
||||
;; a thrown string / Exception. ctor (which keeps the message string) answers
|
||||
;; getMessage with itself; equals is value equality.
|
||||
((or (string=? method "getMessage") (string=? method "getLocalizedMessage")) s)
|
||||
((string=? method "equals") (and (string? (arg 0)) (string=? s (arg 0))))
|
||||
;; String.intern: jolt strings aren't pooled, but value equality holds, so the
|
||||
;; canonical representation is the string itself.
|
||||
((string=? method "intern") s)
|
||||
(else (error #f (string-append "No method " method " for value")))))
|
||||
|
||||
;; --- clojure.core str-* primitives (the substrate clojure.string.clj calls) ---
|
||||
;; clojure.string.clj is pure Clojure over these
|
||||
;; natives; def-var!'d here so the emitted
|
||||
;; clojure.string prelude tier's var-derefs resolve:
|
||||
;; string/ascii-* (ASCII), string/find (index or nil), core-str-* (regex|literal).
|
||||
|
||||
;; (string/split sep s) -> parts, splitting on each non-overlapping sep.
|
||||
(define (str-literal-split s sep)
|
||||
(let ((slen (string-length s)) (plen (string-length sep)))
|
||||
(if (fx=? plen 0)
|
||||
(map string (string->list s))
|
||||
(let loop ((i 0) (start 0) (acc '()))
|
||||
(cond ((fx>? (fx+ i plen) slen)
|
||||
(reverse (cons (substring s start slen) acc)))
|
||||
((string=? (substring s i (fx+ i plen)) sep)
|
||||
(loop (fx+ i plen) (fx+ i plen) (cons (substring s start i) acc)))
|
||||
(else (loop (fx+ i 1) start acc)))))))
|
||||
|
||||
(define (str-upper s) (ascii-string-up s))
|
||||
(define (str-lower s) (ascii-string-down s))
|
||||
(define (str-reverse-b s) (list->string (reverse (string->list s))))
|
||||
|
||||
;; (str-find needle haystack) -> exact int index of first occurrence, or nil.
|
||||
(define (str-find needle s)
|
||||
(let ((i (str-index-of s needle 0)))
|
||||
(if (fx<? i 0) jolt-nil i)))
|
||||
|
||||
;; (str-join coll [sep]) -> stringify each element (Clojure str), join by sep.
|
||||
(define (str-join coll . opt)
|
||||
(let ((sep (if (pair? opt) (jolt-str-render-one (car opt)) ""))
|
||||
(items (map jolt-str-render-one (seq->list coll))))
|
||||
(let loop ((xs items) (first #t) (acc '()))
|
||||
(cond ((null? xs) (apply string-append (reverse acc)))
|
||||
(first (loop (cdr xs) #f (cons (car xs) acc)))
|
||||
(else (loop (cdr xs) #f (cons (car xs) (cons sep acc))))))))
|
||||
|
||||
;; (re-split irx s limit) -> parts, splitting at each match. Keeps interior AND
|
||||
;; trailing empty strings (the clojure.string wrapper drops trailing for limit 0);
|
||||
;; a positive limit yields at most `limit` parts (the rest kept unsplit).
|
||||
;; The clojure.string.clj split wrapper
|
||||
;; layers the trailing-empty trim on top.
|
||||
(define (re-split irx s limit)
|
||||
(let ((len (string-length s)))
|
||||
(let loop ((start 0) (last 0) (out '()))
|
||||
(if (and limit (fx>=? (length out) (fx- limit 1)))
|
||||
(reverse (cons (substring s last len) out))
|
||||
(let ((m (and (fx<=? start len) (irregex-search irx s start))))
|
||||
(if (not m)
|
||||
(reverse (cons (substring s last len) out))
|
||||
(let ((ms (irregex-match-start-index m 0))
|
||||
(me (irregex-match-end-index m 0)))
|
||||
(if (fx=? me ms) ; zero-width: step past to avoid a stall
|
||||
(if (fx>=? start len)
|
||||
(reverse (cons (substring s last len) out))
|
||||
(loop (fx+ start 1) last out))
|
||||
(loop me me (cons (substring s last ms) out))))))))))
|
||||
|
||||
;; (str-split pat s [limit]) -> parts. Regex or literal separator; a positive
|
||||
;; limit caps the part count (the unsplit tail kept), matching core-str-split.
|
||||
(define (str-split pat s . opt)
|
||||
(let ((limit (if (and (pair? opt) (not (jolt-nil? (car opt)))) (jolt->idx (car opt)) #f)))
|
||||
(if (jolt-regex? pat)
|
||||
(apply jolt-vector (re-split (regex-t-irx pat) s limit))
|
||||
(let ((parts (str-literal-split s pat)))
|
||||
(apply jolt-vector
|
||||
(if (and limit (fx>? limit 0) (fx>? (length parts) limit))
|
||||
(append (list-head parts (fx- limit 1))
|
||||
(list (str-join-strs (list-tail parts (fx- limit 1)) pat)))
|
||||
parts))))))
|
||||
(define (str-join-strs strs sep)
|
||||
(let loop ((xs strs) (first #t) (acc '()))
|
||||
(cond ((null? xs) (apply string-append (reverse acc)))
|
||||
(first (loop (cdr xs) #f (cons (car xs) acc)))
|
||||
(else (loop (cdr xs) #f (cons (car xs) (cons sep acc)))))))
|
||||
|
||||
;; $0/$1... expansion in a string replacement against an irregex match (the
|
||||
;; JVM/seed replacement syntax). $N -> group N's text (dropped if non-matching).
|
||||
(define (expand-dollar repl m)
|
||||
(let ((len (string-length repl)))
|
||||
(let loop ((i 0) (acc '()))
|
||||
(if (fx>=? i len)
|
||||
(apply string-append (reverse acc))
|
||||
(let ((c (string-ref repl i)))
|
||||
(if (and (char=? c #\$) (fx<? (fx+ i 1) len)
|
||||
(char<=? #\0 (string-ref repl (fx+ i 1)))
|
||||
(char<=? (string-ref repl (fx+ i 1)) #\9))
|
||||
(let* ((n (fx- (char->integer (string-ref repl (fx+ i 1))) 48))
|
||||
(g (and (fx<=? n (irregex-match-num-submatches m))
|
||||
(irregex-match-substring m n))))
|
||||
(loop (fx+ i 2) (if g (cons g acc) acc)))
|
||||
(loop (fx+ i 1) (cons (string c) acc))))))))
|
||||
|
||||
;; One match's replacement text. A string gets $N expansion; a fn (jolt closure)
|
||||
;; is called with the match result (whole string, or [whole g1 ...] when grouped)
|
||||
;; and its result stringified.
|
||||
(define (replacement-text replacement m)
|
||||
(cond
|
||||
((string? replacement) (expand-dollar replacement m))
|
||||
((procedure? replacement) (jolt-str-render-one (jolt-invoke replacement (irx-result m))))
|
||||
(else (jolt-str-render-one replacement))))
|
||||
|
||||
;; regex replace, first or all matches.
|
||||
(define (re-replace irx s replacement all?)
|
||||
(let ((len (string-length s)))
|
||||
(let loop ((start 0) (last 0) (acc '()))
|
||||
(let ((m (and (fx<=? start len) (irregex-search irx s start))))
|
||||
(if (not m)
|
||||
(apply string-append (reverse (cons (substring s last len) acc)))
|
||||
(let ((ms (irregex-match-start-index m 0))
|
||||
(me (irregex-match-end-index m 0)))
|
||||
(if (fx=? me ms) ; zero-width: step past
|
||||
(if (fx>=? start len)
|
||||
(apply string-append (reverse (cons (substring s last len) acc)))
|
||||
(loop (fx+ start 1) last acc))
|
||||
(let ((acc2 (cons (replacement-text replacement m)
|
||||
(cons (substring s last ms) acc))))
|
||||
(if all?
|
||||
(loop me me acc2)
|
||||
(apply string-append (reverse (cons (substring s me len) acc2))))))))))))
|
||||
|
||||
;; (str-replace-all pat repl s) / (str-replace pat repl s) — regex or literal.
|
||||
(define (str-replace-all pat repl s)
|
||||
(if (jolt-regex? pat)
|
||||
(re-replace (regex-t-irx pat) s repl #t)
|
||||
(str-replace-literal s pat repl)))
|
||||
(define (str-replace-literal-first s a b)
|
||||
(let ((alen (string-length a)) (i (str-index-of s a 0)))
|
||||
(if (fx<? i 0) s
|
||||
(string-append (substring s 0 i) b (substring s (fx+ i alen) (string-length s))))))
|
||||
(define (str-replace pat repl s)
|
||||
(if (jolt-regex? pat)
|
||||
(re-replace (regex-t-irx pat) s repl #f)
|
||||
(str-replace-literal-first s pat repl)))
|
||||
|
||||
(def-var! "clojure.core" "str-upper" str-upper)
|
||||
(def-var! "clojure.core" "str-lower" str-lower)
|
||||
(def-var! "clojure.core" "str-trim" str-trim)
|
||||
(def-var! "clojure.core" "str-triml" str-triml)
|
||||
(def-var! "clojure.core" "str-trimr" str-trimr)
|
||||
(def-var! "clojure.core" "str-find" str-find)
|
||||
(def-var! "clojure.core" "str-reverse-b" str-reverse-b)
|
||||
(def-var! "clojure.core" "str-join" str-join)
|
||||
(def-var! "clojure.core" "str-split" str-split)
|
||||
(def-var! "clojure.core" "str-replace" str-replace)
|
||||
(def-var! "clojure.core" "str-replace-all" str-replace-all)
|
||||
|
||||
;; (require ...) / (use ...) at runtime: register each spec's :as alias + :refer
|
||||
;; names into the runtime ns tables (chez-register-spec!, ns.ss), keyed by the
|
||||
;; current ns. The zero-Janet spine also pre-registers these at analyze time
|
||||
;; (idempotent); but when the JANET analyzer compiled the form (the prelude path)
|
||||
;; the Chez tables were never populated, so ns-aliases/ns-resolve over an :as alias
|
||||
;; need this runtime registration (jolt-cf1q.7). Specs arrive evaluated (quoted).
|
||||
(define (chez-runtime-require . specs)
|
||||
(for-each (lambda (s) (chez-register-spec! (chez-current-ns) s)) specs)
|
||||
jolt-nil)
|
||||
(def-var! "clojure.core" "require" chez-runtime-require)
|
||||
;; use = require + refer ALL of the target's public vars (unless an explicit
|
||||
;; :only/:refer filter is given, which chez-register-spec! handles per-name).
|
||||
(define (chez-runtime-use . specs)
|
||||
(for-each
|
||||
(lambda (spec)
|
||||
(chez-register-spec! (chez-current-ns) spec)
|
||||
(let* ((items (cond ((pvec? spec) (seq->list spec))
|
||||
((or (cseq? spec) (empty-list-t? spec)) (seq->list spec))
|
||||
((symbol-t? spec) (list spec))
|
||||
(else '())))
|
||||
(target (and (pair? items) (symbol-t? (car items)) (symbol-t-name (car items))))
|
||||
(filtered (let scan ((xs (if (pair? items) (cdr items) '())))
|
||||
(cond ((null? xs) #f)
|
||||
((and (keyword? (car xs))
|
||||
(member (keyword-t-name (car xs)) '("only" "refer"))) #t)
|
||||
(else (scan (cdr xs)))))))
|
||||
(when (and target (not filtered))
|
||||
(chez-register-refer-all! (chez-current-ns) target))))
|
||||
specs)
|
||||
jolt-nil)
|
||||
(def-var! "clojure.core" "use" chez-runtime-use)
|
||||
;; import: bring a deftype/defrecord from another ns into the current one. A spec
|
||||
;; [from-ns Type ...] binds each Type's ctor closure under the current ns, so its
|
||||
;; (Type. ...) constructor (host-new resolves it as a var) works after :import.
|
||||
(define (chez-runtime-import . specs)
|
||||
(for-each
|
||||
(lambda (spec)
|
||||
(let ((items (cond ((pvec? spec) (seq->list spec))
|
||||
((or (cseq? spec) (empty-list-t? spec)) (seq->list spec))
|
||||
(else '()))))
|
||||
(when (and (pair? items) (symbol-t? (car items)))
|
||||
(let ((from (symbol-t-name (car items))))
|
||||
(for-each
|
||||
(lambda (tn)
|
||||
(when (symbol-t? tn)
|
||||
(let ((c (var-cell-lookup from (symbol-t-name tn))))
|
||||
(when (and c (var-cell-defined? c))
|
||||
(def-var! (chez-current-ns) (symbol-t-name tn) (var-cell-root c))))))
|
||||
(cdr items))))))
|
||||
specs)
|
||||
jolt-nil)
|
||||
(def-var! "clojure.core" "import" chez-runtime-import)
|
||||
51
host/chez/natives-xform.ss
Normal file
51
host/chez/natives-xform.ss
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
;; volatiles + sequence / transduce (jolt-cf1q.3, jolt-xjx6) — the transducer
|
||||
;; application surface.
|
||||
;;
|
||||
;; `sequence` and `transduce` are seed natives that were jolt-nil on the prelude.
|
||||
;; The stateful transducer arities (take-nth/map-indexed/partition-by/dedupe/
|
||||
;; distinct, all overlay) use volatile!/vswap!/vreset!/deref, also unshimmed — so
|
||||
;; the whole (sequence xform coll) / (transduce xform f coll) surface crashed.
|
||||
;;
|
||||
;; Volatiles are a native mutable box (jvol) — the overlay vreset!/vswap! drive a
|
||||
;; volatile through jolt.host/ref-put!+get, but a Chez volatile is a record, not a
|
||||
;; tagged table, so those overlay versions are overridden natively in
|
||||
;; post-prelude.ss. transduce/sequence build on the existing into-xform / reduce-
|
||||
;; seq machinery (natives-seq.ss / seq.ss). Loaded after those + atoms.ss (deref).
|
||||
|
||||
;; --- volatiles ---------------------------------------------------------------
|
||||
(define-record-type jvol (fields (mutable v)) (nongenerative chez-jvol-v1))
|
||||
(define (jolt-volatile! x) (make-jvol x))
|
||||
(define (jolt-vreset! vol x) (jvol-v-set! vol x) x)
|
||||
(define (jolt-vswap! vol f . args)
|
||||
(let ((nv (apply jolt-invoke f (jvol-v vol) args))) (jvol-v-set! vol nv) nv))
|
||||
(define (jolt-volatile-pred? x) (jvol? x))
|
||||
;; deref reads a volatile too (partition-all/-by transducers @-deref their box).
|
||||
(define %xf-deref jolt-deref)
|
||||
(set! jolt-deref (lambda (x) (if (jvol? x) (jvol-v x) (%xf-deref x))))
|
||||
|
||||
(def-var! "clojure.core" "volatile!" jolt-volatile!)
|
||||
(def-var! "clojure.core" "deref" jolt-deref)
|
||||
|
||||
;; --- transduce / sequence ----------------------------------------------------
|
||||
;; (transduce xform f coll) / (transduce xform f init coll): build the transformed
|
||||
;; reducing fn (xform f), reduce it over coll (reduce-seq honors `reduced`), then
|
||||
;; run the completion (1-arg) arity. The 3-arg init defaults to (f) — the rf's
|
||||
;; 0-arity, e.g. (+) = 0, (conj) = [].
|
||||
(define jolt-transduce
|
||||
(case-lambda
|
||||
((xform f coll) (jolt-transduce xform f (jolt-invoke f) coll))
|
||||
((xform f init coll)
|
||||
(let* ((xf (jolt-invoke xform f))
|
||||
(res (reduce-seq xf init (jolt-seq coll))))
|
||||
(jolt-invoke xf res)))))
|
||||
|
||||
;; (sequence coll) -> a seq; (sequence xform coll) -> coll transformed by xform.
|
||||
;; Materialized eagerly through into-xform then seq'd (corpus inputs are finite; a
|
||||
;; fully-lazy pull is future work). Honors reduced via into-xform/reduce-seq.
|
||||
(define jolt-sequence
|
||||
(case-lambda
|
||||
((coll) (jolt-seq coll))
|
||||
((xform coll) (jolt-seq (into-xform (jolt-vector) xform coll)))))
|
||||
|
||||
(def-var! "clojure.core" "transduce" jolt-transduce)
|
||||
(def-var! "clojure.core" "sequence" jolt-sequence)
|
||||
344
host/chez/ns.ss
Normal file
344
host/chez/ns.ss
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
;; namespaces (jolt-yxqm, Phase 2) — the namespace value model.
|
||||
;;
|
||||
;; Chez has no ctx, so the ctx-coupled seed natives (find-ns/resolve/in-ns/…) are
|
||||
;; reimplemented over the rt.ss var-table (cells carry ns + name + defined?) and
|
||||
;; the multimethods.ss chez-current-ns box. A namespace VALUE is a `jns` record
|
||||
;; carrying its name string — distinct from a map/record so (map? ns) is #f, but
|
||||
;; the overlay's `ns-name` reads (get ns :name); that's overridden natively in
|
||||
;; post-prelude.ss (loads after the overlay clobbers it).
|
||||
;;
|
||||
;; Loaded LAST from rt.ss. SCOPE (jolt-yxqm): the read/resolve/in-ns/*ns* ops.
|
||||
;; use/require cross-ns SWITCHING is deferred (Phase 3) — the analyzer bakes a
|
||||
;; def's target ns at compile time, so a runtime in-ns can't redirect later defs.
|
||||
|
||||
(define-record-type jns (fields name) (nongenerative chez-jns-v1))
|
||||
|
||||
;; registry: name-string -> jns. Seeded with the two always-present namespaces;
|
||||
;; grown by in-ns / create-ns. find-ns ALSO derives existence from the var-table
|
||||
;; (any cell with that ns), so a namespace that only ever had vars def'd into it
|
||||
;; is still found.
|
||||
(define ns-registry (make-hashtable string-hash string=?))
|
||||
(define (intern-ns! name)
|
||||
(or (hashtable-ref ns-registry name #f)
|
||||
(let ((n (make-jns name))) (hashtable-set! ns-registry name n) n)))
|
||||
(intern-ns! "user")
|
||||
(intern-ns! "clojure.core")
|
||||
|
||||
;; --- namespace aliases (jolt-qjr0) -----------------------------------------
|
||||
;; (require '[ns :as a]) registers a -> ns so the analyzer can resolve a/foo to
|
||||
;; ns/foo. Keyed by (compile-ns . alias). On the zero-Janet spine the requires are
|
||||
;; pre-registered at analyze time (compile-eval.ss) — analysis precedes eval, so a
|
||||
;; runtime require no-op is fine. Also drives jolt-ns-aliases below.
|
||||
(define ns-alias-table (make-hashtable equal-hash equal?))
|
||||
(define (chez-register-alias! cns alias target)
|
||||
(hashtable-set! ns-alias-table (cons cns alias) target))
|
||||
(define (chez-resolve-alias cns alias)
|
||||
(hashtable-ref ns-alias-table (cons cns alias) #f))
|
||||
;; :refer brings an UNQUALIFIED name into cns, resolving to target-ns/name.
|
||||
(define ns-refer-table (make-hashtable equal-hash equal?))
|
||||
(define (chez-register-refer! cns name target)
|
||||
(hashtable-set! ns-refer-table (cons cns name) target))
|
||||
;; refer-all (a bare `use`): cns -> list of fully-referred target ns names. A name
|
||||
;; not found per-name resolves to the first refer-all target that defines it.
|
||||
(define ns-refer-all-table (make-hashtable equal-hash equal?))
|
||||
(define (chez-register-refer-all! cns target)
|
||||
(let ((cur (hashtable-ref ns-refer-all-table cns '())))
|
||||
(unless (member target cur)
|
||||
(hashtable-set! ns-refer-all-table cns (cons target cur)))))
|
||||
(define (chez-resolve-refer cns name)
|
||||
(or (hashtable-ref ns-refer-table (cons cns name) #f)
|
||||
(let loop ((ts (hashtable-ref ns-refer-all-table cns '())))
|
||||
(cond ((null? ts) #f)
|
||||
((let ((c (var-cell-lookup (car ts) name))) (and c (var-cell-defined? c))) (car ts))
|
||||
(else (loop (cdr ts)))))))
|
||||
;; parse a require/use spec FORM and register its :as alias + :refer names under
|
||||
;; `cns`. spec: [ns :as a :refer [x y] ...] / (ns ...) / bare ns. opts are
|
||||
;; keyword/value pairs after the ns symbol.
|
||||
(define (chez-register-spec! cns spec)
|
||||
(let ((items (cond ((pvec? spec) (seq->list spec))
|
||||
((or (cseq? spec) (empty-list-t? spec)) (seq->list spec))
|
||||
(else '()))))
|
||||
(when (and (pair? items) (symbol-t? (car items)))
|
||||
(let ((target (symbol-t-name (car items))))
|
||||
(let loop ((xs (cdr items)))
|
||||
(when (and (pair? xs) (pair? (cdr xs)))
|
||||
(let ((k (car xs)) (v (cadr xs)))
|
||||
(when (keyword? k)
|
||||
(cond
|
||||
((string=? (keyword-t-name k) "as")
|
||||
(when (symbol-t? v) (chez-register-alias! cns (symbol-t-name v) target)))
|
||||
((string=? (keyword-t-name k) "refer")
|
||||
(cond
|
||||
;; :refer :all — bring in every public var (require :refer :all)
|
||||
((and (keyword? v) (string=? (keyword-t-name v) "all"))
|
||||
(chez-register-refer-all! cns target))
|
||||
((pvec? v)
|
||||
(for-each (lambda (n)
|
||||
(when (symbol-t? n) (chez-register-refer! cns (symbol-t-name n) target)))
|
||||
(seq->list v))))))))
|
||||
(loop (cddr xs))))))))
|
||||
|
||||
;; a namespace designator -> its name string (a jns or a symbol; the corpus never
|
||||
;; passes a bare string).
|
||||
(define (ns-desig->name d)
|
||||
(if (jns? d) (jns-name d) (symbol-t-name d)))
|
||||
|
||||
(define (ns-has-vars? nm)
|
||||
(let ((found #f))
|
||||
(vector-for-each
|
||||
(lambda (c) (when (and (not found) (string=? (var-cell-ns c) nm)) (set! found #t)))
|
||||
(hashtable-values var-table))
|
||||
found))
|
||||
|
||||
(define (jolt-find-ns desig)
|
||||
(let ((nm (ns-desig->name desig)))
|
||||
(or (hashtable-ref ns-registry nm #f)
|
||||
(and (ns-has-vars? nm) (intern-ns! nm))
|
||||
jolt-nil)))
|
||||
|
||||
(define (jolt-the-ns desig)
|
||||
(if (jns? desig) desig
|
||||
(let ((n (jolt-find-ns desig)))
|
||||
(if (jns? n) n (error #f "No namespace" desig)))))
|
||||
|
||||
(define (jolt-create-ns desig) (intern-ns! (ns-desig->name desig)))
|
||||
|
||||
;; in-ns: register + switch the current ns + re-bind *ns* + return the jns. NOTE
|
||||
;; (Phase-3 deferral): this updates only the RUNTIME current ns — subsequent defs
|
||||
;; in the same program were already ns-baked by the analyzer, so it does not
|
||||
;; redirect them. It is enough for *ns* / str-of-ns to track the switch.
|
||||
(define (jolt-in-ns desig)
|
||||
(let* ((nm (ns-desig->name desig)) (n (intern-ns! nm)))
|
||||
(set-chez-ns! nm)
|
||||
(def-var! "clojure.core" "*ns*" n)
|
||||
n))
|
||||
|
||||
;; ns-name: a namespace's name as a (no-ns) symbol. Overrides the overlay (which
|
||||
;; reads (get ns :name) = nil on a jns record) — wired in via post-prelude.ss.
|
||||
(define (jolt-ns-name desig)
|
||||
(jolt-symbol #f (jns-name (jolt-the-ns desig))))
|
||||
|
||||
(define (jolt-all-ns)
|
||||
(let ((seen (make-hashtable string-hash string=?)))
|
||||
(vector-for-each (lambda (k) (hashtable-set! seen k #t)) (hashtable-keys ns-registry))
|
||||
(vector-for-each (lambda (c) (hashtable-set! seen (var-cell-ns c) #t)) (hashtable-values var-table))
|
||||
(list->cseq (map intern-ns! (vector->list (hashtable-keys seen))))))
|
||||
|
||||
;; ns-publics / ns-map / ns-interns: a {sym -> var-cell} jolt map built by scanning
|
||||
;; the var-table for defined cells in the namespace. (Private vars are not tracked
|
||||
;; yet, so ns-publics == ns-interns.) ns-aliases is an empty map (map? is true).
|
||||
(define (ns-vars-pmap nm)
|
||||
(let ((m (jolt-hash-map)))
|
||||
(vector-for-each
|
||||
(lambda (c)
|
||||
(when (and (string=? (var-cell-ns c) nm) (var-cell-defined? c))
|
||||
(set! m (jolt-assoc m (jolt-symbol #f (var-cell-name c)) c))))
|
||||
(hashtable-values var-table))
|
||||
m))
|
||||
(define (jolt-ns-publics desig) (ns-vars-pmap (ns-desig->name desig)))
|
||||
|
||||
;; ns-aliases (jolt-cf1q.7): the {alias-sym -> ns-value} registered under `desig`
|
||||
;; (default the current ns) via require :as / alias. Reads ns-alias-table.
|
||||
(define (jolt-ns-aliases . desig)
|
||||
(let ((cns (if (pair? desig) (ns-desig->name (car desig)) (chez-current-ns)))
|
||||
(m (jolt-hash-map)))
|
||||
(vector-for-each
|
||||
(lambda (k)
|
||||
(when (string=? (car k) cns)
|
||||
(set! m (jolt-assoc m (jolt-symbol #f (cdr k))
|
||||
(intern-ns! (hashtable-ref ns-alias-table k #f))))))
|
||||
(hashtable-keys ns-alias-table))
|
||||
m))
|
||||
|
||||
;; ns-refers (jolt-cf1q.7): the {sym -> var} referred into `desig` via refer/use.
|
||||
(define (jolt-ns-refers desig)
|
||||
(let ((cns (ns-desig->name desig)) (m (jolt-hash-map)))
|
||||
(vector-for-each
|
||||
(lambda (k)
|
||||
(when (string=? (car k) cns)
|
||||
(let* ((target (hashtable-ref ns-refer-table k #f))
|
||||
(c (and target (var-cell-lookup target (cdr k)))))
|
||||
(when c (set! m (jolt-assoc m (jolt-symbol #f (cdr k)) c))))))
|
||||
(hashtable-keys ns-refer-table))
|
||||
m))
|
||||
|
||||
;; ns-imports: clojure.core auto-imports the 96 public java.lang classes into
|
||||
;; every ns. jolt has no classloader, but returns that map (short symbol ->
|
||||
;; canonical class-name token) so (count (ns-imports 'user)) = 96 like the JVM.
|
||||
(define jolt-default-import-names
|
||||
'("AbstractMethodError" "Appendable" "ArithmeticException" "ArrayIndexOutOfBoundsException"
|
||||
"ArrayStoreException" "AssertionError" "BigDecimal" "BigInteger" "Boolean" "Byte"
|
||||
"Callable" "CharSequence" "Character" "Class" "ClassCastException" "ClassCircularityError"
|
||||
"ClassFormatError" "ClassLoader" "ClassNotFoundException" "CloneNotSupportedException"
|
||||
"Cloneable" "Comparable" "Compiler" "Deprecated" "Double" "Enum"
|
||||
"EnumConstantNotPresentException" "Error" "Exception" "ExceptionInInitializerError" "Float"
|
||||
"IllegalAccessError" "IllegalAccessException" "IllegalArgumentException"
|
||||
"IllegalMonitorStateException" "IllegalStateException" "IllegalThreadStateException"
|
||||
"IncompatibleClassChangeError" "IndexOutOfBoundsException" "InheritableThreadLocal"
|
||||
"InstantiationError" "InstantiationException" "Integer" "InternalError" "InterruptedException"
|
||||
"Iterable" "LinkageError" "Long" "Math" "NegativeArraySizeException" "NoClassDefFoundError"
|
||||
"NoSuchFieldError" "NoSuchFieldException" "NoSuchMethodError" "NoSuchMethodException"
|
||||
"NullPointerException" "Number" "NumberFormatException" "Object" "OutOfMemoryError" "Override"
|
||||
"Package" "Process" "ProcessBuilder" "Readable" "Runnable" "Runtime" "RuntimeException"
|
||||
"RuntimePermission" "SecurityException" "SecurityManager" "Short" "StackOverflowError"
|
||||
"StackTraceElement" "StrictMath" "String" "StringBuffer" "StringBuilder"
|
||||
"StringIndexOutOfBoundsException" "SuppressWarnings" "System" "Thread" "Thread$State"
|
||||
"Thread$UncaughtExceptionHandler" "ThreadDeath" "ThreadGroup" "ThreadLocal" "Throwable"
|
||||
"TypeNotPresentException" "UnknownError" "UnsatisfiedLinkError" "UnsupportedClassVersionError"
|
||||
"UnsupportedOperationException" "VerifyError" "VirtualMachineError" "Void"))
|
||||
(define jolt-default-imports
|
||||
(let loop ((ns jolt-default-import-names) (m (jolt-hash-map)))
|
||||
(if (null? ns) m
|
||||
(loop (cdr ns)
|
||||
(jolt-assoc m (jolt-symbol #f (car ns)) (string-append "java.lang." (car ns)))))))
|
||||
(define (jolt-ns-imports . _) jolt-default-imports)
|
||||
|
||||
;; resolve: an unqualified symbol resolves in the current ns then clojure.core; a
|
||||
;; qualified one in its own ns. Returns the var iff genuinely defined, else nil —
|
||||
;; never interns an empty cell (var-cell-lookup is non-creating).
|
||||
(define (jolt-resolve sym)
|
||||
(let* ((sns (symbol-t-ns sym)) (nm (symbol-t-name sym))
|
||||
(c (if (string? sns)
|
||||
(var-cell-lookup sns nm)
|
||||
(or (var-cell-lookup (chez-current-ns) nm)
|
||||
(var-cell-lookup "clojure.core" nm)))))
|
||||
(if (and c (var-cell-defined? c)) c jolt-nil)))
|
||||
|
||||
(define (jolt-find-var sym)
|
||||
(let ((sns (symbol-t-ns sym)) (nm (symbol-t-name sym)))
|
||||
(if (string? sns)
|
||||
(let ((c (var-cell-lookup sns nm))) (if (and c (var-cell-defined? c)) c jolt-nil))
|
||||
(error #f "find-var requires a fully-qualified symbol" sym))))
|
||||
|
||||
;; ns-unmap: clear the mapping — drop defined? and reset the root to unbound, so a
|
||||
;; later resolve returns nil.
|
||||
(define (jolt-ns-unmap ns-desig sym)
|
||||
(let ((c (var-cell-lookup (ns-desig->name ns-desig) (symbol-t-name sym))))
|
||||
(when c (var-cell-defined?-set! c #f) (var-cell-root-set! c jolt-unbound)))
|
||||
jolt-nil)
|
||||
|
||||
;; --- ns runtime fns (jolt-cf1q.7) -------------------------------------------
|
||||
;; ns-resolve: resolve `sym` as if reading it in namespace `ns-desig`. Qualified
|
||||
;; syms consult that ns's :as aliases; unqualified resolve in the ns, its :refers,
|
||||
;; then clojure.core. Returns the var or nil (never interns).
|
||||
(define (jolt-ns-resolve ns-desig sym)
|
||||
(let* ((cns (ns-desig->name ns-desig))
|
||||
(sns (symbol-t-ns sym)) (nm (symbol-t-name sym))
|
||||
(c (if (string? sns)
|
||||
(var-cell-lookup (or (chez-resolve-alias cns sns) sns) nm)
|
||||
(or (var-cell-lookup cns nm)
|
||||
(let ((ref (chez-resolve-refer cns nm))) (and ref (var-cell-lookup ref nm)))
|
||||
(var-cell-lookup "clojure.core" nm)))))
|
||||
(if (and c (var-cell-defined? c)) c jolt-nil)))
|
||||
|
||||
;; remove-ns: drop the namespace from the registry AND its vars, so find-ns
|
||||
;; (which also derives existence from the var-table) returns nil afterward.
|
||||
(define (jolt-remove-ns desig)
|
||||
(let ((nm (ns-desig->name desig)))
|
||||
(hashtable-delete! ns-registry nm)
|
||||
(vector-for-each
|
||||
(lambda (k) (let ((c (hashtable-ref var-table k #f)))
|
||||
(when (and c (string=? (var-cell-ns c) nm)) (hashtable-delete! var-table k))))
|
||||
(hashtable-keys var-table))
|
||||
jolt-nil))
|
||||
|
||||
;; intern: create/set a var ns/sym to val (or an unbound cell). Returns the var.
|
||||
(define (jolt-intern ns-desig sym . vopt)
|
||||
(let ((nm (ns-desig->name ns-desig)) (s (symbol-t-name sym)))
|
||||
(if (pair? vopt) (def-var! nm s (car vopt)) (declare-var! nm s))))
|
||||
|
||||
;; alias / ns-unalias: register/drop an :as alias under the current (or given) ns.
|
||||
;; A runtime alias is registered into the SAME table the analyzer consults, so a
|
||||
;; later form in the program resolves alias/foo (the spine analyzes form by form).
|
||||
(define (jolt-alias alias-sym ns-sym)
|
||||
(chez-register-alias! (chez-current-ns) (symbol-t-name alias-sym) (ns-desig->name ns-sym))
|
||||
jolt-nil)
|
||||
(define (jolt-ns-unalias ns-desig alias-sym)
|
||||
(hashtable-delete! ns-alias-table (cons (ns-desig->name ns-desig) (symbol-t-name alias-sym)))
|
||||
jolt-nil)
|
||||
|
||||
;; refer: bring every public var of `ns-sym` into the current ns as an unqualified
|
||||
;; name (filters accepted/ignored — the corpus uses the bare form). refer-clojure
|
||||
;; is a no-op (clojure.core always resolves on Chez).
|
||||
(define (jolt-refer ns-sym . _filters)
|
||||
(let ((target (ns-desig->name ns-sym)) (cns (chez-current-ns)))
|
||||
(vector-for-each
|
||||
(lambda (c) (when (and (string=? (var-cell-ns c) target) (var-cell-defined? c))
|
||||
(chez-register-refer! cns (var-cell-name c) target)))
|
||||
(hashtable-values var-table))
|
||||
jolt-nil))
|
||||
(define (jolt-refer-clojure . _) jolt-nil)
|
||||
|
||||
;; alter-meta! / reset-meta!: update a var's metadata (var-meta-table, rt.ss).
|
||||
(define (jolt-alter-meta! ref f . args)
|
||||
(let* ((cur (or (hashtable-ref var-meta-table ref #f) (jolt-hash-map)))
|
||||
(new (apply jolt-invoke f cur args)))
|
||||
(hashtable-set! var-meta-table ref new)
|
||||
new))
|
||||
(define (jolt-reset-meta! ref m) (hashtable-set! var-meta-table ref m) m)
|
||||
|
||||
;; --- RESOLVE FRICTION: native-op cells -------------------------------------
|
||||
;; Native-op primitives (+ map reduce …) are INLINED at emit, so they have no
|
||||
;; var-cell and (resolve '+) would be nil — diverging from Clojure where it is a
|
||||
;; var. def-var! each to its value-position procedure so it has a real, defined
|
||||
;; cell (calls still inline, so no perf hit; #'+ deref and ((resolve '+) 1 2) also
|
||||
;; work now). The clojure.core prelude, loaded AFTER rt.ss, overwrites the cells
|
||||
;; for names it also defines in the overlay (map/filter/…); the purely-inlined
|
||||
;; scalars (+/-/</inc/…) keep these.
|
||||
(for-each
|
||||
(lambda (p) (def-var! "clojure.core" (car p) (cdr p)))
|
||||
(list
|
||||
(cons "+" jolt-add) (cons "-" jolt-sub) (cons "*" jolt-mul) (cons "/" jolt-div)
|
||||
(cons "<" <) (cons ">" >) (cons "<=" <=) (cons ">=" >=)
|
||||
(cons "=" jolt=) (cons "inc" jolt-inc) (cons "dec" jolt-dec) (cons "not" jolt-not)
|
||||
(cons "min" min) (cons "max" max)
|
||||
(cons "mod" modulo) (cons "rem" remainder) (cons "quot" quotient)
|
||||
(cons "vector" jolt-vector) (cons "hash-map" jolt-hash-map) (cons "hash-set" jolt-hash-set)
|
||||
(cons "conj" jolt-conj) (cons "get" jolt-get) (cons "nth" jolt-nth) (cons "count" jolt-count)
|
||||
(cons "assoc" jolt-assoc) (cons "dissoc" jolt-dissoc) (cons "contains?" jolt-contains?)
|
||||
(cons "empty?" jolt-empty?) (cons "peek" jolt-peek) (cons "pop" jolt-pop)
|
||||
(cons "first" jolt-first) (cons "rest" jolt-rest) (cons "next" jolt-next) (cons "seq" jolt-seq)
|
||||
(cons "cons" jolt-cons) (cons "list" jolt-list) (cons "reverse" jolt-reverse) (cons "last" jolt-last)
|
||||
(cons "map" jolt-map) (cons "filter" jolt-filter) (cons "remove" jolt-remove)
|
||||
(cons "reduce" jolt-reduce) (cons "into" jolt-into) (cons "concat" jolt-concat) (cons "apply" jolt-apply)
|
||||
(cons "range" jolt-range) (cons "take" jolt-take) (cons "drop" jolt-drop)
|
||||
(cons "keys" jolt-keys) (cons "vals" jolt-vals)
|
||||
(cons "even?" jolt-even?) (cons "odd?" jolt-odd?) (cons "pos?" jolt-pos?) (cons "neg?" jolt-neg?)
|
||||
(cons "zero?" jolt-zero?) (cons "identity" jolt-identity)
|
||||
(cons "ex-info" jolt-ex-info)))
|
||||
|
||||
;; --- bindings + *ns* --------------------------------------------------------
|
||||
(def-var! "clojure.core" "find-ns" jolt-find-ns)
|
||||
(def-var! "clojure.core" "the-ns" jolt-the-ns)
|
||||
(def-var! "clojure.core" "create-ns" jolt-create-ns)
|
||||
(def-var! "clojure.core" "in-ns" jolt-in-ns)
|
||||
(def-var! "clojure.core" "all-ns" jolt-all-ns)
|
||||
(def-var! "clojure.core" "ns-publics" jolt-ns-publics)
|
||||
(def-var! "clojure.core" "ns-map" jolt-ns-publics)
|
||||
(def-var! "clojure.core" "ns-interns" jolt-ns-publics)
|
||||
(def-var! "clojure.core" "ns-aliases" jolt-ns-aliases)
|
||||
(def-var! "clojure.core" "ns-refers" jolt-ns-refers)
|
||||
(def-var! "clojure.core" "ns-imports" jolt-ns-imports)
|
||||
(def-var! "clojure.core" "resolve" jolt-resolve)
|
||||
(def-var! "clojure.core" "ns-resolve" jolt-ns-resolve)
|
||||
(def-var! "clojure.core" "find-var" jolt-find-var)
|
||||
(def-var! "clojure.core" "ns-unmap" jolt-ns-unmap)
|
||||
(def-var! "clojure.core" "remove-ns" jolt-remove-ns)
|
||||
(def-var! "clojure.core" "intern" jolt-intern)
|
||||
(def-var! "clojure.core" "alias" jolt-alias)
|
||||
(def-var! "clojure.core" "ns-unalias" jolt-ns-unalias)
|
||||
(def-var! "clojure.core" "refer" jolt-refer)
|
||||
(def-var! "clojure.core" "refer-clojure" jolt-refer-clojure)
|
||||
(def-var! "clojure.core" "alter-meta!" jolt-alter-meta!)
|
||||
(def-var! "clojure.core" "reset-meta!" jolt-reset-meta!)
|
||||
;; *ns* starts at the user namespace (the current ns for -e user code). in-ns
|
||||
;; re-binds it. (ns-name is overridden natively in post-prelude.ss.)
|
||||
(def-var! "clojure.core" "*ns*" (intern-ns! "user"))
|
||||
|
||||
;; --- printer patches: a namespace renders as its name (str / pr-str / -e) ----
|
||||
(define %ns-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (jns? x) (jns-name x) (%ns-pr-str x))))
|
||||
(define %ns-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (jns? x) (jns-name x) (%ns-pr-readable x))))
|
||||
(define %ns-str-render-one jolt-str-render-one)
|
||||
(set! jolt-str-render-one (lambda (x) (if (jns? x) (jns-name x) (%ns-str-render-one x))))
|
||||
122
host/chez/png.ss
Normal file
122
host/chez/png.ss
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
;; png.ss (jolt-90sp) — jolt.png: a minimal PNG writer, the built-in the
|
||||
;; ray-tracer-multi example renders through. Truecolor (8-bit RGB), no
|
||||
;; compression: the IDAT zlib stream uses DEFLATE "stored" (uncompressed) blocks,
|
||||
;; so there is no compressor to carry — just CRC-32 / Adler-32 framing over Chez
|
||||
;; bytevectors. def-var!'d into the jolt.png namespace, so a (require '[jolt.png])
|
||||
;; resolves it as a baked namespace (no source file).
|
||||
|
||||
;; --- CRC-32 (PNG chunk checksum) --------------------------------------------
|
||||
(define png-crc-table
|
||||
(let ((t (make-vector 256)))
|
||||
(do ((n 0 (+ n 1))) ((= n 256) t)
|
||||
(let loop ((c n) (k 0))
|
||||
(if (= k 8)
|
||||
(vector-set! t n c)
|
||||
(loop (if (odd? c) (bitwise-xor #xedb88320 (bitwise-arithmetic-shift-right c 1))
|
||||
(bitwise-arithmetic-shift-right c 1))
|
||||
(+ k 1)))))))
|
||||
(define (png-crc32 bv)
|
||||
(let ((len (bytevector-length bv)))
|
||||
(let loop ((i 0) (c #xffffffff))
|
||||
(if (= i len)
|
||||
(bitwise-xor c #xffffffff)
|
||||
(loop (+ i 1)
|
||||
(bitwise-xor (bitwise-arithmetic-shift-right c 8)
|
||||
(vector-ref png-crc-table
|
||||
(bitwise-and (bitwise-xor c (bytevector-u8-ref bv i)) #xff))))))))
|
||||
|
||||
;; --- Adler-32 (zlib checksum) -----------------------------------------------
|
||||
(define (png-adler32 bv)
|
||||
(let ((len (bytevector-length bv)))
|
||||
(let loop ((i 0) (a 1) (b 0))
|
||||
(if (= i len)
|
||||
(bitwise-ior (bitwise-arithmetic-shift-left b 16) a)
|
||||
(let ((a* (modulo (+ a (bytevector-u8-ref bv i)) 65521)))
|
||||
(loop (+ i 1) a* (modulo (+ b a*) 65521)))))))
|
||||
|
||||
;; --- byte helpers -----------------------------------------------------------
|
||||
(define (png-u32be n)
|
||||
(let ((bv (make-bytevector 4)))
|
||||
(bytevector-u8-set! bv 0 (bitwise-and (bitwise-arithmetic-shift-right n 24) #xff))
|
||||
(bytevector-u8-set! bv 1 (bitwise-and (bitwise-arithmetic-shift-right n 16) #xff))
|
||||
(bytevector-u8-set! bv 2 (bitwise-and (bitwise-arithmetic-shift-right n 8) #xff))
|
||||
(bytevector-u8-set! bv 3 (bitwise-and n #xff))
|
||||
bv))
|
||||
(define (png-bytes . bs) (u8-list->bytevector bs))
|
||||
(define (png-cat . bvs)
|
||||
(let* ((total (apply + (map bytevector-length bvs)))
|
||||
(out (make-bytevector total)))
|
||||
(let loop ((bvs bvs) (off 0))
|
||||
(if (null? bvs) out
|
||||
(let ((n (bytevector-length (car bvs))))
|
||||
(bytevector-copy! (car bvs) 0 out off n)
|
||||
(loop (cdr bvs) (+ off n)))))))
|
||||
|
||||
;; one PNG chunk: length(4) + type(4) + data + crc32(type+data)(4)
|
||||
(define (png-chunk type-str data)
|
||||
(let ((type (string->utf8 type-str)))
|
||||
(png-cat (png-u32be (bytevector-length data)) type data
|
||||
(png-u32be (png-crc32 (png-cat type data))))))
|
||||
|
||||
;; DEFLATE "stored" stream of raw: ≤65535-byte blocks, each 1 header byte
|
||||
;; (BFINAL bit) + LEN(2 LE) + NLEN(2 LE) + raw. Wrapped as zlib (0x78 0x01 …
|
||||
;; adler32).
|
||||
(define (png-deflate-stored raw)
|
||||
(let ((len (bytevector-length raw)))
|
||||
(let loop ((off 0) (acc (list (png-bytes #x78 #x01))))
|
||||
(if (>= off len)
|
||||
(apply png-cat (reverse (cons (png-u32be (png-adler32 raw)) acc)))
|
||||
(let* ((n (min 65535 (- len off)))
|
||||
(final (if (>= (+ off n) len) 1 0))
|
||||
(block (png-cat (png-bytes final)
|
||||
(png-bytes (bitwise-and n #xff) (bitwise-arithmetic-shift-right n 8))
|
||||
(png-bytes (bitwise-and (bitwise-not n) #xff)
|
||||
(bitwise-and (bitwise-arithmetic-shift-right (bitwise-not n) 8) #xff))
|
||||
(let ((b (make-bytevector n))) (bytevector-copy! raw off b 0 n) b))))
|
||||
(loop (+ off n) (cons block acc)))))))
|
||||
|
||||
;; --- the image value --------------------------------------------------------
|
||||
(define-record-type pimg (fields w h data (mutable cur)) (nongenerative jolt-png-img-v1))
|
||||
(define (png-clamp-byte n)
|
||||
(let ((x (cond ((and (number? n) (exact? n) (integer? n)) n)
|
||||
((number? n) (exact (floor n)))
|
||||
(else 0))))
|
||||
(cond ((< x 0) 0) ((> x 255) 255) (else x))))
|
||||
|
||||
(define (png-image w h) (make-pimg w h (make-bytevector (* w h 3) 0) 0))
|
||||
(define (png-put! img r g b)
|
||||
(let ((d (pimg-data img)) (c (pimg-cur img)))
|
||||
(when (<= (+ c 3) (bytevector-length d))
|
||||
(bytevector-u8-set! d c (png-clamp-byte r))
|
||||
(bytevector-u8-set! d (+ c 1) (png-clamp-byte g))
|
||||
(bytevector-u8-set! d (+ c 2) (png-clamp-byte b))
|
||||
(pimg-cur-set! img (+ c 3)))
|
||||
jolt-nil))
|
||||
|
||||
;; scanlines with a 0 (None) filter byte per row -> raw -> zlib -> IDAT
|
||||
(define (png-raw img w h)
|
||||
(let* ((stride (* w 3)) (raw (make-bytevector (* h (+ 1 stride)))) (src (pimg-data img)))
|
||||
(do ((y 0 (+ y 1))) ((= y h) raw)
|
||||
(let ((ro (* y (+ 1 stride))))
|
||||
(bytevector-u8-set! raw ro 0) ; filter: None
|
||||
(bytevector-copy! src (* y stride) raw (+ ro 1) stride)))))
|
||||
|
||||
(define png-signature (png-bytes #x89 #x50 #x4e #x47 #x0d #x0a #x1a #x0a))
|
||||
(define (png-ihdr w h)
|
||||
(png-cat (png-u32be w) (png-u32be h)
|
||||
(png-bytes 8 2 0 0 0))) ; bitdepth 8, colortype 2 (RGB), deflate, filter 0, no interlace
|
||||
|
||||
(define (png-write img w h path)
|
||||
(let* ((idat (png-deflate-stored (png-raw img w h)))
|
||||
(bytes (png-cat png-signature
|
||||
(png-chunk "IHDR" (png-ihdr w h))
|
||||
(png-chunk "IDAT" idat)
|
||||
(png-chunk "IEND" (make-bytevector 0))))
|
||||
(p (open-file-output-port path (file-options no-fail) (buffer-mode block))))
|
||||
(put-bytevector p bytes)
|
||||
(close-port p)
|
||||
jolt-nil))
|
||||
|
||||
(def-var! "jolt.png" "image" png-image)
|
||||
(def-var! "jolt.png" "put!" png-put!)
|
||||
(def-var! "jolt.png" "write" png-write)
|
||||
99
host/chez/post-prelude.ss
Normal file
99
host/chez/post-prelude.ss
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
;; post-prelude overrides (jolt-9ziu) — loaded AFTER the assembled clojure.core
|
||||
;; prelude, so these win over the overlay's own def-var!.
|
||||
;;
|
||||
;; A few clojure.core predicates are implemented in the overlay by inspecting a
|
||||
;; Janet-host tagged value's :jolt/type key (e.g. (get x :jolt/type)). That key
|
||||
;; doesn't exist for Chez-native representations: a jolt char is a Scheme char,
|
||||
;; an atom is a Chez record. The overlay's def-var! loads after rt.ss, so it
|
||||
;; clobbers the correct native shims (predicates.ss / atoms.ss) with versions
|
||||
;; that return false on every Chez value. Re-assert the native versions here.
|
||||
;;
|
||||
;; (Long-term these predicates want a host-neutral implementation that calls a
|
||||
;; host primitive instead of reading :jolt/type; until then this is the Chez-host
|
||||
;; override.)
|
||||
(def-var! "clojure.core" "char?" jolt-char-pred?)
|
||||
(def-var! "clojure.core" "atom?" jolt-atom?)
|
||||
;; atom watches/validators: the overlay drives these via jolt.host/ref-put! on a
|
||||
;; Janet table (get a :watches), which a Chez atom record is not — re-assert the
|
||||
;; native versions (defined in atoms.ss), and swap!/reset! notify+validate there.
|
||||
(def-var! "clojure.core" "add-watch" jolt-add-watch)
|
||||
(def-var! "clojure.core" "remove-watch" jolt-remove-watch)
|
||||
(def-var! "clojure.core" "set-validator!" jolt-set-validator!)
|
||||
(def-var! "clojure.core" "get-validator" jolt-get-validator)
|
||||
;; volatiles: a Chez volatile is a jvol record, but the overlay vreset!/vswap!/
|
||||
;; volatile? drive it via jolt.host/ref-put!+get / :jolt/type (tagged-table only).
|
||||
;; Override with the native versions (defined in natives-xform.ss).
|
||||
(def-var! "clojure.core" "vreset!" jolt-vreset!)
|
||||
(def-var! "clojure.core" "vswap!" jolt-vswap!)
|
||||
(def-var! "clojure.core" "volatile?" jolt-volatile-pred?)
|
||||
;; bound?: the overlay reads (get v :root) — nil on a Chez var-cell record, so it
|
||||
;; would wrongly report every var unbound. Native version (defined in vars.ss).
|
||||
(def-var! "clojure.core" "bound?" jolt-bound?)
|
||||
;; uuid?/random-uuid/parse-uuid/tagged-literal? are overlay (read :jolt/type or
|
||||
;; build tagged tables) — re-assert the native versions (defined in natives-misc.ss).
|
||||
(def-var! "clojure.core" "uuid?" jolt-uuid-pred?)
|
||||
(def-var! "clojure.core" "random-uuid" jolt-random-uuid)
|
||||
(def-var! "clojure.core" "parse-uuid" jolt-parse-uuid)
|
||||
(def-var! "clojure.core" "tagged-literal?" jolt-tagged-literal-pred?)
|
||||
;; ns-name: the overlay reads (get ns :name) — nil on a jns namespace record.
|
||||
;; Native version (defined in ns.ss) returns the namespace's name symbol.
|
||||
(def-var! "clojure.core" "ns-name" jolt-ns-name)
|
||||
;; concurrency (jolt-byjr): the overlay's future-done?/future-cancelled?/realized?
|
||||
;; read a Janet future-map's :cached/:cancelled keys, and promise/deliver are a
|
||||
;; non-blocking atom shim. A Chez future/promise is a record, and we want JVM
|
||||
;; (blocking, shared-heap) semantics — re-assert the native versions. realized?
|
||||
;; wraps the overlay (which still handles delay/lazy-seq/atom) for non-futures.
|
||||
(def-var! "clojure.core" "future-done?" jolt-native-future-done?)
|
||||
(def-var! "clojure.core" "future-cancelled?" jolt-native-future-cancelled?)
|
||||
(def-var! "clojure.core" "future?" jolt-future?)
|
||||
(def-var! "clojure.core" "promise" jolt-promise-new)
|
||||
(def-var! "clojure.core" "deliver" jolt-deliver)
|
||||
;; agents: the overlay (50-io) is a synchronous shim (agent = atom, send applies
|
||||
;; immediately). Re-assert the native async agents (per-agent serialized worker),
|
||||
;; matching the JVM. await/restart-agent are new (the overlay has neither).
|
||||
(def-var! "clojure.core" "agent" jolt-agent-new)
|
||||
(def-var! "clojure.core" "agent?" jolt-agent?)
|
||||
(def-var! "clojure.core" "send" jolt-agent-send)
|
||||
(def-var! "clojure.core" "send-off" jolt-agent-send)
|
||||
(def-var! "clojure.core" "await" jolt-agent-await)
|
||||
(def-var! "clojure.core" "agent-error" jolt-agent-error)
|
||||
(def-var! "clojure.core" "restart-agent" jolt-agent-restart)
|
||||
(def-var! "clojure.core" "deref" jolt-deref)
|
||||
(let ((overlay-realized? (var-deref "clojure.core" "realized?")))
|
||||
(def-var! "clojure.core" "realized?"
|
||||
(lambda (x)
|
||||
(cond
|
||||
((or (jolt-future? x) (jolt-promise? x) (jolt-delay? x)) (jolt-conc-realized? x))
|
||||
;; a lazy-seq carries its own realized? flag (lazy-bridge.ss). The overlay
|
||||
;; realized? reads :jolt/type and throws on a jolt-lazyseq record.
|
||||
((jolt-lazyseq? x) (jolt-lazyseq-realized? x))
|
||||
(else (jolt-invoke overlay-realized? x))))))
|
||||
;; clojure.edn/read over a reader: the overlay edn.clj drain-reader uses janet/type;
|
||||
;; the native Chez version (io.ss) drains the jhost reader instead (jolt-uicd/jolt-7t3l).
|
||||
(def-var! "clojure.edn" "read"
|
||||
(case-lambda
|
||||
((reader) (chez-edn-read reader))
|
||||
((opts reader) (chez-edn-read reader))))
|
||||
;; line-seq: a jhost reader (io/reader result) -> drain+split; a map-reader (the
|
||||
;; overlay's :read-line-fn model, e.g. with-in-str) -> the overlay version.
|
||||
(let ((overlay-line-seq (var-deref "clojure.core" "line-seq")))
|
||||
(def-var! "clojure.core" "line-seq"
|
||||
(lambda (rdr)
|
||||
(if (reader-jhost? rdr) (chez-line-seq rdr) (jolt-invoke overlay-line-seq rdr)))))
|
||||
;; JVM-parity numeric tower (jolt-n6al): the overlay (20-coll.clj) carries an
|
||||
;; all-flonum number-predicate web with no Ratio concept (ratio? -> false,
|
||||
;; double? -> not-integer, float? -> double?, rational? -> int?), which
|
||||
;; misclassifies exact rationals on the Chez tower (e.g. (double? 1/2) -> true).
|
||||
;; Re-assert the native tower-correct versions (predicates.ss) so they win over
|
||||
;; the overlay defs. int?/double? alias integer?/float?. == is value-equality.
|
||||
(def-var! "clojure.core" "integer?" jolt-integer?)
|
||||
(def-var! "clojure.core" "int?" jolt-integer?)
|
||||
(def-var! "clojure.core" "float?" jolt-float?)
|
||||
(def-var! "clojure.core" "double?" jolt-float?)
|
||||
(def-var! "clojure.core" "ratio?" jolt-ratio?)
|
||||
(def-var! "clojure.core" "rational?" jolt-rational?)
|
||||
(def-var! "clojure.core" "decimal?" jolt-decimal?)
|
||||
(def-var! "clojure.core" "==" jolt-num-equiv)
|
||||
;; chunked-seq? is true for a vector's seq (a real chunked-seq); the overlay's
|
||||
;; always-false stub loaded over the host fn, so re-assert it (jolt-hs5q).
|
||||
(def-var! "clojure.core" "chunked-seq?" na-chunked-seq?)
|
||||
91
host/chez/predicates.ss
Normal file
91
host/chez/predicates.ss
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
;; type predicates + simple accessors (jolt-9ziu) — host-coupled natives.
|
||||
;;
|
||||
;; These are host primitives (not clojure.core overlay fns), so they're never
|
||||
;; def-var!'d by the assembled prelude; the Chez host must provide them.
|
||||
;; map?/vector?/set? are STRICT
|
||||
;; over the persistent-collection records, seq? is true only for real sequences,
|
||||
;; coll? is the union. Records (shape-recs) are Phase 2, so the record arms of the
|
||||
;; predicates are simply absent here for now.
|
||||
|
||||
(define (jolt-map? x) (pmap? x))
|
||||
;; a map entry is a pvec under the hood AND is vector? — Clojure's MapEntry
|
||||
;; implements IPersistentVector, so (vector? (first {:a 1})) is true
|
||||
;; (jolt-75sv corrected the earlier exclusion).
|
||||
(define (jolt-vector? x) (pvec? x))
|
||||
(define (jolt-set? x) (pset? x))
|
||||
(define (jolt-seq? x) (or (cseq? x) (empty-list-t? x)))
|
||||
;; (list? x): a list-marked cseq node or the empty list (). A lazy/vector-backed
|
||||
;; seq, (rest list), (seq coll), (map …) are seqs but not lists (jolt-75sv).
|
||||
(define (jolt-list-pred? x) (or (and (cseq? x) (cseq-list? x)) (empty-list-t? x)))
|
||||
(define (jolt-coll-pred? x)
|
||||
(or (pvec? x) (pmap? x) (pset? x) (cseq? x) (empty-list-t? x)))
|
||||
(define (jolt-number? x) (number? x))
|
||||
(define (jolt-string? x) (string? x))
|
||||
(define (jolt-char-pred? x) (char? x))
|
||||
;; JVM-parity number-type predicates over the Chez numeric tower. integer? is the
|
||||
;; INTEGER TYPE (exact integer = Long/BigInt), NOT integer-VALUED: (integer? 3.0)
|
||||
;; is false on the JVM (3.0 is a Double). float? = flonum (double). ratio? = exact
|
||||
;; non-integer (= JVM Ratio). rational? = exact (integer or ratio; jolt has no
|
||||
;; BigDecimal). decimal? is always false (no BigDecimal type).
|
||||
(define (jolt-integer? x) (and (number? x) (exact? x) (integer? x)))
|
||||
(define (jolt-float? x) (and (number? x) (flonum? x)))
|
||||
(define (jolt-ratio? x) (and (number? x) (exact? x) (rational? x) (not (integer? x))))
|
||||
(define (jolt-rational? x) (and (number? x) (exact? x)))
|
||||
(define (jolt-decimal? x) #f)
|
||||
(define (jolt-fn? x) (procedure? x))
|
||||
(define (jolt-boolean-pred? x) (boolean? x))
|
||||
|
||||
;; (boolean x) coerces truthiness (nil/false -> false, else true).
|
||||
(define (jolt-boolean x) (if (jolt-truthy? x) #t #f))
|
||||
|
||||
;; (name x): keyword/symbol -> name string; string -> itself.
|
||||
(define (jolt-name x)
|
||||
(cond
|
||||
((keyword? x) (keyword-t-name x))
|
||||
((symbol-t? x) (symbol-t-name x))
|
||||
((string? x) x)
|
||||
(else (error #f "name: expected string/symbol/keyword" x))))
|
||||
|
||||
;; (namespace x): keyword/symbol ns string, or nil when unqualified.
|
||||
(define (jolt-namespace x)
|
||||
(let ((ns (cond ((keyword? x) (keyword-t-ns x))
|
||||
((symbol-t? x) (symbol-t-ns x))
|
||||
(else (error #f "namespace: expected symbol/keyword" x)))))
|
||||
(if (or (jolt-nil? ns) (not ns) (eq? ns '())) jolt-nil ns)))
|
||||
|
||||
(def-var! "clojure.core" "nil?" jolt-nil?)
|
||||
(def-var! "clojure.core" "number?" jolt-number?)
|
||||
(def-var! "clojure.core" "string?" jolt-string?)
|
||||
(def-var! "clojure.core" "char?" jolt-char-pred?)
|
||||
(def-var! "clojure.core" "integer?" jolt-integer?)
|
||||
(def-var! "clojure.core" "float?" jolt-float?)
|
||||
(def-var! "clojure.core" "ratio?" jolt-ratio?)
|
||||
(def-var! "clojure.core" "rational?" jolt-rational?)
|
||||
(def-var! "clojure.core" "decimal?" jolt-decimal?)
|
||||
;; == numeric value-equality (ignores exactness, unlike =): (== 3 3.0) -> true.
|
||||
;; 1-arity is trivially true; 2+ args must all be numbers (Numbers.equiv throws
|
||||
;; otherwise). Uses Scheme = (value across the tower), not jolt= (category-aware).
|
||||
(define (jolt-num-equiv . xs)
|
||||
;; 1-arity short-circuits to true for ANY value (Clojure's == 1-arg returns true
|
||||
;; before the number check); 2+ args must all be numbers.
|
||||
(if (and (pair? xs) (null? (cdr xs)))
|
||||
#t
|
||||
(let all-num? ((ys xs))
|
||||
(cond
|
||||
((null? ys) (or (null? xs) (apply = xs)))
|
||||
((number? (car ys)) (all-num? (cdr ys)))
|
||||
(else (error #f "== requires numbers" xs))))))
|
||||
(def-var! "clojure.core" "==" jolt-num-equiv)
|
||||
(def-var! "clojure.core" "symbol?" jolt-symbol?)
|
||||
(def-var! "clojure.core" "keyword?" keyword?)
|
||||
(def-var! "clojure.core" "map?" jolt-map?)
|
||||
(def-var! "clojure.core" "vector?" jolt-vector?)
|
||||
(def-var! "clojure.core" "set?" jolt-set?)
|
||||
(def-var! "clojure.core" "seq?" jolt-seq?)
|
||||
(def-var! "clojure.core" "list?" jolt-list-pred?)
|
||||
(def-var! "clojure.core" "coll?" jolt-coll-pred?)
|
||||
(def-var! "clojure.core" "fn?" jolt-fn?)
|
||||
(def-var! "clojure.core" "boolean?" jolt-boolean-pred?)
|
||||
(def-var! "clojure.core" "boolean" jolt-boolean)
|
||||
(def-var! "clojure.core" "name" jolt-name)
|
||||
(def-var! "clojure.core" "namespace" jolt-namespace)
|
||||
84
host/chez/printing.ss
Normal file
84
host/chez/printing.ss
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
;; readable printer + output seams (jolt-cf1q.3 Phase 2 inc B) — the __pr-str1 /
|
||||
;; __write / __with-out-str host seams the overlay's pr-str/pr/prn/print/println/
|
||||
;; *-str family is built on (jolt-core/clojure/core/20-coll.clj). They resolved to
|
||||
;; jolt-nil, so the whole print family hit the apply-jolt-nil crash bucket.
|
||||
;;
|
||||
;; jolt-pr-str (rt.ss) is STR-style: strings render raw. pr-str needs READABLE
|
||||
;; (pr) style: strings quoted+escaped at every nesting level. This adds the
|
||||
;; readable renderer; it mirrors jolt-pr-str but quotes strings and recurses into
|
||||
;; itself, delegating scalars (nil/bool/number/keyword/symbol/char/regex) to
|
||||
;; jolt-pr-str (already readable for those). The canonical ORDERED printer is
|
||||
;; still future work — unordered colls render in HAMT order, compared via `=`.
|
||||
|
||||
;; inner string escape (no surrounding quotes): " \ newline tab return.
|
||||
(define (jolt-str-escape s)
|
||||
(let loop ((cs (string->list s)) (acc '()))
|
||||
(if (null? cs)
|
||||
(list->string (reverse acc))
|
||||
(loop (cdr cs)
|
||||
(let ((c (car cs)))
|
||||
(case c
|
||||
((#\") (cons #\" (cons #\\ acc)))
|
||||
((#\\) (cons #\\ (cons #\\ acc)))
|
||||
((#\newline) (cons #\n (cons #\\ acc)))
|
||||
((#\tab) (cons #\t (cons #\\ acc)))
|
||||
((#\return) (cons #\r (cons #\\ acc)))
|
||||
(else (cons c acc))))))))
|
||||
|
||||
(define (jolt-pr-readable x)
|
||||
(cond
|
||||
((string? x) (string-append "\"" (jolt-str-escape x) "\""))
|
||||
;; pr renders the infinities / NaN in READABLE form (##Inf reads back), unlike
|
||||
;; str's "Infinity"/"-Infinity"/"NaN". Applies at every nesting level.
|
||||
((and (flonum? x) (fl= x +inf.0)) "##Inf")
|
||||
((and (flonum? x) (fl= x -inf.0)) "##-Inf")
|
||||
((and (flonum? x) (not (fl= x x))) "##NaN")
|
||||
;; transients print as a cold tagged type (print-method routes this through a
|
||||
;; multimethod; the readable fallback renders it directly).
|
||||
;; forward refs to transients.ss (loaded later) — resolved at call time.
|
||||
((jolt-transient? x)
|
||||
(case (jolt-transient-kind x)
|
||||
((vec) "#<transient vector>") ((set) "#<transient set>") (else "#<transient map>")))
|
||||
((pvec? x)
|
||||
(let ((acc '()))
|
||||
(let loop ((i (fx- (pvec-count x) 1)))
|
||||
(when (fx>=? i 0)
|
||||
(set! acc (cons (jolt-pr-readable (pvec-nth-d x i jolt-nil)) acc))
|
||||
(loop (fx- i 1))))
|
||||
(string-append "[" (jolt-str-join acc) "]")))
|
||||
((pset? x)
|
||||
(string-append "#{" (jolt-str-join (pset-fold x (lambda (e a) (cons (jolt-pr-readable e) a)) '())) "}"))
|
||||
((pmap? x)
|
||||
(string-append "{" (jolt-str-join
|
||||
(pmap-fold x (lambda (k v a)
|
||||
(cons (string-append (jolt-pr-readable k) " " (jolt-pr-readable v)) a)) '())) "}"))
|
||||
((empty-list-t? x) "()")
|
||||
((cseq? x)
|
||||
(string-append "(" (jolt-str-join
|
||||
(let loop ((s x) (acc '()))
|
||||
(if (jolt-nil? s) (reverse acc)
|
||||
(loop (jolt-seq (seq-more s)) (cons (jolt-pr-readable (seq-first s)) acc))))) ")"))
|
||||
(else (jolt-pr-str x))))
|
||||
|
||||
;; __pr-str1: render ONE value readably (the overlay's pr-str joins these).
|
||||
(define (jolt-pr-str1 x) (jolt-pr-readable x))
|
||||
|
||||
;; __write: push a string to *out* (current-output-port, so __with-out-str's
|
||||
;; redirect captures it). Returns nil.
|
||||
(define (jolt-write s) (display s) jolt-nil)
|
||||
|
||||
;; __with-out-str: run a jolt thunk with *out* rebound to a string port, return
|
||||
;; the captured text.
|
||||
(define (jolt-with-out-str thunk)
|
||||
(with-output-to-string (lambda () (jolt-invoke thunk))))
|
||||
|
||||
;; __eprint / __eprintf: stderr seams.
|
||||
(define (jolt-eprint s) (display s (current-error-port)) jolt-nil)
|
||||
(define (jolt-eprintf fmt . args)
|
||||
(apply fprintf (current-error-port) fmt args) jolt-nil)
|
||||
|
||||
(def-var! "clojure.core" "__pr-str1" jolt-pr-str1)
|
||||
(def-var! "clojure.core" "__write" jolt-write)
|
||||
(def-var! "clojure.core" "__with-out-str" jolt-with-out-str)
|
||||
(def-var! "clojure.core" "__eprint" jolt-eprint)
|
||||
(def-var! "clojure.core" "__eprintf" jolt-eprintf)
|
||||
550
host/chez/reader.ss
Normal file
550
host/chez/reader.ss
Normal file
|
|
@ -0,0 +1,550 @@
|
|||
;; Chez-side Clojure data reader (jolt-r8ku, inc Y).
|
||||
;;
|
||||
;; The data half of runtime read/eval: a recursive-descent reader that parses
|
||||
;; ONE Clojure form off a string and produces jolt runtime values
|
||||
;; (the analyzer/eval half — eval, load-string,
|
||||
;; runtime defmacro — stays Phase-3, it needs the compiler at runtime). Two host
|
||||
;; seams hang off it:
|
||||
;; read-string : string -> first form (clojure.core seam, src 772)
|
||||
;; __parse-next : string -> [form rest] | nil (the *in* family seam, src 801)
|
||||
;; read / read+string / with-in-str / line-seq / clojure.edn are Clojure over
|
||||
;; these (jolt-core/clojure/core/50-io.clj, src/jolt/clojure/edn.clj).
|
||||
;;
|
||||
;; Form shapes:
|
||||
;; sets -> {:jolt/type :jolt/set :value [...]} (a FORM, not a set)
|
||||
;; #tag frm -> {:jolt/type :jolt/tagged :tag :#tag :form ...} (NO data reader)
|
||||
;; #"src" -> {:jolt/type :jolt/tagged :tag :regex :form "src"}
|
||||
;; 'x `x ~x ~@x @x -> (quote x)/(syntax-quote x)/(unquote x)/
|
||||
;; (unquote-splicing x)/(clojure.core/deref x)
|
||||
;; ^meta sym -> symbol carrying meta ({:tag "Name"} | {:kw true} | the map)
|
||||
;; read-string of blank / comment-only input is nil (the documented seed wart),
|
||||
;; NOT an EOF throw.
|
||||
|
||||
;; Reader forms reuse these interned keywords for their tag structure.
|
||||
(define rdr-kw-jolt-type (keyword "jolt" "type"))
|
||||
(define rdr-kw-jolt-set (keyword "jolt" "set"))
|
||||
(define rdr-kw-jolt-tagged (keyword "jolt" "tagged"))
|
||||
(define rdr-kw-value (keyword #f "value"))
|
||||
(define rdr-kw-tag (keyword #f "tag"))
|
||||
(define rdr-kw-form (keyword #f "form"))
|
||||
|
||||
;; A unique sentinel meaning "no form here" (EOF, or a close delimiter that the
|
||||
;; caller — read-seq — must consume). Never a legal jolt value, so unambiguous.
|
||||
(define rdr-eof (list 'reader-eof))
|
||||
(define (rdr-eof? x) (eq? x rdr-eof))
|
||||
|
||||
;; A splicing reader conditional #?@(...) yields this wrapper; the enclosing
|
||||
;; sequence reader splices its items in place (never a legal jolt value).
|
||||
(define-record-type rdr-splice-t (fields items) (nongenerative rdr-splice-v1))
|
||||
|
||||
(define (rdr-ws? c)
|
||||
(or (char-whitespace? c) (char=? c #\,)))
|
||||
|
||||
;; `'` (apostrophe) is a NON-terminating macro char in Clojure (isTerminatingMacro
|
||||
;; is false for it), so it's a valid symbol constituent after the first char:
|
||||
;; inc'/+'/foo' read as single symbols. A LEADING ' still dispatches as quote
|
||||
;; (handled before token reading begins). Omit it from the terminator set.
|
||||
(define (rdr-terminator? c)
|
||||
(or (rdr-ws? c)
|
||||
(memv c '(#\( #\) #\[ #\] #\{ #\} #\" #\; #\@ #\^ #\` #\~ #\\))))
|
||||
|
||||
(define (rdr-digit? c) (and (char>=? c #\0) (char<=? c #\9)))
|
||||
|
||||
;; Advance past whitespace, commas, and ;-to-end-of-line comments.
|
||||
(define (rdr-skip-ws s i end)
|
||||
(let loop ((i i))
|
||||
(cond
|
||||
((>= i end) i)
|
||||
((rdr-ws? (string-ref s i)) (loop (+ i 1)))
|
||||
((char=? (string-ref s i) #\;)
|
||||
(let eol ((j (+ i 1)))
|
||||
(if (or (>= j end) (char=? (string-ref s j) #\newline))
|
||||
(loop j)
|
||||
(eol (+ j 1)))))
|
||||
(else i))))
|
||||
|
||||
;; --- numbers ----------------------------------------------------------------
|
||||
;; A token is a number iff it (after an optional sign) starts with a digit and
|
||||
;; parses. Ratios and big-N/M decimals use all-double rendering
|
||||
;; for division; ints/bignums stay exact (Chez's tower IS Clojure's).
|
||||
(define (rdr-string-index-char str c)
|
||||
(let ((n (string-length str)))
|
||||
(let loop ((i 0))
|
||||
(cond ((>= i n) #f)
|
||||
((char=? (string-ref str i) c) i)
|
||||
(else (loop (+ i 1)))))))
|
||||
|
||||
;; jolt models EVERY number as a double (emit-const lowers integer literals to
|
||||
;; flonums too), so the reader coerces every parsed number to inexact — else a
|
||||
;; read int (exact) is not jolt= to a source int literal (flonum).
|
||||
;; Numeric tower (JVM parity): integer literals read as exact integers (= Long/
|
||||
;; BigInt, arbitrary precision), a/b ratios as exact rationals (= Ratio), and
|
||||
;; decimal/exponent literals as flonums (= double).
|
||||
(define (rdr-try-number tok)
|
||||
(rdr-try-number-raw tok))
|
||||
|
||||
(define (rdr-try-number-raw tok)
|
||||
(let ((len (string-length tok)))
|
||||
(and (> len 0)
|
||||
(let* ((c0 (string-ref tok 0))
|
||||
(signed (or (char=? c0 #\+) (char=? c0 #\-)))
|
||||
(start (if signed 1 0)))
|
||||
(and (> len start)
|
||||
(rdr-digit? (string-ref tok start))
|
||||
(rdr-number-body tok start signed c0))))))
|
||||
|
||||
;; parse DDD in base `radix` (2..36); #f on a bad digit. Scheme string->number only
|
||||
;; does radix 2/8/10/16, so Clojure's NrDDD (e.g. 36rZ) needs a manual parse.
|
||||
(define (rdr-parse-radix digits radix)
|
||||
(let ((len (string-length digits)))
|
||||
(and (> len 0)
|
||||
(let loop ((i 0) (acc 0))
|
||||
(if (>= i len)
|
||||
acc
|
||||
(let* ((c (char-downcase (string-ref digits i)))
|
||||
(d (cond ((and (char>=? c #\0) (char<=? c #\9)) (- (char->integer c) 48))
|
||||
((and (char>=? c #\a) (char<=? c #\z)) (+ 10 (- (char->integer c) 97)))
|
||||
(else #f))))
|
||||
(and d (< d radix) (loop (+ i 1) (+ (* acc radix) d)))))))))
|
||||
|
||||
(define (rdr-number-body tok start signed sign-ch)
|
||||
(let* ((sign (if (and signed (char=? sign-ch #\-)) -1 1))
|
||||
(len (string-length tok))
|
||||
(body (substring tok start len))
|
||||
(blen (string-length body))
|
||||
(slash (rdr-string-index-char body #\/)))
|
||||
(cond
|
||||
;; ratio a/b -> exact rational (= JVM Ratio); reduces to an exact integer
|
||||
;; when d divides n.
|
||||
(slash
|
||||
(let ((n (string->number (substring body 0 slash)))
|
||||
(d (string->number (substring body (+ slash 1) blen))))
|
||||
(and (integer? n) (integer? d) (not (= d 0))
|
||||
(* sign (/ n d)))))
|
||||
;; hex 0x..
|
||||
((and (>= blen 2) (char=? (string-ref body 0) #\0)
|
||||
(or (char=? (string-ref body 1) #\x) (char=? (string-ref body 1) #\X)))
|
||||
(let ((h (string->number (substring body 2 blen) 16)))
|
||||
(and h (* sign h))))
|
||||
;; radix NrDDD (Clojure 2r1010 / 16rFF / 36rZ): N in decimal, DDD in base N
|
||||
((let ((ri (or (rdr-string-index-char body #\r) (rdr-string-index-char body #\R))))
|
||||
(and ri (> ri 0) (< (+ ri 1) blen) ri))
|
||||
=> (lambda (ri)
|
||||
(let ((radix (string->number (substring body 0 ri))))
|
||||
(and radix (integer? radix) (>= radix 2) (<= radix 36)
|
||||
(let ((v (rdr-parse-radix (substring body (+ ri 1) blen) radix)))
|
||||
(and v (* sign v)))))))
|
||||
;; bigint suffix N
|
||||
((and (> blen 1) (char=? (string-ref body (- blen 1)) #\N))
|
||||
(let ((n (string->number (substring body 0 (- blen 1)))))
|
||||
(and n (integer? n) (* sign n))))
|
||||
;; bigdecimal suffix M -> a :bigdec form carrying the numeric text; the back
|
||||
;; end lowers it to a runtime jbigdec (jolt-i2jm).
|
||||
((and (> blen 1) (char=? (string-ref body (- blen 1)) #\M))
|
||||
(let ((n (string->number (substring body 0 (- blen 1)))))
|
||||
(and n (real? n)
|
||||
(rdr-make-tagged (keyword #f "bigdec") (substring tok 0 (- len 1))))))
|
||||
(else
|
||||
(let ((n (string->number tok))) ; tok carries its own sign
|
||||
;; keep exactness: "42" -> exact int, "3.14"/"1e3" -> flonum.
|
||||
(and (number? n) (real? n) n))))))
|
||||
|
||||
;; --- string / char literals -------------------------------------------------
|
||||
(define (rdr-hex->int s i n) ; n hex digits at i -> (values int j)
|
||||
(let loop ((k 0) (acc 0) (j i))
|
||||
(if (= k n)
|
||||
(values acc j)
|
||||
(loop (+ k 1) (+ (* acc 16) (rdr-hexdigit (string-ref s j))) (+ j 1)))))
|
||||
|
||||
(define (rdr-hexdigit c)
|
||||
(cond ((and (char>=? c #\0) (char<=? c #\9)) (- (char->integer c) 48))
|
||||
((and (char>=? c #\a) (char<=? c #\f)) (+ 10 (- (char->integer c) 97)))
|
||||
((and (char>=? c #\A) (char<=? c #\F)) (+ 10 (- (char->integer c) 65)))
|
||||
(else (error 'reader "bad hex digit" c))))
|
||||
|
||||
;; opening quote already consumed; read to the closing quote, processing escapes.
|
||||
(define (rdr-read-string-lit s i end)
|
||||
(let loop ((i i) (acc '()))
|
||||
(when (>= i end) (jolt-throw (jolt-ex-info "EOF while reading string" (empty-pmap))))
|
||||
(let ((c (string-ref s i)))
|
||||
(cond
|
||||
((char=? c #\") (values (list->string (reverse acc)) (+ i 1)))
|
||||
((char=? c #\\)
|
||||
(let ((e (string-ref s (+ i 1))))
|
||||
(case e
|
||||
((#\n) (loop (+ i 2) (cons #\newline acc)))
|
||||
((#\t) (loop (+ i 2) (cons #\tab acc)))
|
||||
((#\r) (loop (+ i 2) (cons #\return acc)))
|
||||
((#\\) (loop (+ i 2) (cons #\\ acc)))
|
||||
((#\") (loop (+ i 2) (cons #\" acc)))
|
||||
((#\b) (loop (+ i 2) (cons #\backspace acc)))
|
||||
((#\f) (loop (+ i 2) (cons #\page acc)))
|
||||
((#\0) (loop (+ i 2) (cons #\nul acc)))
|
||||
((#\u)
|
||||
(let-values (((cp j) (rdr-hex->int s (+ i 2) 4)))
|
||||
(loop j (cons (integer->char cp) acc))))
|
||||
(else (loop (+ i 2) (cons e acc))))))
|
||||
(else (loop (+ i 1) (cons c acc)))))))
|
||||
|
||||
;; backslash already consumed; read a Clojure character literal.
|
||||
(define (rdr-read-char s i end)
|
||||
(when (>= i end) (jolt-throw (jolt-ex-info "EOF while reading char" (empty-pmap))))
|
||||
(let ((c0 (string-ref s i)))
|
||||
(if (char-alphabetic? c0)
|
||||
;; named / unicode / single-letter: collect the alnum run
|
||||
(let loop ((j (+ i 1)))
|
||||
(if (and (< j end)
|
||||
(let ((c (string-ref s j)))
|
||||
(or (char-alphabetic? c) (char-numeric? c))))
|
||||
(loop (+ j 1))
|
||||
(let ((name (substring s i j)))
|
||||
(if (= (string-length name) 1)
|
||||
(values c0 j)
|
||||
(values (rdr-named-char name) j)))))
|
||||
;; any other single char (\( \\ \; \space-as-symbol handled above)
|
||||
(values c0 (+ i 1)))))
|
||||
|
||||
(define (rdr-named-char name)
|
||||
(cond
|
||||
((string=? name "newline") #\newline)
|
||||
((string=? name "space") #\space)
|
||||
((string=? name "tab") #\tab)
|
||||
((string=? name "return") #\return)
|
||||
((string=? name "backspace") #\backspace)
|
||||
((string=? name "formfeed") #\page)
|
||||
((char=? (string-ref name 0) #\u)
|
||||
(integer->char (string->number (substring name 1 (string-length name)) 16)))
|
||||
((char=? (string-ref name 0) #\o)
|
||||
(integer->char (string->number (substring name 1 (string-length name)) 8)))
|
||||
(else (jolt-throw (jolt-ex-info (string-append "Unsupported character: \\" name)
|
||||
(empty-pmap))))))
|
||||
|
||||
;; --- token (symbol / keyword / number / nil|true|false) ---------------------
|
||||
(define (rdr-read-token s i end)
|
||||
(let loop ((j i))
|
||||
(if (and (< j end) (not (rdr-terminator? (string-ref s j))))
|
||||
(loop (+ j 1))
|
||||
(values (substring s i j) j))))
|
||||
|
||||
;; split a "ns/name" token on the FIRST slash (a lone "/" is name "/")
|
||||
(define (rdr-sym-parts tok)
|
||||
(let ((slash (rdr-string-index-char tok #\/)))
|
||||
(if (or (not slash) (= (string-length tok) 1) (= slash 0))
|
||||
(values #f tok)
|
||||
(values (substring tok 0 slash) (substring tok (+ slash 1) (string-length tok))))))
|
||||
|
||||
(define (rdr-token->value tok)
|
||||
(let ((n (rdr-try-number tok)))
|
||||
(cond
|
||||
(n n)
|
||||
((string=? tok "nil") jolt-nil)
|
||||
((string=? tok "true") #t)
|
||||
((string=? tok "false") #f)
|
||||
(else (let-values (((ns name) (rdr-sym-parts tok))) (jolt-symbol ns name))))))
|
||||
|
||||
;; --- collections ------------------------------------------------------------
|
||||
;; Read forms until the close delimiter; returns (values reversed?-no list j).
|
||||
(define (rdr-read-seq s i end close)
|
||||
(let loop ((i i) (acc '()))
|
||||
(let ((i (rdr-skip-ws s i end)))
|
||||
(cond
|
||||
((>= i end) (jolt-throw (jolt-ex-info "EOF while reading" (empty-pmap))))
|
||||
((char=? (string-ref s i) close) (values (reverse acc) (+ i 1)))
|
||||
(else
|
||||
(let-values (((form j) (rdr-read-form s i end)))
|
||||
(cond
|
||||
((rdr-eof? form) (loop j acc)) ; a #_ discard or no-match #? — re-check at j
|
||||
((rdr-splice-t? form) ; #?@ — splice the matched collection's items
|
||||
(loop j (append (reverse (rdr-splice-t-items form)) acc)))
|
||||
(else (loop j (cons form acc))))))))))
|
||||
|
||||
;; Map literals must preserve SOURCE key order so the analyzer emits the value
|
||||
;; expressions in source order (Clojure guarantees left-to-right map-literal eval).
|
||||
;; A pmap is hash-ordered, so record each reader-built map's (k1 v1 k2 v2 ...) form
|
||||
;; sequence in a weak side-table the host contract's form-map-pairs consults.
|
||||
(define rdr-map-order (make-weak-eq-hashtable))
|
||||
(define (rdr-make-map es)
|
||||
(let ((m (apply jolt-hash-map es)))
|
||||
(when (pair? es) (hashtable-set! rdr-map-order m es))
|
||||
m))
|
||||
|
||||
(define (rdr-make-set elems)
|
||||
(jolt-hash-map rdr-kw-jolt-type rdr-kw-jolt-set
|
||||
rdr-kw-value (apply jolt-vector elems)))
|
||||
|
||||
(define (rdr-make-tagged tag form)
|
||||
(jolt-hash-map rdr-kw-jolt-type rdr-kw-jolt-tagged
|
||||
rdr-kw-tag tag rdr-kw-form form))
|
||||
|
||||
;; --- metadata ---------------------------------------------------------------
|
||||
(define (rdr-meta-map m)
|
||||
(cond
|
||||
((keyword? m) (jolt-hash-map m #t))
|
||||
((symbol-t? m) (jolt-hash-map rdr-kw-tag (symbol-t-name m)))
|
||||
((string? m) (jolt-hash-map rdr-kw-tag m))
|
||||
((pmap? m) m)
|
||||
(else (jolt-hash-map rdr-kw-tag m))))
|
||||
|
||||
(define (rdr-merge-meta old new)
|
||||
(if (pmap? old)
|
||||
(pmap-fold new (lambda (k v acc) (jolt-assoc1 acc k v)) old)
|
||||
new))
|
||||
|
||||
(define (rdr-attach-meta target meta)
|
||||
(cond
|
||||
((symbol-t? target)
|
||||
(make-symbol-t (symbol-t-ns target) (symbol-t-name target)
|
||||
(rdr-merge-meta (symbol-t-meta target) meta)))
|
||||
;; A LIST form is code: ^Type (expr) is a compile-time hint on the FORM, not a
|
||||
;; runtime operation. Attach the metadata to the form itself (so a quoted list
|
||||
;; keeps it and the analyzer can read :tag) — never lower to a runtime
|
||||
;; (with-meta (expr) meta), which would mis-apply the hint to the call's RESULT
|
||||
;; and throw when that result is a string/number (e.g. ^String (to-str x)).
|
||||
;; Matches Clojure: a tag hint on an evaluated form is discarded at runtime.
|
||||
((cseq? target) (jolt-with-meta target meta))
|
||||
((empty-list-t? target) target)
|
||||
;; A vector/map/set LITERAL: Clojure attaches the metadata to the runtime value
|
||||
;; ((meta ^{:tag :int} [1 2]) / ^:foo {}), so lower to a runtime (with-meta form
|
||||
;; meta). Use the BARE `with-meta` symbol (ns #f) — the fn/defn macros unwrap a
|
||||
;; (with-meta <arglist-vec> _) return-hint by matching the unqualified head, so a
|
||||
;; qualified clojure.core/with-meta would slip past them (^bytes [b]).
|
||||
(else (jolt-list (jolt-symbol #f "with-meta") target meta))))
|
||||
|
||||
;; --- # dispatch -------------------------------------------------------------
|
||||
;; #(...) anonymous fn shorthand (jolt-qjr0): % -> p1, %N -> pN, %& -> rest. The
|
||||
;; fixed arity is the MAX positional used (Clojure: #(do %2 %&) -> [p1 p2 & rest]).
|
||||
;; Param names carry a trailing "#" so a #() inside a syntax-quote still reads them
|
||||
;; as auto-gensyms.
|
||||
(define rdr-anon-counter 0)
|
||||
(define (rdr-anon-gensym)
|
||||
(set! rdr-anon-counter (+ rdr-anon-counter 1))
|
||||
(jolt-symbol #f (string-append "p__" (number->string rdr-anon-counter) "#")))
|
||||
(define (rdr-pct-index nm) ; % ->1, %& ->'rest, %N ->N, else #f
|
||||
(cond ((string=? nm "%") 1)
|
||||
((string=? nm "%&") 'rest)
|
||||
((and (> (string-length nm) 1) (char=? (string-ref nm 0) #\%))
|
||||
(let ((n (string->number (substring nm 1 (string-length nm)))))
|
||||
(if (and n (integer? n) (>= n 1)) n #f)))
|
||||
(else #f)))
|
||||
(define (rdr-anon-set? f) (and (pmap? f) (eq? (jolt-get f rdr-kw-jolt-type) rdr-kw-jolt-set)))
|
||||
(define (rdr-anon-scan f max-box rest-box)
|
||||
(cond
|
||||
((symbol-t? f)
|
||||
(let ((idx (rdr-pct-index (symbol-t-name f))))
|
||||
(cond ((eq? idx 'rest) (set-box! rest-box #t))
|
||||
((and idx (> idx (unbox max-box))) (set-box! max-box idx)))))
|
||||
((or (pvec? f) (cseq? f) (empty-list-t? f))
|
||||
(for-each (lambda (x) (rdr-anon-scan x max-box rest-box)) (seq->list f)))
|
||||
((rdr-anon-set? f)
|
||||
(for-each (lambda (x) (rdr-anon-scan x max-box rest-box)) (seq->list (jolt-get f rdr-kw-value))))
|
||||
((pmap? f)
|
||||
(for-each (lambda (x) (rdr-anon-scan x max-box rest-box)) (or (hashtable-ref rdr-map-order f #f) '())))))
|
||||
(define (rdr-anon-replace f slots rest-sym)
|
||||
(cond
|
||||
((symbol-t? f)
|
||||
(let ((idx (rdr-pct-index (symbol-t-name f))))
|
||||
(cond ((eq? idx 'rest) rest-sym) (idx (vector-ref slots (- idx 1))) (else f))))
|
||||
((pvec? f) (apply jolt-vector (map (lambda (x) (rdr-anon-replace x slots rest-sym)) (seq->list f))))
|
||||
((or (cseq? f) (empty-list-t? f))
|
||||
(apply jolt-list (map (lambda (x) (rdr-anon-replace x slots rest-sym)) (seq->list f))))
|
||||
((rdr-anon-set? f)
|
||||
(rdr-make-set (map (lambda (x) (rdr-anon-replace x slots rest-sym)) (seq->list (jolt-get f rdr-kw-value)))))
|
||||
((pmap? f)
|
||||
(let ((kv (hashtable-ref rdr-map-order f #f)))
|
||||
(if kv (rdr-make-map (map (lambda (x) (rdr-anon-replace x slots rest-sym)) kv)) f)))
|
||||
(else f)))
|
||||
(define (rdr-read-anon-fn s i end) ; i at the '(' after '#'
|
||||
(let-values (((form j) (rdr-read-form s i end)))
|
||||
(let ((max-box (box 0)) (rest-box (box #f)))
|
||||
(rdr-anon-scan form max-box rest-box)
|
||||
(let* ((n (unbox max-box))
|
||||
(slots (make-vector n)))
|
||||
(let loop ((k 0)) (when (< k n) (vector-set! slots k (rdr-anon-gensym)) (loop (+ k 1))))
|
||||
(let* ((rest-sym (if (unbox rest-box) (rdr-anon-gensym) #f))
|
||||
(body (rdr-anon-replace form slots rest-sym))
|
||||
(params (append (vector->list slots)
|
||||
(if rest-sym (list (jolt-symbol #f "&") rest-sym) '()))))
|
||||
(values (jolt-list (jolt-symbol #f "fn*") (apply jolt-vector params) body) j))))))
|
||||
|
||||
;; reader conditionals (jolt-qjr0): jolt's feature set is {:jolt :clj :default};
|
||||
;; the FIRST clause whose feature key is in the set wins (clause order, like
|
||||
;; Clojure). jolt is a Clojure/JVM-compatible host — it emulates clojure.lang.*
|
||||
;; and java.* interop — so it reads the :clj branch of a .cljc library (the JVM
|
||||
;; code path its host shims target), not the :cljs one. A library can still
|
||||
;; override with a :jolt-specific branch (place it before :clj).
|
||||
(define rdr-features '("jolt" "clj" "default"))
|
||||
(define (rdr-feature? kw)
|
||||
(and (keyword? kw) (jolt-nil? (let ((n (keyword-t-ns kw))) (if n n jolt-nil)))
|
||||
(and (member (keyword-t-name kw) rdr-features) #t)))
|
||||
(define (rdr-read-reader-cond s i end) ; i is past the '?'
|
||||
(let* ((splice (and (< i end) (char=? (string-ref s i) #\@)))
|
||||
(start (if splice (+ i 1) i)))
|
||||
(let-values (((form j) (rdr-read-form s start end)))
|
||||
(when (rdr-eof? form) (jolt-throw (jolt-ex-info "EOF after #?" (empty-pmap))))
|
||||
(let ((items (cond ((pvec? form) (seq->list form))
|
||||
((or (cseq? form) (empty-list-t? form)) (seq->list form))
|
||||
(else '()))))
|
||||
(let loop ((xs items))
|
||||
(cond ((or (null? xs) (null? (cdr xs))) (values rdr-eof j)) ; no match -> discard
|
||||
((rdr-feature? (car xs))
|
||||
(if splice
|
||||
;; #?@ — the matched value is a collection whose ITEMS splice
|
||||
;; into the enclosing sequence (read-seq expands the wrapper).
|
||||
(let ((v (cadr xs)))
|
||||
(values (make-rdr-splice-t
|
||||
(cond ((pvec? v) (seq->list v))
|
||||
((or (cseq? v) (empty-list-t? v)) (seq->list v))
|
||||
(else (list v))))
|
||||
j))
|
||||
(values (cadr xs) j)))
|
||||
(else (loop (cddr xs)))))))))
|
||||
|
||||
(define (rdr-read-dispatch s i end) ; i points just past the '#'
|
||||
(when (>= i end) (jolt-throw (jolt-ex-info "EOF after #" (empty-pmap))))
|
||||
(let ((c (string-ref s i)))
|
||||
(cond
|
||||
((char=? c #\{) ; #{...} set
|
||||
(let-values (((elems j) (rdr-read-seq s (+ i 1) end #\})))
|
||||
(values (rdr-make-set elems) j)))
|
||||
((char=? c #\() ; #(...) anonymous fn shorthand
|
||||
(rdr-read-anon-fn s i end))
|
||||
((char=? c #\") ; #"..." regex -> tagged :regex (raw source)
|
||||
(let-values (((src j) (rdr-read-regex s (+ i 1) end)))
|
||||
(values (rdr-make-tagged (keyword #f "regex") src) j)))
|
||||
((char=? c #\_) ; #_ discard the next form
|
||||
(let-values (((_ j) (rdr-read-form s (+ i 1) end)))
|
||||
(when (rdr-eof? _) (jolt-throw (jolt-ex-info "EOF after #_" (empty-pmap))))
|
||||
(rdr-read-form s j end)))
|
||||
((char=? c #\') ; #'x var-quote -> (var x)
|
||||
(let-values (((form j) (rdr-read-form s (+ i 1) end)))
|
||||
(values (jolt-list (jolt-symbol #f "var") form) j)))
|
||||
((char=? c #\^) ; #^meta — deprecated metadata syntax = ^meta
|
||||
(let-values (((mform j) (rdr-read-form s (+ i 1) end)))
|
||||
(let-values (((target k) (rdr-read-form s j end)))
|
||||
(when (rdr-eof? target)
|
||||
(jolt-throw (jolt-ex-info "EOF after #^meta" (empty-pmap))))
|
||||
(values (rdr-attach-meta target (rdr-meta-map mform)) k))))
|
||||
((char=? c #\#) ; ## symbolic value: ##Inf / ##-Inf / ##NaN
|
||||
(let-values (((tok j) (rdr-read-token s (+ i 1) end)))
|
||||
(values (cond ((string=? tok "Inf") +inf.0)
|
||||
((string=? tok "-Inf") -inf.0)
|
||||
((string=? tok "NaN") +nan.0)
|
||||
(else (jolt-throw (jolt-ex-info (string-append "unknown ## literal: " tok)
|
||||
(empty-pmap)))))
|
||||
j)))
|
||||
((char=? c #\?) ; #?(...) / #?@(...) reader conditional
|
||||
(rdr-read-reader-cond s (+ i 1) end))
|
||||
(else ; #tag form -> tagged {:tag :#tag :form ...}
|
||||
(let-values (((tok j) (rdr-read-token s i end)))
|
||||
(let-values (((form k) (rdr-read-form s j end)))
|
||||
(when (rdr-eof? form) (jolt-throw (jolt-ex-info "EOF after #tag" (empty-pmap))))
|
||||
(values (rdr-make-tagged (keyword #f (string-append "#" tok)) form) k)))))))
|
||||
|
||||
;; regex literal source: raw chars to the closing quote; \" is an escaped quote,
|
||||
;; every other backslash sequence is kept verbatim (regex engine semantics).
|
||||
(define (rdr-read-regex s i end)
|
||||
(let loop ((i i) (acc '()))
|
||||
(when (>= i end) (jolt-throw (jolt-ex-info "EOF while reading regex" (empty-pmap))))
|
||||
(let ((c (string-ref s i)))
|
||||
(cond
|
||||
((char=? c #\") (values (list->string (reverse acc)) (+ i 1)))
|
||||
((and (char=? c #\\) (< (+ i 1) end) (char=? (string-ref s (+ i 1)) #\"))
|
||||
(loop (+ i 2) (cons #\" acc)))
|
||||
((char=? c #\\)
|
||||
(loop (+ i 2) (cons (string-ref s (+ i 1)) (cons #\\ acc))))
|
||||
(else (loop (+ i 1) (cons c acc)))))))
|
||||
|
||||
;; --- keyword ----------------------------------------------------------------
|
||||
(define (rdr-read-keyword s i end) ; i points just past the leading ':'
|
||||
;; ::kw auto-resolves; drop the ns, so skip a second ':'
|
||||
(let ((i (if (and (< i end) (char=? (string-ref s i) #\:)) (+ i 1) i)))
|
||||
(let-values (((tok j) (rdr-read-token s i end)))
|
||||
(let-values (((ns name) (rdr-sym-parts tok)))
|
||||
(values (keyword ns name) j)))))
|
||||
|
||||
;; --- the main dispatch ------------------------------------------------------
|
||||
;; Returns (values form j). form is rdr-eof at end-of-input or at an unconsumed
|
||||
;; close delimiter (read-seq consumes the close itself).
|
||||
(define (rdr-read-form s i end)
|
||||
(let ((i (rdr-skip-ws s i end)))
|
||||
(if (>= i end)
|
||||
(values rdr-eof i)
|
||||
(let ((c (string-ref s i)))
|
||||
(cond
|
||||
((char=? c #\() (let-values (((es j) (rdr-read-seq s (+ i 1) end #\))))
|
||||
(values (apply jolt-list es) j)))
|
||||
((char=? c #\[) (let-values (((es j) (rdr-read-seq s (+ i 1) end #\])))
|
||||
(values (apply jolt-vector es) j)))
|
||||
((char=? c #\{) (let-values (((es j) (rdr-read-seq s (+ i 1) end #\})))
|
||||
(values (rdr-make-map es) j)))
|
||||
((or (char=? c #\)) (char=? c #\]) (char=? c #\}))
|
||||
(values rdr-eof i)) ; unconsumed close — read-seq handles it
|
||||
((char=? c #\") (rdr-read-string-lit s (+ i 1) end))
|
||||
((char=? c #\\) (rdr-read-char s (+ i 1) end))
|
||||
((char=? c #\:) (rdr-read-keyword s (+ i 1) end))
|
||||
((char=? c #\#) (rdr-read-dispatch s (+ i 1) end))
|
||||
((char=? c #\') (rdr-wrap s (+ i 1) end (jolt-symbol #f "quote")))
|
||||
;; syntax-quote of a self-evaluating literal collapses to the literal at
|
||||
;; READ time (Clojure's reader), so nested backticks over a literal are
|
||||
;; inert: ``42 reads as 42, ```"meow" as "meow".
|
||||
((char=? c #\`)
|
||||
(let-values (((form j) (rdr-read-form s (+ i 1) end)))
|
||||
(when (rdr-eof? form) (jolt-throw (jolt-ex-info "EOF after `" (empty-pmap))))
|
||||
(values (if (rdr-self-eval-literal? form)
|
||||
form
|
||||
(jolt-list (jolt-symbol #f "syntax-quote") form))
|
||||
j)))
|
||||
((char=? c #\@) (rdr-wrap s (+ i 1) end (jolt-symbol "clojure.core" "deref")))
|
||||
((char=? c #\~)
|
||||
(if (and (< (+ i 1) end) (char=? (string-ref s (+ i 1)) #\@))
|
||||
(rdr-wrap s (+ i 2) end (jolt-symbol #f "unquote-splicing"))
|
||||
(rdr-wrap s (+ i 1) end (jolt-symbol #f "unquote"))))
|
||||
((char=? c #\^)
|
||||
(let-values (((mform j) (rdr-read-form s (+ i 1) end)))
|
||||
(let-values (((target k) (rdr-read-form s j end)))
|
||||
(when (rdr-eof? target)
|
||||
(jolt-throw (jolt-ex-info "EOF after ^meta" (empty-pmap))))
|
||||
(values (rdr-attach-meta target (rdr-meta-map mform)) k))))
|
||||
(else
|
||||
(let-values (((tok j) (rdr-read-token s i end)))
|
||||
(values (rdr-token->value tok) j))))))))
|
||||
|
||||
;; wrap the next form in a 2-element list (READER-MACRO form)
|
||||
;; self-evaluating literals (NOT symbols/collections) — syntax-quote passes these
|
||||
;; through unchanged, collapsed at read time.
|
||||
(define (rdr-self-eval-literal? x)
|
||||
(or (jolt-nil? x) (boolean? x) (number? x) (string? x) (keyword? x) (char? x)))
|
||||
|
||||
(define (rdr-wrap s i end head)
|
||||
(let-values (((form j) (rdr-read-form s i end)))
|
||||
(when (rdr-eof? form)
|
||||
(jolt-throw (jolt-ex-info "EOF while reading reader macro" (empty-pmap))))
|
||||
(values (jolt-list head form) j)))
|
||||
|
||||
;; --- the two host seams -----------------------------------------------------
|
||||
;; clojure.core/read-string: first form, or nil for blank / comment-only input
|
||||
;; (parse-string wart, matched deliberately).
|
||||
(define (jolt-read-string s)
|
||||
(let-values (((form j) (rdr-read-form s 0 (string-length s))))
|
||||
(if (rdr-eof? form) jolt-nil form)))
|
||||
|
||||
;; __parse-next: [form rest-of-string] or nil when only whitespace/comments left.
|
||||
(define (jolt-parse-next s)
|
||||
(let ((end (string-length s)))
|
||||
(let-values (((form j) (rdr-read-form s 0 end)))
|
||||
(if (rdr-eof? form)
|
||||
jolt-nil
|
||||
(jolt-vector form (substring s j end))))))
|
||||
|
||||
;; __read-tagged: apply a built-in data reader to an already-read form. The tag
|
||||
;; is the :#name keyword the reader produced; #uuid/#inst reuse the inc X ctors.
|
||||
(define (jolt-read-tagged tag form)
|
||||
(cond
|
||||
((eq? tag (keyword #f "#uuid")) (jolt-uuid-from-string form))
|
||||
((eq? tag (keyword #f "#inst")) (jolt-inst-from-string form))
|
||||
(else (jolt-throw (jolt-ex-info (string-append "No reader function for tag " (jolt-pr-str tag))
|
||||
(empty-pmap))))))
|
||||
|
||||
(def-var! "clojure.core" "read-string" jolt-read-string)
|
||||
(def-var! "clojure.core" "__parse-next" jolt-parse-next)
|
||||
(def-var! "clojure.core" "__read-tagged" jolt-read-tagged)
|
||||
425
host/chez/records.ss
Normal file
425
host/chez/records.ss
Normal file
|
|
@ -0,0 +1,425 @@
|
|||
;; records + protocols (jolt-cf1q.3 Phase 2 inc D) — the deftype/defrecord +
|
||||
;; defprotocol/extend-type subsystem. These are ctx-capturing natives
|
||||
;; that resolved to jolt-nil on the prelude, so every record
|
||||
;; case hit the apply-jolt-nil crash bucket.
|
||||
;;
|
||||
;; A record is a `jrec`: a type tag ("ns.Name") + an alist of (kw . val) in
|
||||
;; declared field order. It is map?/coll?, equal to another jrec of the same tag
|
||||
;; with equal fields (never equal to a plain map), and prints as #ns.Name{...}.
|
||||
;; The collection dispatchers (jolt-get/count/keys/vals/seq/assoc/contains?/=/
|
||||
;; hash/conj + the printers) are set!-extended with a jrec arm that delegates to
|
||||
;; the original — the transients.ss pattern — so all record logic lives here and
|
||||
;; the hot collection paths are untouched. (get r :jolt/deftype) returns the tag,
|
||||
;; so the overlay record? predicate works unchanged.
|
||||
;;
|
||||
;; Loaded after collections/seq/values/converters/printing/transients/multimethods
|
||||
;; (the dispatchers it wraps + chez-current-ns).
|
||||
|
||||
(define-record-type jrec (fields tag pairs) (nongenerative chez-jrec-v1))
|
||||
(define jolt-deftype-kw (keyword "jolt" "deftype"))
|
||||
|
||||
(define (jrec-lookup r k d)
|
||||
(if (jolt=2 k jolt-deftype-kw)
|
||||
(jrec-tag r)
|
||||
(let loop ((ps (jrec-pairs r)))
|
||||
(cond ((null? ps) d)
|
||||
((jolt=2 (caar ps) k) (cdar ps))
|
||||
(else (loop (cdr ps)))))))
|
||||
(define (jrec-has? r k)
|
||||
(let loop ((ps (jrec-pairs r)))
|
||||
(cond ((null? ps) #f) ((jolt=2 (caar ps) k) #t) (else (loop (cdr ps))))))
|
||||
;; mutate a deftype's mutable field in place (jolt-c3q): the pairs are runtime
|
||||
;; cons cells, so set-cdr! updates the field. (set! field v) inside a method
|
||||
;; lowers to this; returns v, as set! does.
|
||||
(define (jolt-set-field! inst k v)
|
||||
(if (jrec? inst)
|
||||
(let loop ((ps (jrec-pairs inst)))
|
||||
(cond ((null? ps) (error #f "set! of an unknown field" k))
|
||||
((jolt=2 (caar ps) k) (set-cdr! (car ps) v) v)
|
||||
(else (loop (cdr ps)))))
|
||||
(error #f "set! of a field on a non-record" inst)))
|
||||
(define (jrec-replace pairs k v) ; replace existing field (keep order) or append
|
||||
(let loop ((ps pairs) (acc '()) (hit #f))
|
||||
(cond ((null? ps) (reverse (if hit acc (cons (cons k v) acc))))
|
||||
((jolt=2 (caar ps) k) (loop (cdr ps) (cons (cons k v) acc) #t))
|
||||
(else (loop (cdr ps) (cons (car ps) acc) hit)))))
|
||||
(define (jrec=? a b)
|
||||
(and (string=? (jrec-tag a) (jrec-tag b))
|
||||
(= (length (jrec-pairs a)) (length (jrec-pairs b)))
|
||||
(let loop ((ps (jrec-pairs a)))
|
||||
(or (null? ps)
|
||||
(and (jrec-has? b (caar ps))
|
||||
(jolt=2 (cdar ps) (jrec-lookup b (caar ps) jolt-nil))
|
||||
(loop (cdr ps)))))))
|
||||
(define (jrec-hash r)
|
||||
(fold-left (lambda (acc p) (+ acc (jolt-hash (car p)) (jolt-hash (cdr p))))
|
||||
(string-hash (jrec-tag r)) (jrec-pairs r)))
|
||||
(define (jrec-pr r) ; #ns.Name{:k v, :k v}
|
||||
(string-append "#" (jrec-tag r) "{"
|
||||
(let loop ((ps (jrec-pairs r)) (first #t) (acc ""))
|
||||
(if (null? ps) acc
|
||||
(loop (cdr ps) #f
|
||||
(string-append acc (if first "" ", ")
|
||||
(jolt-pr-readable (caar ps)) " " (jolt-pr-readable (cdar ps))))))
|
||||
"}"))
|
||||
|
||||
;; ---- extend the collection dispatchers with a jrec arm ----------------------
|
||||
(define %r-jolt=2 jolt=2)
|
||||
(set! jolt=2 (lambda (a b)
|
||||
(cond ((jrec? a) (and (jrec? b) (jrec=? a b)))
|
||||
((jrec? b) #f)
|
||||
(else (%r-jolt=2 a b)))))
|
||||
(define %r-jolt-hash jolt-hash)
|
||||
(set! jolt-hash (lambda (x) (if (jrec? x) (jrec-hash x) (%r-jolt-hash x))))
|
||||
(define %r-jolt-get jolt-get)
|
||||
(set! jolt-get (case-lambda
|
||||
((coll k) (if (jrec? coll) (jrec-lookup coll k jolt-nil) (%r-jolt-get coll k)))
|
||||
((coll k d) (if (jrec? coll) (jrec-lookup coll k d) (%r-jolt-get coll k d)))))
|
||||
(define %r-jolt-count jolt-count)
|
||||
(set! jolt-count (lambda (coll) (if (jrec? coll) (length (jrec-pairs coll)) (%r-jolt-count coll))))
|
||||
(define %r-jolt-contains? jolt-contains?)
|
||||
(set! jolt-contains? (lambda (coll k) (if (jrec? coll) (jrec-has? coll k) (%r-jolt-contains? coll k))))
|
||||
(define %r-jolt-assoc1 jolt-assoc1)
|
||||
(set! jolt-assoc1 (lambda (coll k v)
|
||||
(if (jrec? coll) (make-jrec (jrec-tag coll) (jrec-replace (jrec-pairs coll) k v)) (%r-jolt-assoc1 coll k v))))
|
||||
(define %r-jolt-keys jolt-keys)
|
||||
(set! jolt-keys (lambda (m) (if (jrec? m) (list->cseq (map car (jrec-pairs m))) (%r-jolt-keys m))))
|
||||
(define %r-jolt-vals jolt-vals)
|
||||
(set! jolt-vals (lambda (m) (if (jrec? m) (list->cseq (map cdr (jrec-pairs m))) (%r-jolt-vals m))))
|
||||
(define %r-jolt-seq jolt-seq)
|
||||
(set! jolt-seq (lambda (x)
|
||||
(if (jrec? x) (list->cseq (map (lambda (p) (make-map-entry (car p) (cdr p))) (jrec-pairs x))) (%r-jolt-seq x))))
|
||||
(define %r-jolt-conj1 jolt-conj1)
|
||||
(set! jolt-conj1 (lambda (coll x)
|
||||
(if (jrec? coll) (jolt-assoc1 coll (jolt-nth x 0) (jolt-nth x 1)) (%r-jolt-conj1 coll x))))
|
||||
(define %r-jolt-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (jrec? x) (jrec-pr x) (%r-jolt-pr-str x))))
|
||||
(define %r-jolt-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (jrec? x) (jrec-pr x) (%r-jolt-pr-readable x))))
|
||||
|
||||
;; records are map? and coll? (Clojure: a record IS an associative map). Override
|
||||
;; the public predicates to include jrec.
|
||||
;; records are map? and coll? (Clojure: a record IS an associative map). The
|
||||
;; predicates.ss vars hold a snapshot, so re-def-var! after extending. record? is
|
||||
;; the overlay's (some? (get x :jolt/deftype)) — works for free since the get
|
||||
;; override returns the tag for that key.
|
||||
(define %r-jolt-map? jolt-map?)
|
||||
(set! jolt-map? (lambda (x) (or (jrec? x) (%r-jolt-map? x))))
|
||||
(def-var! "clojure.core" "map?" jolt-map?)
|
||||
(def-var! "clojure.core" "coll?" (lambda (x) (or (jrec? x) (jolt-coll-pred? x))))
|
||||
|
||||
;; ---- protocol registry ------------------------------------------------------
|
||||
;; type-tag -> (proto-name -> (method-name -> fn))
|
||||
(define type-registry (make-hashtable string-hash string=?))
|
||||
(define (register-protocol-method type-tag proto method fn)
|
||||
(let* ((ti (or (hashtable-ref type-registry type-tag #f)
|
||||
(let ((h (make-hashtable string-hash string=?))) (hashtable-set! type-registry type-tag h) h)))
|
||||
(pi (or (hashtable-ref ti proto #f)
|
||||
(let ((h (make-hashtable string-hash string=?))) (hashtable-set! ti proto h) h))))
|
||||
(hashtable-set! pi method fn)))
|
||||
(define (find-protocol-method type-tag proto method)
|
||||
(let ((ti (hashtable-ref type-registry type-tag #f)))
|
||||
(and ti (let ((pi (hashtable-ref ti proto #f))) (and pi (hashtable-ref pi method #f))))))
|
||||
(define (find-method-any-protocol type-tag method)
|
||||
(let ((ti (hashtable-ref type-registry type-tag #f)))
|
||||
(and ti (let loop ((protos (vector->list (hashtable-keys ti))))
|
||||
(and (pair? protos)
|
||||
(let ((f (hashtable-ref (hashtable-ref ti (car protos) #f) method #f)))
|
||||
(or f (loop (cdr protos)))))))))
|
||||
(define (type-satisfies? type-tag proto)
|
||||
(let ((ti (hashtable-ref type-registry type-tag #f)))
|
||||
(and ti (hashtable-ref ti proto #f) #t)))
|
||||
|
||||
;; host type-tag candidates for a non-record value (extend-protocol on builtins).
|
||||
(define (value-host-tags obj)
|
||||
(cond ((and (number? obj) (and (exact? obj) (not (integer? obj))))
|
||||
'("Ratio" "Number" "Object"))
|
||||
((number? obj) '("Long" "Integer" "Number" "Double" "Object"))
|
||||
((string? obj) '("String" "CharSequence" "Object"))
|
||||
((boolean? obj) '("Boolean" "Object"))
|
||||
((keyword? obj) '("Keyword" "Named" "Object"))
|
||||
((jolt-symbol? obj) '("Symbol" "Named" "Object"))
|
||||
((pvec? obj) '("PersistentVector" "IPersistentVector" "IPersistentCollection"
|
||||
"List" "java.util.List" "Sequential" "Collection" "Object"))
|
||||
((pmap? obj) '("PersistentArrayMap" "IPersistentMap" "Associative"
|
||||
"Map" "java.util.Map" "Object"))
|
||||
((pset? obj) '("PersistentHashSet" "IPersistentSet" "Set" "java.util.Set" "Collection" "Object"))
|
||||
((or (cseq? obj) (empty-list-t? obj)) '("ISeq" "IPersistentCollection" "Sequential" "Collection" "Object"))
|
||||
((jolt-nil? obj) '("nil"))
|
||||
(else '("Object"))))
|
||||
|
||||
(define (record-tag obj) (and (jrec? obj) (jrec-tag obj)))
|
||||
|
||||
;; ---- the native that handles the analyzer/overlay call ----------------------
|
||||
;; make-deftype-ctor: (name-sym field-kws field-tags field-muts) -> ctor closure.
|
||||
;; The tag is baked at definition time in the type's ns (chez-current-ns).
|
||||
(define (make-deftype-ctor name-sym field-kws . _ignored)
|
||||
(let* ((tag (string-append (chez-current-ns) "." (symbol-t-name name-sym)))
|
||||
(kws (seq->list field-kws))
|
||||
(ctor (lambda args
|
||||
(make-jrec tag (let loop ((ks kws) (as args) (acc '()))
|
||||
(if (null? ks) (reverse acc)
|
||||
(loop (cdr ks) (if (null? as) '() (cdr as))
|
||||
(cons (cons (car ks) (if (null? as) jolt-nil (car as))) acc))))))))
|
||||
;; Register the ctor globally by simple class name (like StringBuilder) so
|
||||
;; (Name. …) interop resolves ns-agnostically: a deftype used across files works
|
||||
;; even when the runtime current ns is the caller's, not the defining ns
|
||||
;; (host-new checks class-ctors-tbl before the current-ns var fallback).
|
||||
(register-class-ctor! (symbol-t-name name-sym) ctor)
|
||||
ctor))
|
||||
|
||||
;; make-protocol: a protocol value the overlay reads via (get p :name)/(get p :methods).
|
||||
(define (make-protocol name-str methods)
|
||||
(jolt-hash-map (keyword #f "jolt/type") (keyword #f "jolt/protocol")
|
||||
(keyword #f "name") (jolt-symbol jolt-nil name-str)
|
||||
(keyword #f "methods") methods))
|
||||
|
||||
;; register-protocol-methods!: a no-op for Chez dispatch.
|
||||
(define (register-protocol-methods! proto-name method-names) jolt-nil)
|
||||
|
||||
;; register-method: extend-type/extend register an impl. Host type names keep a
|
||||
;; bare canonical tag; record names qualify to the current ns.
|
||||
(define host-type-set
|
||||
(let ((h (make-hashtable string-hash string=?)))
|
||||
(for-each (lambda (n) (hashtable-set! h n #t))
|
||||
'("Long" "Integer" "Number" "Double" "Ratio" "BigInt" "BigInteger"
|
||||
"String" "CharSequence" "Boolean" "Character"
|
||||
"Keyword" "Symbol" "Named" "Object" "nil"
|
||||
"PersistentVector" "IPersistentVector"
|
||||
"PersistentArrayMap" "IPersistentMap" "PersistentHashSet" "IPersistentSet"
|
||||
"ISeq" "IPersistentCollection" "Associative" "Sequential"
|
||||
"Map" "java.util.Map" "List" "java.util.List" "Set" "java.util.Set"
|
||||
"Collection" "java.util.Collection"))
|
||||
h))
|
||||
(define (strip-prefix s p)
|
||||
(let ((pl (string-length p)))
|
||||
(and (> (string-length s) pl) (string=? (substring s 0 pl) p) (substring s pl (string-length s)))))
|
||||
(define (canonical-host-tag type-name)
|
||||
(let ((base (or (strip-prefix type-name "java.lang.")
|
||||
(strip-prefix type-name "java.util.")
|
||||
(strip-prefix type-name "clojure.lang.")
|
||||
type-name)))
|
||||
(and (hashtable-ref host-type-set base #f) base)))
|
||||
;; An extend/extend-type/extend-protocol registration marks the tag as an
|
||||
;; extender of the protocol (recorded inside type-registry so the per-case prune
|
||||
;; restores it). deftype/defrecord inline impls go through register-inline-method
|
||||
;; and skip the mark: the JVM compiles inline protocol methods into the class, so
|
||||
;; extenders excludes them.
|
||||
(define extend-mark "__jolt_extend__")
|
||||
(define (mark-extend! tag proto-name)
|
||||
(let ((ti (hashtable-ref type-registry tag #f)))
|
||||
(when ti (let ((pi (hashtable-ref ti proto-name #f)))
|
||||
(when pi (hashtable-set! pi extend-mark #t))))))
|
||||
(define (register-method type-name proto-name method-name fn)
|
||||
(let* ((host (canonical-host-tag type-name))
|
||||
(tag (or host (string-append (chez-current-ns) "." type-name))))
|
||||
(register-protocol-method tag proto-name method-name fn)
|
||||
(mark-extend! tag proto-name)
|
||||
jolt-nil))
|
||||
|
||||
;; register-inline-method: a deftype/defrecord inline impl. Registers for dispatch
|
||||
;; under the ns-qualified record tag but does NOT mark it as an extender.
|
||||
(define (register-inline-method type-name proto-name method-name fn)
|
||||
(register-protocol-method (string-append (chez-current-ns) "." type-name) proto-name method-name fn)
|
||||
jolt-nil)
|
||||
|
||||
;; protocol-dispatch: look up the impl by the value's type tag (record) or host
|
||||
;; candidates, invoke it; reified objects carry instance-local methods.
|
||||
(define (protocol-dispatch proto-name method-name obj rest-args)
|
||||
(let ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args))))
|
||||
(cond
|
||||
((and (jrec? obj) (find-protocol-method (jrec-tag obj) proto-name method-name))
|
||||
=> (lambda (f) (apply jolt-invoke f obj rest)))
|
||||
((reified-methods obj)
|
||||
=> (lambda (rm) (let ((f (hashtable-ref rm method-name #f)))
|
||||
(if f (apply jolt-invoke f obj rest)
|
||||
(error #f (string-append "No reified method " method-name))))))
|
||||
(else
|
||||
(let loop ((tags (value-host-tags obj)))
|
||||
(cond ((null? tags) (error #f (string-append "No method " method-name " in " proto-name)))
|
||||
((find-protocol-method (car tags) proto-name method-name)
|
||||
=> (lambda (f) (apply jolt-invoke f obj rest)))
|
||||
(else (loop (cdr tags)))))))))
|
||||
|
||||
;; dot-dispatch fallback used by emit for (.method record args): find the method
|
||||
;; in ANY protocol the record's type implements.
|
||||
;; java.util.Iterator over a jolt seqable: (.iterator coll) returns a jiterator
|
||||
;; holding a mutable cursor over (seq coll); (.hasNext it)/(.next it) walk it.
|
||||
;; hiccup/compiler's run! loop iterates collections this way.
|
||||
(define-record-type jiterator (fields (mutable cur)) (nongenerative jolt-iterator-v1))
|
||||
;; A Chez condition's message string (for Throwable .getMessage/.toString): the
|
||||
;; &message text plus any &irritants, or display-condition output as a fallback.
|
||||
(define (condition->message-string c)
|
||||
(if (message-condition? c)
|
||||
(let ((m (condition-message c))
|
||||
(irr (if (irritants-condition? c) (condition-irritants c) '())))
|
||||
(let loop ((xs irr) (acc m))
|
||||
(if (null? xs) acc (loop (cdr xs) (string-append acc " " (jolt-pr-str (car xs)))))))
|
||||
(with-output-to-string (lambda () (display-condition c)))))
|
||||
(define (record-method-dispatch obj method-name rest-args)
|
||||
(let ((rest (if (jolt-nil? rest-args) '() (seq->list rest-args))))
|
||||
(cond
|
||||
((and (jrec? obj) (find-method-any-protocol (jrec-tag obj) method-name))
|
||||
=> (lambda (f) (apply jolt-invoke f obj rest)))
|
||||
((reified-methods obj)
|
||||
=> (lambda (rm) (let ((f (hashtable-ref rm method-name #f)))
|
||||
(if f (apply jolt-invoke f obj rest) (error #f (string-append "No method " method-name))))))
|
||||
;; java.lang.String interop (jolt-nfca): defined in natives-str.ss, loaded
|
||||
;; after this file (free reference, resolved at call time).
|
||||
((string? obj) (jolt-string-method method-name obj rest))
|
||||
((jiterator? obj)
|
||||
(cond ((string=? method-name "hasNext") (not (jolt-nil? (jolt-seq (jiterator-cur obj)))))
|
||||
((string=? method-name "next")
|
||||
(let ((s (jolt-seq (jiterator-cur obj))))
|
||||
(if (jolt-nil? s) (error #f "iterator exhausted")
|
||||
(let ((v (jolt-first s))) (jiterator-cur-set! obj (jolt-rest s)) v))))
|
||||
(else (error #f (string-append "No method " method-name " on Iterator")))))
|
||||
((string=? method-name "iterator") (make-jiterator (jolt-seq obj)))
|
||||
;; clojure.lang.Keyword interop: a Keyword carries an interned `sym` field
|
||||
;; (the symbol form, ns + name) plus the Named methods. honeysql/reitit read
|
||||
;; (.sym k) on their :clj branch to recover the symbol without the colon.
|
||||
((keyword-t? obj)
|
||||
(cond ((string=? method-name "sym")
|
||||
(jolt-symbol (keyword-t-ns obj) (keyword-t-name obj)))
|
||||
((string=? method-name "getName") (keyword-t-name obj))
|
||||
((string=? method-name "getNamespace") (or (keyword-t-ns obj) jolt-nil))
|
||||
((string=? method-name "toString")
|
||||
(string-append ":" (if (keyword-t-ns obj) (string-append (keyword-t-ns obj) "/") "")
|
||||
(keyword-t-name obj)))
|
||||
((string=? method-name "hashCode") (keyword-t-khash obj))
|
||||
((string=? method-name "equals") (and (pair? rest) (eq? obj (car rest))))
|
||||
(else (error #f (string-append "No method " method-name " on Keyword")))))
|
||||
;; clojure.lang.Symbol interop: the Named methods + getName/getNamespace.
|
||||
((symbol-t? obj)
|
||||
(cond ((string=? method-name "getName") (symbol-t-name obj))
|
||||
((string=? method-name "getNamespace") (or (symbol-t-ns obj) jolt-nil))
|
||||
((string=? method-name "toString")
|
||||
(string-append (if (symbol-t-ns obj) (string-append (symbol-t-ns obj) "/") "")
|
||||
(symbol-t-name obj)))
|
||||
((string=? method-name "equals") (and (pair? rest) (jolt=2 obj (car rest))))
|
||||
(else (error #f (string-append "No method " method-name " on Symbol")))))
|
||||
;; java.lang.Throwable interop over a Chez condition. A jolt host error
|
||||
;; (`error`/`assertion-violationf`) raises a Chez condition; Clojure code
|
||||
;; that catches it as a Throwable reads (.getMessage e) / (.toString e).
|
||||
((condition? obj)
|
||||
(cond ((or (string=? method-name "getMessage") (string=? method-name "getLocalizedMessage"))
|
||||
(condition->message-string obj))
|
||||
((string=? method-name "toString") (condition->message-string obj))
|
||||
((string=? method-name "getCause") jolt-nil)
|
||||
(else (error #f (string-append "No method " method-name " on Throwable")))))
|
||||
;; java.lang.Character interop: (.toString \+) -> "+", etc.
|
||||
((char? obj)
|
||||
(cond ((string=? method-name "toString") (string obj))
|
||||
((string=? method-name "charValue") obj)
|
||||
((string=? method-name "hashCode") (char->integer obj))
|
||||
((string=? method-name "equals") (and (pair? rest) (char? (car rest)) (char=? obj (car rest))))
|
||||
((string=? method-name "compareTo")
|
||||
(let ((o (car rest))) (cond ((char<? obj o) -1) ((char>? obj o) 1) (else 0))))
|
||||
(else (error #f (string-append "No method " method-name " on char")))))
|
||||
(else (error #f (string-append "No method " method-name " for value: "
|
||||
(jolt-pr-str obj)))))))
|
||||
|
||||
;; reify: instance-local method table. obj is a jreify carrying a method ht +
|
||||
;; the protocol short-names it implements (for satisfies?/instance?).
|
||||
(define-record-type jreify (fields methods protos) (nongenerative chez-jreify-v1))
|
||||
(define (reified-methods obj) (and (jreify? obj) (jreify-methods obj)))
|
||||
(define (make-reified methods-map . proto-names)
|
||||
(let ((ht (make-hashtable string-hash string=?))
|
||||
(protos (if (and (pair? proto-names) (null? (cdr proto-names)) (jolt-coll-pred? (car proto-names)))
|
||||
(seq->list (car proto-names)) proto-names)))
|
||||
(for-each (lambda (p) (hashtable-set! ht (if (keyword? p) (keyword-t-name p) p)
|
||||
(jolt-get methods-map p jolt-nil)))
|
||||
(seq->list (jolt-keys methods-map)))
|
||||
(make-jreify ht (map (lambda (p) (if (symbol-t? p) (symbol-t-name p) p)) protos))))
|
||||
|
||||
;; satisfies?: does obj's type implement the protocol?
|
||||
(define (jolt-satisfies? proto obj)
|
||||
(let* ((pn (jolt-get proto (keyword #f "name") jolt-nil))
|
||||
(pn-str (if (symbol-t? pn) (symbol-t-name pn) pn)))
|
||||
(cond
|
||||
((jrec? obj) (type-satisfies? (jrec-tag obj) pn-str))
|
||||
((jreify? obj)
|
||||
(let ((short (last-dot pn-str)))
|
||||
(and (memp (lambda (p) (string=? (last-dot p) short)) (jreify-protos obj)) #t)))
|
||||
(else (let loop ((tags (value-host-tags obj)))
|
||||
(cond ((null? tags) #f)
|
||||
((type-satisfies? (car tags) pn-str) #t)
|
||||
(else (loop (cdr tags)))))))))
|
||||
(define (last-dot s)
|
||||
(let loop ((i (- (string-length s) 1)))
|
||||
(cond ((< i 0) s) ((char=? (string-ref s i) #\.) (substring s (+ i 1) (string-length s))) (else (loop (- i 1))))))
|
||||
(define (memp pred lst) (cond ((null? lst) #f) ((pred (car lst)) lst) (else (memp pred (cdr lst)))))
|
||||
|
||||
;; extenders: type-tags that extend a protocol via extend/extend-type/extend-
|
||||
;; protocol, as symbols (extends? reads this). Inline deftype/defrecord impls are
|
||||
;; excluded — only tags carrying the extend mark count, matching the JVM.
|
||||
(define (extenders proto)
|
||||
(let* ((pn (jolt-get proto (keyword #f "name") jolt-nil))
|
||||
(pn-str (if (symbol-t? pn) (symbol-t-name pn) pn))
|
||||
(out '()))
|
||||
(vector-for-each
|
||||
(lambda (tag)
|
||||
(let ((ti (hashtable-ref type-registry tag #f)))
|
||||
(when ti (let ((pi (hashtable-ref ti pn-str #f)))
|
||||
(when (and pi (hashtable-ref pi extend-mark #f))
|
||||
(set! out (cons (jolt-symbol jolt-nil tag) out)))))))
|
||||
(hashtable-keys type-registry))
|
||||
(if (null? out) jolt-nil (list->cseq out))))
|
||||
|
||||
;; instance-check: (type-sym val) — type/protocol membership.
|
||||
(define (instance-check type-sym val)
|
||||
(let ((tname (symbol-t-name type-sym)))
|
||||
(cond
|
||||
((jrec? val)
|
||||
(let ((tag (jrec-tag val)))
|
||||
(or (string=? tag tname)
|
||||
(and (> (string-length tag) (string-length tname))
|
||||
(string=? (substring tag (- (string-length tag) (string-length tname)) (string-length tag)) tname)))))
|
||||
((jreify? val) (let ((short (last-dot tname)))
|
||||
(and (memp (lambda (p) (string=? (last-dot p) short)) (jreify-protos val)) #t)))
|
||||
(else (case-string tname val)))))
|
||||
(define (case-string tname val)
|
||||
(cond
|
||||
((member tname '("Number" "java.lang.Number")) (number? val))
|
||||
((member tname '("Long" "java.lang.Long" "Integer" "java.lang.Integer"))
|
||||
(and (number? val) (exact? val) (integer? val)))
|
||||
((member tname '("Double" "java.lang.Double" "Float" "java.lang.Float")) (and (number? val) (flonum? val)))
|
||||
((member tname '("Ratio" "clojure.lang.Ratio")) (and (number? val) (exact? val) (rational? val) (not (integer? val))))
|
||||
((member tname '("String" "java.lang.String" "CharSequence" "java.lang.CharSequence")) (string? val))
|
||||
((member tname '("Boolean" "java.lang.Boolean")) (boolean? val))
|
||||
((member tname '("Character" "java.lang.Character")) (char? val))
|
||||
((member tname '("Keyword" "clojure.lang.Keyword")) (keyword? val))
|
||||
((member tname '("Symbol" "clojure.lang.Symbol")) (jolt-symbol? val))
|
||||
((member tname '("Atom" "clojure.lang.Atom")) (jolt-atom? val))
|
||||
((member tname '("IFn" "clojure.lang.IFn" "Fn" "clojure.lang.Fn")) (procedure? val))
|
||||
(else #f)))
|
||||
|
||||
;; str of a record uses a custom (Object toString) impl if the type defines one
|
||||
;; (deftype with no default toString relies on this); otherwise the map form
|
||||
;; without the leading # (Clojure's record .toString). converters.ss loads before
|
||||
;; records.ss, so this set! sees the registry — forward refs resolve at call time.
|
||||
(define %r-str-render-one jolt-str-render-one)
|
||||
(set! jolt-str-render-one
|
||||
(lambda (v)
|
||||
(if (jrec? v)
|
||||
(let ((f (find-protocol-method (jrec-tag v) "Object" "toString")))
|
||||
(if f (jolt-invoke f v)
|
||||
(let ((s (jrec-pr v))) (substring s 1 (string-length s)))))
|
||||
(%r-str-render-one v))))
|
||||
|
||||
;; `type` lives in natives-meta.ss (jolt-fmm4): it needs jolt-meta for the :type
|
||||
;; override and a total value->taxonomy mapping, so it sits with meta — a record
|
||||
;; yields (jolt-symbol #f (jrec-tag x)), the ns.Name class-name symbol.
|
||||
|
||||
(def-var! "clojure.core" "make-deftype-ctor" make-deftype-ctor)
|
||||
(def-var! "clojure.core" "make-protocol" make-protocol)
|
||||
(def-var! "clojure.core" "register-protocol-methods!" register-protocol-methods!)
|
||||
(def-var! "clojure.core" "register-method" register-method)
|
||||
(def-var! "clojure.core" "register-inline-method" register-inline-method)
|
||||
(def-var! "jolt.host" "set-field!" jolt-set-field!)
|
||||
(def-var! "clojure.core" "protocol-dispatch" (lambda (pn mn obj rest) (protocol-dispatch pn mn obj rest)))
|
||||
(def-var! "clojure.core" "satisfies?" jolt-satisfies?)
|
||||
(def-var! "clojure.core" "extenders" extenders)
|
||||
(def-var! "clojure.core" "instance-check" instance-check)
|
||||
(def-var! "clojure.core" "make-reified" (lambda (mm . rest) (apply make-reified mm rest)))
|
||||
(def-var! "clojure.core" "record-method-dispatch" (lambda (obj m rest) (record-method-dispatch obj m rest)))
|
||||
167
host/chez/regex.ss
Normal file
167
host/chez/regex.ss
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
;; Phase 1 (jolt-cf1q.2) — regex on Chez via vendored irregex (jolt-i0s3).
|
||||
;;
|
||||
;; Chez has no regex at all. We vendor
|
||||
;; Alex Shinn's irregex (vendor/irregex, BSD) — a portable Scheme regex with
|
||||
;; PCRE/Java-style STRING patterns — and wrap jolt's re-* surface over it.
|
||||
;;
|
||||
;; irregex maps cleanly onto the Clojure fns: irregex-match is an anchored
|
||||
;; whole-string match (= re-matches), irregex-search finds the first match
|
||||
;; anywhere (= re-find), irregex-match-substring extracts group N (0 = whole).
|
||||
;; Results follow Clojure shape: a 0-group match is the whole string; a grouped
|
||||
;; match is a jolt VECTOR [whole g1 ...] (a non-participating group is nil); a nil
|
||||
;; result is jolt-nil; re-seq is a jolt seq (nil when there are no matches).
|
||||
;;
|
||||
;; The re-* fns are def-var!'d into clojure.core so prelude / -e code resolves
|
||||
;; them at runtime (they're NOT subset native-ops: irregex's Unicode/property-
|
||||
;; class semantics keep them out
|
||||
;; of the subset-parity corpus). Loaded from rt.ss after def-var! is defined.
|
||||
|
||||
;; irregex.scm is portable R[457]RS; two small adaptations for Chez's top level:
|
||||
;; a cond-expand at expression position (Chez's is library-only), and `error`
|
||||
;; called with a lone string (Chez's error wants who+msg). The wrapper normalizes
|
||||
;; both without changing behavior for valid patterns.
|
||||
(define-syntax cond-expand
|
||||
(syntax-rules (else)
|
||||
((_ (else e ...)) (begin e ...))
|
||||
((_ (else e ...) c ...) (begin e ...))
|
||||
((_ (req e ...) c ...) (cond-expand c ...))
|
||||
((_) (if #f #f))))
|
||||
(define %chez-error error)
|
||||
(define (error . args)
|
||||
(if (and (pair? args) (string? (car args)))
|
||||
(apply %chez-error #f args)
|
||||
(apply %chez-error args)))
|
||||
(load "vendor/irregex/irregex.scm")
|
||||
|
||||
;; Unicode property classes \p{...} (jolt-y1zq): irregex's string syntax has no
|
||||
;; \p{...}, so translate a fixed set of property names
|
||||
;; to ASCII char classes before compiling. ASCII-only — \p{L} would need
|
||||
;; UTF-8 high bytes counted as letters, which a Unicode-char Scheme string can't
|
||||
;; reproduce byte-for-byte; the corpus tests ASCII inputs, where they agree. An
|
||||
;; unmapped name is left as-is (irregex errors, as before — no new behavior). The
|
||||
;; ORIGINAL source is kept for printing; only the compiled pattern is translated.
|
||||
(define (prop-class name)
|
||||
(cond
|
||||
;; L/Alpha: ASCII letters + non-ASCII up to just below the UTF-16 surrogate gap
|
||||
;; (D800). This covers essentially every real letter (Latin/Greek/Cyrillic/CJK/…
|
||||
;; live below D800); the supplementary planes above it are rare and a range that
|
||||
;; reaches them makes irregex's char-set construction call integer->char on a
|
||||
;; surrogate and crash. N/Z stay ASCII-only.
|
||||
((or (string=? name "L") (string=? name "Alpha")) "a-zA-Z\\x80-\\x{D7FF}")
|
||||
((string=? name "Lu") "A-Z")
|
||||
((string=? name "Ll") "a-z")
|
||||
((or (string=? name "N") (string=? name "Nd") (string=? name "Digit")) "0-9")
|
||||
((or (string=? name "Z") (string=? name "Zs")) " ")
|
||||
((string=? name "Ps") "([{")
|
||||
((string=? name "Pe") ")\\]}")
|
||||
(else #f)))
|
||||
;; Tracks whether the cursor is inside a [...] char class: a \p{X} there emits the
|
||||
;; class CONTENT (inlined), standalone it emits a wrapping [X]. Escapes
|
||||
;; (\[, \]) don't toggle the class. \P (negation) only wraps when standalone.
|
||||
(define (translate-prop-classes src)
|
||||
(let ((len (string-length src)) (out (open-output-string)))
|
||||
(let loop ((i 0) (in-class #f))
|
||||
(if (fx>=? i len)
|
||||
(get-output-string out)
|
||||
(let ((c (string-ref src i)))
|
||||
(cond
|
||||
;; \p{Name} / \P{Name}
|
||||
((and (char=? c #\\) (fx<? (fx+ i 2) len)
|
||||
(let ((p (string-ref src (fx+ i 1)))) (or (char=? p #\p) (char=? p #\P)))
|
||||
(char=? (string-ref src (fx+ i 2)) #\{))
|
||||
(let* ((close (let scan ((j (fx+ i 3)))
|
||||
(cond ((fx>=? j len) #f)
|
||||
((char=? (string-ref src j) #\}) j)
|
||||
(else (scan (fx+ j 1))))))
|
||||
(cls (and close (prop-class (substring src (fx+ i 3) close)))))
|
||||
(cond
|
||||
((not cls) (write-char c out) (loop (fx+ i 1) in-class))
|
||||
(in-class (display cls out) (loop (fx+ close 1) in-class))
|
||||
(else
|
||||
(display "[" out)
|
||||
(when (char=? (string-ref src (fx+ i 1)) #\P) (display "^" out))
|
||||
(display cls out) (display "]" out)
|
||||
(loop (fx+ close 1) in-class)))))
|
||||
;; any other escape: copy the pair verbatim, don't toggle class state
|
||||
((and (char=? c #\\) (fx<? (fx+ i 1) len))
|
||||
(write-char c out) (write-char (string-ref src (fx+ i 1)) out)
|
||||
(loop (fx+ i 2) in-class))
|
||||
((and (not in-class) (char=? c #\[))
|
||||
(write-char c out) (loop (fx+ i 1) #t))
|
||||
((and in-class (char=? c #\]))
|
||||
(write-char c out) (loop (fx+ i 1) #f))
|
||||
(else (write-char c out) (loop (fx+ i 1) in-class))))))))
|
||||
|
||||
;; Java/Clojure inline flags: a leading (?imsx…) group sets a flag over the whole
|
||||
;; pattern. irregex has the same semantics but as constructor OPTIONS, not inline
|
||||
;; syntax (it rejects (?s)/(?s:…)), so peel any leading flag groups off the source
|
||||
;; and pass the equivalent option symbols. Scoped groups ((?:…), (?=…), (?<n>…))
|
||||
;; and groups with a flag irregex can't express are left untouched for irregex.
|
||||
(define (regex-flag->opt c)
|
||||
(cond ((char=? c #\s) 'single-line) ; DOTALL — . matches newline
|
||||
((char=? c #\i) 'case-insensitive)
|
||||
((char=? c #\m) 'multi-line) ; ^/$ match at line boundaries
|
||||
(else #f)))
|
||||
(define (regex-parse-flags src)
|
||||
(let loop ((s src) (opts '()))
|
||||
(if (and (>= (string-length s) 4)
|
||||
(char=? (string-ref s 0) #\() (char=? (string-ref s 1) #\?))
|
||||
(let scan ((i 2) (fs '()))
|
||||
(cond
|
||||
((>= i (string-length s)) (values (reverse opts) s))
|
||||
((char=? (string-ref s i) #\))
|
||||
(let ((mapped (map regex-flag->opt fs)))
|
||||
(if (and (pair? fs) (for-all (lambda (x) x) mapped))
|
||||
(loop (substring s (+ i 1) (string-length s)) (append opts mapped))
|
||||
(values (reverse opts) s)))) ; unmappable flag — leave as-is
|
||||
((char=? (string-ref s i) #\:) (values (reverse opts) s)) ; scoped group
|
||||
(else (scan (+ i 1) (cons (string-ref s i) fs)))))
|
||||
(values (reverse opts) s))))
|
||||
|
||||
;; A jolt regex value: the source string (for printing / str) + the compiled
|
||||
;; irregex. regex? recognizes it; the printer renders #"source".
|
||||
(define-record-type regex-t (fields source irx) (nongenerative jolt-regex-v1))
|
||||
(define (jolt-regex source)
|
||||
(let-values (((opts pat) (regex-parse-flags source)))
|
||||
(make-regex-t source (apply irregex (translate-prop-classes pat) opts))))
|
||||
(define (jolt-regex? x) (regex-t? x))
|
||||
(define (jolt-re-pattern x) (if (regex-t? x) x (jolt-regex x)))
|
||||
|
||||
;; An irregex match -> the Clojure result: whole string (no groups) or the
|
||||
;; [whole g1 ... gn] vector (nil for a non-participating group).
|
||||
(define (irx-result m)
|
||||
(let ((n (irregex-match-num-submatches m)))
|
||||
(if (= n 0)
|
||||
(irregex-match-substring m 0)
|
||||
(let loop ((i n) (acc '()))
|
||||
(if (< i 0)
|
||||
(apply jolt-vector acc)
|
||||
(let ((s (irregex-match-substring m i)))
|
||||
(loop (- i 1) (cons (if s s jolt-nil) acc))))))))
|
||||
|
||||
(define (jolt-re-matches re s)
|
||||
(let ((m (irregex-match (regex-t-irx (jolt-re-pattern re)) s)))
|
||||
(if m (irx-result m) jolt-nil)))
|
||||
|
||||
(define (jolt-re-find re s)
|
||||
(let ((m (irregex-search (regex-t-irx (jolt-re-pattern re)) s)))
|
||||
(if m (irx-result m) jolt-nil)))
|
||||
|
||||
;; All non-overlapping matches, left to right. Advance past each match end (or by
|
||||
;; one on a zero-width match). nil when there are no matches (Clojure: seq-able as
|
||||
;; nil, so (if-let [m (re-seq ...)] ...) works).
|
||||
(define (jolt-re-seq re s)
|
||||
(let ((irx (regex-t-irx (jolt-re-pattern re)))
|
||||
(len (string-length s)))
|
||||
(let loop ((start 0) (acc '()))
|
||||
(let ((m (and (<= start len) (irregex-search irx s start))))
|
||||
(if m
|
||||
(let ((e (irregex-match-end-index m 0)))
|
||||
(loop (if (> e start) e (+ start 1)) (cons (irx-result m) acc)))
|
||||
(list->cseq (reverse acc)))))))
|
||||
|
||||
(def-var! "clojure.core" "re-pattern" jolt-re-pattern)
|
||||
(def-var! "clojure.core" "re-matches" jolt-re-matches)
|
||||
(def-var! "clojure.core" "re-find" jolt-re-find)
|
||||
(def-var! "clojure.core" "re-seq" jolt-re-seq)
|
||||
(def-var! "clojure.core" "regex?" jolt-regex?)
|
||||
30
host/chez/remint.sh
Executable file
30
host/chez/remint.sh
Executable file
|
|
@ -0,0 +1,30 @@
|
|||
#!/bin/sh
|
||||
# Re-mint the checked-in Chez seed. Run after changing a seed source — the reader
|
||||
# (host/chez/reader.ss), the analyzer/IR/backend (jolt-core/jolt/*.clj), or the
|
||||
# clojure.core overlay (jolt-core/clojure/core/*.clj). Iterates bootstrap.ss from the
|
||||
# current seed to a byte-fixpoint and overwrites host/chez/seed/.
|
||||
set -e
|
||||
root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
|
||||
cd "$root"
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
|
||||
cp host/chez/seed/prelude.ss "$tmp/cur-p.ss"
|
||||
cp host/chez/seed/image.ss "$tmp/cur-i.ss"
|
||||
i=0
|
||||
while [ "$i" -lt 8 ]; do
|
||||
i=$((i + 1))
|
||||
chez --script host/chez/bootstrap.ss \
|
||||
"$tmp/cur-p.ss" "$tmp/cur-i.ss" "$tmp/new-p.ss" "$tmp/new-i.ss" >/dev/null
|
||||
if diff -q "$tmp/cur-p.ss" "$tmp/new-p.ss" >/dev/null \
|
||||
&& diff -q "$tmp/cur-i.ss" "$tmp/new-i.ss" >/dev/null; then
|
||||
cp "$tmp/new-p.ss" host/chez/seed/prelude.ss
|
||||
cp "$tmp/new-i.ss" host/chez/seed/image.ss
|
||||
echo "re-minted seed (converged after $i pass(es))"
|
||||
exit 0
|
||||
fi
|
||||
cp "$tmp/new-p.ss" "$tmp/cur-p.ss"
|
||||
cp "$tmp/new-i.ss" "$tmp/cur-i.ss"
|
||||
done
|
||||
echo "re-mint did not converge in 8 passes" >&2
|
||||
exit 1
|
||||
354
host/chez/rt.ss
Normal file
354
host/chez/rt.ss
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
;; Phase 1 (jolt-cf1q.2) — the minimal Chez RT the emitted Scheme rests on.
|
||||
;;
|
||||
;; Sits above the value model (values.ss) and below an emitted program. Adds the
|
||||
;; two things the back end's output references that aren't in the value layer:
|
||||
;; 1. the var-cell late-binding registry (Clojure vars — a global root that a
|
||||
;; reference reads at call time, so redefinition / mutual recursion work);
|
||||
;; 2. the rt primitive shims the emitter names (jolt-inc/dec/not) and jolt's
|
||||
;; number printing (all jolt numbers model Clojure doubles; integer-valued
|
||||
;; print without a trailing ".0").
|
||||
;;
|
||||
;; Emitted programs do `(load "host/chez/rt.ss")`; this loads values.ss in turn.
|
||||
|
||||
(load "host/chez/values.ss")
|
||||
(load "host/chez/collections.ss")
|
||||
(load "host/chez/seq.ss")
|
||||
|
||||
;; --- rt arithmetic / logic shims (named in the emitter's native-ops) ----------
|
||||
(define (jolt-inc x) (+ x 1))
|
||||
(define (jolt-dec x) (- x 1))
|
||||
;; jolt `not`: only nil and false are falsey.
|
||||
(define (jolt-not x) (if (jolt-truthy? x) #f #t))
|
||||
|
||||
;; --- exceptions (jolt-vcsl) --------------------------------------------------
|
||||
;; throw raises the jolt value RAW (no envelope);
|
||||
;; catch (emitted as `guard`) binds it directly. Chez `raise` accepts any
|
||||
;; object, so a thrown number/map/ex-info all work; uncaught -> non-zero exit.
|
||||
(define (jolt-throw v) (raise v))
|
||||
;; ex-info builds the tagged map {:jolt/type :jolt/ex-info :message :data :cause}
|
||||
;; — a real jolt-hash-map, so the ex-data/ex-message/ex-cause tier fns read it
|
||||
;; via jolt-get for free. Arity 2 (msg data) or 3 (msg data cause).
|
||||
(define jolt-kw-ex-type (keyword "jolt" "type"))
|
||||
(define jolt-kw-ex-info (keyword "jolt" "ex-info"))
|
||||
(define jolt-kw-message (keyword #f "message"))
|
||||
(define jolt-kw-data (keyword #f "data"))
|
||||
(define jolt-kw-cause (keyword #f "cause"))
|
||||
(define (jolt-ex-info msg data . more)
|
||||
(jolt-hash-map jolt-kw-ex-type jolt-kw-ex-info
|
||||
jolt-kw-message msg
|
||||
jolt-kw-data data
|
||||
jolt-kw-cause (if (null? more) jolt-nil (car more))))
|
||||
|
||||
;; --- host interop (jolt-0kf5) ------------------------------------------------
|
||||
;; (.method target arg*) lowers to (jolt-host-call "method" target arg*). JVM
|
||||
;; interop has no general Chez analog, but the few methods jolt-core's io tier
|
||||
;; calls map onto Chez equivalents: a writer's .write is a port display; a File's
|
||||
;; .isDirectory / .listFiles work over a path string (Chez has no File type, so
|
||||
;; file-seq's File branch is unreachable here — these keep the forms honest). An
|
||||
;; unsupported method raises rather than silently returning nil.
|
||||
(define (jolt-host-call method target . args)
|
||||
(cond
|
||||
((string=? method "write") (display (car args) target) jolt-nil)
|
||||
((string=? method "isDirectory") (if (file-directory? target) #t #f))
|
||||
((string=? method "listFiles") (list->cseq (directory-list target)))
|
||||
(else (error 'jolt-host-call (string-append "unsupported host method: ." method)))))
|
||||
|
||||
;; --- var cells: late-bound global roots (Clojure vars) -----------------------
|
||||
;; A var is a mutable cell keyed by "ns/name". A `:def` sets the root; a `:var`
|
||||
;; reference reads it at use time (late binding), so a forward/mutually-recursive
|
||||
;; reference resolves to whatever the cell holds when the call actually runs.
|
||||
;; declare / (def name) with no init reserves a cell holding this placeholder
|
||||
;; until the real def overwrites it (a forward reference resolves to the cell, and
|
||||
;; correct code never reads it before the binding def runs).
|
||||
(define jolt-unbound (string->symbol "#<jolt-unbound>"))
|
||||
;; `defined?` distinguishes a genuinely interned var (def / declare / a native-op
|
||||
;; cell) from a cell lazily materialised by a forward `var-deref` / `(var x)` on a
|
||||
;; not-yet-defined name — `resolve` returns the cell iff defined? (jolt-yxqm).
|
||||
;; ns-unmap clears it. Avoids the (def x nil) edge of probing the root.
|
||||
(define-record-type var-cell (fields ns name (mutable root) (mutable defined?)) (nongenerative var-cell-v2))
|
||||
(define var-table (make-hashtable string-hash string=?))
|
||||
(define (jolt-var ns name)
|
||||
(let ((k (string-append ns "/" name)))
|
||||
(or (hashtable-ref var-table k #f)
|
||||
(let ((c (make-var-cell ns name jolt-nil #f)))
|
||||
(hashtable-set! var-table k c)
|
||||
c))))
|
||||
;; non-creating lookup (resolve / find-var / ns-unmap): #f when absent, so a
|
||||
;; probe never interns an empty cell.
|
||||
(define (var-cell-lookup ns name) (hashtable-ref var-table (string-append ns "/" name) #f))
|
||||
(define (var-deref ns name) (var-cell-root (jolt-var ns name)))
|
||||
;; def-var! / declare-var! return the VAR CELL, not the value — Clojure's `def`
|
||||
;; evaluates to #'ns/name (a first-class var), so (var? (def x 1)) is true and
|
||||
;; (pr-str (def x 1)) is "#'ns/x". The prelude's def-var! forms discard the
|
||||
;; return, so this is transparent there.
|
||||
(define (def-var! ns name v) (let ((c (jolt-var ns name))) (var-cell-root-set! c v) (var-cell-defined?-set! c #t) c))
|
||||
;; var def-time metadata (jolt-zikh): the :def emit passes the def's reader meta
|
||||
;; (^:private / ^Type tag / docstring -> {:doc}) here, stored in an eq side-table
|
||||
;; keyed by the cell. jolt-meta (natives-meta.ss) merges it onto {:ns :name},
|
||||
;; which it derives from the cell — so EVERY var (plain def, native-op, declare)
|
||||
;; reports {:ns :name} like Clojure, with the user meta layered on when present.
|
||||
(define var-meta-table (make-eq-hashtable))
|
||||
(define jolt-kw-var-ns (keyword #f "ns"))
|
||||
(define jolt-kw-var-name (keyword #f "name"))
|
||||
(define (def-var-with-meta! ns name v m)
|
||||
(let ((c (def-var! ns name v))) (hashtable-set! var-meta-table c m) c))
|
||||
;; runtime-macro registry (jolt-r9lm, inc6b): a var whose root holds a macro
|
||||
;; expander fn is flagged here, so the ON-CHEZ analyzer's form-macro?/form-expand-1
|
||||
;; (host-contract.ss) expand it. The prelude emits each core/stdlib defmacro as a
|
||||
;; def-var! of its (cross-compiled) expander followed by (mark-macro! ns name).
|
||||
;; Keyed by cell (eq), like var-meta-table — survives a later (def name ...) that
|
||||
;; replaces the expander but keeps the same cell, matching Clojure (a defmacro IS a
|
||||
;; def whose var carries :macro).
|
||||
(define var-macro-table (make-eq-hashtable))
|
||||
(define (mark-macro! ns name)
|
||||
(let ((c (jolt-var ns name))) (hashtable-set! var-macro-table c #t) c))
|
||||
(define (macro-var? cell) (and cell (hashtable-ref var-macro-table cell #f) #t))
|
||||
;; declare / (def name) with no init: reserve the cell ONLY if absent. An
|
||||
;; existing root is left intact — Clojure's (def x) with no init does not clobber
|
||||
;; a prior binding (do (def x 7) (def x) x) => 7. Returns the cell either way.
|
||||
(define (declare-var! ns name)
|
||||
(let ((k (string-append ns "/" name)))
|
||||
(or (hashtable-ref var-table k #f)
|
||||
(let ((c (make-var-cell ns name jolt-unbound #t))) ; declared => interned/resolvable
|
||||
(hashtable-set! var-table k c)
|
||||
c))))
|
||||
|
||||
;; regex (jolt-i0s3): defines regex-t + the re-* fns (def-var!'d into
|
||||
;; clojure.core), so it loads after def-var! and before the printer below (which
|
||||
;; renders a regex-t as #"source").
|
||||
(load "host/chez/regex.ss")
|
||||
|
||||
;; atoms (jolt-9ziu): host-coupled mutable cells; def-var!'d into clojure.core
|
||||
;; (atom/deref/swap!/reset! + the compare/vals kernel). Loads after def-var! and
|
||||
;; jolt-invoke (seq.ss) / jolt= (values.ss) / jolt-vector (collections.ss).
|
||||
(load "host/chez/atoms.ss")
|
||||
|
||||
;; type predicates + simple accessors (jolt-9ziu): seed natives the overlay
|
||||
;; assumes (map?/vector?/nil?/number?/.../name/namespace), def-var!'d into
|
||||
;; clojure.core. Loads after the value-model record predicates they wrap.
|
||||
(load "host/chez/predicates.ss")
|
||||
|
||||
;; --- jolt number printing ----------------------------------------------------
|
||||
;; jolt has a numeric tower (exact integer / ratio / double, distinguished by
|
||||
;; class). Exact integer-valued values print without a ".0" ((+ 1 2) -> "3");
|
||||
;; a double prints with one ((* 1.0 5) -> "5.0", as the JVM does).
|
||||
(define (jolt-num->string x)
|
||||
(cond
|
||||
;; the -e / element printer renders the infinities and NaN in READABLE form
|
||||
;; (##Inf reads back, like Clojure's REPL/pr); str/print uses "Infinity"/"NaN"
|
||||
;; (see jolt-str-render-one in converters.ss).
|
||||
((and (flonum? x) (fl= x +inf.0)) "##Inf")
|
||||
((and (flonum? x) (fl= x -inf.0)) "##-Inf")
|
||||
((and (flonum? x) (not (fl= x x))) "##NaN")
|
||||
((and (exact? x) (integer? x)) (number->string x))
|
||||
(else (number->string x))))
|
||||
|
||||
;; Program-final-value printer. jolt's `-e` prints in str-style: strings raw (no
|
||||
;; quotes), chars as `\c`/`\newline`, collections recursively. NOTE: maps/sets
|
||||
;; render in HAMT-iteration order, which is not a stable insertion order —
|
||||
;; so unordered values are compared via `=` (true/false), not printed form.
|
||||
;; The full canonical printer is Phase 2.
|
||||
(define (jolt-str-join strs)
|
||||
(cond ((null? strs) "") ((null? (cdr strs)) (car strs))
|
||||
(else (string-append (car strs) " " (jolt-str-join (cdr strs))))))
|
||||
(define (jolt-char->string c)
|
||||
(string-append "\\" (case c ((#\newline) "newline") ((#\space) "space") ((#\tab) "tab")
|
||||
((#\return) "return") (else (string c)))))
|
||||
;; Program-final printer: jolt's `-e` is str-style at the top level, where a
|
||||
;; bare nil renders as the empty string (a nil ELEMENT inside a collection still
|
||||
;; prints "nil", which jolt-pr-str handles).
|
||||
(define (jolt-final-str x) (if (jolt-nil? x) "" (jolt-pr-str x)))
|
||||
(define (jolt-pr-str x)
|
||||
(cond
|
||||
((jolt-nil? x) "nil")
|
||||
((eq? x #t) "true")
|
||||
((eq? x #f) "false")
|
||||
((number? x) (jolt-num->string x))
|
||||
((string? x) x)
|
||||
((char? x) (jolt-char->string x))
|
||||
((keyword? x) (let ((ns (keyword-t-ns x)))
|
||||
(if ns (string-append ":" ns "/" (keyword-t-name x)) (string-append ":" (keyword-t-name x)))))
|
||||
((jolt-symbol? x) (let ((ns (symbol-t-ns x)))
|
||||
(if (or (jolt-nil? ns) (not ns) (eq? ns '())) (symbol-t-name x)
|
||||
(string-append ns "/" (symbol-t-name x)))))
|
||||
((regex-t? x) (string-append "#\"" (regex-t-source x) "\""))
|
||||
((pvec? x) (let ((acc '())) (let loop ((i (fx- (pvec-count x) 1)))
|
||||
(when (fx>=? i 0) (set! acc (cons (jolt-pr-str (pvec-nth-d x i jolt-nil)) acc)) (loop (fx- i 1))))
|
||||
(string-append "[" (jolt-str-join acc) "]")))
|
||||
((pset? x) (string-append "#{" (jolt-str-join (pset-fold x (lambda (e a) (cons (jolt-pr-str e) a)) '())) "}"))
|
||||
((pmap? x) (string-append "{" (jolt-str-join
|
||||
(pmap-fold x (lambda (k v a) (cons (string-append (jolt-pr-str k) " " (jolt-pr-str v)) a)) '())) "}"))
|
||||
;; lists / cons / lazy seqs all print as (...) — forces a finite seq.
|
||||
((empty-list-t? x) "()")
|
||||
((cseq? x) (string-append "(" (jolt-str-join
|
||||
(let loop ((s x) (acc '()))
|
||||
(if (jolt-nil? s) (reverse acc)
|
||||
(loop (jolt-seq (seq-more s)) (cons (jolt-pr-str (seq-first s)) acc))))) ")"))
|
||||
(else (format "~a" x))))
|
||||
|
||||
;; converters + string ops (jolt-t6cr): str/subs/vec/keyword/symbol/compare/int/
|
||||
;; double/gensym — host-coupled seed natives def-var!'d into clojure.core. Loaded
|
||||
;; LAST because `str` reuses jolt-pr-str (defined just above).
|
||||
(load "host/chez/converters.ss")
|
||||
|
||||
;; transients (jolt-kl2l): copy-on-write transient collections + persistent disj;
|
||||
;; extends get/count/contains? to see through a transient. After collections.ss
|
||||
;; (the persistent ops it delegates to).
|
||||
(load "host/chez/transients.ss")
|
||||
|
||||
;; seq-native shims (jolt-y6mv): mapcat/take-while/drop-while/partition/sort +
|
||||
;; reduced/reduced?/identical? — seed-native fns the overlay assumes are core
|
||||
;; natives. Over the seq layer + jolt-compare, so loaded after converters.ss.
|
||||
(load "host/chez/natives-seq.ss")
|
||||
|
||||
;; readable printer + output seams (jolt-9zhh, Phase 2 inc B): __pr-str1/__write/
|
||||
;; __with-out-str/__eprint/__eprintf — the host seams the overlay print family
|
||||
;; (pr-str/pr/prn/print/println/*-str) is built on. After converters.ss (uses
|
||||
;; jolt-pr-str/jolt-str-join) + seq.ss (jolt-invoke).
|
||||
(load "host/chez/printing.ss")
|
||||
|
||||
;; collection constructors + rand (jolt-agw6, Phase 2 inc A): bind the public
|
||||
;; clojure.core names hash-map/hash-set/array-map/set/rand to the existing
|
||||
;; pmap/pset ctors. After collections.ss (the ctors) + seq.ss (seq->list).
|
||||
(load "host/chez/natives-coll.ss")
|
||||
|
||||
;; bit ops + parse-long/parse-double (jolt-cf1q.3 inc C): host-coupled scalar
|
||||
;; seed natives over the all-flonum number model.
|
||||
(load "host/chez/natives-num.ss")
|
||||
|
||||
;; multimethods (jolt-9ls5): defmulti/defmethod dispatch runtime. Needs jolt-invoke
|
||||
;; (seq.ss), jolt=/key-hash/jolt-hash-map (collections.ss), jolt-atom? (atoms.ss),
|
||||
;; jolt-pr-str (above), and the var-cell machinery — so loaded last.
|
||||
(load "host/chez/multimethods.ss")
|
||||
|
||||
;; records + protocols (jolt-jgoc, Phase 2 inc D): defrecord/deftype/defprotocol/
|
||||
;; extend-type/reify. A jrec record type set!-extended into the collection
|
||||
;; dispatchers + a protocol registry. After multimethods.ss (chez-current-ns) and
|
||||
;; the dispatchers/printers it wraps (collections/seq/values/converters/printing/
|
||||
;; transients).
|
||||
(load "host/chez/records.ss")
|
||||
|
||||
;; metadata (jolt-rkbc, Phase 2 inc E): meta / with-meta over an identity-keyed
|
||||
;; side-table. After records.ss (jrec) + the collection ctors it copies.
|
||||
(load "host/chez/natives-meta.ss")
|
||||
|
||||
;; host class tokens (jolt-13zk): bare class names (String/Keyword/File...) ->
|
||||
;; canonical JVM class-name strings + (class x). After natives-meta.ss (jolt-type)
|
||||
;; and the printer (jolt-str-render-one).
|
||||
(load "host/chez/host-class.ss")
|
||||
|
||||
;; dynamic vars (jolt-9ls5): *clojure-version* / *unchecked-math* constants the host
|
||||
;; binds natively. After collections.ss (jolt-hash-map) + def-var!.
|
||||
(load "host/chez/dynamic-vars.ss")
|
||||
|
||||
;; host tables + sorted collections (jolt-0zoy, Phase 2): jolt.host/tagged-table/
|
||||
;; ref-put!/ref-get + the 25-sorted tier's runtime (sorted-map/sorted-set routed
|
||||
;; through their :ops table). Loaded LAST — wraps the jrec-extended dispatchers
|
||||
;; (records.ss), jolt-disj (transients.ss), and value-host-tags (records.ss).
|
||||
(load "host/chez/host-table.ss")
|
||||
|
||||
;; lazy-seq bridge (jolt-dmw9, Phase 2): make-lazy-seq / coll->cells over the
|
||||
;; cseq model — unblocks every overlay fn built on the lazy-seq macro (repeat/
|
||||
;; iterate/cycle/dedupe/take-nth/keep/interpose/reductions/tree-seq/lazy-cat).
|
||||
;; Loaded LAST so %ls-seq captures the fully-extended (sorted-aware) jolt-seq.
|
||||
(load "host/chez/lazy-bridge.ss")
|
||||
|
||||
;; volatiles + sequence / transduce (jolt-xjx6, Phase 2): native volatile boxes +
|
||||
;; the transduce/sequence entry points over into-xform/reduce-seq. After
|
||||
;; natives-seq.ss (into-xform), seq.ss (reduce-seq) + atoms.ss (deref).
|
||||
(load "host/chez/natives-xform.ss")
|
||||
|
||||
;; vars as first-class objects (jolt-n7rz, Phase 2): var?/var-get/deref/invoke/=/
|
||||
;; pr-str over the rt.ss var-cell. After natives-xform.ss (chains deref) + the
|
||||
;; printers. emit lowers :the-var to (jolt-var ns name).
|
||||
(load "host/chez/vars.ss")
|
||||
|
||||
;; misc scalar natives (jolt-cf1q.3): UUID (random-uuid/parse-uuid/uuid?), format/
|
||||
;; printf, tagged-literal, bigint. After the printers + converters (str/pr-str of
|
||||
;; a uuid). Overlay names (uuid?/random-uuid/parse-uuid/tagged-literal?) re-asserted
|
||||
;; in post-prelude.ss.
|
||||
(load "host/chez/natives-misc.ss")
|
||||
|
||||
;; namespaces (jolt-yxqm, Phase 2): the namespace value model — find-ns/ns-name/
|
||||
;; all-ns/the-ns/create-ns/in-ns/ns-publics/ns-map/ns-interns/ns-aliases/resolve/
|
||||
;; find-var/ns-unmap/*ns*, over the var-table + chez-current-ns. Loaded LAST: needs
|
||||
;; var-cell + var-cell-defined?, jolt-symbol/jolt-hash-map/jolt-assoc, chez-current-ns
|
||||
;; (multimethods.ss), list->cseq (seq.ss), and the fully-patched printers (vars.ss).
|
||||
(load "host/chez/ns.ss")
|
||||
|
||||
;; dynamic var binding (jolt-2o7x, Phase 2): the per-thread binding stack +
|
||||
;; push/pop/get-thread-bindings/__thread-bound?/var-set/alter-var-root/__local-var.
|
||||
;; Chains var-deref (rt.ss) and jolt-var-get (vars.ss) onto the stack, so a `binding`
|
||||
;; frame is seen by every var read. Loaded LAST: needs the fully-extended var-read
|
||||
;; paths + jolt-hash-map/pmap-fold/pmap-assoc (collections.ss).
|
||||
(load "host/chez/dyn-binding.ss")
|
||||
|
||||
;; java.lang.String method interop (jolt-nfca, Phase 2): jolt-string-method, the
|
||||
;; portable String/CharSequence surface record-method-dispatch falls through to on
|
||||
;; a string target. After regex.ss (jolt-re-pattern/regex-t-irx) + records.ss
|
||||
;; (which references jolt-string-method).
|
||||
(load "host/chez/natives-str.ss")
|
||||
|
||||
;; host class statics + constructors (jolt-avt6, Phase 2): host-static-ref/
|
||||
;; host-static-call/host-new + the jhost method registry. Loads LAST — it extends
|
||||
;; record-method-dispatch (records.ss) and reuses natives-str helpers (str-trim,
|
||||
;; ascii-string-down, re-split, str-split-drop-trailing) + the regex-t accessors.
|
||||
(load "host/chez/host-static.ss")
|
||||
|
||||
;; generic dot-form dispatch (jolt-kuic): field access + map/vector member access
|
||||
;; for the `.` / `.-field` desugar. Loads after host-static.ss so it wraps every
|
||||
;; record-method-dispatch arm (jhost/number/regex/jrec/string) and falls through.
|
||||
(load "host/chez/dot-forms.ss")
|
||||
|
||||
;; java.io.File + host file I/O (jolt-yyud): path-backed jfile record, slurp/spit/
|
||||
;; flush, file-seq dir primitives, clojure.java.io/file. Loads LAST so its jfile
|
||||
;; arm wraps the fully-built record-method-dispatch and the str/type/instance-check
|
||||
;; extensions sit over every prior shim.
|
||||
(load "host/chez/io.ss")
|
||||
|
||||
;; #inst values + java.time formatting (jolt-at0a inc X): jinst (RFC3339 ms) +
|
||||
;; DateTimeFormatter/Instant/ZoneId/LocalDateTime/FormatStyle/Locale/Date. Loads
|
||||
;; LAST — it extends record-method-dispatch / jolt-get / jolt= / jolt-hash /
|
||||
;; jolt-pr-str / jolt-type / instance-check and uses host-static.ss's registries.
|
||||
(load "host/chez/inst-time.ss")
|
||||
|
||||
;; Chez-side data reader (jolt-r8ku inc Y): read-string / __parse-next /
|
||||
;; __read-tagged. Loads after inst-time.ss — __read-tagged reuses its #uuid/#inst
|
||||
;; constructors, and the reader needs the full value/collection layer above.
|
||||
(load "host/chez/reader.ss")
|
||||
|
||||
;; clojure.math (jolt-22vo): native flonum-math shims def-var!'d into the
|
||||
;; clojure.math ns. Self-contained (only def-var! + Chez math), order-independent.
|
||||
(load "host/chez/math.ss")
|
||||
|
||||
;; parity shims (jolt-cf1q.7): native clojure.core fns missing on the zero-Janet
|
||||
;; spine (hash family / rseq / cat / transient?). After host-table.ss (sorted),
|
||||
;; transients.ss, values.ss (jolt-hash), seq.ss.
|
||||
(load "host/chez/natives-parity.ss")
|
||||
|
||||
;; Java-style arrays (jolt-cf1q.7): object/typed array constructors + a jolt-array
|
||||
;; backing; extends count/nth/seq/get/ref-put! so the overlay aget/aset/alength see
|
||||
;; it. After the dispatchers it chains.
|
||||
(load "host/chez/natives-array.ss")
|
||||
|
||||
;; syntax-quote form builders (jolt-r9lm, inc6b): __sqcat/__sqvec/__sqmap/__sqset/
|
||||
;; __sq1, def-var!'d into clojure.core. A cross-compiled macro expander (analyzer
|
||||
;; on Chez, inc6b) calls these to build its expansion as reader forms. Needs the
|
||||
;; collection/seq layer + def-var!; order-independent past those.
|
||||
(load "host/chez/syntax-quote.ss")
|
||||
|
||||
;; concurrency (jolt-byjr): real OS-thread futures + blocking promises, shared-heap
|
||||
;; (JVM) semantics. Loaded LAST — chains the fully-built jolt-deref and conveys the
|
||||
;; thread-local binding stack (dyn-binding.ss) into workers. pmap/pcalls/pvalues
|
||||
;; (overlay, over `future`) light up once future-call exists here.
|
||||
(load "host/chez/concurrency.ss")
|
||||
|
||||
;; clojure.core.async (jolt-byjr): real-thread blocking channels + go/go-loop/
|
||||
;; thread macros, def-var!'d into clojure.core.async. After concurrency.ss (reuses
|
||||
;; ms->duration) and the collection/seq layer.
|
||||
(load "host/chez/async.ss")
|
||||
|
||||
;; BigDecimal (jolt-i2jm): the jbigdec value type + bigdec/decimal?/class/equality/
|
||||
;; printing. Loads LAST so its set!-wraps of jolt-class/jolt=2/the printers sit
|
||||
;; outermost over every earlier extension.
|
||||
(load "host/chez/bigdec.ss")
|
||||
205
host/chez/run-corpus.ss
Normal file
205
host/chez/run-corpus.ss
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
;; run-corpus.ss — the standing correctness gate, pure Chez. NO Janet.
|
||||
;;
|
||||
;; Loads the checked-in seed (host/chez/seed/{prelude,image}.ss) + the zero-Janet
|
||||
;; spine, reads test/chez/corpus.edn, and for each row evaluates :actual and
|
||||
;; :expected through jolt-compile-eval and compares by value-equality (jolt=). The
|
||||
;; corpus :expected is JVM-sourced (test/conformance/regen-corpus.clj), so this
|
||||
;; measures jolt-on-Chez against reference Clojure.
|
||||
;;
|
||||
;; Each case runs as its own top-level program (a top-level do unrolls, so a macro
|
||||
;; defined earlier in the program is usable later), and mutable global state is
|
||||
;; reset between cases so there is no leakage — same isolation a fresh process gives.
|
||||
;;
|
||||
;; chez --script host/chez/run-corpus.ss
|
||||
;; JOLT_CHEZ_ZJ_FLOOR=N override the regression floor (default 2730)
|
||||
;; JOLT_CORPUS_LIMIT=N every-Nth stride (fast iteration; floor drops to 0)
|
||||
;; JOLT_DUMP_CRASH_LABELS=1 list crash + allowlisted labels
|
||||
(import (chezscheme))
|
||||
|
||||
(load "host/chez/rt.ss")
|
||||
(set-chez-ns! "clojure.core")
|
||||
(load "host/chez/seed/prelude.ss")
|
||||
(load "host/chez/post-prelude.ss")
|
||||
(set-chez-ns! "user")
|
||||
(load "host/chez/host-contract.ss")
|
||||
(load "host/chez/seed/image.ss")
|
||||
(load "host/chez/compile-eval.ss")
|
||||
|
||||
(define (slurp path)
|
||||
(call-with-input-file path
|
||||
(lambda (p)
|
||||
(let loop ((cs '()) (c (read-char p)))
|
||||
(if (eof-object? c) (list->string (reverse cs))
|
||||
(loop (cons c cs) (read-char p)))))))
|
||||
|
||||
(define corpus (jolt-read-string (slurp "test/chez/corpus.edn")))
|
||||
(define kw-label (keyword #f "label"))
|
||||
(define kw-actual (keyword #f "actual"))
|
||||
(define kw-expected (keyword #f "expected"))
|
||||
(define kw-throws (keyword #f "throws"))
|
||||
|
||||
;; --- per-case isolation: snapshot the world after setup, restore it each case ----
|
||||
;; (1) var-table keys a case ADDS (its defs) are removed; (2) a base cell whose ROOT
|
||||
;; a case mutated (e.g. in-ns rebinds clojure.core/*ns*) is restored; (3) the ns +
|
||||
;; type registries are pruned to their base keys; (4) global-hierarchy's contents
|
||||
;; (mutated by derive) are reset to a fresh hierarchy.
|
||||
(define zj-base (let ((h (make-hashtable string-hash string=?)))
|
||||
(vector-for-each (lambda (k) (hashtable-set! h k #t)) (hashtable-keys var-table)) h))
|
||||
(define zj-roots '())
|
||||
(vector-for-each (lambda (k) (let ((c (hashtable-ref var-table k #f)))
|
||||
(when c (set! zj-roots (cons (cons c (var-cell-root c)) zj-roots)))))
|
||||
(hashtable-keys var-table))
|
||||
(define (zj-snap ht) (let ((h (make-hashtable string-hash string=?)))
|
||||
(vector-for-each (lambda (k) (hashtable-set! h k #t)) (hashtable-keys ht)) h))
|
||||
(define (zj-prune! ht base) (vector-for-each
|
||||
(lambda (k) (unless (hashtable-ref base k #f) (hashtable-delete! ht k))) (hashtable-keys ht)))
|
||||
(define zj-ns-base (zj-snap ns-registry))
|
||||
(define zj-type-base (zj-snap type-registry))
|
||||
(define zj-ghier (var-cell-lookup "clojure.core" "global-hierarchy"))
|
||||
(define (zj-reset!)
|
||||
(vector-for-each (lambda (k) (unless (hashtable-ref zj-base k #f) (hashtable-delete! var-table k)))
|
||||
(hashtable-keys var-table))
|
||||
(for-each (lambda (cr) (unless (eq? (var-cell-root (car cr)) (cdr cr))
|
||||
(var-cell-root-set! (car cr) (cdr cr)))) zj-roots)
|
||||
(zj-prune! ns-registry zj-ns-base)
|
||||
(zj-prune! type-registry zj-type-base)
|
||||
(hashtable-clear! ns-alias-table)
|
||||
(hashtable-clear! ns-refer-table)
|
||||
(hashtable-clear! ns-refer-all-table)
|
||||
(when zj-ghier (jolt-invoke (var-deref "clojure.core" "reset!")
|
||||
(var-cell-root zj-ghier) (jolt-invoke (var-deref "clojure.core" "make-hierarchy"))))
|
||||
(set-chez-ns! "user"))
|
||||
|
||||
(define kw-message (keyword #f "message"))
|
||||
(define (zj-err->str e)
|
||||
(cond ((and (pmap? e) (string? (jolt-get e kw-message))) (jolt-get e kw-message))
|
||||
((condition? e) (call-with-string-output-port (lambda (p) (display-condition e p))))
|
||||
((string? e) e)
|
||||
(else (call-with-string-output-port (lambda (p) (write e p))))))
|
||||
(define (zj-clean s)
|
||||
(list->string (map (lambda (c) (if (or (char=? c #\tab) (char=? c #\newline)) #\space c))
|
||||
(string->list s))))
|
||||
|
||||
;; --- allowlist: conformance gaps vs the JVM spec (no JVM host on Chez) -----------
|
||||
;; Keyed by label. jolt does not match because it has no Class objects / Java arrays
|
||||
;; / BigDecimal, supports the :jolt reader-conditional, or prints its own forms for
|
||||
;; transients/atoms/Infinity. These DIVERGE but are tolerated; the gate fails only on
|
||||
;; a NEW (unlisted) divergence or a drop below the floor.
|
||||
(define known-fail-labels
|
||||
'("getMessage on a thrown string"
|
||||
"close on throw" "macroexpand-1"
|
||||
"bean is the map" "proxy resolves nil"
|
||||
"transient vector" "transient map"
|
||||
"atom override fires nested"
|
||||
"reader conditional" "reader cond :jolt" "reader cond no match"
|
||||
"reader cond splice" "reader cond splice no match"
|
||||
"nil nested" "bool nested"
|
||||
"no param vector"))
|
||||
(define known-fail (make-hashtable string-hash string=?))
|
||||
(for-each (lambda (l) (hashtable-set! known-fail l #t)) known-fail-labels)
|
||||
|
||||
;; Cases skipped like :throws so they can't perturb the pass count:
|
||||
;; - "promise undelivered" BLOCKS forever on a shared-heap host (deref of an
|
||||
;; undelivered promise), so one hung case can't stall the run.
|
||||
;; - the future-cancel races: whether `future-cancel` catches a trivial
|
||||
;; `(future 1)` in-flight is pure thread-scheduling luck (the JVM expects the
|
||||
;; future still queued; on a loaded host it may already have completed). A racy
|
||||
;; outcome must not be a deterministic gate criterion — counting it inflates the
|
||||
;; floor on a fast machine and trips CI on a slow one.
|
||||
(define skip-blocking (make-hashtable string-hash string=?))
|
||||
(for-each (lambda (l) (hashtable-set! skip-blocking l #t))
|
||||
'("promise undelivered"
|
||||
"cancel an in-flight future returns true"
|
||||
"future-cancelled? after cancel"))
|
||||
|
||||
;; Coarse crash bucket for the punch-list (informational; not gate-critical).
|
||||
(define (crash-reason m)
|
||||
(define (has? sub) (let loop ((i 0))
|
||||
(cond ((> (+ i (string-length sub)) (string-length m)) #f)
|
||||
((string=? (substring m i (+ i (string-length sub))) sub) #t)
|
||||
(else (loop (+ i 1))))))
|
||||
(cond ((has? "unsupported stdlib") "emit: unsupported stdlib fn")
|
||||
((has? "unsupported host") "emit: unsupported host call")
|
||||
((has? "host-static") "emit: host-static")
|
||||
((has? "uncompil") "analyzer: uncompilable")
|
||||
((has? "Unknown class") "runtime: unknown class")
|
||||
((has? "No constructor") "runtime: no constructor")
|
||||
((has? "No method") "runtime: no method")
|
||||
((has? "not a fn") "runtime: not a fn")
|
||||
((has? "not seqable") "runtime: not seqable")
|
||||
(else (substring m 0 (min 56 (string-length m))))))
|
||||
|
||||
;; --- run ------------------------------------------------------------------------
|
||||
(define limit (let ((s (getenv "JOLT_CORPUS_LIMIT")))
|
||||
(and s (string->number s))))
|
||||
(define stride (if (and limit (> limit 0)) (max 1 (quotient (pvec-count corpus) limit)) 1))
|
||||
|
||||
(define pass 0) (define throws 0)
|
||||
(define crashes '()) ; (label . reason)
|
||||
(define diverged '()) ; (label . got) — NEW divergence; gate fails
|
||||
(define known-hit '()) ; label
|
||||
(define crash-keys (make-hashtable string-hash string=?))
|
||||
(define (bucket! ht k) (hashtable-set! ht k (+ 1 (hashtable-ref ht k 0))))
|
||||
|
||||
(define t0 (current-time))
|
||||
(let loop ((i 0))
|
||||
(when (< i (pvec-count corpus))
|
||||
(let* ((row (pvec-nth-d corpus i jolt-nil))
|
||||
(label (jolt-get row kw-label))
|
||||
(ev-src (jolt-get row kw-expected))
|
||||
(av-src (jolt-get row kw-actual)))
|
||||
(cond
|
||||
((or (eq? ev-src kw-throws) (hashtable-ref skip-blocking label #f))
|
||||
(set! throws (+ throws 1)))
|
||||
(else
|
||||
(guard (e (#t (let ((r (crash-reason (zj-clean (zj-err->str e)))))
|
||||
(bucket! crash-keys r)
|
||||
(set! crashes (cons (cons label r) crashes)))))
|
||||
;; discard a case's own stdout (a (println ...) side effect) so it can't
|
||||
;; pollute the gate report — as if the case ran in its own process.
|
||||
(let* ((sink (open-output-string))
|
||||
(av (parameterize ((current-output-port sink)) (jolt-compile-eval av-src "user")))
|
||||
(ev (parameterize ((current-output-port sink)) (jolt-compile-eval ev-src "user"))))
|
||||
(cond
|
||||
((jolt= ev av) (set! pass (+ pass 1)))
|
||||
((hashtable-ref known-fail label #f) (set! known-hit (cons label known-hit)))
|
||||
(else (set! diverged (cons (cons label (zj-clean (jolt-final-str av))) diverged))))))
|
||||
(zj-reset!))))
|
||||
(loop (+ i stride))))
|
||||
|
||||
(define n-eval (+ pass (length crashes) (length diverged) (length known-hit)))
|
||||
(define secs (let ((d (time-difference (current-time) t0)))
|
||||
(+ (time-second d) (/ (time-nanosecond d) 1e9))))
|
||||
(printf "\nZero-Janet corpus parity: ~a/~a evaluated cases pass (~as)\n"
|
||||
pass n-eval (/ (round (* secs 10)) 10.0))
|
||||
(printf " crash: ~a NEW divergence: ~a known: ~a (throws skipped: ~a)\n"
|
||||
(length crashes) (length diverged) (length known-hit) throws)
|
||||
|
||||
(when (> (hashtable-size crash-keys) 0)
|
||||
(printf "\ncrash reasons:\n")
|
||||
(let-values (((ks vs) (hashtable-entries crash-keys)))
|
||||
(for-each (lambda (pair) (printf " ~a x ~a\n" (cdr pair) (car pair)))
|
||||
(list-sort (lambda (a b) (> (cdr a) (cdr b)))
|
||||
(vector->list (vector-map cons ks vs))))))
|
||||
(when (getenv "JOLT_DUMP_CRASH_LABELS")
|
||||
(printf "\nCRASH LABELS:\n")
|
||||
(for-each (lambda (p) (printf " [~a] :: ~a\n" (cdr p) (car p)))
|
||||
(list-sort (lambda (a b) (string<? (cdr a) (cdr b))) crashes))
|
||||
(printf "\nKNOWN-HIT LABELS:\n")
|
||||
(for-each (lambda (l) (printf " ~a\n" l)) (list-sort string<? known-hit)))
|
||||
(when (> (length diverged) 0)
|
||||
(printf "\nNEW divergences (ran, wrong value) — gate FAILS:\n")
|
||||
(for-each (lambda (p) (printf " [~a] got ~a\n" (car p) (cdr p)))
|
||||
(list-head diverged (min 40 (length diverged)))))
|
||||
(when (> (length known-hit) 0)
|
||||
(printf "\n~a known (allowlisted) failures tolerated.\n" (length known-hit)))
|
||||
|
||||
;; Regression floor: fail on any NEW divergence or if pass drops below the floor.
|
||||
(define base-floor (let ((s (getenv "JOLT_CHEZ_ZJ_FLOOR")))
|
||||
(if s (string->number s) 2730)))
|
||||
(define floor (if limit 0 base-floor))
|
||||
(when (or (> (length diverged) 0) (< pass floor))
|
||||
(printf "REGRESSION: pass ~a < floor ~a or ~a new divergence(s)\n"
|
||||
pass floor (length diverged)))
|
||||
(flush-output-port)
|
||||
(exit (if (or (> (length diverged) 0) (< pass floor)) 1 0))
|
||||
81
host/chez/run-sci.ss
Normal file
81
host/chez/run-sci.ss
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
;; run-sci.ss — SCI conformance: load borkdude/sci's own source (vendor/sci) through
|
||||
;; joltc and require its forms to compile+eval. A real-world Clojure-compatibility
|
||||
;; stress test. Pure Chez, no Janet. Floor-gated like the corpus: a regression below
|
||||
;; the floor (or the count today, 205/218) fails. Raise the floor as host gaps close
|
||||
;; (the tail is genuine gaps — set! on vars, some macro/def shapes).
|
||||
;;
|
||||
;; chez --script host/chez/run-sci.ss
|
||||
;; JOLT_SCI_FLOOR=N override the floor (default 205)
|
||||
;; SCI_VERBOSE=1 print each failing form's error
|
||||
(import (chezscheme))
|
||||
|
||||
;; Skip cleanly when the submodule isn't checked out.
|
||||
(unless (file-exists? "vendor/sci/src/sci/core.cljc")
|
||||
(display "skip: vendor/sci not checked out (git submodule update --init vendor/sci)\n")
|
||||
(exit 0))
|
||||
|
||||
(load "host/chez/rt.ss")
|
||||
(set-chez-ns! "clojure.core")
|
||||
(load "host/chez/seed/prelude.ss")
|
||||
(load "host/chez/post-prelude.ss")
|
||||
(set-chez-ns! "user")
|
||||
(load "host/chez/host-contract.ss")
|
||||
(load "host/chez/seed/image.ss")
|
||||
(load "host/chez/compile-eval.ss")
|
||||
|
||||
;; SCI's .cljc selects host code via #?(:clj ...) with no :jolt branch — read clj.
|
||||
(set! rdr-features (list "clj" "jolt" "default"))
|
||||
|
||||
(define (slurp path)
|
||||
(call-with-input-file path
|
||||
(lambda (p) (let loop ((cs '()) (c (read-char p)))
|
||||
(if (eof-object? c) (list->string (reverse cs)) (loop (cons c cs) (read-char p)))))))
|
||||
|
||||
;; Load every form in a file, evaluating each in the current ns (an (ns ...) form
|
||||
;; switches it). Returns (ok . fail); failures are tolerated (lenient — SCI requires
|
||||
;; host libs that don't exist here).
|
||||
(define (load-forms path verbose)
|
||||
(let ((src (slurp path)) (ok 0) (fail 0))
|
||||
(let ((end (string-length src)))
|
||||
(let loop ((i 0))
|
||||
(call-with-values (lambda () (rdr-read-form src i end))
|
||||
(lambda (form j)
|
||||
(unless (rdr-eof? form)
|
||||
(guard (e (#t (set! fail (+ fail 1))
|
||||
(when verbose
|
||||
(printf " FAIL: ~a\n" (call-with-string-output-port
|
||||
(lambda (p) (display-condition (if (condition? e) e
|
||||
(make-message-condition (jolt-final-str e))) p)))))))
|
||||
(jolt-compile-eval-form form (chez-current-ns))
|
||||
(set! ok (+ ok 1)))
|
||||
(loop j))))))
|
||||
(cons ok fail)))
|
||||
|
||||
(define verbose (and (getenv "SCI_VERBOSE") #t))
|
||||
|
||||
;; stubs first (host shims SCI's source expects)
|
||||
(for-each (lambda (f) (load-forms (string-append "src/jolt/clojure/sci/" f) verbose))
|
||||
'("lang_stubs.clj" "io_stubs.clj" "host_stubs.clj"))
|
||||
|
||||
(define sci-base "vendor/sci/src/sci/")
|
||||
(define load-order
|
||||
'("impl/macros.cljc" "impl/protocols.cljc" "impl/types.cljc" "impl/unrestrict.cljc"
|
||||
"impl/vars.cljc" "lang.cljc" "impl/utils.cljc" "ctx_store.cljc" "impl/deftype.cljc"
|
||||
"impl/records.cljc" "impl/core_protocols.cljc" "impl/hierarchies.cljc"
|
||||
"impl/destructure.cljc" "impl/doseq_macro.cljc" "impl/for_macro.cljc" "impl/fns.cljc"
|
||||
"impl/multimethods.cljc" "impl/namespaces.cljc" "core.cljc"))
|
||||
|
||||
(define total-ok 0) (define total-fail 0)
|
||||
(for-each
|
||||
(lambda (f)
|
||||
(let* ((r (load-forms (string-append sci-base f) verbose)) (ok (car r)) (fail (cdr r)))
|
||||
(set! total-ok (+ total-ok ok)) (set! total-fail (+ total-fail fail))
|
||||
(printf " ~a: ~a ok, ~a fail\n" f ok fail)))
|
||||
load-order)
|
||||
|
||||
(printf "\nSCI load: ~a/~a forms ok (~a fail)\n" total-ok (+ total-ok total-fail) total-fail)
|
||||
(define floor (let ((s (getenv "JOLT_SCI_FLOOR"))) (if s (string->number s) 205)))
|
||||
(when (< total-ok floor)
|
||||
(printf "REGRESSION: ~a forms loaded < floor ~a\n" total-ok floor))
|
||||
(flush-output-port)
|
||||
(exit (if (< total-ok floor) 1 0))
|
||||
104
host/chez/run-unit.ss
Normal file
104
host/chez/run-unit.ss
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
;; run-unit.ss — host-specific unit gate, pure Chez. NO Janet.
|
||||
;;
|
||||
;; Loads the checked-in seed + spine, reads test/chez/unit.edn, and for each case
|
||||
;; evaluates :expr (wrapped in (do ...), as `joltc -e` does) and compares its PRINTED
|
||||
;; value (jolt-final-str) to the literal :expected string. :expected :throws asserts
|
||||
;; the case raises. These cover host-specific behavior (dot-forms, java statics, io,
|
||||
;; reader, walk, …) that isn't in the JVM-portable corpus. Global state is reset
|
||||
;; between cases for per-case isolation.
|
||||
;;
|
||||
;; chez --script host/chez/run-unit.ss
|
||||
(import (chezscheme))
|
||||
|
||||
(load "host/chez/rt.ss")
|
||||
(set-chez-ns! "clojure.core")
|
||||
(load "host/chez/seed/prelude.ss")
|
||||
(load "host/chez/post-prelude.ss")
|
||||
(set-chez-ns! "user")
|
||||
(load "host/chez/host-contract.ss")
|
||||
(load "host/chez/seed/image.ss")
|
||||
(load "host/chez/compile-eval.ss")
|
||||
|
||||
(define (slurp path)
|
||||
(call-with-input-file path
|
||||
(lambda (p)
|
||||
(let loop ((cs '()) (c (read-char p)))
|
||||
(if (eof-object? c) (list->string (reverse cs))
|
||||
(loop (cons c cs) (read-char p)))))))
|
||||
|
||||
(define cases (jolt-read-string (slurp "test/chez/unit.edn")))
|
||||
(define kw-suite (keyword #f "suite"))
|
||||
(define kw-expr (keyword #f "expr"))
|
||||
(define kw-expected (keyword #f "expected"))
|
||||
(define kw-throws (keyword #f "throws"))
|
||||
|
||||
;; --- per-case isolation (snapshot the world after setup, restore each case) -------
|
||||
(define zj-base (let ((h (make-hashtable string-hash string=?)))
|
||||
(vector-for-each (lambda (k) (hashtable-set! h k #t)) (hashtable-keys var-table)) h))
|
||||
(define zj-roots '())
|
||||
(vector-for-each (lambda (k) (let ((c (hashtable-ref var-table k #f)))
|
||||
(when c (set! zj-roots (cons (cons c (var-cell-root c)) zj-roots)))))
|
||||
(hashtable-keys var-table))
|
||||
(define (zj-snap ht) (let ((h (make-hashtable string-hash string=?)))
|
||||
(vector-for-each (lambda (k) (hashtable-set! h k #t)) (hashtable-keys ht)) h))
|
||||
(define (zj-prune! ht base) (vector-for-each
|
||||
(lambda (k) (unless (hashtable-ref base k #f) (hashtable-delete! ht k))) (hashtable-keys ht)))
|
||||
(define zj-ns-base (zj-snap ns-registry))
|
||||
(define zj-type-base (zj-snap type-registry))
|
||||
(define zj-ghier (var-cell-lookup "clojure.core" "global-hierarchy"))
|
||||
(define (zj-reset!)
|
||||
(vector-for-each (lambda (k) (unless (hashtable-ref zj-base k #f) (hashtable-delete! var-table k)))
|
||||
(hashtable-keys var-table))
|
||||
(for-each (lambda (cr) (unless (eq? (var-cell-root (car cr)) (cdr cr))
|
||||
(var-cell-root-set! (car cr) (cdr cr)))) zj-roots)
|
||||
(zj-prune! ns-registry zj-ns-base)
|
||||
(zj-prune! type-registry zj-type-base)
|
||||
(hashtable-clear! ns-alias-table)
|
||||
(hashtable-clear! ns-refer-table)
|
||||
(hashtable-clear! ns-refer-all-table)
|
||||
(when zj-ghier (jolt-invoke (var-deref "clojure.core" "reset!")
|
||||
(var-cell-root zj-ghier) (jolt-invoke (var-deref "clojure.core" "make-hierarchy"))))
|
||||
(set-chez-ns! "user"))
|
||||
|
||||
;; --- run ------------------------------------------------------------------------
|
||||
(define pass 0)
|
||||
(define fails '()) ; (suite expr msg)
|
||||
(define suite-pass (make-hashtable string-hash string=?))
|
||||
(define suite-total (make-hashtable string-hash string=?))
|
||||
(define (bump! ht k) (hashtable-set! ht k (+ 1 (hashtable-ref ht k 0))))
|
||||
|
||||
(let loop ((i 0))
|
||||
(when (< i (pvec-count cases))
|
||||
(let* ((row (pvec-nth-d cases i jolt-nil))
|
||||
(suite (jolt-get row kw-suite))
|
||||
(expr (jolt-get row kw-expr))
|
||||
(expected (jolt-get row kw-expected))
|
||||
(throws? (eq? expected kw-throws))
|
||||
(sink (open-output-string)))
|
||||
(bump! suite-total suite)
|
||||
(guard (e (#t (if throws?
|
||||
(begin (set! pass (+ pass 1)) (bump! suite-pass suite))
|
||||
(set! fails (cons (list suite expr "raised") fails)))))
|
||||
(let ((got (jolt-final-str
|
||||
(parameterize ((current-output-port sink))
|
||||
(jolt-compile-eval (string-append "(do " expr ")") "user")))))
|
||||
(cond
|
||||
(throws? (set! fails (cons (list suite expr (string-append "expected throw; got " got)) fails)))
|
||||
((string=? got expected) (begin (set! pass (+ pass 1)) (bump! suite-pass suite)))
|
||||
(else (set! fails (cons (list suite expr
|
||||
(string-append "want `" expected "` got `" got "`")) fails))))))
|
||||
(zj-reset!))
|
||||
(loop (+ i 1))))
|
||||
|
||||
(printf "\nunit gate: ~a/~a passed\n" pass (pvec-count cases))
|
||||
(let-values (((ks vs) (hashtable-entries suite-total)))
|
||||
(for-each (lambda (p)
|
||||
(printf " ~a/~a ~a\n" (hashtable-ref suite-pass (car p) 0) (cdr p) (car p)))
|
||||
(list-sort (lambda (a b) (string<? (car a) (car b)))
|
||||
(vector->list (vector-map cons ks vs)))))
|
||||
(when (> (length fails) 0)
|
||||
(printf "\n~a FAIL(s):\n" (length fails))
|
||||
(for-each (lambda (f) (printf " [~a] ~a\n ~a\n" (car f) (caddr f) (cadr f)))
|
||||
(list-head (reverse fails) (min 40 (length fails)))))
|
||||
(flush-output-port)
|
||||
(exit (if (> (length fails) 0) 1 0))
|
||||
25
host/chez/seed/README.md
Normal file
25
host/chez/seed/README.md
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
# Chez bootstrap seed
|
||||
|
||||
These two files are the **bootstrap compiler** for jolt — the seed that makes
|
||||
the build self-hosting:
|
||||
|
||||
- `prelude.ss` — the `clojure.core` prelude (all tiers + clojure.string/walk/
|
||||
template/edn/set/pprint) as Scheme `def-var!` forms.
|
||||
- `image.ss` — the compiler image (`jolt.ir` + `jolt.analyzer` +
|
||||
`jolt.backend-scheme`) as Scheme `def-var!` forms.
|
||||
|
||||
Both are **generated**, not hand-written. They are checked in because a fresh
|
||||
checkout must be able to build jolt-on-Chez using only Chez: `host/chez/bootstrap.ss`
|
||||
loads this seed, then rebuilds the prelude + image from the `.clj`/`.ss` sources via
|
||||
the on-Chez compiler (read → analyze → emit, all on Chez). The seed is a **joint
|
||||
byte-fixpoint**: rebuilding from an up-to-date seed reproduces it exactly.
|
||||
`make selfhost` (`host/chez/selfcheck.sh`) runs `host/chez/bootstrap.ss` and diffs
|
||||
the rebuilt artifacts against the checked-in seed.
|
||||
|
||||
## Re-minting
|
||||
|
||||
When the seed sources change (the core tiers, the compiler namespaces, the host
|
||||
contract, the reader, `emit-image.ss`), the seed drifts and `make selfhost`
|
||||
fails. Re-mint it by running `host/chez/bootstrap.ss` and writing the freshly
|
||||
rebuilt prelude/image back to `host/chez/seed/prelude.ss` /
|
||||
`host/chez/seed/image.ss`, then commit the refreshed files.
|
||||
186
host/chez/seed/image.ss
Normal file
186
host/chez/seed/image.ss
Normal file
File diff suppressed because one or more lines are too long
1104
host/chez/seed/prelude.ss
Normal file
1104
host/chez/seed/prelude.ss
Normal file
File diff suppressed because one or more lines are too long
18
host/chez/selfcheck.sh
Executable file
18
host/chez/selfcheck.sh
Executable file
|
|
@ -0,0 +1,18 @@
|
|||
#!/bin/sh
|
||||
# self-host fixpoint gate: bootstrap.ss rebuilds the prelude + compiler image from
|
||||
# source on pure Chez; the rebuild must equal the checked-in seed byte-for-byte. If
|
||||
# it doesn't, a seed source changed without a re-mint — run `make remint`.
|
||||
set -e
|
||||
root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
|
||||
cd "$root"
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
chez --script host/chez/bootstrap.ss \
|
||||
host/chez/seed/prelude.ss host/chez/seed/image.ss "$tmp/p.ss" "$tmp/i.ss" >/dev/null
|
||||
if diff -q host/chez/seed/prelude.ss "$tmp/p.ss" >/dev/null \
|
||||
&& diff -q host/chez/seed/image.ss "$tmp/i.ss" >/dev/null; then
|
||||
echo "self-host fixpoint: rebuild == checked-in seed"
|
||||
else
|
||||
echo "self-host FAILED: bootstrap rebuild != checked-in seed; run 'make remint'" >&2
|
||||
exit 1
|
||||
fi
|
||||
288
host/chez/seq.ss
Normal file
288
host/chez/seq.ss
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
;; Phase 1 (jolt-cf1q.2, inc 3b) — the seq tier on the Chez RT.
|
||||
;;
|
||||
;; One lazy-capable node (cseq) models Clojure's list, cons, and lazy seq — all
|
||||
;; print as (...), all sequential-= to each other AND to vectors. `jolt-seq`
|
||||
;; coerces any seqable (vector/map/set/string/list/seq/nil) to a cseq or nil.
|
||||
;; The empty seq is a distinct value (jolt-empty-list) that prints "()" — Clojure
|
||||
;; (rest [1]) is () not nil, (seq []) is nil. The higher-order fns
|
||||
;; (map/filter/reduce/into/remove) apply their fn argument through `jolt-invoke`,
|
||||
;; so a procedure, a keyword, or a collection all work as the fn (IFn dispatch).
|
||||
;;
|
||||
;; Loaded by rt.ss after collections.ss. values.ss / collections.ss reach the
|
||||
;; jolt-sequential? / seq=? / seq-hash hooks defined here as forward refs (nothing
|
||||
;; is CALLED during load).
|
||||
|
||||
;; ============================================================================
|
||||
;; the seq node + the empty-seq sentinel
|
||||
;; ============================================================================
|
||||
;; head : the realized first element. tail : EITHER a realized seq (cseq |
|
||||
;; jolt-nil) when forced? is #t, OR a 0-arg thunk producing one when forced? is
|
||||
;; #f. Forcing memoizes (set the tail to the produced seq, flip forced?).
|
||||
;; list? : #t when this cell is a PersistentList node (list literal / (list ...)
|
||||
;; / cons / reverse / conj-onto-list) vs a lazy or vector-backed seq cell — the
|
||||
;; only thing that distinguishes a list from any other realized seq on this host,
|
||||
;; since one record type backs both (clojure.core/list? — jolt-75sv). The marker
|
||||
;; lives on the cell, so (rest a-list) / (seq a-vector) / (map …) yield plain seq
|
||||
;; cells and are not list?.
|
||||
;; cvec/ci: for a vector-backed seq cell, the backing vector and this cell's
|
||||
;; element index — so it is a real chunked-seq (chunked-seq? true, chunk-first
|
||||
;; hands out a 32-element block, chunk-rest is the seq at the next block) and
|
||||
;; reduce iterates the vector directly with no per-element cells (jolt-hs5q).
|
||||
;; cvec is #f for every other seq; stored as two fields (not a cons) so a vector
|
||||
;; seq cell costs no extra allocation. The rest of the seq layer ignores them, so
|
||||
;; first/rest/count/printing are unchanged.
|
||||
(define-record-type cseq (fields head (mutable tail) (mutable forced?) list? cvec ci) (nongenerative chez-cseq-v3))
|
||||
(define (cseq-realized head tail) (make-cseq head tail #t #f #f 0)) ; tail already a seq
|
||||
(define (cseq-lazy head tail-thunk) (make-cseq head tail-thunk #f #f #f 0))
|
||||
(define (cseq-list head tail) (make-cseq head tail #t #t #f 0)) ; a PersistentList node
|
||||
(define (cseq-vec head tail-thunk v i) (make-cseq head tail-thunk #f #f v i)) ; vector-backed
|
||||
(define (seq-first s) (cseq-head s))
|
||||
(define (seq-more s) ; force the tail; returns a seq (cseq | jolt-nil)
|
||||
(if (cseq-forced? s) (cseq-tail s)
|
||||
(let ((t ((cseq-tail s)))) (cseq-tail-set! s t) (cseq-forced?-set! s #t) t)))
|
||||
|
||||
;; The empty seq (Clojure's empty list ()), distinct from nil.
|
||||
(define-record-type empty-list-t (fields) (nongenerative empty-list-v1))
|
||||
(define jolt-empty-list (make-empty-list-t))
|
||||
|
||||
;; reduced (jolt-y6mv): a box a reducing fn returns to stop reduce early. The
|
||||
;; reduce machinery below unwraps it; (deref a-reduced) / unreduced also read it.
|
||||
;; reduced?/reduced are def-var!'d into clojure.core in natives-seq.ss.
|
||||
(define-record-type jolt-reduced (fields val) (nongenerative jolt-reduced-v1))
|
||||
|
||||
;; ============================================================================
|
||||
;; jolt-seq — coerce a seqable to a non-empty seq, or jolt-nil when empty
|
||||
;; ============================================================================
|
||||
(define (list->cseq xs) ; Scheme list -> realized cseq chain (jolt-nil if empty)
|
||||
(if (null? xs) jolt-nil (cseq-realized (car xs) (list->cseq (cdr xs)))))
|
||||
(define (vec->seq v i) ; chunked index seq over a persistent vector
|
||||
(if (fx>=? i (pvec-count v)) jolt-nil
|
||||
(cseq-vec (pvec-nth-d v i jolt-nil) (lambda () (vec->seq v (fx+ i 1))) v i)))
|
||||
(define (str->seq s i)
|
||||
(if (fx>=? i (string-length s)) jolt-nil
|
||||
(cseq-lazy (string-ref s i) (lambda () (str->seq s (fx+ i 1))))))
|
||||
(define (jolt-seq x)
|
||||
(cond
|
||||
((jolt-nil? x) jolt-nil)
|
||||
((empty-list-t? x) jolt-nil)
|
||||
((cseq? x) x)
|
||||
((pvec? x) (vec->seq x 0))
|
||||
((pmap? x) (list->cseq (pmap-fold x (lambda (k v a) (cons (make-map-entry k v) a)) '())))
|
||||
((pset? x) (list->cseq (pset-fold x cons '())))
|
||||
((string? x) (str->seq x 0))
|
||||
(else (error 'seq "not seqable" x))))
|
||||
|
||||
(define (jolt-sequential? x) (or (pvec? x) (cseq? x) (empty-list-t? x)))
|
||||
(define (seq->list s) ; force a finite seq to a Scheme list
|
||||
(let loop ((s (jolt-seq s)) (acc '()))
|
||||
(if (jolt-nil? s) (reverse acc) (loop (jolt-seq (seq-more s)) (cons (seq-first s) acc)))))
|
||||
|
||||
;; ============================================================================
|
||||
;; the seq leaf ops the emitter lowers core fns to
|
||||
;; ============================================================================
|
||||
(define (jolt-first x) (let ((s (jolt-seq x))) (if (jolt-nil? s) jolt-nil (seq-first s))))
|
||||
(define (jolt-rest x) ; () when the seq has 0/1 elements (NOT nil)
|
||||
(let ((s (jolt-seq x)))
|
||||
(if (jolt-nil? s) jolt-empty-list
|
||||
(let ((m (seq-more s))) (if (jolt-nil? m) jolt-empty-list m)))))
|
||||
(define (jolt-next x) ; nil when the rest is empty
|
||||
;; next = (seq (rest x)): the rest must be RE-SEQ'd so an empty tail collapses to
|
||||
;; nil. seq-more on a lazy seq (e.g. map's) forces to jolt-empty-list, which is
|
||||
;; truthy — returning it raw made (next 1-elem-lazy-seq) non-nil, so butlast and
|
||||
;; other (if (next s) ...) loops over a lazy seq ran one step too far.
|
||||
(let ((s (jolt-seq x))) (if (jolt-nil? s) jolt-nil (jolt-seq (seq-more s)))))
|
||||
;; Only the HEAD cell carries the list marker — (rest a-list)/(next a-list) return
|
||||
;; the unmarked tail, so they are seqs and not list? (rest-of-a-list is a non-list
|
||||
;; seq). cons/list/reverse/conj therefore mark
|
||||
;; just the cell they create.
|
||||
;;
|
||||
;; cons always yields a list — (list? (cons x anything)) is true (cons
|
||||
;; onto a vector/seq/nil all report list?).
|
||||
(define (jolt-cons x coll) (cseq-list x (jolt-seq coll)))
|
||||
;; Scheme list -> a jolt PersistentList: head is a list cell, the tail chain is
|
||||
;; plain seq cells. For (list …) and quoted list literals (the emitter lowers
|
||||
;; '(a b) to (jolt-list a b)).
|
||||
(define (jolt-list . xs)
|
||||
(if (null? xs) jolt-empty-list (cseq-list (car xs) (list->cseq (cdr xs)))))
|
||||
;; reverse yields a list (seed: (list? (reverse coll)) is always true). Build a
|
||||
;; plain seq chain, then mark its head as a list cell.
|
||||
(define (jolt-reverse coll)
|
||||
(let loop ((s (jolt-seq coll)) (acc jolt-empty-list))
|
||||
(if (jolt-nil? s)
|
||||
(if (empty-list-t? acc) acc (cseq-list (seq-first acc) (seq-more acc)))
|
||||
(loop (jolt-seq (seq-more s)) (cseq-realized (seq-first s) (if (empty-list-t? acc) jolt-nil acc))))))
|
||||
(define (jolt-last coll) (let loop ((s (jolt-seq coll)) (last jolt-nil))
|
||||
(if (jolt-nil? s) last (loop (jolt-seq (seq-more s)) (seq-first s)))))
|
||||
;; nth over a seq (walks; forces lazily). default? selects the 3-arg behavior.
|
||||
(define (seq-nth coll i default? d)
|
||||
(if (fx<? i 0) (if default? d (error 'nth "index out of bounds"))
|
||||
(let loop ((s (jolt-seq coll)) (i i))
|
||||
(cond ((jolt-nil? s) (if default? d (error 'nth "index out of bounds")))
|
||||
((fx=? i 0) (seq-first s))
|
||||
(else (loop (jolt-seq (seq-more s)) (fx- i 1)))))))
|
||||
|
||||
;; value-position arithmetic (the higher-order forms: (reduce + []), (apply * xs)).
|
||||
;; Scheme's +/-/*// already implement the JVM-parity numeric tower: exact+exact ->
|
||||
;; exact, exact/exact -> Ratio, any flonum -> flonum. Identities (+)=0 / (*)=1 are
|
||||
;; exact, matching exact integer arithmetic. The hot path uses the inlined native
|
||||
;; ops, not these.
|
||||
(define (jolt-add . xs) (apply + xs))
|
||||
(define (jolt-sub . xs) (apply - xs))
|
||||
(define (jolt-mul . xs) (apply * xs))
|
||||
(define (jolt-div . xs) (apply / xs))
|
||||
|
||||
;; ============================================================================
|
||||
;; IFn dispatch — the dynamic "value as fn" fallback. A callee that the emitter
|
||||
;; can't statically resolve to a procedure (a keyword/coll/proc held in a local)
|
||||
;; routes here. Off the arithmetic/self-recursion hot path by construction.
|
||||
;; ============================================================================
|
||||
(define (jolt-invoke f . args)
|
||||
(cond
|
||||
((procedure? f) (apply f args))
|
||||
((keyword? f) (apply jolt-get (car args) f (cdr args))) ; (:k m [d]) -> (get m :k [d])
|
||||
((jolt-coll? f) (apply jolt-get f args)) ; (coll k [d]) -> (get coll k [d])
|
||||
((jolt-transient? f) (apply jolt-get f args)) ; a transient vec/map/set is callable on the JVM
|
||||
(else (error 'invoke "not a fn" f))))
|
||||
|
||||
;; ============================================================================
|
||||
;; map / filter / reduce / into / remove + range / take / concat / apply
|
||||
;; ============================================================================
|
||||
(define (any-nil? seqs) (and (pair? seqs) (or (jolt-nil? (car seqs)) (any-nil? (cdr seqs)))))
|
||||
;; An EMPTY seq result is () (jolt-empty-list), NOT nil — Clojure's (map f []) is
|
||||
;; an empty seq, so (= () (map f [])) is true and (nil? (map f [])) is false.
|
||||
;; jolt-empty-list seqs back to nil, so it stays a valid lazy-tail terminator for
|
||||
;; the non-empty case (printing / seq= / reduce all walk via jolt-seq).
|
||||
(define (map-seq f s)
|
||||
(if (jolt-nil? s) jolt-empty-list
|
||||
(cseq-lazy (jolt-invoke f (seq-first s)) (lambda () (map-seq f (jolt-seq (seq-more s)))))))
|
||||
(define (map-seq* f seqs) ; multi-collection map; stops at the shortest
|
||||
(if (any-nil? seqs) jolt-empty-list
|
||||
(cseq-lazy (apply jolt-invoke f (map seq-first seqs))
|
||||
(lambda () (map-seq* f (map (lambda (s) (jolt-seq (seq-more s))) seqs))))))
|
||||
(define (jolt-map f . colls)
|
||||
(if (null? (cdr colls))
|
||||
(map-seq f (jolt-seq (car colls)))
|
||||
(map-seq* f (map jolt-seq colls))))
|
||||
|
||||
(define (filter-seq pred s keep)
|
||||
(let loop ((s s))
|
||||
(cond ((jolt-nil? s) jolt-empty-list) ; empty result is () (see map-seq)
|
||||
((eq? keep (jolt-truthy? (jolt-invoke pred (seq-first s))))
|
||||
(cseq-lazy (seq-first s) (lambda () (filter-seq pred (jolt-seq (seq-more s)) keep))))
|
||||
(else (loop (jolt-seq (seq-more s)))))))
|
||||
(define (jolt-filter pred coll) (filter-seq pred (jolt-seq coll) #t))
|
||||
(define (jolt-remove pred coll) (filter-seq pred (jolt-seq coll) #f))
|
||||
|
||||
;; honors `reduced`: a reducing fn that returns (reduced x) stops the fold and
|
||||
;; unwraps to x (so does a reduced INIT). Checked at entry, so the value returned
|
||||
;; by the last step is unwrapped on the next turn before the seq is consulted.
|
||||
;; reduce a vector's backing store directly by index from element i — no per-
|
||||
;; element seq cells. Honors `reduced`. The chunked-seq fast path.
|
||||
(define (vec-reduce f acc v i)
|
||||
(let ((n (pvec-count v)) (raw (pvec-v v)))
|
||||
(let loop ((i i) (acc acc))
|
||||
(cond ((jolt-reduced? acc) (jolt-reduced-val acc))
|
||||
((fx>=? i n) acc)
|
||||
(else (loop (fx+ i 1) (jolt-invoke f acc (vector-ref raw i))))))))
|
||||
(define (reduce-seq f acc s)
|
||||
(cond
|
||||
((jolt-reduced? acc) (jolt-reduced-val acc))
|
||||
((jolt-nil? s) acc)
|
||||
;; a vector-backed (chunked) seq reduces its vector directly, in a tight loop.
|
||||
((and (cseq? s) (cseq-cvec s)) (vec-reduce f acc (cseq-cvec s) (cseq-ci s)))
|
||||
(else (reduce-seq f (jolt-invoke f acc (seq-first s)) (jolt-seq (seq-more s))))))
|
||||
(define jolt-reduce
|
||||
(case-lambda
|
||||
((f coll) (let ((s (jolt-seq coll)))
|
||||
(if (jolt-nil? s) (jolt-invoke f) ; (reduce f []) -> (f)
|
||||
(reduce-seq f (seq-first s) (jolt-seq (seq-more s))))))
|
||||
((f init coll)
|
||||
;; IReduceInit: a reify/record with its own `reduce` method drives the
|
||||
;; reduction (reduce f init (reify clojure.lang.IReduceInit (reduce [_ f i] ...))).
|
||||
(cond
|
||||
((and (jreify? coll) (reified-methods coll)
|
||||
(hashtable-ref (reified-methods coll) "reduce" #f))
|
||||
=> (lambda (m) (let ((r (jolt-invoke m coll f init)))
|
||||
(if (jolt-reduced? r) (jolt-reduced-val r) r))))
|
||||
(else (reduce-seq f init (jolt-seq coll)))))))
|
||||
|
||||
(define (jolt-into to from) (reduce-seq (lambda (acc x) (jolt-conj1 acc x)) to (jolt-seq from)))
|
||||
|
||||
(define (range-from n) (cseq-lazy n (lambda () (range-from (+ n 1)))))
|
||||
(define (range-bounded n end step)
|
||||
(if (if (> step 0.0) (< n end) (> n end))
|
||||
(cseq-lazy n (lambda () (range-bounded (+ n step) end step)))
|
||||
jolt-nil))
|
||||
;; numeric tower (jolt-n6al): exact 0/1 defaults so (range 3) yields exact ints
|
||||
;; (= JVM longs); flonum args still produce flonums (Scheme arithmetic preserves).
|
||||
(define jolt-range
|
||||
(case-lambda
|
||||
(() (range-from 0))
|
||||
((end) (range-bounded 0 end 1))
|
||||
((start end) (range-bounded start end 1))
|
||||
((start end step) (range-bounded start end step))))
|
||||
|
||||
(define (jolt-take n coll)
|
||||
(let ((n (->idx n)))
|
||||
(let loop ((n n) (s (jolt-seq coll)))
|
||||
(if (or (fx<=? n 0) (jolt-nil? s)) jolt-nil
|
||||
(cseq-lazy (seq-first s) (lambda () (loop (fx- n 1) (jolt-seq (seq-more s)))))))))
|
||||
(define (jolt-drop n coll)
|
||||
(let loop ((n (->idx n)) (s (jolt-seq coll)))
|
||||
(if (or (fx<=? n 0) (jolt-nil? s)) (if (jolt-nil? s) jolt-empty-list s)
|
||||
(loop (fx- n 1) (jolt-seq (seq-more s))))))
|
||||
|
||||
;; lazily append seq a then the seqable produced by the thunk `brest` — the rest
|
||||
;; is NOT forced until a is exhausted, so concat is fully lazy (Clojure semantics).
|
||||
;; This matters for a self-referential lazy-cat (fib = (lazy-cat [0 1] (map + (rest
|
||||
;; fib) fib))): forcing the rest eagerly at construction would read fib before its
|
||||
;; def binds, memoizing the tail as empty.
|
||||
(define (concat2 a brest)
|
||||
(if (jolt-nil? a) (jolt-seq (brest))
|
||||
(cseq-lazy (seq-first a) (lambda () (concat2 (jolt-seq (seq-more a)) brest)))))
|
||||
(define (jolt-concat . colls)
|
||||
(cond ((null? colls) jolt-empty-list)
|
||||
((null? (cdr colls)) (jolt-seq (car colls)))
|
||||
(else (concat2 (jolt-seq (car colls)) (lambda () (apply jolt-concat (cdr colls)))))))
|
||||
|
||||
;; (apply f a b ... coll): spread the trailing seqable into the call.
|
||||
(define (jolt-apply f . args)
|
||||
(let* ((r (reverse args)) (spread (seq->list (jolt-seq (car r)))) (fixed (reverse (cdr r))))
|
||||
(apply jolt-invoke f (append fixed spread))))
|
||||
|
||||
;; ============================================================================
|
||||
;; numeric predicates / identity — usable in fn AND value position (map/filter).
|
||||
;; Return Scheme #t/#f (= jolt true/false). All-flonum model: coerce to an exact
|
||||
;; integer for the parity tests.
|
||||
;; ============================================================================
|
||||
;; Parity over the full integer range (JVM even?/odd? accept any integer,
|
||||
;; bignums included); a fixnum-only fxand crashes on a large value (e.g. a hash).
|
||||
(define (parity-int n) (if (flonum? n) (exact (floor n)) n))
|
||||
(define (jolt-even? n) (even? (parity-int n)))
|
||||
(define (jolt-odd? n) (odd? (parity-int n)))
|
||||
(define (jolt-pos? n) (> n 0))
|
||||
(define (jolt-neg? n) (< n 0))
|
||||
(define (jolt-zero? n) (= n 0))
|
||||
(define (jolt-identity x) x)
|
||||
|
||||
;; ============================================================================
|
||||
;; keys / vals — return seqs (nil on the empty map), HAMT-iteration order
|
||||
;; ============================================================================
|
||||
(define (jolt-keys m) (if (jolt-nil? m) jolt-nil (list->cseq (pmap-fold m (lambda (k v a) (cons k a)) '()))))
|
||||
(define (jolt-vals m) (if (jolt-nil? m) jolt-nil (list->cseq (pmap-fold m (lambda (k v a) (cons v a)) '()))))
|
||||
|
||||
;; ============================================================================
|
||||
;; sequential equality + hash (hooks called from values.ss / collections.ss);
|
||||
;; consistent with the persistent vector's element-wise =/hash so a vector and a
|
||||
;; list of the same elements are jolt= and hash alike.
|
||||
;; ============================================================================
|
||||
(define (seq=? a b)
|
||||
(let loop ((sa (jolt-seq a)) (sb (jolt-seq b)))
|
||||
(cond ((and (jolt-nil? sa) (jolt-nil? sb)) #t)
|
||||
((or (jolt-nil? sa) (jolt-nil? sb)) #f)
|
||||
((jolt= (seq-first sa) (seq-first sb)) (loop (jolt-seq (seq-more sa)) (jolt-seq (seq-more sb))))
|
||||
(else #f))))
|
||||
(define (seq-hash x)
|
||||
(let loop ((s (jolt-seq x)) (h 1))
|
||||
(if (jolt-nil? s) (bitwise-and h hmask)
|
||||
(loop (jolt-seq (seq-more s)) (bitwise-and (+ (* 31 h) (key-hash (seq-first s))) hmask)))))
|
||||
36
host/chez/smoke.sh
Executable file
36
host/chez/smoke.sh
Executable file
|
|
@ -0,0 +1,36 @@
|
|||
#!/bin/sh
|
||||
# CLI smoke: exercise the real bin/joltc process end to end — core eval, runtime
|
||||
# eval/load-string, runtime defmacro, futures, and the numeric tower. The in-process
|
||||
# corpus/unit gates cover semantics in depth; this confirms the CLI entry itself.
|
||||
root="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
|
||||
cd "$root"
|
||||
|
||||
fails=0
|
||||
check() {
|
||||
got="$(bin/joltc -e "$1" 2>/dev/null | tail -1)"
|
||||
if [ "$got" = "$2" ]; then
|
||||
pass=$((pass + 1))
|
||||
else
|
||||
echo " FAIL: $1"
|
||||
echo " want \`$2\` got \`$got\`"
|
||||
fails=$((fails + 1))
|
||||
fi
|
||||
}
|
||||
pass=0
|
||||
|
||||
check '(+ 1 2)' '3'
|
||||
check '(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 15)' '610'
|
||||
check '(->> (range 10) (filter even?) (map (fn [x] (* x x))) (reduce +))' '120'
|
||||
check '(let [{:keys [a b] :or {b 99}} {:a 1}] [a b])' '[1 99]'
|
||||
check '(map inc [1 2 3])' '(2 3 4)'
|
||||
check '(require [clojure.string :as s]) (s/upper-case "hello")' 'HELLO'
|
||||
check '(eval (quote (+ 1 2)))' '3'
|
||||
check '(load-string "(def y 5) (* y y)")' '25'
|
||||
check '(defmacro add1 [x] (list (quote +) x 1)) (add1 10)' '11'
|
||||
check '(deref (future (+ 1 2)))' '3'
|
||||
check '(/ 1 2)' '1/2'
|
||||
check '(= 3 3.0)' 'false'
|
||||
check '(== 3 3.0)' 'true'
|
||||
|
||||
echo "cli smoke: $pass passed, $fails failed"
|
||||
[ "$fails" -eq 0 ]
|
||||
153
host/chez/sqlite.ss
Normal file
153
host/chez/sqlite.ss
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
;; sqlite.ss (jolt-90sp) — jolt.sqlite + a jdbc.core API over the system
|
||||
;; libsqlite3 via Chez's FFI. The sqlite3 C API is non-variadic, so it binds
|
||||
;; directly (unlike libcurl). Enough of the surface for a small app: open/close,
|
||||
;; exec (DDL/DML), a prepared query returning row maps, parameter binding
|
||||
;; (text/int/double), and last_insert_rowid.
|
||||
;;
|
||||
;; def-var!'d into jolt.sqlite AND jdbc.core (jolt-lang/db's API: connection /
|
||||
;; execute! / fetch / fetch-one / last-insert-id), so an app that requires
|
||||
;; jdbc.core resolves it as a baked namespace.
|
||||
|
||||
(define sqlite-available?
|
||||
(let loop ((names '("libsqlite3.0.dylib" "libsqlite3.so.0" "libsqlite3.dylib" "libsqlite3.so")))
|
||||
(cond ((null? names) #f)
|
||||
((guard (e (#t #f)) (load-shared-object (car names)) #t) #t)
|
||||
(else (loop (cdr names))))))
|
||||
|
||||
(define sqlite3_open (foreign-procedure "sqlite3_open" (string void*) int))
|
||||
(define sqlite3_close (foreign-procedure "sqlite3_close" (void*) int))
|
||||
(define sqlite3_errmsg (foreign-procedure "sqlite3_errmsg" (void*) string))
|
||||
(define sqlite3_prepare_v2 (foreign-procedure "sqlite3_prepare_v2" (void* string int void* uptr) int))
|
||||
(define sqlite3_step (foreign-procedure "sqlite3_step" (void*) int))
|
||||
(define sqlite3_finalize (foreign-procedure "sqlite3_finalize" (void*) int))
|
||||
(define sqlite3_column_count (foreign-procedure "sqlite3_column_count" (void*) int))
|
||||
(define sqlite3_column_name (foreign-procedure "sqlite3_column_name" (void* int) string))
|
||||
(define sqlite3_column_type (foreign-procedure "sqlite3_column_type" (void* int) int))
|
||||
(define sqlite3_column_text (foreign-procedure "sqlite3_column_text" (void* int) string))
|
||||
(define sqlite3_column_int64 (foreign-procedure "sqlite3_column_int64" (void* int) integer-64))
|
||||
(define sqlite3_column_double (foreign-procedure "sqlite3_column_double" (void* int) double))
|
||||
(define sqlite3_bind_text (foreign-procedure "sqlite3_bind_text" (void* int string int iptr) int))
|
||||
(define sqlite3_bind_int64 (foreign-procedure "sqlite3_bind_int64" (void* int integer-64) int))
|
||||
(define sqlite3_bind_double (foreign-procedure "sqlite3_bind_double" (void* int double) int))
|
||||
(define sqlite3_bind_null (foreign-procedure "sqlite3_bind_null" (void* int) int))
|
||||
(define sqlite3_last_insert_rowid (foreign-procedure "sqlite3_last_insert_rowid" (void*) integer-64))
|
||||
|
||||
(define SQLITE_OK 0) (define SQLITE_ROW 100) (define SQLITE_DONE 101)
|
||||
(define SQLITE_TRANSIENT -1)
|
||||
|
||||
;; a connection is a jhost "sqlite-conn" wrapping the sqlite3* (as an integer addr)
|
||||
(define (sql-conn db) (make-jhost "sqlite-conn" (vector db)))
|
||||
(define (sql-conn-db c) (vector-ref (jhost-state c) 0))
|
||||
(define (sql-conn? x) (and (jhost? x) (string=? (jhost-tag x) "sqlite-conn")))
|
||||
|
||||
(define (sql-open path)
|
||||
(unless sqlite-available? (error #f "jolt.sqlite: libsqlite3 not found"))
|
||||
(let ((pp (foreign-alloc 8)))
|
||||
(foreign-set! 'void* pp 0 0)
|
||||
(let ((rc (sqlite3_open path pp)))
|
||||
(let ((db (foreign-ref 'void* pp 0)))
|
||||
(foreign-free pp)
|
||||
(if (= rc SQLITE_OK) (sql-conn db)
|
||||
(error #f (string-append "sqlite open failed: " path)))))))
|
||||
|
||||
(define (sql-close c) (sqlite3_close (sql-conn-db c)) jolt-nil)
|
||||
|
||||
(define (sql-prepare db sql)
|
||||
(let ((pp (foreign-alloc 8)))
|
||||
(foreign-set! 'void* pp 0 0)
|
||||
(let ((rc (sqlite3_prepare_v2 db sql -1 pp 0)))
|
||||
(let ((stmt (foreign-ref 'void* pp 0)))
|
||||
(foreign-free pp)
|
||||
(if (= rc SQLITE_OK) stmt
|
||||
(error #f (string-append "sqlite prepare failed: " (sqlite3_errmsg db) " — " sql)))))))
|
||||
|
||||
;; bind a jolt value to parameter i (1-based)
|
||||
(define (sql-bind! stmt i v)
|
||||
(cond
|
||||
((jolt-nil? v) (sqlite3_bind_null stmt i))
|
||||
((and (number? v) (exact? v) (integer? v)) (sqlite3_bind_int64 stmt i v))
|
||||
((number? v) (sqlite3_bind_double stmt i (inexact v)))
|
||||
((string? v) (sqlite3_bind_text stmt i v -1 SQLITE_TRANSIENT))
|
||||
(else (sqlite3_bind_text stmt i (jolt-str-render-one v) -1 SQLITE_TRANSIENT))))
|
||||
|
||||
;; read the current row as a jolt map {keyword-col -> value}
|
||||
(define (sql-row stmt)
|
||||
(let ((n (sqlite3_column_count stmt)) (m (jolt-hash-map)))
|
||||
(do ((i 0 (+ i 1))) ((= i n) m)
|
||||
(let* ((nm (sqlite3_column_name stmt i))
|
||||
(ty (sqlite3_column_type stmt i))
|
||||
(v (cond ((= ty 1) (sqlite3_column_int64 stmt i))
|
||||
((= ty 2) (sqlite3_column_double stmt i))
|
||||
((= ty 5) jolt-nil)
|
||||
(else (sqlite3_column_text stmt i)))))
|
||||
(set! m (jolt-assoc m (keyword #f nm) v))))))
|
||||
|
||||
;; run sql with params; return a vector of row maps (empty for a non-SELECT).
|
||||
(define (sql-query c sql params)
|
||||
(let ((db (sql-conn-db c)) (stmt (sql-prepare (sql-conn-db c) sql)))
|
||||
(let bind ((i 1) (ps params)) (when (pair? ps) (sql-bind! stmt i (car ps)) (bind (+ i 1) (cdr ps))))
|
||||
(let loop ((rows '()))
|
||||
(let ((rc (sqlite3_step stmt)))
|
||||
(cond
|
||||
((= rc SQLITE_ROW) (loop (cons (sql-row stmt) rows)))
|
||||
((= rc SQLITE_DONE) (sqlite3_finalize stmt) (apply jolt-vector (reverse rows)))
|
||||
(else (let ((msg (sqlite3_errmsg db))) (sqlite3_finalize stmt)
|
||||
(error #f (string-append "sqlite step failed: " msg)))))))))
|
||||
|
||||
;; --- jolt.sqlite (a small direct API) ---------------------------------------
|
||||
(define (sqlite-vec-args a) (if (and (pair? a) (or (pvec? (car a)) (cseq? (car a)) (empty-list-t? (car a))))
|
||||
(seq->list (car a)) a))
|
||||
(def-var! "jolt.sqlite" "open" (lambda (path) (sql-open path)))
|
||||
(def-var! "jolt.sqlite" "close" (lambda (c) (sql-close c)))
|
||||
(def-var! "jolt.sqlite" "query" (lambda (c sql . ps) (sql-query c sql (sqlite-vec-args ps))))
|
||||
(def-var! "jolt.sqlite" "execute!" (lambda (c sql . ps) (sql-query c sql (sqlite-vec-args ps)) jolt-nil))
|
||||
(def-var! "jolt.sqlite" "last-insert-id" (lambda (c) (sqlite3_last_insert_rowid (sql-conn-db c))))
|
||||
(def-var! "jolt.sqlite" "available?" (lambda () (if sqlite-available? #t #f)))
|
||||
|
||||
;; --- jdbc.core (jolt-lang/db API) -------------------------------------------
|
||||
;; A honeysql sql-vector is [sql & params]; jdbc fns take that directly. The
|
||||
;; connection string is "sqlite:<path>" (or "jdbc:sqlite:<path>").
|
||||
(define (jdbc-strip-scheme url)
|
||||
(let ((u (jolt-str-render-one url)))
|
||||
(let strip ((prefixes '("jdbc:sqlite:" "sqlite:")))
|
||||
(cond ((null? prefixes) u)
|
||||
((and (>= (string-length u) (string-length (car prefixes)))
|
||||
(string=? (substring u 0 (string-length (car prefixes))) (car prefixes)))
|
||||
(substring u (string-length (car prefixes)) (string-length u)))
|
||||
(else (strip (cdr prefixes)))))))
|
||||
(define (jdbc-sqlvec v) ; [sql & params] -> (values sql params-list)
|
||||
(let ((items (cond ((pvec? v) (seq->list v))
|
||||
((or (cseq? v) (empty-list-t? v)) (seq->list v))
|
||||
((string? v) (list v))
|
||||
(else '()))))
|
||||
(values (if (pair? items) (jolt-str-render-one (car items)) "")
|
||||
(if (pair? items) (cdr items) '()))))
|
||||
(def-var! "jdbc.core" "connection" (lambda (url) (sql-open (jdbc-strip-scheme url))))
|
||||
(def-var! "jdbc.core" "execute!"
|
||||
(lambda (c sqlvec) (let-values (((sql ps) (jdbc-sqlvec sqlvec))) (sql-query c sql ps) jolt-nil)))
|
||||
;; jdbc.core (jolt-lang/db) returns kebab-cased column keys, so an `id_seq`
|
||||
;; column reads as :id-seq — the Clojure jdbc convention the templates/queries
|
||||
;; expect. (The lower jolt.sqlite/query keeps the raw column names.)
|
||||
(define (kebab-keyword k)
|
||||
(if (keyword-t? k)
|
||||
(let ((nm (keyword-t-name k)))
|
||||
(if (memv #\_ (string->list nm))
|
||||
(keyword (keyword-t-ns k) (list->string (map (lambda (c) (if (char=? c #\_) #\- c)) (string->list nm))))
|
||||
k))
|
||||
k))
|
||||
(define (kebab-row row)
|
||||
(let loop ((s (jolt-seq row)) (m (jolt-hash-map)))
|
||||
(if (jolt-nil? s) m
|
||||
(let ((e (jolt-first s)))
|
||||
(loop (jolt-seq (jolt-rest s)) (jolt-assoc m (kebab-keyword (jolt-nth e 0)) (jolt-nth e 1)))))))
|
||||
(define (kebab-rows rows)
|
||||
(let loop ((i 0) (out (jolt-vector)))
|
||||
(if (>= i (pvec-count rows)) out
|
||||
(loop (+ i 1) (jolt-conj out (kebab-row (pvec-nth-d rows i jolt-nil)))))))
|
||||
(def-var! "jdbc.core" "fetch"
|
||||
(lambda (c sqlvec) (let-values (((sql ps) (jdbc-sqlvec sqlvec))) (kebab-rows (sql-query c sql ps)))))
|
||||
(def-var! "jdbc.core" "fetch-one"
|
||||
(lambda (c sqlvec) (let-values (((sql ps) (jdbc-sqlvec sqlvec)))
|
||||
(let ((rows (sql-query c sql ps)))
|
||||
(if (> (pvec-count rows) 0) (kebab-row (pvec-nth-d rows 0 jolt-nil)) jolt-nil)))))
|
||||
(def-var! "jdbc.core" "last-insert-id" (lambda (c) (sqlite3_last_insert_rowid (sql-conn-db c))))
|
||||
50
host/chez/syntax-quote.ss
Normal file
50
host/chez/syntax-quote.ss
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
;; syntax-quote form builders (jolt-r9lm, inc6b). A macro expander whose body was a
|
||||
;; syntax-quote template (lowered by jolt.host/form-syntax-quote-lower) calls these
|
||||
;; at RUNTIME on Chez to build the EXPANSION as
|
||||
;; Chez READER forms (cseq list / pvec / pmap / tagged-set pmap) so the on-Chez
|
||||
;; analyzer can re-analyze it. def-var!'d into clojure.core, so the lowered body's
|
||||
;; unqualified __sqcat/__sqvec/__sqmap/__sqset/__sq1 refs (which lower to var-deref
|
||||
;; in prelude mode) resolve here.
|
||||
;;
|
||||
;; A list/vector/set template lowers to (__sqcat part ...) where each part is
|
||||
;; either (__sq1 x) — a single non-spliced item — or a ~@ expr that evaluates to a
|
||||
;; seqable spliced in place. Both kinds are seqables, so __sqcat just flattens each
|
||||
;; part's jolt-seq in order. A map template lowers to (__sqmap k v ...) with no
|
||||
;; splicing (alternating key/value, already lowered).
|
||||
;;
|
||||
;; Loaded by rt.ss after collections.ss/seq.ss (jolt-list/jolt-vector/jolt-hash-map/
|
||||
;; jolt-seq) and def-var!.
|
||||
|
||||
;; flatten the __sqcat/__sqvec/__sqset parts (each a seqable) into a Scheme list.
|
||||
(define (sq-flatten parts)
|
||||
(let loop ((ps parts) (acc '()))
|
||||
(if (null? ps)
|
||||
(reverse acc)
|
||||
(loop (cdr ps)
|
||||
(let inner ((s (jolt-seq (car ps))) (a acc))
|
||||
(if (jolt-nil? s)
|
||||
a
|
||||
(inner (jolt-seq (seq-more s)) (cons (seq-first s) a))))))))
|
||||
|
||||
;; single non-spliced item -> a one-element seqable (__sqcat flattens it).
|
||||
(define (jolt-sq1 x) (jolt-list x))
|
||||
;; list FORM: cseq with list?=#t, so the analyzer's form-list? sees a list.
|
||||
(define (jolt-sqcat . parts) (apply jolt-list (sq-flatten parts)))
|
||||
;; vector FORM: pvec.
|
||||
(define (jolt-sqvec . parts) (apply jolt-vector (sq-flatten parts)))
|
||||
;; set: a REAL set value (pset). A syntax-quote builds VALUES, and the cseq/pvec/
|
||||
;; pmap that __sqcat/__sqvec/__sqmap build double as their own form rep — but a set
|
||||
;; value (pset) differs from the reader's set FORM ({:jolt/type :jolt/set :value
|
||||
;; <pvec>}), so building the tagged form here would make a runtime `#{~@xs} a map,
|
||||
;; not a set (jolt-r9lm regression). Build the value; the analyzer's form-set?
|
||||
;; (host-contract.ss) additionally recognizes a pset, so a macro template's #{...}
|
||||
;; expansion still re-analyzes as a set literal.
|
||||
(define (jolt-sqset . parts) (apply jolt-hash-set (sq-flatten parts)))
|
||||
;; map FORM: a plain pmap (the analyzer's form-map? = pmap with no :jolt/type).
|
||||
(define (jolt-sqmap . parts) (apply jolt-hash-map parts))
|
||||
|
||||
(def-var! "clojure.core" "__sq1" jolt-sq1)
|
||||
(def-var! "clojure.core" "__sqcat" jolt-sqcat)
|
||||
(def-var! "clojure.core" "__sqvec" jolt-sqvec)
|
||||
(def-var! "clojure.core" "__sqset" jolt-sqset)
|
||||
(def-var! "clojure.core" "__sqmap" jolt-sqmap)
|
||||
206
host/chez/transients.ss
Normal file
206
host/chez/transients.ss
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
;; transients (jolt-kl2l) — mutable backing per collection kind, snapshotted to
|
||||
;; the immutable collection on persistent!. A faithful port of the Janet host's
|
||||
;; mutable transients: conj!/assoc!/dissoc!/disj!/pop! mutate in place (amortized
|
||||
;; O(1)); persistent! converts back to a pvec / pmap / pset once.
|
||||
;;
|
||||
;; vec : a growable Scheme vector (capacity) + a fill count `n`. conj!/pop! are
|
||||
;; O(1) amortized — the old copy-on-write rebuilt the whole vector per op,
|
||||
;; so building an N-vector was O(N^2).
|
||||
;; map : a Chez hashtable keyed by key-hash / jolt= (value-equality, nil-safe —
|
||||
;; a jolt-nil key stores fine here, unlike a Janet table).
|
||||
;; set : a Chez hashtable of elements.
|
||||
;; cow : fallback for anything else (e.g. a sorted coll) — copy-on-write over
|
||||
;; the persistent ops, preserving jolt's superset of Clojure's transients.
|
||||
;;
|
||||
;; get/count/contains?/nth see THROUGH a transient (frequencies/group-by read a
|
||||
;; transient map; a transient is callable). vector? on a transient is false (it's
|
||||
;; this record, not a pvec), which group-by relies on. Loaded after collections.ss
|
||||
;; (persistent ops + key-hash) and converters.ss.
|
||||
|
||||
(define-record-type jolt-transient
|
||||
(fields kind (mutable buf) (mutable n) (mutable active))
|
||||
(nongenerative jolt-transient-v2))
|
||||
|
||||
(define tvec-min-cap 8)
|
||||
|
||||
(define (jolt-transient-new coll)
|
||||
(cond
|
||||
((pvec? coll)
|
||||
(let* ((v (pvec-v coll)) (cnt (vector-length v)) (cap (fxmax tvec-min-cap cnt))
|
||||
(buf (make-vector cap jolt-nil)))
|
||||
(let loop ((i 0)) (when (fx<? i cnt) (vector-set! buf i (vector-ref v i)) (loop (fx+ i 1))))
|
||||
(make-jolt-transient 'vec buf cnt #t)))
|
||||
((pmap? coll)
|
||||
(let ((ht (make-hashtable key-hash jolt=2)))
|
||||
(pmap-fold coll (lambda (k v acc) (hashtable-set! ht k v) acc) 0)
|
||||
(make-jolt-transient 'map ht 0 #t)))
|
||||
((pset? coll)
|
||||
(let ((ht (make-hashtable key-hash jolt=2)))
|
||||
(pset-fold coll (lambda (e acc) (hashtable-set! ht e #t) acc) 0)
|
||||
(make-jolt-transient 'set ht 0 #t)))
|
||||
(else (make-jolt-transient 'cow coll 0 #t))))
|
||||
|
||||
(define (jolt-trans-check t who)
|
||||
(unless (jolt-transient? t) (error #f (string-append who ": not a transient") t))
|
||||
(unless (jolt-transient-active t) (error #f (string-append who ": transient used after persistent!"))))
|
||||
|
||||
;; --- persistent! : snapshot back to the immutable collection -----------------
|
||||
(define (jolt-persistent! t)
|
||||
(jolt-trans-check t "persistent!")
|
||||
(jolt-transient-active-set! t #f)
|
||||
(case (jolt-transient-kind t)
|
||||
((vec)
|
||||
(let ((buf (jolt-transient-buf t)) (cnt (jolt-transient-n t)))
|
||||
;; exact fit: hand off the buffer (no other reference exists, and the
|
||||
;; transient is now inactive so it can't mutate it). Else trim to size —
|
||||
;; a pvec's backing length must equal its count.
|
||||
(if (fx=? cnt (vector-length buf))
|
||||
(make-pvec buf)
|
||||
(let ((out (make-vector cnt)))
|
||||
(let loop ((i 0))
|
||||
(if (fx<? i cnt) (begin (vector-set! out i (vector-ref buf i)) (loop (fx+ i 1)))
|
||||
(make-pvec out)))))))
|
||||
((map)
|
||||
(let ((ht (jolt-transient-buf t)) (m empty-pmap))
|
||||
(vector-for-each (lambda (k) (set! m (pmap-assoc m k (hashtable-ref ht k jolt-nil)))) (hashtable-keys ht))
|
||||
m))
|
||||
((set)
|
||||
(let ((ht (jolt-transient-buf t)) (s empty-pset))
|
||||
(vector-for-each (lambda (e) (set! s (pset-conj s e))) (hashtable-keys ht))
|
||||
s))
|
||||
(else (jolt-transient-buf t))))
|
||||
|
||||
;; --- in-place mutation -------------------------------------------------------
|
||||
(define (tvec-ensure! t need) ; grow capacity to >= need by doubling
|
||||
(let ((buf (jolt-transient-buf t)))
|
||||
(when (fx>? need (vector-length buf))
|
||||
(let* ((ncap (let grow ((c (fxmax tvec-min-cap (vector-length buf)))) (if (fx>=? c need) c (grow (fx* 2 c)))))
|
||||
(nbuf (make-vector ncap jolt-nil)) (cnt (jolt-transient-n t)))
|
||||
(let loop ((i 0)) (when (fx<? i cnt) (vector-set! nbuf i (vector-ref buf i)) (loop (fx+ i 1))))
|
||||
(jolt-transient-buf-set! t nbuf)))))
|
||||
(define (tvec-conj1! t x)
|
||||
(let ((cnt (jolt-transient-n t)))
|
||||
(tvec-ensure! t (fx+ cnt 1))
|
||||
(vector-set! (jolt-transient-buf t) cnt x)
|
||||
(jolt-transient-n-set! t (fx+ cnt 1))))
|
||||
(define (tvec-assoc1! t i x)
|
||||
(let ((i (->idx i)) (cnt (jolt-transient-n t)))
|
||||
(cond ((and (fixnum? i) (fx>=? i 0) (fx<? i cnt)) (vector-set! (jolt-transient-buf t) i x))
|
||||
((and (fixnum? i) (fx=? i cnt)) (tvec-conj1! t x))
|
||||
(else (error #f "assoc!: index out of bounds")))))
|
||||
;; conj! onto a transient map: a [k v] pair (vector/map-entry) or a whole map.
|
||||
(define (tmap-conj-entry! t x)
|
||||
(cond
|
||||
((jolt-nil? x) #t)
|
||||
((pvec? x) (hashtable-set! (jolt-transient-buf t) (pvec-nth-d x 0 jolt-nil) (pvec-nth-d x 1 jolt-nil)))
|
||||
((pmap? x) (pmap-fold x (lambda (k v acc) (hashtable-set! (jolt-transient-buf t) k v) acc) 0))
|
||||
(else (error #f "conj!: a transient map takes a map entry or a map" x))))
|
||||
|
||||
;; (conj!) -> fresh transient vector; (conj! coll) -> the 1-arity transducer-
|
||||
;; completion identity (JVM: no transient check). (conj! t x ...) mutates t.
|
||||
(define (jolt-conj! . args)
|
||||
(cond
|
||||
((null? args) (jolt-transient-new (jolt-vector)))
|
||||
((null? (cdr args)) (car args))
|
||||
(else
|
||||
(let ((t (car args)) (xs (cdr args)))
|
||||
(jolt-trans-check t "conj!")
|
||||
(case (jolt-transient-kind t)
|
||||
((vec) (for-each (lambda (x) (tvec-conj1! t x)) xs))
|
||||
((set) (for-each (lambda (x) (hashtable-set! (jolt-transient-buf t) x #t)) xs))
|
||||
((map) (for-each (lambda (x) (tmap-conj-entry! t x)) xs))
|
||||
(else (jolt-transient-buf-set! t (apply jolt-conj (jolt-transient-buf t) xs))))
|
||||
t))))
|
||||
|
||||
;; assoc! is variadic. JVM: a complete first key/val pair present (>=3 kvs) with a
|
||||
;; trailing lone key fills nil; a lone key alone (1 kv) is a wrong-arity throw.
|
||||
(define (assoc-pad kvs) (if (and (>= (length kvs) 3) (odd? (length kvs))) (append kvs (list jolt-nil)) kvs))
|
||||
(define (jolt-assoc! t . kvs0)
|
||||
(jolt-trans-check t "assoc!")
|
||||
(let ((kvs (assoc-pad kvs0)))
|
||||
(when (odd? (length kvs)) (error #f "assoc!: no value supplied for key"))
|
||||
(case (jolt-transient-kind t)
|
||||
((map) (let lp ((xs kvs)) (unless (null? xs) (hashtable-set! (jolt-transient-buf t) (car xs) (cadr xs)) (lp (cddr xs)))))
|
||||
((vec) (let lp ((xs kvs)) (unless (null? xs) (tvec-assoc1! t (car xs) (cadr xs)) (lp (cddr xs)))))
|
||||
(else (jolt-transient-buf-set! t (apply jolt-assoc (jolt-transient-buf t) kvs)))))
|
||||
t)
|
||||
(define (jolt-dissoc! t . ks)
|
||||
(jolt-trans-check t "dissoc!")
|
||||
(case (jolt-transient-kind t)
|
||||
((map) (for-each (lambda (k) (hashtable-delete! (jolt-transient-buf t) k)) ks))
|
||||
(else (jolt-transient-buf-set! t (apply jolt-dissoc (jolt-transient-buf t) ks))))
|
||||
t)
|
||||
(define (jolt-disj! t . xs)
|
||||
(jolt-trans-check t "disj!")
|
||||
(case (jolt-transient-kind t)
|
||||
((set) (for-each (lambda (x) (hashtable-delete! (jolt-transient-buf t) x)) xs))
|
||||
(else (jolt-transient-buf-set! t (apply jolt-disj (jolt-transient-buf t) xs))))
|
||||
t)
|
||||
(define (jolt-pop! t)
|
||||
(jolt-trans-check t "pop!")
|
||||
(case (jolt-transient-kind t)
|
||||
((vec) (let ((cnt (jolt-transient-n t)))
|
||||
(if (fx=? cnt 0) (error #f "pop!: can't pop empty transient vector")
|
||||
(jolt-transient-n-set! t (fx- cnt 1)))))
|
||||
(else (jolt-transient-buf-set! t (jolt-pop (jolt-transient-buf t)))))
|
||||
t)
|
||||
|
||||
;; persistent disj over sets (pset-disj already exists in collections.ss).
|
||||
(define (jolt-disj s . xs)
|
||||
(let loop ((s s) (xs xs)) (if (null? xs) s (loop (pset-disj s (car xs)) (cdr xs)))))
|
||||
|
||||
;; --- see-through accessors ---------------------------------------------------
|
||||
(define (tvec-in-bounds? t i) (and (fixnum? i) (fx>=? i 0) (fx<? i (jolt-transient-n t))))
|
||||
(define (t-get t k d)
|
||||
(case (jolt-transient-kind t)
|
||||
((vec) (let ((i (->idx k))) (if (tvec-in-bounds? t i) (vector-ref (jolt-transient-buf t) i) d)))
|
||||
((map) (hashtable-ref (jolt-transient-buf t) k d))
|
||||
((set) (if (hashtable-contains? (jolt-transient-buf t) k) k d))
|
||||
(else (%prev-jolt-get (jolt-transient-buf t) k d))))
|
||||
(define (t-count t)
|
||||
(case (jolt-transient-kind t)
|
||||
((vec) (jolt-transient-n t))
|
||||
((map set) (hashtable-size (jolt-transient-buf t)))
|
||||
(else (%prev-jolt-count (jolt-transient-buf t)))))
|
||||
(define (t-contains? t k)
|
||||
(case (jolt-transient-kind t)
|
||||
((vec) (tvec-in-bounds? t (->idx k)))
|
||||
((map set) (hashtable-contains? (jolt-transient-buf t) k))
|
||||
(else (%prev-jolt-contains? (jolt-transient-buf t) k))))
|
||||
|
||||
;; Redefine the native get/count/contains?/nth (captured first) so the existing
|
||||
;; emit lowerings unwrap a transient; non-transients are untouched.
|
||||
(define %prev-jolt-get jolt-get)
|
||||
(set! jolt-get
|
||||
(case-lambda
|
||||
((coll k) (if (jolt-transient? coll) (t-get coll k jolt-nil) (%prev-jolt-get coll k)))
|
||||
((coll k d) (if (jolt-transient? coll) (t-get coll k d) (%prev-jolt-get coll k d)))))
|
||||
(define %prev-jolt-count jolt-count)
|
||||
(set! jolt-count (lambda (coll) (if (jolt-transient? coll) (t-count coll) (%prev-jolt-count coll))))
|
||||
(define %prev-jolt-contains? jolt-contains?)
|
||||
(set! jolt-contains? (lambda (coll k) (if (jolt-transient? coll) (t-contains? coll k) (%prev-jolt-contains? coll k))))
|
||||
(define %prev-jolt-nth jolt-nth)
|
||||
(set! jolt-nth
|
||||
(case-lambda
|
||||
((coll i)
|
||||
(if (jolt-transient? coll)
|
||||
(if (eq? (jolt-transient-kind coll) 'vec)
|
||||
(let ((idx (->idx i)))
|
||||
(if (tvec-in-bounds? coll idx) (vector-ref (jolt-transient-buf coll) idx) (error 'nth "index out of bounds")))
|
||||
(%prev-jolt-nth (jolt-transient-buf coll) i))
|
||||
(%prev-jolt-nth coll i)))
|
||||
((coll i d)
|
||||
(if (jolt-transient? coll)
|
||||
(if (eq? (jolt-transient-kind coll) 'vec)
|
||||
(let ((idx (->idx i))) (if (tvec-in-bounds? coll idx) (vector-ref (jolt-transient-buf coll) idx) d))
|
||||
(%prev-jolt-nth (jolt-transient-buf coll) i d))
|
||||
(%prev-jolt-nth coll i d)))))
|
||||
|
||||
(def-var! "clojure.core" "transient" jolt-transient-new)
|
||||
(def-var! "clojure.core" "persistent!" jolt-persistent!)
|
||||
(def-var! "clojure.core" "conj!" jolt-conj!)
|
||||
(def-var! "clojure.core" "assoc!" jolt-assoc!)
|
||||
(def-var! "clojure.core" "dissoc!" jolt-dissoc!)
|
||||
(def-var! "clojure.core" "disj!" jolt-disj!)
|
||||
(def-var! "clojure.core" "pop!" jolt-pop!)
|
||||
(def-var! "clojure.core" "disj" jolt-disj)
|
||||
89
host/chez/values.ss
Normal file
89
host/chez/values.ss
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
;; Jolt value model on Chez Scheme — Phase 0a (jolt-cf1q.1).
|
||||
;;
|
||||
;; The irreducible value layer the self-hosted RT rests on. Maps Clojure's value
|
||||
;; types onto Chez natives where possible, and adds records only where Chez lacks
|
||||
;; a distinct type (nil sentinel, keywords, ns-bearing symbols). Loaded into an
|
||||
;; env that has already (import (chezscheme)); becomes a real library in Phase 1.
|
||||
;;
|
||||
;; Design notes:
|
||||
;; - nil is a UNIQUE sentinel, distinct from #f and '() (the classic Lisp-on-Lisp
|
||||
;; trap). jolt false -> Chez #f, jolt true -> #t.
|
||||
;; - Chez's numeric tower IS Clojure's: long->exact integer, double->flonum,
|
||||
;; ratio->exact rational, bigint->bignum. A windfall vs Janet (ratios/bignums
|
||||
;; for free). Clojure `=` is exactness-aware: (= 1 1.0) is FALSE.
|
||||
|
||||
;; --- nil ---------------------------------------------------------------------
|
||||
(define-record-type jolt-nil-t (fields) (nongenerative jolt-nil-v1))
|
||||
(define jolt-nil (make-jolt-nil-t))
|
||||
(define (jolt-nil? x) (jolt-nil-t? x))
|
||||
|
||||
;; --- truthiness: only nil and false are falsey -------------------------------
|
||||
(define (jolt-truthy? x) (not (or (jolt-nil? x) (eq? x #f))))
|
||||
|
||||
;; --- keywords: interned so identity works; optional namespace ----------------
|
||||
(define-record-type keyword-t (fields ns name khash) (nongenerative keyword-v1))
|
||||
(define keyword-table (make-hashtable string-hash string=?))
|
||||
;; NUL separator can't occur in a keyword ns/name, so the intern key is
|
||||
;; unambiguous (a "/" separator would collide ns="a" name="b/c" with ns="a/b").
|
||||
(define (keyword-intern-key ns name) (string-append (or ns "") "\x0;" name))
|
||||
(define (keyword ns name)
|
||||
(let ((k (keyword-intern-key ns name)))
|
||||
(or (hashtable-ref keyword-table k #f)
|
||||
(let ((kw (make-keyword-t ns name (equal-hash k))))
|
||||
(hashtable-set! keyword-table k kw)
|
||||
kw))))
|
||||
(define (keyword? x) (keyword-t? x))
|
||||
|
||||
;; --- symbols: ns + name + meta; NOT interned (meta varies), = by ns/name ------
|
||||
(define-record-type symbol-t (fields ns name meta) (nongenerative symbol-v1))
|
||||
(define (jolt-symbol ns name) (make-symbol-t ns name jolt-nil))
|
||||
(define (jolt-symbol/meta ns name meta) (make-symbol-t ns name meta))
|
||||
(define (jolt-symbol? x) (symbol-t? x))
|
||||
|
||||
;; chars/strings: Chez natives (strings treated immutable).
|
||||
|
||||
;; --- jolt equality (Clojure =) — scalars; collections land in Phase 2 --------
|
||||
(define (jolt=2 a b)
|
||||
(cond
|
||||
((and (jolt-nil? a) (jolt-nil? b)) #t)
|
||||
((or (jolt-nil? a) (jolt-nil? b)) #f)
|
||||
((and (number? a) (number? b)) ; exactness-aware
|
||||
(and (eq? (exact? a) (exact? b)) (= a b)))
|
||||
((and (keyword-t? a) (keyword-t? b)) (eq? a b)) ; interned
|
||||
((and (symbol-t? a) (symbol-t? b))
|
||||
(and (equal? (symbol-t-ns a) (symbol-t-ns b))
|
||||
(string=? (symbol-t-name a) (symbol-t-name b))))
|
||||
((and (char? a) (char? b)) (char=? a b))
|
||||
((and (string? a) (string? b)) (string=? a b))
|
||||
((and (boolean? a) (boolean? b)) (eq? a b))
|
||||
;; sequential (vector / list / lazy seq) compare element-wise, cross-type:
|
||||
;; (= [1 2 3] (list 1 2 3)) is true. Forward to seq.ss (loaded by rt.ss).
|
||||
((and (jolt-sequential? a) (jolt-sequential? b)) (seq=? a b))
|
||||
((or (jolt-sequential? a) (jolt-sequential? b)) #f)
|
||||
;; other collections (map/set): forward to collections.ss.
|
||||
((and (jolt-coll? a) (jolt-coll? b)) (jolt-coll=? a b))
|
||||
(else (eq? a b))))
|
||||
(define (jolt= a . rest)
|
||||
(let loop ((a a) (rest rest))
|
||||
(cond ((null? rest) #t)
|
||||
((jolt=2 a (car rest)) (loop (car rest) (cdr rest)))
|
||||
(else #f))))
|
||||
|
||||
;; --- jolt hash — consistent with jolt= (for the HAMT in 0c / Phase 2) ---------
|
||||
(define (jolt-hash x)
|
||||
(cond
|
||||
((jolt-nil? x) 0)
|
||||
((keyword-t? x) (keyword-t-khash x))
|
||||
((symbol-t? x) (equal-hash (cons (symbol-t-ns x) (symbol-t-name x))))
|
||||
;; distinguish inexact from exact (1 and 1.0 are not jolt=); guard non-finite
|
||||
;; (inexact->exact would error on NaN/inf)
|
||||
((number? x) (if (exact? x) (equal-hash x)
|
||||
(if (and (flonum? x) (or (nan? x) (infinite? x)))
|
||||
(equal-hash (cons 'inexact (number->string x)))
|
||||
(equal-hash (cons 'inexact (inexact->exact x))))))
|
||||
((string? x) (string-hash x))
|
||||
((char? x) (char->integer x))
|
||||
((boolean? x) (if x 1 2))
|
||||
((jolt-sequential? x) (seq-hash x)) ; vector/list/seq hash alike (forward to seq.ss)
|
||||
((jolt-coll? x) (jolt-coll-hash x)) ; map/set; forward to collections.ss
|
||||
(else (equal-hash x))))
|
||||
57
host/chez/vars.ss
Normal file
57
host/chez/vars.ss
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
;; vars as first-class objects (jolt-cf1q.3, jolt-n7rz) — (var x) / #'x.
|
||||
;;
|
||||
;; The emitter lowers :the-var to (jolt-var ns name) — the rt.ss var-cell, which
|
||||
;; is now also a Clojure VAR value. var? / var-get / deref-of-var / var-as-IFn /
|
||||
;; var equality / pr-str(#'ns/name) operate on it. bound? is overridden natively
|
||||
;; in post-prelude.ss (the overlay reads (get v :root), nil on a record).
|
||||
;;
|
||||
;; Dynamic binding (binding / with-bindings* / var-set / thread-bound? /
|
||||
;; with-redefs) is a separate follow-up — those crash on nil host primitives,
|
||||
;; which is safe (a crash stays a crash, not a divergence).
|
||||
;;
|
||||
;; Loaded LAST (after natives-xform.ss): chains jolt-deref (atom/volatile arms)
|
||||
;; and the printers.
|
||||
|
||||
(define (jolt-var-pred? x) (var-cell? x))
|
||||
|
||||
;; the var's current root; unbound is an error (Clojure throws on an unbound var).
|
||||
(define (jolt-var-get v)
|
||||
(if (var-cell? v)
|
||||
(let ((r (var-cell-root v)))
|
||||
(if (eq? r jolt-unbound) (error #f "Unbound var" v) r))
|
||||
(error #f "var-get: not a var" v)))
|
||||
|
||||
;; deref of a var -> its root.
|
||||
(define %v-deref jolt-deref)
|
||||
(set! jolt-deref (lambda (x) (if (var-cell? x) (jolt-var-get x) (%v-deref x))))
|
||||
|
||||
;; a var is an IFn — invoking it invokes its root value ((var f) args -> (f args)).
|
||||
(define %v-invoke jolt-invoke)
|
||||
(set! jolt-invoke (lambda (f . args)
|
||||
(if (var-cell? f) (apply jolt-invoke (var-cell-root f) args) (apply %v-invoke f args))))
|
||||
|
||||
;; two var cells are = iff same ns/name (Clojure var identity).
|
||||
(define %v-=2 jolt=2)
|
||||
(set! jolt=2 (lambda (a b)
|
||||
(cond ((var-cell? a) (and (var-cell? b)
|
||||
(string=? (var-cell-ns a) (var-cell-ns b))
|
||||
(string=? (var-cell-name a) (var-cell-name b))))
|
||||
((var-cell? b) #f)
|
||||
(else (%v-=2 a b)))))
|
||||
|
||||
;; pr-str / str of a var -> #'ns/name.
|
||||
(define (var->str v) (string-append "#'" (var-cell-ns v) "/" (var-cell-name v)))
|
||||
(define %v-pr-str jolt-pr-str)
|
||||
(set! jolt-pr-str (lambda (x) (if (var-cell? x) (var->str x) (%v-pr-str x))))
|
||||
(define %v-pr-readable jolt-pr-readable)
|
||||
(set! jolt-pr-readable (lambda (x) (if (var-cell? x) (var->str x) (%v-pr-readable x))))
|
||||
(define %v-str-render-one jolt-str-render-one)
|
||||
(set! jolt-str-render-one (lambda (x) (if (var-cell? x) (var->str x) (%v-str-render-one x))))
|
||||
|
||||
;; bound? — native (the overlay's (get v :root) is nil on a var-cell record).
|
||||
(define (jolt-var-bound-one? v) (and (var-cell? v) (not (eq? (var-cell-root v) jolt-unbound))))
|
||||
(define (jolt-bound? . vars) (if (for-all jolt-var-bound-one? vars) #t #f))
|
||||
|
||||
(def-var! "clojure.core" "var?" jolt-var-pred?)
|
||||
(def-var! "clojure.core" "var-get" jolt-var-get)
|
||||
(def-var! "clojure.core" "deref" jolt-deref)
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
;; clojure.core — kernel tier (stage just above the Janet seed).
|
||||
;; clojure.core — kernel tier (stage just above the host primitives).
|
||||
;;
|
||||
;; These are the structural fns the self-hosted compiler itself uses
|
||||
;; (jolt.analyzer): second/peek/subvec/mapv/update. Because the compiler must be
|
||||
|
|
@ -6,12 +6,11 @@
|
|||
;; before it is built. So this tier is loaded FIRST and, in compile mode, is
|
||||
;; bootstrap-compiled directly into clojure.core (not routed through the
|
||||
;; self-hosted pipeline, which would need these to already exist — the
|
||||
;; circularity that previously forced `second` to stay in Janet). With this tier
|
||||
;; in place the analyzer is built against the Clojure definitions and the Janet
|
||||
;; primitives are gone.
|
||||
;; circularity that previously forced `second` to stay a host primitive). With this tier
|
||||
;; in place the analyzer is built against the Clojure definitions.
|
||||
;;
|
||||
;; Constraint: depend only on core-renames primitives (first/next/nth/count/conj/
|
||||
;; vec/map/apply/assoc/get/…, all hardwired to the Janet seed) and on each other.
|
||||
;; vec/map/apply/assoc/get/…, all hardwired to host primitives) and on each other.
|
||||
|
||||
(defn second [coll] (first (next coll)))
|
||||
|
||||
|
|
@ -28,12 +27,12 @@
|
|||
([v start end]
|
||||
(when (not (vector? v)) (throw (str "subvec requires a vector")))
|
||||
;; Clojure coerces indices with (int ...): NaN -> 0, floats/ratios truncate
|
||||
;; toward zero ((quot x 1)); non-numbers throw. Only then range-check.
|
||||
;; toward zero; non-numbers throw. Only then range-check.
|
||||
(let [coerce (fn [x]
|
||||
(cond
|
||||
(not (number? x)) (throw (str "subvec index must be a number"))
|
||||
(not= x x) 0
|
||||
:else (quot x 1)))
|
||||
:else (long x)))
|
||||
s (coerce start)
|
||||
e (coerce end)]
|
||||
(when (or (< s 0) (< e s) (< (count v) e))
|
||||
|
|
|
|||
|
|
@ -157,8 +157,8 @@
|
|||
(defmacro declare [& syms]
|
||||
`(do ~@(map (fn* [s] `(def ~s)) syms)))
|
||||
|
||||
;; destructure — Clojure's binding-vector expander, ported from the Janet seed
|
||||
;; (was core-destructure). Turns a binding vector that may contain destructuring
|
||||
;; destructure — Clojure's binding-vector expander.
|
||||
;; Turns a binding vector that may contain destructuring
|
||||
;; patterns into a plain binding vector (alternating symbol / init-form) built from
|
||||
;; nth/nthnext/get, so the COMPILER only ever sees plain symbols (analyze-bindings
|
||||
;; rejects patterns). `let` consumes it directly; `loop`/`fn` reuse it transitively
|
||||
|
|
@ -247,7 +247,7 @@
|
|||
a
|
||||
(proc k `(get ~gm ~(get pat k)) a)))
|
||||
g3 (keys pat)))
|
||||
:else (throw (str "unsupported destructuring pattern"))))
|
||||
:else (throw (str "unsupported destructuring pattern: " (pr-str pat)))))
|
||||
ploop
|
||||
(fn* ploop [i acc]
|
||||
(if (< i (count bindings))
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
;; clojure.core — seq tier. Pure-Clojure leaf sequence fns on top of the kernel
|
||||
;; tier (00-kernel) and the Janet seed. Loaded after the kernel tier; in compile
|
||||
;; tier (00-kernel) and the host primitives. Loaded after the kernel tier; in compile
|
||||
;; mode these self-host through the now-built analyzer (interpreted otherwise).
|
||||
;;
|
||||
;; Migration rule for adding fns here: the fn must (1) NOT be in
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@
|
|||
;; neg? throws on non-numbers via <, as Clojure's Numbers.isNeg does.
|
||||
(defn neg? [x] (< x 0))
|
||||
|
||||
;; even?/odd? stay in the seed: (filter even? ...) is idiomatic-hot and the
|
||||
;; even?/odd? stay host primitives: (filter even? ...) is idiomatic-hot and the
|
||||
;; overlay versions cost an extra call layer per element (seq-pipe bench 4x).
|
||||
|
||||
;; Variadic bit ops — canonical Clojure arities folding the binary host op
|
||||
|
|
@ -55,10 +55,16 @@
|
|||
|
||||
(defn prn [& xs] (apply pr xs) (__write "\n") nil)
|
||||
|
||||
;; print renders each arg non-readably (strings/chars unquoted) like str — except
|
||||
;; nil, which prints as "nil" (str yields ""). Only the top-level arg needs the
|
||||
;; guard; nil nested in a collection already renders as "nil" via the collection
|
||||
;; printer.
|
||||
(defn print [& xs]
|
||||
(__write (loop [out "" s (seq xs) first? true]
|
||||
(if s
|
||||
(recur (str out (if first? "" " ") (str (first s))) (next s) false)
|
||||
(let [x (first s)
|
||||
r (if (nil? x) "nil" (str x))]
|
||||
(recur (str out (if first? "" " ") r) (next s) false))
|
||||
out)))
|
||||
nil)
|
||||
|
||||
|
|
@ -210,7 +216,11 @@
|
|||
(recur (dec n) (next xs))
|
||||
xs)))
|
||||
|
||||
(defn bounded-count [n coll] (min n (count coll)))
|
||||
(defn bounded-count [n coll]
|
||||
(if (counted? coll)
|
||||
(count coll)
|
||||
(loop [i 0 s (seq coll)]
|
||||
(if (and s (< i n)) (recur (inc i) (next s)) i))))
|
||||
|
||||
(defn run! [proc coll] (reduce (fn [_ x] (proc x) nil) nil coll) nil)
|
||||
|
||||
|
|
@ -345,9 +355,9 @@
|
|||
(make-hierarchy) (partition 2 deriv-seq))
|
||||
h))))
|
||||
|
||||
;; --- Stage 3 tier shrink: pure-over-core leaves moved off the Janet seed ----
|
||||
;; --- Stage 3 tier shrink: pure-over-core leaves moved off the host primitives ----
|
||||
|
||||
;; Representation predicates over the overlay's own predicates (no Janet reps).
|
||||
;; Representation predicates over the overlay's own predicates.
|
||||
(defn sequential? [x] (or (vector? x) (seq? x)))
|
||||
(defn associative? [x] (or (map? x) (vector? x)))
|
||||
(defn counted? [x]
|
||||
|
|
@ -371,10 +381,10 @@
|
|||
|
||||
|
||||
;; realized?: defined on the pending types only (delay/lazy-seq/future read
|
||||
;; Tagged-value predicates. The constructors (atom/volatile!/...) stay in Janet,
|
||||
;; but every tagged value carries its kind under :jolt/type (records under
|
||||
;; :jolt/deftype), reachable via get — which is nil on non-tables — so the
|
||||
;; predicates are pure over get and move out of the seed.
|
||||
;; Tagged-value predicates. The constructors (atom/volatile!/...) are host
|
||||
;; primitives, but every tagged value carries its kind under :jolt/type (records
|
||||
;; under :jolt/deftype), reachable via get — which is nil on non-tables — so the
|
||||
;; predicates are pure over get.
|
||||
(defn atom? [x] (= (get x :jolt/type) :jolt/atom))
|
||||
(defn volatile? [x] (= (get x :jolt/type) :jolt/volatile))
|
||||
(defn reader-conditional? [x] (= (get x :jolt/type) :jolt/reader-conditional))
|
||||
|
|
@ -408,7 +418,7 @@
|
|||
:else (throw (str "pop not supported on: " coll))))
|
||||
|
||||
;; doall/dorun: realization boundaries. dorun walks (optionally at most n
|
||||
;; steps — the Janet seed version ignored n); doall walks then returns coll.
|
||||
;; steps); doall walks then returns coll.
|
||||
(defn dorun
|
||||
([coll]
|
||||
(loop [s (seq coll)]
|
||||
|
|
@ -581,23 +591,35 @@
|
|||
|
||||
;; rand-int: random integer in [0, n). Uses Janet math/random.
|
||||
|
||||
;; Eager dedupe of consecutive equal elements (Jolt has no transducer arity yet).
|
||||
(defn dedupe [coll]
|
||||
(let [step (fn step [s prev]
|
||||
(make-lazy-seq
|
||||
(fn* []
|
||||
(let [s (seq s)]
|
||||
(if s
|
||||
(let [x (first s)]
|
||||
(if (= x prev)
|
||||
(coll->cells (step (rest s) prev))
|
||||
(coll->cells (cons x (step (rest s) x)))))
|
||||
nil)))))]
|
||||
(let [s (seq coll)]
|
||||
(if s
|
||||
(make-lazy-seq
|
||||
(fn* [] (coll->cells (cons (first s) (step (rest s) (first s))))))
|
||||
()))))
|
||||
;; 0-arg: a stateful transducer (tracks [seen? prev] in a volatile, so no sentinel
|
||||
;; value is needed). 1-arg: eager dedupe of consecutive equal elements.
|
||||
(defn dedupe
|
||||
([]
|
||||
(fn [rf]
|
||||
(let [pv (volatile! [false nil])]
|
||||
(fn
|
||||
([] (rf))
|
||||
([result] (rf result))
|
||||
([result input]
|
||||
(let [[seen prior] @pv]
|
||||
(vreset! pv [true input])
|
||||
(if (and seen (= prior input)) result (rf result input))))))))
|
||||
([coll]
|
||||
(let [step (fn step [s prev]
|
||||
(make-lazy-seq
|
||||
(fn* []
|
||||
(let [s (seq s)]
|
||||
(if s
|
||||
(let [x (first s)]
|
||||
(if (= x prev)
|
||||
(coll->cells (step (rest s) prev))
|
||||
(coll->cells (cons x (step (rest s) x)))))
|
||||
nil)))))]
|
||||
(let [s (seq coll)]
|
||||
(if s
|
||||
(make-lazy-seq
|
||||
(fn* [] (coll->cells (cons (first s) (step (rest s) (first s))))))
|
||||
())))))
|
||||
|
||||
;; Internal helper for {:keys [...]} destructuring over a seq of k/v pairs —
|
||||
;; canonical Clojure 1.11 shape (core.clj seq-to-map-for-destructuring):
|
||||
|
|
@ -650,7 +672,6 @@
|
|||
(defn ex-message [e]
|
||||
(let [e (ex-unwrap e)]
|
||||
(cond (ex-info-val? e) (get e :message)
|
||||
(string? e) e
|
||||
:else nil)))
|
||||
(defn ex-cause [e]
|
||||
(let [e (ex-unwrap e)] (if (ex-info-val? e) (get e :cause) nil)))
|
||||
|
|
@ -777,16 +798,19 @@
|
|||
|
||||
(defn clojure-version [] "1.11.0-jolt")
|
||||
|
||||
;; Jolt numbers are doubles; no BigDecimal, no ratios.
|
||||
(defn bigdec [x] (* 1.0 x))
|
||||
;; bigdec is a host fn (host/chez/bigdec.ss) — a real BigDecimal value type.
|
||||
(defn numerator [x] (throw (ex-info "numerator requires a ratio (Jolt has no ratios)" {})))
|
||||
(defn denominator [x] (throw (ex-info "denominator requires a ratio (Jolt has no ratios)" {})))
|
||||
|
||||
;; No class hierarchy on the Janet host.
|
||||
;; No class hierarchy on this host.
|
||||
(defn supers [x] #{})
|
||||
|
||||
;; The kernel's munge only rewrote dashes; kept as-is for parity.
|
||||
(defn munge [s] (str-replace-all "-" "_" (str s)))
|
||||
;; Like Clojure's munge: rewrite dashes to underscores, preserving the argument's
|
||||
;; type — a symbol munges to a symbol, anything else to a string. (jolt only
|
||||
;; rewrites dashes, not the full Compiler CHAR_MAP.)
|
||||
(defn munge [s]
|
||||
(let [m (str-replace-all "-" "_" (str s))]
|
||||
(if (symbol? s) (symbol m) m)))
|
||||
|
||||
(defn test
|
||||
"Calls the :test fn from v's metadata; :ok if it runs, :no-test if absent."
|
||||
|
|
@ -936,7 +960,7 @@
|
|||
;; inst-ms itself.
|
||||
(defn inst-ms* [i] (inst-ms i))
|
||||
|
||||
;; Canonical comp — here rather than the seed so each stage is invoked with
|
||||
;; Canonical comp — here rather than a host primitive so each stage is invoked with
|
||||
;; jolt call semantics: (comp seq :content) works because the keyword stage
|
||||
;; goes through IFn dispatch (raw Janet keyword application does not).
|
||||
(defn comp
|
||||
|
|
@ -1047,12 +1071,11 @@
|
|||
(defn to-array-2d [coll] (to-array (map to-array coll)))
|
||||
|
||||
;; Masking integer coercions (not aliases): byte/short wrap to their width.
|
||||
;; unchecked-char keeps jolt's historical NUMBER result (Clojure returns a
|
||||
;; char) — the char wrapper is a different value type here. int handles chars,
|
||||
;; so (unchecked-byte \a) works as on the JVM.
|
||||
;; unchecked-byte/short truncate to a number; unchecked-char returns a char (as on
|
||||
;; the JVM). int handles chars, so (unchecked-byte \a) works.
|
||||
(defn unchecked-byte [x] (bit-and (int x) 0xff))
|
||||
(defn unchecked-short [x] (bit-and (int x) 0xffff))
|
||||
(defn unchecked-char [x] (bit-and (int x) 0xffff))
|
||||
(defn unchecked-char [x] (char (bit-and (int x) 0xffff)))
|
||||
(defn unchecked-float [x] (double x))
|
||||
(defn unchecked-double [x] (double x))
|
||||
|
||||
|
|
@ -1065,7 +1088,7 @@
|
|||
(let [xf (xform f)]
|
||||
(xf (reduce xf init coll)))))
|
||||
|
||||
;; into stays in the seed: it's perf-wall hot (the into-vec bench pays ~11%
|
||||
;; into stays a host primitive: it's perf-wall hot (the into-vec bench pays ~11%
|
||||
;; through the overlay call layers — same lesson as even?/odd? in round 4).
|
||||
|
||||
;; eduction is EAGER on jolt (documented divergence, as before): the composed
|
||||
|
|
@ -1103,8 +1126,8 @@
|
|||
|
||||
;; print-method / print-dup are real multimethods in the io tier (50-io.clj).
|
||||
|
||||
;; JVM proxies don't exist on a Janet host: the read-only surface is inert,
|
||||
;; the constructive surface throws (matching the prior seed stubs).
|
||||
;; JVM proxies don't exist on this host: the read-only surface is inert,
|
||||
;; the constructive surface throws.
|
||||
(defn proxy-mappings [p] {})
|
||||
(defn proxy-call-with-super [f p meth] (f))
|
||||
(defn init-proxy [p mappings] p)
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@
|
|||
;; and the methods become functions — the algorithm is identical.
|
||||
;;
|
||||
;; A sorted-SET stores its elements as keys with a nil value; its ops project the
|
||||
;; key. ALL the semantics live here in Clojure; the Janet seed keeps only its
|
||||
;; key. ALL the semantics live here in Clojure; the host keeps only its
|
||||
;; dispatch branches (conj/assoc/get/seq/count/…), each a one-line call through
|
||||
;; the value's own :ops table, so the ops travel WITH the value (correct across
|
||||
;; contexts, forks, and AOT images). The wrapper is minted/read through the host
|
||||
|
|
@ -221,7 +221,9 @@
|
|||
(tree-collect (sfield sc :tree) proj []))
|
||||
|
||||
;; --- sorted-map ops ---------------------------------------------------------
|
||||
(defn- map-entry [t] [(nd-key t) (nd-val t)])
|
||||
;; a real map-entry (map-entry? true), so key/val/seq destructuring work like a
|
||||
;; regular map's entries.
|
||||
(defn- map-entry [t] (jolt.host/map-entry (nd-key t) (nd-val t)))
|
||||
|
||||
(defn- sm-get [sm k not-found]
|
||||
(let [n (tree-lookup (sfield sm :tree) (the-cmp sm) k)]
|
||||
|
|
@ -286,7 +288,7 @@
|
|||
|
||||
(defn- ss-disj-many [ss xs] (reduce ss-disj-1 ss xs))
|
||||
|
||||
;; --- the ops tables the Janet seed dispatches through ------------------------
|
||||
;; --- the ops tables the host dispatches through ------------------------
|
||||
|
||||
(def ^:private sm-ops
|
||||
{:count (fn [sm] (sfield sm :cnt))
|
||||
|
|
|
|||
|
|
@ -5,9 +5,9 @@
|
|||
;; IMPORTANT — only macros NOT used by the self-hosted compiler (jolt-core/jolt/*)
|
||||
;; or by the earlier overlay tiers belong here; those (and/or/when/when-not/
|
||||
;; when-let/cond/case/doseq/declare/cond->/->) must stay available before this
|
||||
;; tier loads, so they remain in Janet for now. Everything here is user-facing.
|
||||
;; tier loads, so they remain host primitives for now. Everything here is user-facing.
|
||||
;;
|
||||
;; Migration: remove the Janet core-X macro fn AND its core-macro-names entry when
|
||||
;; Migration: remove the host core-X macro fn AND its core-macro-names entry when
|
||||
;; moving a macro here (defmacro installs the :macro flag itself).
|
||||
|
||||
(defmacro comment [& body] nil)
|
||||
|
|
@ -122,8 +122,11 @@
|
|||
`(bound-fn* (fn ~@fntail)))
|
||||
|
||||
(defmacro defonce [name expr]
|
||||
;; only def when the var has no root value. In a top-level (do ...) the name is
|
||||
;; already interned (an unbound cell) by the time this runs, so check bound? —
|
||||
;; var-get would throw on the unbound cell.
|
||||
`(let [v# (resolve (quote ~name))]
|
||||
(if (and v# (some? (var-get v#)))
|
||||
(if (and v# (bound? v#))
|
||||
v#
|
||||
(def ~name ~expr))))
|
||||
|
||||
|
|
@ -222,10 +225,10 @@
|
|||
|
||||
;; Build the fn* form via a template (a reader-list array): cons/list in a macro
|
||||
;; body produce a plist the evaluator can't call as a form.
|
||||
(defmacro letfn [fnspecs & body]
|
||||
(let [binds (reduce (fn [acc spec] (conj (conj acc (first spec)) `(fn* ~@(rest spec))))
|
||||
[] fnspecs)]
|
||||
`(let* [~@binds] ~@body)))
|
||||
;; letfn is a primitive special form (analyze-letfn -> letrec*), not a macro: its
|
||||
;; fns are mutually recursive, which a (let* …) expansion cannot express. Defining
|
||||
;; it as a macro would shadow the special once macroexpansion runs first (the
|
||||
;; canonical order), so it is intentionally NOT a macro here.
|
||||
|
||||
;; Dynamic binding: install a thread-binding frame of var->value (array-map keeps
|
||||
;; var-get happy, unlike a phm), restore on exit.
|
||||
|
|
@ -304,13 +307,33 @@
|
|||
(:volatile-mutable mt)))
|
||||
true false)))
|
||||
fields)
|
||||
;; mutable field symbols (^:unsynchronized-mutable / ^:volatile-mutable):
|
||||
;; (set! field v) in a method body lowers to (set! (.-field inst) v), the
|
||||
;; in-place field write the analyzer compiles to jolt-set-field! (jolt-c3q).
|
||||
mutable-syms (map first (filter second (map vector fields field-muts)))
|
||||
mutable? (fn [s] (boolean (some (fn [m] (= m s)) mutable-syms)))
|
||||
rewrite-set (fn rw [inst form]
|
||||
(cond
|
||||
(and (seq? form) (seq form) (symbol? (first form))
|
||||
(= "set!" (name (first form)))
|
||||
(symbol? (second form)) (mutable? (second form)))
|
||||
(list 'set! (list (symbol (str ".-" (name (second form)))) inst)
|
||||
(rw inst (nth form 2)))
|
||||
(seq? form) (map (fn [x] (rw inst x)) form)
|
||||
(vector? form) (mapv (fn [x] (rw inst x)) form)
|
||||
:else form))
|
||||
;; inline impls register for dispatch but are NOT extenders of the
|
||||
;; protocol (the JVM compiles them into the class) — register-inline-method,
|
||||
;; not extend-type.
|
||||
impl (fn [proto specs]
|
||||
`(extend-type ~tname ~proto
|
||||
`(do
|
||||
~@(map (fn [spec]
|
||||
(let [argv (nth spec 1)
|
||||
inst (first argv)
|
||||
binds (vec (mapcat (fn [f] [f `(get ~inst ~(keyword (name f)))]) fields))]
|
||||
`(~(first spec) ~argv (let [~@binds] ~@(drop 2 spec)))))
|
||||
binds (vec (mapcat (fn [f] [f `(get ~inst ~(keyword (name f)))]) fields))
|
||||
mbody (map (fn [bf] (rewrite-set inst bf)) (drop 2 spec))]
|
||||
`(register-inline-method ~(name tname) ~(name proto) ~(name (first spec))
|
||||
(fn ~argv (let [~@binds] ~@mbody)))))
|
||||
specs)))]
|
||||
`(do
|
||||
(def ~tname (make-deftype-ctor (quote ~tname) [~@field-kws] [~@field-tags] [~@field-muts]))
|
||||
|
|
@ -412,8 +435,10 @@
|
|||
;; extend is a real FUNCTION now — defined above extend-type.
|
||||
;; JVM proxies are unsupported.
|
||||
(defmacro proxy [& args] nil)
|
||||
;; definterface is JVM-only; bind the name to an empty marker.
|
||||
(defmacro definterface [name-sym & body] `(def ~name-sym {}))
|
||||
;; definterface is JVM-only; bind the name to a marker and return the name (not a
|
||||
;; var), matching the JVM where definterface yields the interface Class.
|
||||
(defmacro definterface [name-sym & body]
|
||||
`(do (def ~name-sym {}) (quote ~name-sym)))
|
||||
|
||||
;; make-reified is a fn (clojure.core); the method map {kw (fn* ...)} is an
|
||||
;; ordinary map literal that evaluates to {keyword fn}, and the protocol NAME is
|
||||
|
|
@ -440,8 +465,11 @@
|
|||
;; each method body sees the record fields, bound from the instance (the
|
||||
;; method's first param), matching Clojure's defrecord method scope. vec the
|
||||
;; spliced binding seq so ~@ splices its elements, not the lazy-seq itself.
|
||||
;; inline impls register for dispatch but are NOT extenders of the
|
||||
;; protocol (the JVM compiles them into the class) — register-inline-method,
|
||||
;; not extend-type.
|
||||
impl (fn [proto specs]
|
||||
`(extend-type ~name-sym ~proto
|
||||
`(do
|
||||
~@(map (fn [spec]
|
||||
(let [argv (nth spec 1)
|
||||
inst (first argv)
|
||||
|
|
@ -450,7 +478,8 @@
|
|||
;; instead of going through the runtime tag guard.
|
||||
hinted (assoc argv 0 (vary-meta inst assoc :tag (name name-sym)))
|
||||
binds (vec (mapcat (fn [f] [f `(get ~inst ~(keyword (name f)))]) fields))]
|
||||
`(~(first spec) ~hinted (let [~@binds] ~@(drop 2 spec)))))
|
||||
`(register-inline-method ~(name name-sym) ~(name proto) ~(name (first spec))
|
||||
(fn ~hinted (let [~@binds] ~@(drop 2 spec))))))
|
||||
specs)))]
|
||||
`(do
|
||||
;; deftype already defines ->name (= the ctor); no (name. …) interop needed,
|
||||
|
|
|
|||
|
|
@ -86,7 +86,7 @@
|
|||
()))
|
||||
|
||||
;; --- repeatedly --- ((f) throws on a non-fn; (take n …) throws on a non-number
|
||||
;; count — both now enforced in the seed (jolt-call / core-take), so the canonical
|
||||
;; count — both enforced by the host (jolt-call / take), so the canonical
|
||||
;; CLJ form matches the repeatedly.cljc exception cases.)
|
||||
(defn repeatedly
|
||||
([f] (lazy-seq (cons (f) (repeatedly f))))
|
||||
|
|
@ -105,8 +105,8 @@
|
|||
;; --- partition-all --- (transducer + [n coll] + [n step coll])
|
||||
;; The collection arities realize EXACTLY n per chunk via a first/rest loop and
|
||||
;; continue from the advanced cursor (not a re-drop / nthrest), so they realize
|
||||
;; minimally — matching the Janet pstep the §6.3 laziness counters were written
|
||||
;; against. (A take/nthrest form is correct but over-realizes.)
|
||||
;; minimally — the §6.3 laziness counters depend on this.
|
||||
;; (A take/nthrest form is correct but over-realizes.)
|
||||
(defn partition-all
|
||||
([n]
|
||||
(fn [rf]
|
||||
|
|
|
|||
|
|
@ -15,76 +15,98 @@
|
|||
|
||||
(def ^:private reader-eof :jolt/reader-eof)
|
||||
|
||||
;; *in* is a Reader, not a map — so (map? *in*) is false, matching the JVM
|
||||
;; (java.io.Reader). The reader is a reify over IReader (a non-map value, unlike
|
||||
;; a defrecord which IS a map); read/read-line/read+string dispatch through its
|
||||
;; methods. Each implementation closes over its own buffer atom: read may pull a
|
||||
;; whole line to parse a form and hands the remainder to the next read/read-line.
|
||||
(defprotocol IReader
|
||||
(-read-line [rdr] "Next line, newline stripped; nil at EOF.")
|
||||
(-read-form [rdr] "Next form; the reader-eof sentinel at end of input.")
|
||||
(-read+string [rdr eof-error? eof-value]
|
||||
"Next form plus the exact text consumed (leading whitespace included), as
|
||||
[form text]. On EOF: throws, or returns [eof-value \"\"] when eof-error? is false."))
|
||||
|
||||
(defn __string-reader
|
||||
"A reader over string s (the with-in-str expansion calls this)."
|
||||
[s]
|
||||
(let [buf (atom s)]
|
||||
{:buf buf
|
||||
:fill-fn nil
|
||||
:read-line-fn
|
||||
(fn []
|
||||
(let [cur @buf]
|
||||
(when (pos? (count cur))
|
||||
(let [i (str-find "\n" cur)]
|
||||
(if (nil? i)
|
||||
(do (reset! buf "") cur)
|
||||
(do (reset! buf (subs cur (inc i))) (subs cur 0 i)))))))
|
||||
:read-fn
|
||||
(fn []
|
||||
(let [r (__parse-next @buf)]
|
||||
(if (nil? r)
|
||||
reader-eof
|
||||
(do (reset! buf (nth r 1)) (nth r 0)))))}))
|
||||
(reify IReader
|
||||
(-read-line [_]
|
||||
(let [cur @buf]
|
||||
(when (pos? (count cur))
|
||||
(let [i (str-find "\n" cur)]
|
||||
(if (nil? i)
|
||||
(do (reset! buf "") cur)
|
||||
(do (reset! buf (subs cur (inc i))) (subs cur 0 i)))))))
|
||||
(-read-form [_]
|
||||
(let [r (__parse-next @buf)]
|
||||
(if (nil? r)
|
||||
reader-eof
|
||||
(do (reset! buf (nth r 1)) (nth r 0)))))
|
||||
(-read+string [_ eof-error? eof-value]
|
||||
(let [s @buf
|
||||
r (__parse-next s)]
|
||||
(if (nil? r)
|
||||
(if eof-error?
|
||||
(throw (ex-info "EOF while reading" {}))
|
||||
[eof-value ""])
|
||||
(do (reset! buf (nth r 1))
|
||||
[(nth r 0) (subs s 0 (- (count s) (count (nth r 1))))])))))))
|
||||
|
||||
;; Real stdin, with a leftover buffer shared by read and read-line: read may
|
||||
;; pull a whole line to parse a form and must hand the remainder to the next
|
||||
;; read/read-line.
|
||||
;; Real stdin, with a leftover buffer shared by read and read-line.
|
||||
(def ^:private stdin-buf (atom ""))
|
||||
|
||||
(def ^:dynamic *in*
|
||||
{:buf stdin-buf
|
||||
:fill-fn (fn []
|
||||
(let [line (__stdin-read-line)]
|
||||
(if (nil? line)
|
||||
false
|
||||
(do (swap! stdin-buf (fn [b] (str b line "\n"))) true))))
|
||||
:read-line-fn
|
||||
(fn []
|
||||
(let [cur @stdin-buf]
|
||||
(if (pos? (count cur))
|
||||
(let [i (str-find "\n" cur)]
|
||||
(if (nil? i)
|
||||
(do (reset! stdin-buf "") cur)
|
||||
(do (reset! stdin-buf (subs cur (inc i))) (subs cur 0 i))))
|
||||
(__stdin-read-line))))
|
||||
:read-fn
|
||||
(fn []
|
||||
(loop []
|
||||
(let [r (__parse-next @stdin-buf)]
|
||||
(if (nil? r)
|
||||
(let [line (__stdin-read-line)]
|
||||
(if (nil? line)
|
||||
reader-eof
|
||||
(do (swap! stdin-buf (fn [b] (str b line "\n"))) (recur))))
|
||||
(do (reset! stdin-buf (nth r 1)) (nth r 0))))))})
|
||||
(reify IReader
|
||||
(-read-line [_]
|
||||
(let [cur @stdin-buf]
|
||||
(if (pos? (count cur))
|
||||
(let [i (str-find "\n" cur)]
|
||||
(if (nil? i)
|
||||
(do (reset! stdin-buf "") cur)
|
||||
(do (reset! stdin-buf (subs cur (inc i))) (subs cur 0 i))))
|
||||
(__stdin-read-line))))
|
||||
(-read-form [_]
|
||||
(loop []
|
||||
(let [r (__parse-next @stdin-buf)]
|
||||
(if (nil? r)
|
||||
(let [line (__stdin-read-line)]
|
||||
(if (nil? line)
|
||||
reader-eof
|
||||
(do (swap! stdin-buf (fn [b] (str b line "\n"))) (recur))))
|
||||
(do (reset! stdin-buf (nth r 1)) (nth r 0))))))
|
||||
(-read+string [_ eof-error? eof-value]
|
||||
(loop []
|
||||
(let [s @stdin-buf
|
||||
r (__parse-next s)]
|
||||
(if (nil? r)
|
||||
(let [line (__stdin-read-line)]
|
||||
(if (nil? line)
|
||||
(if eof-error?
|
||||
(throw (ex-info "EOF while reading" {}))
|
||||
[eof-value ""])
|
||||
(do (swap! stdin-buf (fn [b] (str b line "\n"))) (recur))))
|
||||
(do (reset! stdin-buf (nth r 1))
|
||||
[(nth r 0) (subs s 0 (- (count s) (count (nth r 1))))])))))))
|
||||
|
||||
(defn read-line
|
||||
"Reads the next line from the stream that is the current value of *in*.
|
||||
Returns nil at EOF."
|
||||
[]
|
||||
((:read-line-fn *in*)))
|
||||
(-read-line *in*))
|
||||
|
||||
(defn read
|
||||
"Reads the next object from stream (defaults to *in*). At EOF, throws —
|
||||
or returns eof-value when eof-error? is false."
|
||||
([] (read *in*))
|
||||
([stream]
|
||||
(let [v ((:read-fn stream))]
|
||||
(let [v (-read-form stream)]
|
||||
(if (= v reader-eof)
|
||||
(throw (ex-info "EOF while reading" {}))
|
||||
v)))
|
||||
([stream eof-error? eof-value]
|
||||
(let [v ((:read-fn stream))]
|
||||
(let [v (-read-form stream)]
|
||||
(if (= v reader-eof)
|
||||
(if eof-error? (throw (ex-info "EOF while reading" {})) eof-value)
|
||||
v))))
|
||||
|
|
@ -95,26 +117,11 @@
|
|||
`(binding [*in* (__string-reader ~s)]
|
||||
~@body))
|
||||
|
||||
;; Like read, and also returns the exact text consumed for the form (leading
|
||||
;; whitespace included). On EOF: throws, or returns [eof-value ""] when
|
||||
;; eof-error? is false.
|
||||
(defn read+string
|
||||
([] (read+string *in*))
|
||||
([stream] (read+string stream true nil))
|
||||
([stream eof-error? eof-value]
|
||||
(let [buf (get stream :buf)
|
||||
fill (get stream :fill-fn)]
|
||||
(loop []
|
||||
(let [s (deref buf)
|
||||
r (__parse-next s)]
|
||||
(if (nil? r)
|
||||
(if (and fill (fill))
|
||||
(recur)
|
||||
(if eof-error?
|
||||
(throw (ex-info "EOF while reading" {}))
|
||||
[eof-value ""]))
|
||||
(do (reset! buf (nth r 1))
|
||||
[(nth r 0) (subs s 0 (- (count s) (count (nth r 1))))])))))))
|
||||
(-read+string stream eof-error? eof-value)))
|
||||
|
||||
(defn line-seq
|
||||
"Returns the lines of text from rdr as a lazy sequence of strings, as by
|
||||
|
|
@ -124,7 +131,7 @@
|
|||
(if (string? rdr)
|
||||
(seq (str-split "\n" rdr))
|
||||
(lazy-seq
|
||||
(let [line ((:read-line-fn rdr))]
|
||||
(let [line (-read-line rdr)]
|
||||
(when line
|
||||
(cons line (line-seq rdr)))))))
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
bootstrap can compile this namespace via its plain :var path. ctx is an opaque
|
||||
host handle threaded to the contract fns; the analyzer never inspects it.
|
||||
|
||||
Coverage grows toward compiler.janet; unsupported forms throw :jolt/uncompilable
|
||||
Unsupported forms throw :jolt/uncompilable
|
||||
so the caller falls back to the interpreter (the hybrid contract).
|
||||
|
||||
`env` carries lexical state: {:locals #{names} :recur recur-target-name|nil}.
|
||||
|
|
@ -16,20 +16,25 @@
|
|||
them to one keeps the compiled namespace simple."
|
||||
(:require [jolt.ir :refer [const local var-ref the-var host-ref if-node do-node invoke
|
||||
def-node let-node fn-node vector-node map-node set-node
|
||||
quote-node throw-node]]
|
||||
quote-node throw-node host-static host-new]]
|
||||
[jolt.host :refer [form-sym? form-sym-name form-sym-ns form-list?
|
||||
form-vec? form-map? form-set? form-char?
|
||||
form-literal? form-elements form-vec-items
|
||||
form-literal? form-keyword? form-elements form-vec-items
|
||||
form-map-pairs form-set-items form-special? compile-ns
|
||||
form-regex? form-regex-source
|
||||
form-inst? form-inst-source form-uuid? form-uuid-source
|
||||
form-bigdec? form-bigdec-source
|
||||
form-ns-value? form-ns-value-name
|
||||
form-macro? form-expand-1 resolve-global
|
||||
form-sym-meta host-intern! form-syntax-quote-lower
|
||||
record-type? record-ctor-key form-position]]))
|
||||
record-type? record-ctor-key form-position late-bind?
|
||||
resolve-class-hint]]))
|
||||
|
||||
(declare analyze)
|
||||
|
||||
(def ^:private handled
|
||||
#{"quote" "if" "do" "def" "fn*" "let*" "loop*" "recur" "throw" "try"
|
||||
"syntax-quote" "var"})
|
||||
"syntax-quote" "var" "letfn" "set!" "defmacro"})
|
||||
|
||||
(defn- uncompilable [why]
|
||||
(throw (str "jolt/uncompilable: " why)))
|
||||
|
|
@ -109,9 +114,25 @@
|
|||
(if ph (conj phints [nm ph]) phints)))))
|
||||
{:fixed fixed :rest rest-name :hints hints :phints phints})))
|
||||
|
||||
;; Clojure lets a later param shadow an earlier same-named one (a macro expander
|
||||
;; uses _ for both its &form and &env slots, so its param list is (_ _ …)); the
|
||||
;; body binds the LAST occurrence. Chez rejects duplicate formals, so rename every
|
||||
;; earlier duplicate to a fresh name — it is shadowed and unreferenceable.
|
||||
(defn- uniquify-params [names]
|
||||
(let [n (count names)]
|
||||
(loop [i 0 out []]
|
||||
(if (< i n)
|
||||
(let [nm (nth names i)
|
||||
dup? (loop [j (inc i)]
|
||||
(cond (>= j n) false
|
||||
(= nm (nth names j)) true
|
||||
:else (recur (inc j))))]
|
||||
(recur (inc i) (conj out (if dup? (gen-name (str nm "_")) nm))))
|
||||
out))))
|
||||
|
||||
(defn- analyze-arity [ctx pvec body env fn-name]
|
||||
(let [pp (parse-params ctx (vec (form-vec-items pvec)))
|
||||
fixed (:fixed pp)
|
||||
fixed (uniquify-params (:fixed pp))
|
||||
rst (:rest pp)
|
||||
;; Always a recur target, variadic included: the back end gives the rest
|
||||
;; param an ordinary positional slot (holding the collected seq), so recur
|
||||
|
|
@ -134,11 +155,28 @@
|
|||
;; but keeps a fixed arity a nil-free struct rather than a phm.
|
||||
(if rst (assoc arity :rest rst) arity)))
|
||||
|
||||
;; A reader that lowers ^meta on a collection to a runtime (with-meta <coll> <meta>)
|
||||
;; form (the Chez data reader) wraps an arglist vector carrying a return-type hint
|
||||
;; (^bytes [b] / ^String [x y]). Unwrap to the underlying vector so fn parsing sees
|
||||
;; the params — the hint is ignored at runtime. Only the (with-meta <vec> _) shape
|
||||
;; matches, so a real arity clause (head is a vector) and a
|
||||
;; meta-on-vector arglist pass through unchanged.
|
||||
(defn- strip-arglist-meta [form]
|
||||
(if (form-list? form)
|
||||
(let [es (vec (form-elements form))]
|
||||
(if (and (= 3 (count es))
|
||||
(form-sym? (first es))
|
||||
(= "with-meta" (form-sym-name (first es)))
|
||||
(form-vec? (nth es 1)))
|
||||
(nth es 1)
|
||||
form))
|
||||
form))
|
||||
|
||||
(defn- analyze-fn [ctx items env]
|
||||
(let [named (form-sym? (nth items 1))
|
||||
fn-name (when named (form-sym-name (nth items 1)))
|
||||
rest-items (if named (drop 2 items) (drop 1 items))
|
||||
first* (first rest-items)]
|
||||
first* (strip-arglist-meta (first rest-items))]
|
||||
(cond
|
||||
(form-vec? first*)
|
||||
(fn-node fn-name [(analyze-arity ctx first* (rest rest-items) env fn-name)])
|
||||
|
|
@ -146,7 +184,7 @@
|
|||
(fn-node fn-name
|
||||
(mapv (fn [clause]
|
||||
(let [cl (vec (form-elements clause))]
|
||||
(analyze-arity ctx (first cl) (rest cl) env fn-name)))
|
||||
(analyze-arity ctx (strip-arglist-meta (first cl)) (rest cl) env fn-name)))
|
||||
rest-items))
|
||||
:else (uncompilable "fn: bad params"))))
|
||||
|
||||
|
|
@ -162,6 +200,12 @@
|
|||
(cond
|
||||
(= hname "catch")
|
||||
(let [cl (vec (form-elements c))]
|
||||
;; (catch class binding body*) — binding (3rd elem) MUST be a symbol.
|
||||
;; Validate eagerly (plain throw, NOT uncompilable, so it's a real
|
||||
;; error rather than a compile->interpret punt) instead of letting
|
||||
;; form-sym-name crash on a non-symbol.
|
||||
(when (or (< (count cl) 3) (not (form-sym? (nth cl 2))))
|
||||
(throw "Unable to parse catch clause; expected (catch class binding body*)"))
|
||||
(reset! catch-sym (form-sym-name (nth cl 2)))
|
||||
(reset! catch-body (drop 3 cl)))
|
||||
(= hname "finally")
|
||||
|
|
@ -184,6 +228,27 @@
|
|||
n)]
|
||||
n)))
|
||||
|
||||
;; letfn: (letfn [(name [params] body*)...] body*). The named local fns are
|
||||
;; MUTUALLY recursive, so bind every name into the env BEFORE analyzing any spec
|
||||
;; — each spec then resolves its siblings (and itself) as locals. Emitted as a
|
||||
;; :let flagged :letrec so the back end knows the bindings forward-reference each
|
||||
;; other: Chez lowers it to `letrec*`. The interpreter's shared mutable env already
|
||||
;; gives the letrec semantics that a
|
||||
;; compiled sequential let* lacks — the reason letfn was uncompilable before.
|
||||
(defn- analyze-letfn [ctx items env]
|
||||
(let [specs (vec (form-vec-items (nth items 1)))
|
||||
names (mapv #(form-sym-name (first (vec (form-elements %)))) specs)
|
||||
env* (add-locals env names)
|
||||
binds (mapv (fn [spec]
|
||||
(let [cl (vec (form-elements spec))]
|
||||
;; analyze as a named fn (items[1] = the name): self- and
|
||||
;; sibling-calls resolve, the fn carries its own name.
|
||||
[(form-sym-name (first cl))
|
||||
(analyze-fn ctx (vec (cons (first cl) cl)) env*)]))
|
||||
specs)]
|
||||
{:op :let :letrec true :bindings binds
|
||||
:body (analyze-seq ctx (drop 2 items) env*)}))
|
||||
|
||||
(defn- analyze-special [ctx op items env]
|
||||
(case op
|
||||
"quote" (quote-node (second items))
|
||||
|
|
@ -204,20 +269,36 @@
|
|||
;; the whole def (it unwraps the name and merges the meta).
|
||||
(when-not (form-sym? name-sym)
|
||||
(uncompilable "def name with map metadata"))
|
||||
;; (def name) with no init (declare) just interns — interpreter's job
|
||||
(when (< (count items) 3)
|
||||
(uncompilable "def with no init"))
|
||||
(let [nm (form-sym-name name-sym)
|
||||
cur (compile-ns ctx)
|
||||
;; (def name docstring value): docstring is form 2, value form 3.
|
||||
;; Matches the interpreter; without this the docstring was taken
|
||||
;; as the value and the real init dropped (jolt-6ym).
|
||||
has-doc (and (> (count items) 3) (string? (nth items 2)))
|
||||
val-form (nth items (if has-doc 3 2))
|
||||
base-meta (or (form-sym-meta name-sym) {})
|
||||
node-meta (if has-doc (assoc base-meta :doc (nth items 2)) base-meta)]
|
||||
(host-intern! ctx cur nm)
|
||||
(def-node cur nm (analyze ctx val-form env) node-meta)))
|
||||
(if (< (count items) 3)
|
||||
;; (def name) with no init (declare): intern + reserve the cell so a
|
||||
;; forward reference resolves. The back end keys on :no-init — Chez
|
||||
;; def-var!s an unbound placeholder; the interpreter interns a
|
||||
;; genuinely-unbound var.
|
||||
(let [nm (form-sym-name name-sym) cur (compile-ns ctx)]
|
||||
(host-intern! ctx cur nm)
|
||||
{:op :def :ns cur :name nm :no-init true})
|
||||
(let [nm (form-sym-name name-sym)
|
||||
cur (compile-ns ctx)
|
||||
;; (def name docstring value): docstring is form 2, value form 3.
|
||||
;; Matches the interpreter; without this the docstring was taken
|
||||
;; as the value and the real init dropped (jolt-6ym).
|
||||
has-doc (and (> (count items) 3) (string? (nth items 2)))
|
||||
val-form (nth items (if has-doc 3 2))
|
||||
base0 (or (form-sym-meta name-sym) {})
|
||||
;; resolve a ^Type hint to its canonical class name at def
|
||||
;; time (jolt-a1ir), as the JVM compiler does: ^String ->
|
||||
;; java.lang.String. A record/unknown hint is left untouched.
|
||||
tag (get base0 :tag)
|
||||
tag-name (cond (form-sym? tag) (form-sym-name tag)
|
||||
(string? tag) tag
|
||||
:else nil)
|
||||
base-meta (if tag-name
|
||||
(let [c (resolve-class-hint tag-name)]
|
||||
(if c (assoc base0 :tag c) base0))
|
||||
base0)
|
||||
node-meta (if has-doc (assoc base-meta :doc (nth items 2)) base-meta)]
|
||||
(host-intern! ctx cur nm)
|
||||
(def-node cur nm (analyze ctx val-form env) node-meta))))
|
||||
"let*" (let [bvec (vec (form-vec-items (nth items 1)))
|
||||
r (analyze-bindings ctx bvec env)]
|
||||
(let-node (first r) (analyze-seq ctx (drop 2 items) (second r))))
|
||||
|
|
@ -232,6 +313,7 @@
|
|||
{:op :recur :recur-name rt
|
||||
:args (mapv #(analyze ctx % env) (rest items))})
|
||||
"try" (analyze-try ctx items env)
|
||||
"letfn" (analyze-letfn ctx items env)
|
||||
"fn*" (analyze-fn ctx items env)
|
||||
;; Lower the backtick to construction code (zero runtime cost), then analyze
|
||||
;; it — the macroexpand/compile-time step, per read -> macroexpand -> compile.
|
||||
|
|
@ -241,8 +323,110 @@
|
|||
(if (= :var (:kind r))
|
||||
(the-var (:ns r) (:name r))
|
||||
(uncompilable (str "var of non-var " (form-sym-name sym)))))
|
||||
;; (set! *var* val): set the var's innermost thread binding, else its root
|
||||
;; (jolt-var-set). A local target is a deftype mutable field — not yet
|
||||
;; supported (jolt binds fields immutably); an interop (.-field) target too.
|
||||
;; A defmacro that is not top-level (the spine intercepts those) — e.g. one
|
||||
;; produced by a macro like (when … (defmacro …)). Lower it the way the spine
|
||||
;; does: def the expander fn, then mark the var a macro at runtime so later
|
||||
;; forms expand it. Strip a leading docstring / attr-map, as defmacro allows.
|
||||
"defmacro" (let [name-sym (nth items 1)
|
||||
nm (form-sym-name name-sym)
|
||||
cur (compile-ns ctx)
|
||||
after (drop 2 items)
|
||||
after (if (string? (first after)) (rest after) after)
|
||||
after (if (form-map? (first after)) (rest after) after)
|
||||
;; build (fn params body…) and analyze it through the fn MACRO
|
||||
;; so a destructuring macro arglist desugars (the fn* primitive
|
||||
;; would not), then def it and mark the var a macro.
|
||||
fn-form (cons (symbol "fn") after)]
|
||||
(host-intern! ctx cur nm)
|
||||
{:op :defmacro :ns cur :name nm
|
||||
:fn (analyze ctx fn-form env)})
|
||||
"set!" (let [target (nth items 1)
|
||||
val-node (analyze ctx (nth items 2) env)
|
||||
ti (when (form-list? target) (vec (form-elements target)))
|
||||
thead (when (and ti (pos? (count ti)) (form-sym? (first ti)))
|
||||
(form-sym-name (first ti)))]
|
||||
(cond
|
||||
;; (set! (.-field obj) v): mutate a deftype instance field in place.
|
||||
;; A deftype method's (set! mutable-field v) lowers to this shape.
|
||||
(and thead (field-head? thead))
|
||||
{:op :set-field :obj (analyze ctx (nth ti 1) env)
|
||||
:field (subs thead 2) :val val-node}
|
||||
;; (set! *var* v): set the var's innermost binding, else its root.
|
||||
(form-sym? target)
|
||||
(do (when (local? env (form-sym-name target)) (uncompilable "set! of a local"))
|
||||
(let [r (resolve-global ctx target)]
|
||||
(when-not (= :var (:kind r)) (uncompilable "set! of a non-var"))
|
||||
{:op :set-var :the-var (the-var (:ns r) (:name r)) :val val-node}))
|
||||
:else (uncompilable "set! of an unsupported target")))
|
||||
(uncompilable (str "special form " op))))
|
||||
|
||||
;; Host interop method call (jolt-0kf5). `(.method target arg*)` — a head that
|
||||
;; starts with "." but not ".-" (field access stays punted). Analyzes to a
|
||||
;; :host-call node; the Chez back end lowers it to a jolt-host-call dispatch.
|
||||
(defn- method-head? [nm]
|
||||
(and (> (count nm) 1)
|
||||
(= "." (subs nm 0 1))
|
||||
(not (= "-" (subs nm 1 2))) ; .-field is field access
|
||||
(not (= "." (subs nm 1 2))))) ; .. is the threading macro, not .method
|
||||
|
||||
(defn- analyze-host-call [ctx hname items env]
|
||||
(when (< (count items) 2)
|
||||
(throw (str "Malformed member expression, expecting (.method target ...): " hname)))
|
||||
{:op :host-call
|
||||
:method (subs hname 1)
|
||||
:target (analyze ctx (nth items 1) env)
|
||||
:args (mapv #(analyze ctx % env) (drop 2 items))})
|
||||
|
||||
;; A constructor head: `Class.` — a symbol ending in "." (but not the member
|
||||
;; access `.method` / `..` forms). `(Class. args*)` builds an instance.
|
||||
(defn- ctor-head? [nm]
|
||||
(and (> (count nm) 1)
|
||||
(= "." (subs nm (dec (count nm)) (count nm)))
|
||||
(not (= "." (subs nm 0 1)))))
|
||||
|
||||
;; `(Class. args*)` and `(new Class args*)` -> a :host-new node carrying the class
|
||||
;; token and the analyzed args. The Chez back end lowers it to a runtime
|
||||
;; constructor dispatch (jolt-avt6).
|
||||
(defn- analyze-ctor [ctx class args env]
|
||||
(host-new class (mapv #(analyze ctx % env) args)))
|
||||
|
||||
;; The `.` special form: `(. target member arg*)` — member access / method call.
|
||||
;; A symbol member whose name starts with "-" is a field read; otherwise it is a
|
||||
;; method (call with the trailing args). Both lower to a :host-call carrying the
|
||||
;; member name verbatim (the leading "-" survives so the runtime dispatcher reads
|
||||
;; it as a field). The Chez back end dispatches it through record-method-dispatch
|
||||
;; (jolt-kuic).
|
||||
(defn- analyze-dot [ctx items env]
|
||||
(when (< (count items) 3)
|
||||
(throw (str "Malformed (. target member ...) form")))
|
||||
(let [member (nth items 2)]
|
||||
(cond
|
||||
(form-sym? member)
|
||||
{:op :host-call
|
||||
:method (form-sym-name member)
|
||||
:target (analyze ctx (nth items 1) env)
|
||||
:args (mapv #(analyze ctx % env) (drop 3 items))}
|
||||
;; (. obj :kw) is a keyword lookup — invoke the keyword on the target.
|
||||
(form-keyword? member)
|
||||
(invoke (analyze ctx member env) [(analyze ctx (nth items 1) env)])
|
||||
:else (uncompilable "special form . (non-symbol member)"))))
|
||||
|
||||
;; A `.-field` head: `(.-field target)` is field access. Lowers to a :host-call
|
||||
;; with the "-field" method (the dash signals field access to the dispatcher).
|
||||
(defn- field-head? [nm]
|
||||
(and (> (count nm) 2) (= ".-" (subs nm 0 2))))
|
||||
|
||||
(defn- analyze-field [ctx hname items env]
|
||||
(when (< (count items) 2)
|
||||
(throw (str "Malformed (.-field target) form")))
|
||||
{:op :host-call
|
||||
:method (subs hname 1) ; ".-field" -> "-field"
|
||||
:target (analyze ctx (nth items 1) env)
|
||||
:args []})
|
||||
|
||||
(defn- analyze-symbol [ctx form env]
|
||||
(let [nm (form-sym-name form) ns (form-sym-ns form)]
|
||||
(cond
|
||||
|
|
@ -251,7 +435,10 @@
|
|||
ns (let [r (resolve-global ctx form)]
|
||||
(if (= :var (:kind r))
|
||||
(var-ref (:ns r) (:name r))
|
||||
(uncompilable (str "qualified ref " ns "/" nm))))
|
||||
;; A non-var qualified ref `Class/member` is a host class static
|
||||
;; (Math/sqrt, Long/MAX_VALUE, System/getenv). The Chez back end
|
||||
;; lowers it to a runtime static dispatch (jolt-avt6).
|
||||
(host-static ns nm)))
|
||||
:else (let [r (resolve-global ctx form)]
|
||||
(case (:kind r)
|
||||
:var (var-ref (:ns r) (:name r))
|
||||
|
|
@ -266,7 +453,13 @@
|
|||
;; (defmulti's setup call) legitimately reference the var they
|
||||
;; are about to create when nested in a non-top-level do. Real
|
||||
;; forward references want (declare ...), as in Clojure.
|
||||
(uncompilable (str "Unable to resolve symbol: " nm " in this context")))))))
|
||||
;; Under late-bind? (the Chez back end, which has no interpreter
|
||||
;; to punt to) an unresolved symbol instead lowers to a var-ref
|
||||
;; against the compile ns — resolved at runtime, the open-world
|
||||
;; semantics of -e — so defmulti/defmethod forward references work.
|
||||
(if (late-bind? ctx)
|
||||
(var-ref (compile-ns ctx) nm)
|
||||
(uncompilable (str "Unable to resolve symbol: " nm " in this context"))))))))
|
||||
|
||||
(defn- analyze-list [ctx form env]
|
||||
(let [items (vec (form-elements form))]
|
||||
|
|
@ -276,12 +469,35 @@
|
|||
hname (when (and (form-sym? head) (nil? (form-sym-ns head))) (form-sym-name head))
|
||||
shadowed (and hname (local? env hname))]
|
||||
(cond
|
||||
(and hname (not shadowed) (contains? handled hname))
|
||||
(analyze-special ctx hname items env)
|
||||
(and hname (not shadowed) (form-special? hname))
|
||||
(uncompilable (str "special form " hname))
|
||||
;; Canonical order (Clojure/CLJS analyze-seq): macroexpand FIRST, then
|
||||
;; dispatch special forms / interop / invoke. Expanding before the
|
||||
;; special-form check means a head that is a macro always expands — even
|
||||
;; one whose name is also in the special-form set — matching reference
|
||||
;; read -> macroexpand -> analyze. A local shadows both.
|
||||
(and (form-sym? head) (not shadowed) (form-macro? ctx head))
|
||||
(analyze ctx (form-expand-1 ctx form) env)
|
||||
;; special-form heads are NOT shadowable (unlike macros): a local named
|
||||
;; `if` does not change the meaning of (if …) in operator position, per
|
||||
;; spec §3 and the reference. No (not shadowed) guard here.
|
||||
(and hname (contains? handled hname))
|
||||
(analyze-special ctx hname items env)
|
||||
(and hname (not shadowed) (method-head? hname))
|
||||
(analyze-host-call ctx hname items env)
|
||||
;; (Class. args*) — trailing-dot constructor sugar.
|
||||
(and hname (not shadowed) (ctor-head? hname))
|
||||
(analyze-ctor ctx (subs hname 0 (dec (count hname))) (rest items) env)
|
||||
;; (new Class args*) — explicit constructor.
|
||||
(and (= hname "new") (not shadowed) (>= (count items) 2)
|
||||
(form-sym? (nth items 1)))
|
||||
(analyze-ctor ctx (form-sym-name (nth items 1)) (drop 2 items) env)
|
||||
;; (. target member arg*) — the `.` special form.
|
||||
(and (= hname ".") (not shadowed))
|
||||
(analyze-dot ctx items env)
|
||||
;; (.-field target) — field-access head.
|
||||
(and hname (not shadowed) (field-head? hname))
|
||||
(analyze-field ctx hname items env)
|
||||
(and hname (not shadowed) (form-special? hname))
|
||||
(uncompilable (str "special form " hname))
|
||||
:else
|
||||
;; stamp the list form's source offset onto the :invoke (jolt-fqy)
|
||||
;; so the success checker can report file:line:col. nil when the
|
||||
|
|
@ -303,4 +519,17 @@
|
|||
(form-map-pairs form)))
|
||||
(form-set? form) (set-node (mapv #(analyze ctx % env) (form-set-items form)))
|
||||
(form-list? form) (analyze-list ctx form env)
|
||||
;; regex literal #"…" -> a :regex IR node (leaf). The Chez back end emits a
|
||||
;; jolt-regex value over the vendored irregex.
|
||||
(form-regex? form) {:op :regex :source (form-regex-source form)}
|
||||
;; #inst / #uuid literals -> :inst / :uuid IR leaves. The Chez back
|
||||
;; end emits a runtime inst/uuid value (host/chez/inst-time.ss).
|
||||
(form-inst? form) {:op :inst :source (form-inst-source form)}
|
||||
(form-uuid? form) {:op :uuid :source (form-uuid-source form)}
|
||||
;; bigdecimal literal (1.5M) -> a :bigdec leaf; the back end emits a runtime
|
||||
;; jbigdec built from the numeric text.
|
||||
(form-bigdec? form) {:op :bigdec :source (form-bigdec-source form)}
|
||||
;; a live namespace value spliced into a form (~*ns* in a macro) -> a
|
||||
;; :the-ns leaf the back end reconstructs by name at the call site.
|
||||
(form-ns-value? form) {:op :the-ns :name (form-ns-value-name form)}
|
||||
:else (uncompilable "unsupported form"))))
|
||||
|
|
|
|||
506
jolt-core/jolt/backend_scheme.clj
Normal file
506
jolt-core/jolt/backend_scheme.clj
Normal file
|
|
@ -0,0 +1,506 @@
|
|||
(ns jolt.backend-scheme
|
||||
"Portable Clojure IR -> Chez Scheme emitter (Chez Phase 3, jolt-cf1q.4).
|
||||
|
||||
Consumes the
|
||||
host-neutral IR (jolt.ir, see jolt-core/jolt/ir.clj) the analyzer produces and
|
||||
emits Chez Scheme source TEXT. Pure jolt-core (clojure.core + clojure.string
|
||||
only) so that, once cross-compiled, it runs ON Chez and the analyzer can emit
|
||||
its own code — the bootstrap spine.
|
||||
|
||||
Output is a STRING of Scheme source; `host/compile` on Chez is `(eval (read
|
||||
...))`. Lowers each IR op to Scheme.
|
||||
|
||||
INCREMENT 1 (jolt-hg7z): const/local/var/the-var/if/do/let/loop/recur/invoke
|
||||
(+ native-ops)/fn/def + the escaping/flonum/munge helpers.
|
||||
INCREMENT 2 (jolt-7jvp): collection literals (vector/map/set, emit-ordered) +
|
||||
quote (emit-quoted, walks the raw reader form via the portable jolt.host form-*
|
||||
contract — same seam the analyzer uses, so it stays host-neutral).
|
||||
INCREMENT 3 (jolt-me6m): try/throw + host-call + regex/inst/uuid + def-meta +
|
||||
quoted-symbol-meta. With this the emitter covers every IR op.
|
||||
emit-quoted now also reconstructs plain jolt VALUES (def/symbol :meta), enabled
|
||||
by making :meta a portable struct at the host seam (h-sym-meta). Program
|
||||
assembly + the prelude driver port land with compile-from-source (inc 4+)."
|
||||
(:require [clojure.string :as str]
|
||||
[jolt.host :refer [form-sym? form-sym-name form-sym-ns form-sym-meta
|
||||
form-list? form-vec? form-map? form-set? form-char?
|
||||
form-literal? form-elements form-vec-items
|
||||
form-map-pairs form-set-items form-char-code]]))
|
||||
|
||||
;; Hot clojure.core primitives lowered to native Scheme.
|
||||
;; `=` is the exactness-aware jolt= from values.ss; inc/dec/
|
||||
;; not are rt shims; mod/rem/quot map to Scheme's (Scheme has all three).
|
||||
(def ^:private native-ops
|
||||
{"+" "+" "-" "-" "*" "*" "/" "/"
|
||||
"<" "<" ">" ">" "<=" "<=" ">=" ">="
|
||||
"=" "jolt=" "inc" "jolt-inc" "dec" "jolt-dec" "not" "jolt-not"
|
||||
"min" "min" "max" "max"
|
||||
"mod" "modulo" "rem" "remainder" "quot" "quotient"
|
||||
"vector" "jolt-vector" "hash-map" "jolt-hash-map" "hash-set" "jolt-hash-set"
|
||||
"conj" "jolt-conj" "get" "jolt-get" "nth" "jolt-nth" "count" "jolt-count"
|
||||
"assoc" "jolt-assoc" "dissoc" "jolt-dissoc" "contains?" "jolt-contains?"
|
||||
"empty?" "jolt-empty?" "peek" "jolt-peek" "pop" "jolt-pop"
|
||||
"first" "jolt-first" "rest" "jolt-rest" "next" "jolt-next" "seq" "jolt-seq"
|
||||
"cons" "jolt-cons" "list" "jolt-list" "reverse" "jolt-reverse" "last" "jolt-last"
|
||||
"map" "jolt-map" "filter" "jolt-filter" "remove" "jolt-remove"
|
||||
"reduce" "jolt-reduce" "into" "jolt-into" "concat" "jolt-concat" "apply" "jolt-apply"
|
||||
"range" "jolt-range" "take" "jolt-take" "drop" "jolt-drop"
|
||||
"keys" "jolt-keys" "vals" "jolt-vals"
|
||||
"even?" "jolt-even?" "odd?" "jolt-odd?" "pos?" "jolt-pos?" "neg?" "jolt-neg?"
|
||||
"zero?" "jolt-zero?" "identity" "jolt-identity"
|
||||
"ex-info" "jolt-ex-info"})
|
||||
|
||||
;; Value-position resolution for a clojure.core ref passed AS A VALUE (to map /
|
||||
;; filter / reduce / apply). Arithmetic is the exception — Scheme's +/-/*// return
|
||||
;; EXACT results for exact/zero-arg inputs, breaking the all-double model in
|
||||
;; higher-order use, so value-position arithmetic routes to the flonum wrappers.
|
||||
(def ^:private core-value-procs
|
||||
(merge native-ops {"+" "jolt-add" "-" "jolt-sub" "*" "jolt-mul" "/" "jolt-div"}))
|
||||
|
||||
;; Per-op arity gate: only lower when the Scheme prim and the jolt fn agree at
|
||||
;; this arity. Ops absent from the table are variadic (legal at any arity).
|
||||
(def ^:private op-arity
|
||||
{"inc" #(= % 1) "dec" #(= % 1) "not" #(= % 1)
|
||||
"count" #(= % 1) "empty?" #(= % 1) "peek" #(= % 1) "pop" #(= % 1)
|
||||
"mod" #(= % 2) "rem" #(= % 2) "quot" #(= % 2) "contains?" #(= % 2)
|
||||
"get" #(or (= % 2) (= % 3)) "nth" #(or (= % 2) (= % 3))
|
||||
"assoc" #(and (>= % 3) (odd? %)) "dissoc" #(>= % 1) "conj" #(>= % 1)
|
||||
"first" #(= % 1) "rest" #(= % 1) "next" #(= % 1) "seq" #(= % 1)
|
||||
"reverse" #(= % 1) "last" #(= % 1) "keys" #(= % 1) "vals" #(= % 1)
|
||||
"even?" #(= % 1) "odd?" #(= % 1) "pos?" #(= % 1) "neg?" #(= % 1)
|
||||
"zero?" #(= % 1) "identity" #(= % 1)
|
||||
"cons" #(= % 2) "filter" #(= % 2) "remove" #(= % 2) "into" #(= % 2)
|
||||
"take" #(= % 2) "drop" #(= % 2) "map" #(>= % 2) "apply" #(>= % 2)
|
||||
"reduce" #(or (= % 2) (= % 3)) "range" #(and (>= % 0) (<= % 3))
|
||||
"ex-info" #(or (= % 2) (= % 3))})
|
||||
|
||||
;; jolt's comparison ops are vacuously true at arity 1 and DON'T inspect the arg,
|
||||
;; but Scheme's < demands a number even there — special-case.
|
||||
(def ^:private cmp1-ops #{"<" ">" "<=" ">="})
|
||||
|
||||
;; Host interop methods with a Chez RT shim (rt.ss jolt-host-call). A `.method`
|
||||
;; call on any other method routes to record-method-dispatch (a reify/record
|
||||
;; protocol method).
|
||||
(def ^:private supported-host-methods #{"isDirectory" "listFiles"})
|
||||
|
||||
;; Native-op Scheme procedures that return a genuine Scheme boolean (#t/#f), so an
|
||||
;; :if test built from them needs no jolt-truthy? wrapper (jolt-nkcb).
|
||||
(def ^:private bool-returning-ops
|
||||
#{"<" "<=" ">" ">=" "jolt=" "jolt-not"
|
||||
"jolt-even?" "jolt-odd?" "jolt-pos?" "jolt-neg?"
|
||||
"jolt-zero?" "jolt-empty?" "jolt-contains?"})
|
||||
|
||||
;; PRELUDE MODE (inc 3d). The default (subset) mode rejects any clojure.core ref
|
||||
;; that isn't a native-op — a clean "out of subset" signal for user-facing `-e`.
|
||||
;; When emitting clojure.core ITSELF as a prelude, core fns reference each other
|
||||
;; constantly; those lower to var-deref (resolved at runtime).
|
||||
(def prelude-mode? (atom false))
|
||||
(defn set-prelude-mode! [on] (reset! prelude-mode? on))
|
||||
|
||||
;; recur-target and the set of munged local names known to hold a procedure (a
|
||||
;; named fn's self-recursion name) are lexically scoped — dynamic vars so the
|
||||
;; recursion auto-restores them (no manual save/restore, no throw-leak).
|
||||
(def ^:dynamic *recur-target* nil)
|
||||
(def ^:dynamic *known-procs* #{})
|
||||
|
||||
(def ^:private gensym-counter (atom 0))
|
||||
(defn- fresh-label [prefix] (str prefix (swap! gensym-counter inc)))
|
||||
|
||||
;; Scheme syntactic keywords. A jolt local with one of these names would, when
|
||||
;; emitted verbatim, shadow the Scheme form in operator position (a local named
|
||||
;; `if` would turn the special form (if …) the back end emits into a call), so
|
||||
;; such locals are prefixed. Matches the spec: special-form heads are not
|
||||
;; shadowable, but a value local may legally be named `if`.
|
||||
(def ^:private scheme-reserved
|
||||
#{"if" "begin" "lambda" "let" "let*" "letrec" "letrec*" "quote" "quasiquote"
|
||||
"unquote" "set!" "define" "define-syntax" "cond" "case" "when" "unless"
|
||||
"and" "or" "do" "else" "guard" "parameterize" "delay" "values"})
|
||||
|
||||
;; Most jolt names are already valid Scheme identifiers. The one that isn't is
|
||||
;; `#`, which jolt auto-gensyms use as a suffix (p1__0000X4# from #(...)) — `#`
|
||||
;; starts a datum in Scheme, so replace it with `_`. A name that collides with a
|
||||
;; Scheme keyword is prefixed with `_` so it can never shadow the emitted form.
|
||||
(defn- munge-name [s]
|
||||
;; A Clojure symbol may contain chars that break a Scheme identifier: ' is the
|
||||
;; quote reader macro (a bare f' would read as f then 'rest), # already maps to
|
||||
;; _. Munge both to safe tokens; the same mapping applies at the binding and at
|
||||
;; every reference, so resolution stays consistent.
|
||||
(let [s (-> s
|
||||
(str/replace "#" "_")
|
||||
(str/replace "'" "_PRIME_"))]
|
||||
(if (contains? scheme-reserved s) (str "_" s) s)))
|
||||
|
||||
(declare emit)
|
||||
|
||||
;; A Chez string literal (jolt-x0os). Every char outside printable ASCII becomes a
|
||||
;; codepoint hex escape \x<cp>; ; the named escapes (\n \t \r \" \\) match what
|
||||
;; Chez's reader accepts. For pure printable ASCII this is byte-identical to %j.
|
||||
(defn- char-escape [cp]
|
||||
(cond
|
||||
(= cp 34) "\\\""
|
||||
(= cp 92) "\\\\"
|
||||
(= cp 10) "\\n"
|
||||
(= cp 9) "\\t"
|
||||
(= cp 13) "\\r"
|
||||
(and (>= cp 32) (< cp 127)) (str (char cp))
|
||||
:else (str "\\x" (format "%x" cp) ";")))
|
||||
|
||||
(defn- chez-str-lit [s]
|
||||
(str "\"" (apply str (map (fn [c] (char-escape (int c))) s)) "\""))
|
||||
|
||||
(defn- emit-const [v]
|
||||
(cond
|
||||
(nil? v) "jolt-nil"
|
||||
(boolean? v) (if v "#t" "#f")
|
||||
;; Numeric tower (jolt-n6al): emit a literal Chez re-reads as the SAME number.
|
||||
;; Exact integers -> "42", exact ratios -> "1/2" (str renders both faithfully);
|
||||
;; a flonum must carry a decimal point/exponent or Chez reads it back as exact,
|
||||
;; so a whole flonum (str drops its .0) gets ".0" appended. ##Inf/##-Inf/##NaN
|
||||
;; -> Chez's flonum literals.
|
||||
(number? v) (cond
|
||||
(= v ##Inf) "+inf.0"
|
||||
(= v ##-Inf) "-inf.0"
|
||||
(not= v v) "+nan.0"
|
||||
(float? v) (let [s (str v)]
|
||||
(if (or (str/includes? s ".") (str/includes? s "e")) s (str s ".0")))
|
||||
:else (str v))
|
||||
(string? v) (chez-str-lit v)
|
||||
;; keyword literal -> (keyword ns name)
|
||||
(keyword? v) (if-let [kns (namespace v)]
|
||||
(str "(keyword " (chez-str-lit kns) " " (chez-str-lit (name v)) ")")
|
||||
(str "(keyword #f " (chez-str-lit (name v)) ")"))
|
||||
;; char literal -> (integer->char <codepoint>). Get the codepoint via the host
|
||||
;; contract (form-char-code), NOT (get v :ch): on Janet a char is a struct with
|
||||
;; a :ch field, but on Chez (the self-hosted spine) it's a native char, so the
|
||||
;; struct-field read returns nil and emits (integer->char) with no arg.
|
||||
(form-char? v) (str "(integer->char " (form-char-code v) ")")
|
||||
:else (throw (ex-info (str "emit-const: unsupported literal " (pr-str v)) {}))))
|
||||
|
||||
;; Emit a call `(ctor a0 a1 ...)` with the args evaluated LEFT-TO-RIGHT. Chez's
|
||||
;; procedure-argument evaluation order is unspecified (in practice right-to-left),
|
||||
;; but Clojure evaluates collection-literal elements left to right, so a literal
|
||||
;; like [(read r) (read r)] over side-effecting reads must bind in source order.
|
||||
;; Bind each arg to a fresh temp in a let* then construct. Only wraps at >= 2 args.
|
||||
(defn- emit-ordered [ctor arg-strs]
|
||||
(if (< (count arg-strs) 2)
|
||||
(str "(" ctor (if (empty? arg-strs) "" (str " " (str/join " " arg-strs))) ")")
|
||||
(let [tmps (map (fn [_] (fresh-label "_o$")) arg-strs)
|
||||
binds (str/join " " (map (fn [t a] (str "(" t " " a ")")) tmps arg-strs))]
|
||||
(str "(let* (" binds ") (" ctor " " (str/join " " tmps) "))"))))
|
||||
|
||||
;; An operand whose evaluation has no observable effect and whose result doesn't
|
||||
;; depend on when it runs: constants, locals, var/the-var reads, quoted literals.
|
||||
;; Re-ordering such operands relative to others is invisible.
|
||||
(defn- side-effect-free? [n]
|
||||
(contains? #{:const :local :var :the-var :quote} (:op n)))
|
||||
|
||||
;; Clojure evaluates a call's operands (and recur's args) left to right; Chez's
|
||||
;; application order is unspecified (right-to-left in practice). Force source
|
||||
;; order by binding operands to fresh temps in a let* — but only when two or more
|
||||
;; could have observable effects, so hot calls over locals/consts stay un-wrapped.
|
||||
(defn- needs-order? [nodes]
|
||||
(> (count (remove side-effect-free? nodes)) 1))
|
||||
|
||||
;; Build a call from operand strings, forcing left-to-right evaluation when
|
||||
;; needed. `nodes`/`strs` are the operands (parallel); `build` receives the
|
||||
;; operand strings to splice (temps when wrapped, raw otherwise) and returns the
|
||||
;; call. Operands that don't need ordering are passed through inline.
|
||||
(defn- ordered-call [nodes strs build]
|
||||
(if (needs-order? nodes)
|
||||
(let [tmps (mapv (fn [_] (fresh-label "_a$")) strs)
|
||||
binds (str/join " " (map (fn [t a] (str "(" t " " a ")")) tmps strs))]
|
||||
(str "(let* (" binds ") " (build tmps) ")"))
|
||||
(build strs)))
|
||||
|
||||
;; Quoted literals (jolt-u8j7). A :quote node's :form is the RAW reader form;
|
||||
;; reconstruct each as the matching Chez RT constructor — the runtime value of a
|
||||
;; quote is just that literal data. The form is walked via the jolt.host form-*
|
||||
;; contract (the portable seam the analyzer uses), NOT host-native predicates, so
|
||||
;; this stays host-neutral — the contract walks the host's reader forms.
|
||||
(declare emit-quoted)
|
||||
(defn- emit-quoted-map [pairs]
|
||||
;; pairs: a jolt vector of [k-form v-form] pairs (form-map-pairs)
|
||||
(str "(jolt-hash-map "
|
||||
(str/join " " (mapcat (fn [p] [(emit-quoted (nth p 0)) (emit-quoted (nth p 1))]) pairs))
|
||||
")"))
|
||||
(defn- emit-quoted-map-value [m]
|
||||
;; a jolt map VALUE (def/symbol metadata is a value, not a reader form)
|
||||
(str "(jolt-hash-map "
|
||||
(str/join " " (mapcat (fn [k] [(emit-quoted k) (emit-quoted (get m k))]) (keys m)))
|
||||
")"))
|
||||
;; emit-quoted reconstructs both raw reader forms (from :quote) AND plain jolt
|
||||
;; values (def/symbol :meta). Reader forms are walked via the jolt.host form-*
|
||||
;; contract; the native-predicate branches below catch genuine jolt collection
|
||||
;; VALUES. The form-* branches come first so a reader form (a host-native struct/
|
||||
;; array that a native predicate might also match) is always handled as a form.
|
||||
(defn- emit-quoted [form]
|
||||
(cond
|
||||
(form-char? form) (emit-const form)
|
||||
(form-literal? form) (emit-const form)
|
||||
(form-sym? form)
|
||||
(let [m (form-sym-meta form) sns (form-sym-ns form) nm (form-sym-name form)]
|
||||
(if (and m (pos? (count m)))
|
||||
;; carry reader metadata (^:foo bar) onto the quoted symbol so (meta 'x) sees it
|
||||
(str "(jolt-symbol/meta " (if sns (chez-str-lit sns) "#f") " " (chez-str-lit nm) " "
|
||||
(emit-quoted m) ")")
|
||||
(str "(jolt-symbol " (if sns (chez-str-lit sns) "#f") " " (chez-str-lit nm) ")")))
|
||||
(form-set? form) (str "(jolt-hash-set " (str/join " " (map emit-quoted (form-set-items form))) ")")
|
||||
(form-list? form) (str "(jolt-list " (str/join " " (map emit-quoted (form-elements form))) ")")
|
||||
(form-vec? form) (str "(jolt-vector " (str/join " " (map emit-quoted (form-vec-items form))) ")")
|
||||
(form-map? form) (emit-quoted-map (form-map-pairs form))
|
||||
;; plain jolt VALUES (metadata maps and anything nested in them)
|
||||
(map? form) (emit-quoted-map-value form)
|
||||
(vector? form) (str "(jolt-vector " (str/join " " (map emit-quoted form)) ")")
|
||||
(set? form) (str "(jolt-hash-set " (str/join " " (map emit-quoted form)) ")")
|
||||
(seq? form) (str "(jolt-list " (str/join " " (map emit-quoted form)) ")")
|
||||
:else (throw (ex-info (str "emit-quoted: unsupported quoted form " (pr-str form)) {}))))
|
||||
|
||||
;; A def's :meta is a jolt map value. Non-empty? (a plain def carries {}).
|
||||
(defn- jmeta-nonempty? [m] (and (map? m) (pos? (count m))))
|
||||
|
||||
(defn- emit-binding [b]
|
||||
(str "(" (munge-name (nth b 0)) " " (emit (nth b 1)) ")"))
|
||||
|
||||
;; letfn lowers to a :let flagged :letrec (mutually-recursive named local fns):
|
||||
;; Scheme `letrec*` binds them so each sees its siblings. A plain let uses let*.
|
||||
(defn- emit-let [node]
|
||||
(let [kw (if (:letrec node) "letrec*" "let*")]
|
||||
(str "(" kw " (" (str/join " " (map emit-binding (:bindings node))) ") "
|
||||
(emit (:body node)) ")")))
|
||||
|
||||
(defn- emit-loop [node]
|
||||
(let [label (fresh-label "loop")
|
||||
pairs (:bindings node)
|
||||
names (map #(munge-name (nth % 0)) pairs)
|
||||
;; inits evaluate in the OUTER scope (recur-target unchanged) and, like
|
||||
;; Clojure loop/let, SEQUENTIALLY — wrap a let* around the named let.
|
||||
inits (map #(emit (nth % 1)) pairs)
|
||||
seq-bs (str/join " " (map (fn [n i] (str "(" n " " i ")")) names inits))
|
||||
rebinds (str/join " " (map (fn [n] (str "(" n " " n ")")) names))
|
||||
body (binding [*recur-target* label] (emit (:body node)))]
|
||||
(str "(let* (" seq-bs ") (let " label " (" rebinds ") " body "))")))
|
||||
|
||||
(defn- emit-recur [node]
|
||||
(when-not *recur-target* (throw (ex-info "emit: recur outside a loop/fn target" {})))
|
||||
(let [arg-nodes (:args node)]
|
||||
(ordered-call arg-nodes (mapv emit arg-nodes)
|
||||
(fn [as] (str "(" *recur-target* " " (str/join " " as) ")")))))
|
||||
|
||||
;; One arity -> a Scheme lambda param-list + a named-let-wrapped body. The named
|
||||
;; let lets fn-level `recur` rebind this arity's params. A variadic arity takes a
|
||||
;; Scheme rest arg coerced to a jolt seq (nil when empty); recur carries the rest
|
||||
;; seq directly, and the named let's init only runs on first entry.
|
||||
(defn- emit-arity-clause [a]
|
||||
(let [params (map munge-name (:params a))
|
||||
restp (when-let [r (:rest a)] (munge-name r))
|
||||
label (fresh-label "fnrec")
|
||||
body (binding [*recur-target* label] (emit (:body a)))
|
||||
paramlist (cond
|
||||
(and restp (empty? params)) restp
|
||||
restp (str "(" (str/join " " params) " . " restp ")")
|
||||
:else (str "(" (str/join " " params) ")"))
|
||||
binds (if restp
|
||||
(concat (map (fn [p] (str "(" p " " p ")")) params)
|
||||
[(str "(" restp " (list->cseq " restp "))")])
|
||||
(map (fn [p] (str "(" p " " p ")")) params))]
|
||||
[paramlist (str "(let " label " (" (str/join " " binds) ") " body ")")]))
|
||||
|
||||
(defn- emit-fn [node]
|
||||
(let [arities (:arities node)
|
||||
;; a named fn binds its own name as a known-procedure local across ALL
|
||||
;; arities, so self-calls emit directly rather than via jolt-invoke.
|
||||
self (when-let [nm (:name node)] (munge-name nm))
|
||||
clauses (binding [*known-procs* (if self (conj *known-procs* self) *known-procs*)]
|
||||
(mapv emit-arity-clause arities))
|
||||
lambda (if (= 1 (count clauses))
|
||||
(let [c (first clauses)] (str "(lambda " (nth c 0) " " (nth c 1) ")"))
|
||||
(str "(case-lambda "
|
||||
(str/join " " (map (fn [c] (str "(" (nth c 0) " " (nth c 1) ")")) clauses))
|
||||
")"))]
|
||||
;; A named fn references itself by name — the analyzer binds that name as a
|
||||
;; :local in the body. letrec makes the name visible to the lambda.
|
||||
(if-let [nm (:name node)]
|
||||
(let [m (munge-name nm)] (str "(letrec ((" m " " lambda ")) " m ")"))
|
||||
lambda)))
|
||||
|
||||
;; If fnode is a clojure.core (or host) ref to a native-op primitive, return the
|
||||
;; Scheme op string — only at an arity where the Scheme op and the jolt fn agree.
|
||||
(defn- native-op [fnode nargs]
|
||||
(let [nm (case (:op fnode)
|
||||
:var (when (= "clojure.core" (:ns fnode)) (:name fnode))
|
||||
:host (:name fnode)
|
||||
nil)
|
||||
op (when nm (native-ops nm))
|
||||
arity-ok (when nm (op-arity nm))]
|
||||
(cond
|
||||
(nil? op) nil
|
||||
(and arity-ok (not (arity-ok nargs))) nil
|
||||
:else op)))
|
||||
|
||||
;; IFn dispatch for a LITERAL callee (Clojure's "value as fn"): a keyword looks
|
||||
;; itself up in its arg; a map/set/vector literal looks up its arg.
|
||||
(defn- ifn-kind [fnode]
|
||||
(case (:op fnode)
|
||||
:const (when (keyword? (:val fnode)) :keyword)
|
||||
(:map :set :vector) :coll
|
||||
nil))
|
||||
|
||||
;; A reference into the Clojure stdlib (clojure.*) with no impl on Chez yet.
|
||||
(defn- stdlib-var? [n]
|
||||
(and (= :var (:op n)) (str/starts-with? (or (:ns n) "") "clojure.")))
|
||||
|
||||
(defn- emit-invoke [node]
|
||||
(let [fnode (:fn node)
|
||||
arg-nodes (:args node)
|
||||
args (mapv emit arg-nodes)
|
||||
nop (native-op fnode (count args))
|
||||
kind (ifn-kind fnode)
|
||||
;; order args left-to-right (build receives the spliced operand strings)
|
||||
order-args (fn [build] (ordered-call arg-nodes args build))
|
||||
defstr (fn [as] (if (> (count as) 1) (str " " (nth as 1)) ""))
|
||||
;; jolt-invoke dispatch: Clojure evaluates the fn expr before the args, so
|
||||
;; order [callee & args] together when ordering is observable.
|
||||
invoke (fn []
|
||||
(ordered-call (cons fnode arg-nodes) (cons (emit fnode) args)
|
||||
(fn [[f & as]]
|
||||
(str "(jolt-invoke " f (if (seq as) (str " " (str/join " " as)) "") ")"))))]
|
||||
(cond
|
||||
;; zero-arg + / * : exact integer identity (= JVM long: (+) -> 0, (*) -> 1).
|
||||
(and nop (empty? args) (= nop "+")) "0"
|
||||
(and nop (empty? args) (= nop "*")) "1"
|
||||
(and nop (= 1 (count args)) (cmp1-ops nop)) (str "(begin " (first args) " #t)")
|
||||
nop (order-args (fn [as] (str "(" nop " " (str/join " " as) ")")))
|
||||
;; (:k coll [default]) -> (jolt-get coll :k [default]) — the key (fnode) is a
|
||||
;; const, so only the coll/default args carry order.
|
||||
(= kind :keyword)
|
||||
(order-args (fn [as] (str "(jolt-get " (first as) " " (emit fnode) (defstr as) ")")))
|
||||
;; (coll k [default]) -> (jolt-get coll k [default]) — coll (fnode) is the
|
||||
;; callee, evaluated before the key/default args.
|
||||
(= kind :coll)
|
||||
(ordered-call (cons fnode arg-nodes) (cons (emit fnode) args)
|
||||
(fn [[c & as]] (str "(jolt-get " c " " (str/join " " as) ")")))
|
||||
(and (stdlib-var? fnode) (not (deref prelude-mode?)))
|
||||
(throw (ex-info (str "emit: unsupported stdlib fn `" (:ns fnode) "/" (:name fnode)
|
||||
"` (no core on Chez yet)") {}))
|
||||
;; static method call (Class/method arg*) -> (host-static-call ...).
|
||||
(= :host-static (:op fnode))
|
||||
(order-args (fn [as]
|
||||
(str "(host-static-call " (chez-str-lit (:class fnode)) " " (chez-str-lit (:member fnode))
|
||||
(if (empty? as) "" (str " " (str/join " " as))) ")")))
|
||||
(= :host (:op fnode))
|
||||
(throw (ex-info (str "emit: unsupported host call `" (:name fnode) "`") {}))
|
||||
;; a :local callee that isn't a known procedure -> dynamic IFn dispatch.
|
||||
(and (= :local (:op fnode)) (not (*known-procs* (munge-name (:name fnode)))))
|
||||
(invoke)
|
||||
;; a late-bound :var call head can hold a procedure OR a non-applicable
|
||||
;; value the RT dispatches (multimethod, keyword/coll IFn) — route via
|
||||
;; jolt-invoke (transparent for a procedure).
|
||||
(= :var (:op fnode))
|
||||
(invoke)
|
||||
;; a computed callee can yield ANY IFn — route through jolt-invoke.
|
||||
:else
|
||||
(invoke))))
|
||||
|
||||
;; try/catch/finally (jolt-vcsl). throw raises the jolt value RAW (jolt-throw =
|
||||
;; Scheme `raise`); catch lowers to `guard` with an `else` clause (the IR drops
|
||||
;; the class), finally to `dynamic-wind`'s after-thunk (runs on success, catch and
|
||||
;; escape — Clojure finally semantics). Both keys optional on the node.
|
||||
(defn- emit-try [node]
|
||||
(let [core (if-let [cs (:catch-sym node)]
|
||||
(str "(guard (" (munge-name cs) " (else " (emit (:catch-body node)) ")) "
|
||||
(emit (:body node)) ")")
|
||||
(emit (:body node)))]
|
||||
(if-let [fin (:finally node)]
|
||||
(str "(dynamic-wind (lambda () #f) (lambda () " core ") (lambda () " (emit fin) "))")
|
||||
core)))
|
||||
|
||||
;; Does this IR node emit to an expression that yields a Scheme boolean? Used to
|
||||
;; drop the redundant jolt-truthy? on an :if test.
|
||||
(defn- returns-scheme-bool? [node]
|
||||
(cond
|
||||
(and (= :const (:op node)) (boolean? (:val node))) true
|
||||
(= :invoke (:op node))
|
||||
(let [nop (native-op (:fn node) (count (:args node)))]
|
||||
(if (and nop (bool-returning-ops nop)) true false))
|
||||
:else false))
|
||||
|
||||
(defn emit [node]
|
||||
(case (:op node)
|
||||
:const (emit-const (:val node))
|
||||
:local (munge-name (:name node))
|
||||
;; late-bound var: read the cell's current root at use time. A value-position
|
||||
;; ref to a clojure.core fn the RT provides lowers to the RT procedure.
|
||||
:var (let [core-proc (and (= "clojure.core" (:ns node)) (core-value-procs (:name node)))]
|
||||
(cond
|
||||
core-proc core-proc
|
||||
(and (stdlib-var? node) (not (deref prelude-mode?)))
|
||||
(throw (ex-info (str "emit: unsupported stdlib ref `" (:ns node) "/" (:name node)
|
||||
"` (no core on Chez yet)") {}))
|
||||
:else (str "(var-deref " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) ")")))
|
||||
:the-var (str "(jolt-var " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) ")")
|
||||
;; (set! *var* val) -> set the var's innermost binding (else root); returns val.
|
||||
:set-var (str "(jolt-var-set " (emit (:the-var node)) " " (emit (:val node)) ")")
|
||||
;; (set! (.-field obj) val) -> mutate the deftype instance field in place.
|
||||
:set-field (str "(jolt-set-field! " (emit (:obj node)) " (keyword #f "
|
||||
(chez-str-lit (:field node)) ") " (emit (:val node)) ")")
|
||||
;; a non-top-level defmacro -> def the expander fn + mark the var a macro at
|
||||
;; runtime (the spine does the same for top-level forms).
|
||||
:defmacro (str "(begin (def-var! " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) " "
|
||||
(emit (:fn node)) ") (mark-macro! " (chez-str-lit (:ns node)) " "
|
||||
(chez-str-lit (:name node)) ") jolt-nil)")
|
||||
:host (throw (ex-info (str "emit: unsupported host ref `" (:name node) "`") {}))
|
||||
:host-static (str "(host-static-ref " (chez-str-lit (:class node)) " "
|
||||
(chez-str-lit (:member node)) ")")
|
||||
:host-new (str "(host-new " (chez-str-lit (:class node))
|
||||
(let [args (map emit (:args node))]
|
||||
(if (empty? args) "" (str " " (str/join " " args)))) ")")
|
||||
:if (let [test (:test node)
|
||||
t (if (returns-scheme-bool? test) (emit test)
|
||||
(str "(jolt-truthy? " (emit test) ")"))]
|
||||
(str "(if " t " " (emit (:then node)) " " (emit (:else node)) ")"))
|
||||
:do (str "(begin " (str/join " " (map emit (:statements node)))
|
||||
(if (empty? (:statements node)) "" " ") (emit (:ret node)) ")")
|
||||
:invoke (emit-invoke node)
|
||||
;; collection literals -> rt constructors (collections.ss). Elements are
|
||||
;; already-analyzed IR nodes; evaluate LEFT-TO-RIGHT (emit-ordered).
|
||||
:vector (emit-ordered "jolt-vector" (map emit (:items node)))
|
||||
:set (emit-ordered "jolt-hash-set" (map emit (:items node)))
|
||||
:map (emit-ordered "jolt-hash-map"
|
||||
(mapcat (fn [p] [(emit (nth p 0)) (emit (nth p 1))]) (:pairs node)))
|
||||
:quote (emit-quoted (:form node))
|
||||
:throw (str "(jolt-throw " (emit (:expr node)) ")")
|
||||
:try (emit-try node)
|
||||
;; regex literal #"…" -> a jolt-regex value (regex.ss, vendored irregex).
|
||||
:regex (str "(jolt-regex " (chez-str-lit (:source node)) ")")
|
||||
;; #inst / #uuid literals -> runtime inst / uuid values.
|
||||
:inst (str "(jolt-inst-from-string " (chez-str-lit (:source node)) ")")
|
||||
:uuid (str "(jolt-uuid-from-string " (chez-str-lit (:source node)) ")")
|
||||
;; bigdecimal literal (1.5M) -> a runtime jbigdec from its numeric text.
|
||||
:bigdec (str "(jolt-bigdec-from-string " (chez-str-lit (:source node)) ")")
|
||||
;; a namespace value spliced into a form (~*ns*) -> reconstruct by name.
|
||||
:the-ns (str "(intern-ns! " (chez-str-lit (:name node)) ")")
|
||||
;; (.method target arg*) -> jolt-host-call for an rt-shimmed method, else
|
||||
;; record-method-dispatch (a reify/record protocol method, jolt-jgoc).
|
||||
:host-call (let [m (:method node)
|
||||
target (emit (:target node))
|
||||
args (map emit (:args node))]
|
||||
(if (supported-host-methods m)
|
||||
(str "(jolt-host-call " (chez-str-lit m) " " target
|
||||
(if (empty? args) "" (str " " (str/join " " args))) ")")
|
||||
(str "(record-method-dispatch " target " " (chez-str-lit m)
|
||||
" (jolt-vector" (if (empty? args) "" (str " " (str/join " " args))) "))")))
|
||||
:let (emit-let node)
|
||||
:loop (emit-loop node)
|
||||
:recur (emit-recur node)
|
||||
:fn (emit-fn node)
|
||||
;; (def name) with no init (declare): reserve the cell. A def with non-empty
|
||||
;; reader metadata lowers to def-var-with-meta! (ported in a later increment).
|
||||
:def (cond
|
||||
(:no-init node)
|
||||
(str "(declare-var! " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) ")")
|
||||
(jmeta-nonempty? (:meta node))
|
||||
(str "(def-var-with-meta! " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) " "
|
||||
(emit (:init node)) " " (emit-quoted (:meta node)) ")")
|
||||
:else
|
||||
(str "(def-var! " (chez-str-lit (:ns node)) " " (chez-str-lit (:name node)) " "
|
||||
(emit (:init node)) ")"))
|
||||
(throw (ex-info (str "emit: op not yet ported / unhandled: " (pr-str (:op node))) {}))))
|
||||
125
jolt-core/jolt/deps.clj
Normal file
125
jolt-core/jolt/deps.clj
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
(ns jolt.deps
|
||||
"Resolve a deps.edn into an ordered list of source roots — git + local deps
|
||||
only, no Maven. A reduced tools.deps: :paths, :deps (`:git/url`+`:git/sha` /
|
||||
`:local/root`), :aliases (:extra-paths / :extra-deps / :main-opts), :tasks.
|
||||
|
||||
The deps walk is breadth-first so a top-level coordinate registers before any
|
||||
transitive one (a top-level pin wins). Git deps clone into a sha-immutable
|
||||
cache ($JOLT_GITLIBS, else ~/.jolt/gitlibs) shared across projects. Resolution
|
||||
shells out to `git` through jolt.host/sh; nothing here touches the JVM."
|
||||
(:require [clojure.edn :as edn]
|
||||
[clojure.string :as str]))
|
||||
|
||||
;; --- small host seams -------------------------------------------------------
|
||||
(defn- getenv [n] (jolt.host/getenv n))
|
||||
(defn- file-exists? [p] (jolt.host/file-exists? p))
|
||||
(defn- sh [cmd] (jolt.host/sh cmd)) ; exit code, inherits stdout/stderr
|
||||
(defn- sh-out [cmd] (jolt.host/sh-out cmd)) ; captured stdout
|
||||
(defn- warn [& xs] (println (str "[jolt.deps] " (apply str xs))))
|
||||
|
||||
(defn- read-edn [path]
|
||||
(when (file-exists? path)
|
||||
(try (edn/read-string (slurp path))
|
||||
(catch :default e (warn "could not read " path ": " (ex-message e)) nil))))
|
||||
|
||||
(defn- abspath [dir p]
|
||||
(if (str/starts-with? p "/") p (str dir "/" p)))
|
||||
|
||||
;; --- git cache --------------------------------------------------------------
|
||||
(defn- gitlibs-dir []
|
||||
(or (getenv "JOLT_GITLIBS")
|
||||
(str (or (getenv "HOME") ".") "/.jolt/gitlibs")))
|
||||
|
||||
(defn- alnum? [c]
|
||||
(let [n (int c)]
|
||||
(or (and (>= n 48) (<= n 57)) ; 0-9
|
||||
(and (>= n 65) (<= n 90)) ; A-Z
|
||||
(and (>= n 97) (<= n 122))))) ; a-z
|
||||
(defn- sanitize [s]
|
||||
(str/join (map (fn [c] (if (or (alnum? c) (= c \.) (= c \-)) c \_)) (seq s))))
|
||||
|
||||
(defn- ensure-git
|
||||
"Clone url at sha into the cache (once); return the checkout dir."
|
||||
[url sha]
|
||||
(let [dir (str (gitlibs-dir) "/" (sanitize url) "/" sha)]
|
||||
(if (file-exists? dir)
|
||||
dir
|
||||
(do
|
||||
(warn "fetching " url " @ " (subs sha 0 (min 12 (count sha))))
|
||||
(sh (str "mkdir -p " (pr-str dir)))
|
||||
(when-not (zero? (sh (str "git clone --quiet " (pr-str url) " " (pr-str dir))))
|
||||
(throw (ex-info (str "git clone failed: " url) {:url url})))
|
||||
(when-not (zero? (sh (str "git -C " (pr-str dir) " checkout --quiet " (pr-str sha))))
|
||||
(throw (ex-info (str "git checkout failed: " sha " in " url) {:url url :sha sha})))
|
||||
;; submodules are pinned in the checkout; pull them if the dep uses any.
|
||||
(sh (str "git -C " (pr-str dir) " submodule update --init --recursive --quiet"))
|
||||
dir))))
|
||||
|
||||
;; --- coordinate -> root dir -------------------------------------------------
|
||||
(defn- coord-root
|
||||
"The on-disk root directory for one dependency coordinate, or nil to skip."
|
||||
[coord spec base-dir]
|
||||
(cond
|
||||
(:local/root spec) (abspath base-dir (:local/root spec))
|
||||
(and (:git/url spec) (:git/sha spec))
|
||||
(let [checkout (ensure-git (:git/url spec) (:git/sha spec))]
|
||||
(if-let [root (:deps/root spec)] (str checkout "/" root) checkout))
|
||||
(:jolt/module spec)
|
||||
(do (warn "skipping janet dependency " coord " (:jolt/module is obsolete on Chez)") nil)
|
||||
:else
|
||||
(do (warn "skipping unsupported coordinate " coord " " (pr-str spec)) nil)))
|
||||
|
||||
(defn- dep-source-roots
|
||||
"Source roots a resolved dep contributes: its deps.edn :paths (default [\"src\"])
|
||||
resolved under its root dir."
|
||||
[root]
|
||||
(let [edn (read-edn (str root "/deps.edn"))
|
||||
paths (or (:paths edn) ["src"])]
|
||||
(map #(abspath root %) paths)))
|
||||
|
||||
(defn- resolve-deps
|
||||
"Breadth-first walk of a deps map; returns an ordered, de-duplicated list of
|
||||
source-root directories. `base-dir` resolves :local/root and is replaced by a
|
||||
dep's own root as the walk descends."
|
||||
[deps base-dir]
|
||||
(loop [queue (mapv (fn [[c s]] [c s base-dir]) (seq deps))
|
||||
seen #{}
|
||||
roots []]
|
||||
(if (empty? queue)
|
||||
(distinct roots)
|
||||
(let [[coord spec bd] (first queue)
|
||||
queue (subvec (vec queue) 1)]
|
||||
(if (contains? seen coord)
|
||||
(recur queue seen roots)
|
||||
(let [root (coord-root coord spec bd)]
|
||||
(if (nil? root)
|
||||
(recur queue (conj seen coord) roots)
|
||||
(let [edn (read-edn (str root "/deps.edn"))
|
||||
child (mapv (fn [[c s]] [c s root]) (seq (:deps edn)))]
|
||||
(recur (into queue child)
|
||||
(conj seen coord)
|
||||
(into roots (dep-source-roots root)))))))))))
|
||||
|
||||
;; --- public -----------------------------------------------------------------
|
||||
(defn resolve-project
|
||||
"Resolve `project-dir`'s deps.edn with the selected alias keywords. Returns
|
||||
{:roots [...] :main-opts [...] :tasks {...}}; :main-opts is the last selected
|
||||
alias's, else nil."
|
||||
([project-dir] (resolve-project project-dir []))
|
||||
([project-dir alias-kws]
|
||||
(let [edn (read-edn (str project-dir "/deps.edn"))
|
||||
aliases (:aliases edn)
|
||||
selected (keep #(get aliases %) alias-kws)
|
||||
extra-paths (mapcat :extra-paths selected)
|
||||
extra-deps (apply merge (map :extra-deps selected))
|
||||
main-opts (some :main-opts (reverse selected))
|
||||
project-paths (concat (or (:paths edn) ["src"]) extra-paths)
|
||||
project-roots (map #(abspath project-dir %) project-paths)
|
||||
all-deps (merge (:deps edn) extra-deps)
|
||||
dep-roots (resolve-deps all-deps project-dir)]
|
||||
{:roots (vec (distinct (concat project-roots dep-roots)))
|
||||
:main-opts main-opts
|
||||
:tasks (:tasks edn)})))
|
||||
|
||||
(defn has-deps-edn? [project-dir]
|
||||
(file-exists? (str project-dir "/deps.edn")))
|
||||
|
|
@ -27,6 +27,17 @@
|
|||
;; Janet) — the back end emits a host-appropriate reference.
|
||||
(defn host-ref [name] {:op :host :name name})
|
||||
|
||||
;; A qualified static reference to a host class member, `Class/member` (e.g.
|
||||
;; Math/sqrt, Long/MAX_VALUE, System/getenv). A leaf node carrying the class and
|
||||
;; member names. The Chez back end lowers a value ref to host-static-ref and a
|
||||
;; call head to host-static-call (host-static.ss).
|
||||
(defn host-static [class member] {:op :host-static :class class :member member})
|
||||
|
||||
;; A host constructor, `(Class. args*)` / `(new Class args*)`. Carries the class
|
||||
;; name and the analyzed argument nodes. Chez lowers to host-new (host-static.ss
|
||||
;; class-ctor registry).
|
||||
(defn host-new [class args] {:op :host-new :class class :args args})
|
||||
|
||||
(defn if-node [test then else] {:op :if :test test :then then :else else})
|
||||
|
||||
(defn do-node [statements ret] {:op :do :statements statements :ret ret})
|
||||
|
|
@ -85,6 +96,9 @@
|
|||
(= op :do) (assoc node :statements (mapv f (get node :statements))
|
||||
:ret (f (get node :ret)))
|
||||
(= op :throw) (assoc node :expr (f (get node :expr)))
|
||||
(= op :set-var) (assoc node :val (f (get node :val)))
|
||||
(= op :set-field) (assoc node :obj (f (get node :obj)) :val (f (get node :val)))
|
||||
(= op :defmacro) (assoc node :fn (f (get node :fn)))
|
||||
(= op :invoke) (assoc node :fn (f (get node :fn))
|
||||
:args (mapv f (get node :args)))
|
||||
(= op :vector) (assoc node :items (mapv f (get node :items)))
|
||||
|
|
@ -101,6 +115,9 @@
|
|||
(= op :fn) (assoc node :arities (mapv (fn [a] (assoc a :body (f (get a :body))))
|
||||
(get node :arities)))
|
||||
(= op :def) (assoc node :init (f (get node :init)))
|
||||
(= op :host-call) (assoc node :target (f (get node :target))
|
||||
:args (mapv f (get node :args)))
|
||||
(= op :host-new) (assoc node :args (mapv f (get node :args)))
|
||||
;; :catch-body / :finally are optional; recurse them only when PRESENT.
|
||||
;; Assoc'ing them nil-when-absent would turn the node into a phm (jolt's
|
||||
;; nil-valued-key representation) and force backend densification — so we
|
||||
|
|
@ -110,5 +127,5 @@
|
|||
n (if (get node :catch-body) (assoc n :catch-body (f (get node :catch-body))) n)
|
||||
n (if (get node :finally) (assoc n :finally (f (get node :finally))) n)]
|
||||
n)
|
||||
;; :const :local :var :host :the-var :rt :quote — no child nodes
|
||||
;; :const :local :var :host :host-static :the-var :rt :quote — no child nodes
|
||||
:else node)))
|
||||
|
|
|
|||
106
jolt-core/jolt/main.clj
Normal file
106
jolt-core/jolt/main.clj
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
(ns jolt.main
|
||||
"The jolt CLI dispatch: resolve a project's deps.edn, set the source roots, and
|
||||
run a namespace's -main, a file, a deps.edn task, or a REPL. Driven by cli.ss,
|
||||
which hands it the raw argv; the project directory is JOLT_PWD (the user's cwd
|
||||
before the launcher cd'd to the jolt repo)."
|
||||
(:require [jolt.deps :as deps]
|
||||
[clojure.string :as str]))
|
||||
|
||||
(defn- project-dir [] (or (jolt.host/getenv "JOLT_PWD") "."))
|
||||
|
||||
;; Apply a resolved project's roots on top of the current (jolt-core) roots so app
|
||||
;; namespaces resolve while jolt.* stays loadable.
|
||||
(defn- apply-roots! [roots]
|
||||
(jolt.host/set-source-roots! (vec (distinct (concat roots (jolt.host/source-roots))))))
|
||||
|
||||
(defn- run-ns
|
||||
"Require ns-name and invoke its -main with the string app args."
|
||||
[ns-name app-args]
|
||||
(require (symbol ns-name))
|
||||
(if-let [mainv (ns-resolve (symbol ns-name) (symbol "-main"))]
|
||||
(apply (deref mainv) app-args)
|
||||
(throw (ex-info (str "namespace " ns-name " has no -main") {:ns ns-name}))))
|
||||
|
||||
;; main-opts is a vector like ["-m" "app.core"] (optionally trailing args). Apply
|
||||
;; it with the user-supplied extra args appended.
|
||||
(defn- apply-main-opts [main-opts extra-args]
|
||||
(cond
|
||||
(and (seq main-opts) (= "-m" (first main-opts)))
|
||||
(run-ns (second main-opts) (concat (drop 2 main-opts) extra-args))
|
||||
:else
|
||||
(throw (ex-info (str "unsupported :main-opts " (pr-str main-opts)) {}))))
|
||||
|
||||
(defn- parse-aliases [s] ; "-M:a:b" / ":a:b" -> [:a :b]
|
||||
(let [s (if (str/starts-with? s "-") (subs s 2) s)]
|
||||
(->> (str/split s #":") (remove str/blank?) (map keyword) vec)))
|
||||
|
||||
;; run [-m NS args… | FILE]
|
||||
(defn- cmd-run [more]
|
||||
(let [{:keys [roots]} (deps/resolve-project (project-dir))]
|
||||
(apply-roots! roots)
|
||||
(cond
|
||||
(= "-m" (first more)) (run-ns (second more) (drop 2 more))
|
||||
(seq more) (do (load-file (first more)) nil)
|
||||
:else (throw (ex-info "run needs -m NS or a FILE" {})))))
|
||||
|
||||
;; -M:alias… — resolve with the aliases, run their :main-opts
|
||||
(defn- cmd-M [arg more]
|
||||
(let [aliases (parse-aliases arg)
|
||||
{:keys [roots main-opts]} (deps/resolve-project (project-dir) aliases)]
|
||||
(apply-roots! roots)
|
||||
(if main-opts
|
||||
(apply-main-opts main-opts more)
|
||||
(throw (ex-info (str "alias(es) " (pr-str aliases) " have no :main-opts") {})))))
|
||||
|
||||
;; -A:alias… — add the aliases' paths/deps, then run the remaining argv as a command
|
||||
(defn- cmd-A [arg more]
|
||||
(let [aliases (parse-aliases arg)
|
||||
{:keys [roots]} (deps/resolve-project (project-dir) aliases)]
|
||||
(apply-roots! roots)
|
||||
(when (seq more) (run-ns (second more) (drop 2 more)))))
|
||||
|
||||
(defn- cmd-path []
|
||||
(let [{:keys [roots]} (deps/resolve-project (project-dir))]
|
||||
(println (str/join ":" roots))))
|
||||
|
||||
(defn- repl []
|
||||
(println ";; jolt repl — ^D to exit")
|
||||
(loop []
|
||||
(print "user=> ") (flush)
|
||||
(let [line (read-line)]
|
||||
(when line
|
||||
(try (println (pr-str (load-string line)))
|
||||
(catch :default e (println "error:" (ex-message e))))
|
||||
(recur)))))
|
||||
|
||||
;; A deps.edn :tasks entry: a string is a shell command; a map is {:main-opts …}.
|
||||
(defn- run-task [name more]
|
||||
(let [{:keys [roots tasks]} (deps/resolve-project (project-dir))
|
||||
task (get tasks (symbol name))]
|
||||
(cond
|
||||
(nil? task) (throw (ex-info (str "unknown command or task: " name) {:name name}))
|
||||
(string? task) (jolt.host/sh task)
|
||||
(map? task) (do (apply-roots! roots) (apply-main-opts (:main-opts task) more))
|
||||
:else (throw (ex-info (str "bad task " name) {})))))
|
||||
|
||||
(defn- usage []
|
||||
(println "usage: jolt <command> [args]")
|
||||
(println " run -m NS [args] resolve deps.edn, load NS, call its -main")
|
||||
(println " run FILE load a Clojure file")
|
||||
(println " -M:alias [args] run the alias's :main-opts")
|
||||
(println " -A:alias [args] add the alias's paths/deps")
|
||||
(println " repl start a line REPL")
|
||||
(println " path print the resolved source roots")
|
||||
(println " <task> run a deps.edn :tasks entry"))
|
||||
|
||||
(defn -main [& args]
|
||||
(let [[cmd & more] args]
|
||||
(cond
|
||||
(nil? cmd) (usage)
|
||||
(= cmd "run") (cmd-run more)
|
||||
(= cmd "repl") (repl)
|
||||
(= cmd "path") (cmd-path)
|
||||
(str/starts-with? cmd "-M") (cmd-M cmd more)
|
||||
(str/starts-with? cmd "-A") (cmd-A cmd more)
|
||||
(= cmd "-m") (cmd-run (cons "-m" more))
|
||||
:else (run-task cmd more))))
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue