diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 05fd2bb..9c6d491 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -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 diff --git a/.gitmodules b/.gitmodules index 959062d..77affa0 100644 --- a/.gitmodules +++ b/.gitmodules @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md index aa36b0b..89d3e3b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,75 +53,64 @@ bd close # 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/.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. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5ece564 --- /dev/null +++ b/Makefile @@ -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 diff --git a/README.md b/README.md index e9de902..5956a3f 100644 --- a/README.md +++ b/README.md @@ -2,266 +2,108 @@ [![tests](https://github.com/jolt-lang/jolt/actions/workflows/tests.yml/badge.svg)](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/` for a Janet root binding and `janet./` -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./` 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 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 diff --git a/bench/README.md b/bench/README.md index 01ab8bc..549a5c1 100644 --- a/bench/README.md +++ b/bench/README.md @@ -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. diff --git a/bench/dump-mandelbrot-emit.janet b/bench/dump-mandelbrot-emit.janet deleted file mode 100644 index 7b196c7..0000000 --- a/bench/dump-mandelbrot-emit.janet +++ /dev/null @@ -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)) diff --git a/bench/mandelbrot-hand-rec.janet b/bench/mandelbrot-hand-rec.janet deleted file mode 100644 index d8e0249..0000000 --- a/bench/mandelbrot-hand-rec.janet +++ /dev/null @@ -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))) diff --git a/bench/mandelbrot-hand.janet b/bench/mandelbrot-hand.janet deleted file mode 100644 index 08c8d53..0000000 --- a/bench/mandelbrot-hand.janet +++ /dev/null @@ -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)) diff --git a/bin/joltc b/bin/joltc new file mode 100755 index 0000000..0ccce51 --- /dev/null +++ b/bin/joltc @@ -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 | 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 "$@" diff --git a/docs/architecture-refactor-plan.md b/docs/architecture-refactor-plan.md deleted file mode 100644 index 7be4b73..0000000 --- a/docs/architecture-refactor-plan.md +++ /dev/null @@ -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-
` 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). diff --git a/docs/building-and-deps.md b/docs/building-and-deps.md index 4bece89..7251486 100644 --- a/docs/building-and-deps.md +++ b/docs/building-and-deps.md @@ -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 # 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 ""} 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 `. -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 `/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. diff --git a/docs/foundational-runtime-handoff.md b/docs/foundational-runtime-handoff.md deleted file mode 100644 index 31f123f..0000000 --- a/docs/foundational-runtime-handoff.md +++ /dev/null @@ -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? diff --git a/docs/foundational-runtime-lever1-native-codegen.md b/docs/foundational-runtime-lever1-native-codegen.md deleted file mode 100644 index a037d7e..0000000 --- a/docs/foundational-runtime-lever1-native-codegen.md +++ /dev/null @@ -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 diff --git a/docs/foundational-runtime-spike-results.md b/docs/foundational-runtime-spike-results.md deleted file mode 100644 index 6bdb242..0000000 --- a/docs/foundational-runtime-spike-results.md +++ /dev/null @@ -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). diff --git a/docs/grammar.ebnf b/docs/grammar.ebnf index ba29ca7..113eff5 100644 --- a/docs/grammar.ebnf +++ b/docs/grammar.ebnf @@ -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" ; diff --git a/docs/libraries.md b/docs/libraries.md index 8b03f95..046918e 100644 --- a/docs/libraries.md +++ b/docs/libraries.md @@ -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`/ diff --git a/docs/rfc/0001-language-specification.md b/docs/rfc/0001-language-specification.md index 06222e7..bc078f9 100644 --- a/docs/rfc/0001-language-specification.md +++ b/docs/rfc/0001-language-specification.md @@ -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 diff --git a/docs/rfc/0003-transients.md b/docs/rfc/0003-transients.md index 8c451db..cee6dc5 100644 --- a/docs/rfc/0003-transients.md +++ b/docs/rfc/0003-transients.md @@ -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. diff --git a/docs/rfc/0004-type-hints.md b/docs/rfc/0004-type-hints.md index 5c47070..4fa2e3e 100644 --- a/docs/rfc/0004-type-hints.md +++ b/docs/rfc/0004-type-hints.md @@ -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 diff --git a/docs/rfc/0005-structural-type-inference.md b/docs/rfc/0005-structural-type-inference.md index 42cad41..f3e309b 100644 --- a/docs/rfc/0005-structural-type-inference.md +++ b/docs/rfc/0005-structural-type-inference.md @@ -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) diff --git a/docs/seed-overlay-registry.md b/docs/seed-overlay-registry.md index 5bbcbcf..674a6b7 100644 --- a/docs/seed-overlay-registry.md +++ b/docs/seed-overlay-registry.md @@ -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. diff --git a/docs/self-hosting-architecture.md b/docs/self-hosting-architecture.md deleted file mode 100644 index e208b87..0000000 --- a/docs/self-hosting-architecture.md +++ /dev/null @@ -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." diff --git a/docs/self-hosting-compiler.md b/docs/self-hosting-compiler.md deleted file mode 100644 index b46b57e..0000000 --- a/docs/self-hosting-compiler.md +++ /dev/null @@ -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. diff --git a/docs/spec/00-front-matter.md b/docs/spec/00-front-matter.md index 63d1d54..1e974952 100644 --- a/docs/spec/00-front-matter.md +++ b/docs/spec/00-front-matter.md @@ -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 diff --git a/docs/spec/02-reader.md b/docs/spec/02-reader.md index 6d7fb70..88e782b 100644 --- a/docs/spec/02-reader.md +++ b/docs/spec/02-reader.md @@ -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 diff --git a/docs/spec/03-special-forms.md b/docs/spec/03-special-forms.md index e90a02d..3a19e3f 100644 --- a/docs/spec/03-special-forms.md +++ b/docs/spec/03-special-forms.md @@ -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 | diff --git a/docs/spec/README.md b/docs/spec/README.md index 7c710f2..69f2ec0 100644 --- a/docs/spec/README.md +++ b/docs/spec/README.md @@ -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 diff --git a/docs/tools-deps.md b/docs/tools-deps.md index 12999a2..84461ca 100644 --- a/docs/tools-deps.md +++ b/docs/tools-deps.md @@ -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 - (`/.cache/git__`) 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 -`/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 `.clj` -then `.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; +- `` → 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 ` 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{…}`). diff --git a/host/chez/async.ss b/host/chez/async.ss new file mode 100644 index 0000000..cab5c0b --- /dev/null +++ b/host/chez/async.ss @@ -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)) + +;; 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-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") diff --git a/host/chez/atoms.ss b/host/chez/atoms.ss new file mode 100644 index 0000000..f92ce57 --- /dev/null +++ b/host/chez/atoms.ss @@ -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) diff --git a/host/chez/bigdec.ss b/host/chez/bigdec.ss new file mode 100644 index 0000000..9b91012 --- /dev/null +++ b/host/chez/bigdec.ss @@ -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?) diff --git a/host/chez/bootstrap.ss b/host/chez/bootstrap.ss new file mode 100644 index 0000000..498f115 --- /dev/null +++ b/host/chez/bootstrap.ss @@ -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") diff --git a/host/chez/cli.ss b/host/chez/cli.ss new file mode 100644 index 0000000..f77ea6e --- /dev/null +++ b/host/chez/cli.ss @@ -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))))) diff --git a/host/chez/collections.ss b/host/chez/collections.ss new file mode 100644 index 0000000..797d716 --- /dev/null +++ b/host/chez/collections.ss @@ -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 (fxvector 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) (fxidx i))) + (cond ((and (fx>=? i 0) (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 []; (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) (fxidx i))) + (cond ((pvec? coll) (let ((v (pvec-v coll))) + (if (and (fx>=? i 0) (fxidx i))) + (cond ((pvec? coll) (pvec-nth-d coll i d)) + ((string? coll) (if (and (fx>=? i 0) (fx 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) (fxemit 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) diff --git a/host/chez/concurrency.ss b/host/chez/concurrency.ss new file mode 100644 index 0000000..9785e6c --- /dev/null +++ b/host/chez/concurrency.ss @@ -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) diff --git a/host/chez/converters.ss b/host/chez/converters.ss new file mode 100644 index 0000000..cbb72de --- /dev/null +++ b/host/chez/converters.ss @@ -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) (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) diff --git a/host/chez/dot-forms.ss b/host/chez/dot-forms.ss new file mode 100644 index 0000000..945f810 --- /dev/null +++ b/host/chez/dot-forms.ss @@ -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)))))) diff --git a/host/chez/dyn-binding.ss b/host/chez/dyn-binding.ss new file mode 100644 index 0000000..e1d59fe --- /dev/null +++ b/host/chez/dyn-binding.ss @@ -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) diff --git a/host/chez/dynamic-vars.ss b/host/chez/dynamic-vars.ss new file mode 100644 index 0000000..5b2883c --- /dev/null +++ b/host/chez/dynamic-vars.ss @@ -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) diff --git a/host/chez/emit-image.ss b/host/chez/emit-image.ss new file mode 100644 index 0000000..ea63d29 --- /dev/null +++ b/host/chez/emit-image.ss @@ -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 ) + +;; (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)) diff --git a/host/chez/host-class.ss b/host/chez/host-class.ss new file mode 100644 index 0000000..9d9a333 --- /dev/null +++ b/host/chez/host-class.ss @@ -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")) diff --git a/host/chez/host-contract.ss b/host/chez/host-contract.ss new file mode 100644 index 0000000..1d1ef33 --- /dev/null +++ b/host/chez/host-contract.ss @@ -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 } 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 ) 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!) diff --git a/host/chez/host-static.ss b/host/chez/host-static.ss new file mode 100644 index 0000000..57a081c --- /dev/null +++ b/host/chez/host-static.ss @@ -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)) \ No newline at end of file diff --git a/host/chez/host-table.ss b/host/chez/host-table.ss new file mode 100644 index 0000000..39fcdbf --- /dev/null +++ b/host/chez/host-table.ss @@ -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))))) diff --git a/host/chez/http-client.ss b/host/chez/http-client.ss new file mode 100644 index 0000000..7c19bb2 --- /dev/null +++ b/host/chez/http-client.ss @@ -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:"; 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")) diff --git a/host/chez/http-server.ss b/host/chez/http-server.ss new file mode 100644 index 0000000..c4e129d --- /dev/null +++ b/host/chez/http-server.ss @@ -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) diff --git a/host/chez/inst-time.ss b/host/chez/inst-time.ss new file mode 100644 index 0000000..6930385 --- /dev/null +++ b/host/chez/inst-time.ss @@ -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))))) diff --git a/host/chez/io.ss b/host/chez/io.ss new file mode 100644 index 0000000..20c081c --- /dev/null +++ b/host/chez/io.ss @@ -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 (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))))) diff --git a/host/chez/lazy-bridge.ss b/host/chez/lazy-bridge.ss new file mode 100644 index 0000000..d035bb3 --- /dev/null +++ b/host/chez/lazy-bridge.ss @@ -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) diff --git a/host/chez/loader.ss b/host/chez/loader.ss new file mode 100644 index 0000000..b338e2d --- /dev/null +++ b/host/chez/loader.ss @@ -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)))) diff --git a/host/chez/math.ss b/host/chez/math.ss new file mode 100644 index 0000000..fddd914 --- /dev/null +++ b/host/chez/math.ss @@ -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) diff --git a/host/chez/multimethods.ss b/host/chez/multimethods.ss new file mode 100644 index 0000000..c5f99a6 --- /dev/null +++ b/host/chez/multimethods.ss @@ -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) diff --git a/host/chez/natives-array.ss b/host/chez/natives-array.ss new file mode 100644 index 0000000..5f53cee --- /dev/null +++ b/host/chez/natives-array.ss @@ -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?))) diff --git a/host/chez/natives-coll.ss b/host/chez/natives-coll.ss new file mode 100644 index 0000000..f7a6d5e --- /dev/null +++ b/host/chez/natives-coll.ss @@ -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?) diff --git a/host/chez/natives-meta.ss b/host/chez/natives-meta.ss new file mode 100644 index 0000000..80c930d --- /dev/null +++ b/host/chez/natives-meta.ss @@ -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) diff --git a/host/chez/natives-misc.ss b/host/chez/natives-misc.ss new file mode 100644 index 0000000..ab860c4 --- /dev/null +++ b/host/chez/natives-misc.ss @@ -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 (fxnumber 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) diff --git a/host/chez/natives-parity.ss b/host/chez/natives-parity.ss new file mode 100644 index 0000000..c5a188e --- /dev/null +++ b/host/chez/natives-parity.ss @@ -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) diff --git a/host/chez/natives-seq.ss b/host/chez/natives-seq.ss new file mode 100644 index 0000000..12b831e --- /dev/null +++ b/host/chez/natives-seq.ss @@ -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?) diff --git a/host/chez/natives-str.ss b/host/chez/natives-str.ss new file mode 100644 index 0000000..ac09f65 --- /dev/null +++ b/host/chez/natives-str.ss @@ -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? (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 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) (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 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 #\$) (fxinteger (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 (fxlist 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) diff --git a/host/chez/natives-xform.ss b/host/chez/natives-xform.ss new file mode 100644 index 0000000..5275ac3 --- /dev/null +++ b/host/chez/natives-xform.ss @@ -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) diff --git a/host/chez/ns.ss b/host/chez/ns.ss new file mode 100644 index 0000000..e20e0f2 --- /dev/null +++ b/host/chez/ns.ss @@ -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 (+/-/" >) (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)))) diff --git a/host/chez/png.ss b/host/chez/png.ss new file mode 100644 index 0000000..dfabe4f --- /dev/null +++ b/host/chez/png.ss @@ -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) diff --git a/host/chez/post-prelude.ss b/host/chez/post-prelude.ss new file mode 100644 index 0000000..6534f1d --- /dev/null +++ b/host/chez/post-prelude.ss @@ -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?) diff --git a/host/chez/predicates.ss b/host/chez/predicates.ss new file mode 100644 index 0000000..2eb4823 --- /dev/null +++ b/host/chez/predicates.ss @@ -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) diff --git a/host/chez/printing.ss b/host/chez/printing.ss new file mode 100644 index 0000000..a50ed9c --- /dev/null +++ b/host/chez/printing.ss @@ -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) "#") ((set) "#") (else "#"))) + ((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) diff --git a/host/chez/reader.ss b/host/chez/reader.ss new file mode 100644 index 0000000..6de5442 --- /dev/null +++ b/host/chez/reader.ss @@ -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 _) 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) diff --git a/host/chez/records.ss b/host/chez/records.ss new file mode 100644 index 0000000..00cd03a --- /dev/null +++ b/host/chez/records.ss @@ -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) (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))) diff --git a/host/chez/regex.ss b/host/chez/regex.ss new file mode 100644 index 0000000..ccd0938 --- /dev/null +++ b/host/chez/regex.ss @@ -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=? 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…)) +;; 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?) diff --git a/host/chez/remint.sh b/host/chez/remint.sh new file mode 100755 index 0000000..a39eed8 --- /dev/null +++ b/host/chez/remint.sh @@ -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 diff --git a/host/chez/rt.ss b/host/chez/rt.ss new file mode 100644 index 0000000..7b1f690 --- /dev/null +++ b/host/chez/rt.ss @@ -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 "#")) +;; `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") diff --git a/host/chez/run-corpus.ss b/host/chez/run-corpus.ss new file mode 100644 index 0000000..0f6e3d7 --- /dev/null +++ b/host/chez/run-corpus.ss @@ -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 (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)) diff --git a/host/chez/run-sci.ss b/host/chez/run-sci.ss new file mode 100644 index 0000000..0a434b2 --- /dev/null +++ b/host/chez/run-sci.ss @@ -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)) diff --git a/host/chez/run-unit.ss b/host/chez/run-unit.ss new file mode 100644 index 0000000..d57b831 --- /dev/null +++ b/host/chez/run-unit.ss @@ -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) (stringlist (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)) diff --git a/host/chez/seed/README.md b/host/chez/seed/README.md new file mode 100644 index 0000000..65833b8 --- /dev/null +++ b/host/chez/seed/README.md @@ -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. diff --git a/host/chez/seed/image.ss b/host/chez/seed/image.ss new file mode 100644 index 0000000..e5e5033 --- /dev/null +++ b/host/chez/seed/image.ss @@ -0,0 +1,186 @@ +(guard (e (#t #f)) + (def-var! "jolt.ir" "const" (letrec ((const (lambda (v) (let fnrec3450 ((v v)) (let* ((_o$3451 (keyword #f "op")) (_o$3452 (keyword #f "const")) (_o$3453 (keyword #f "val")) (_o$3454 v)) (jolt-hash-map _o$3451 _o$3452 _o$3453 _o$3454)))))) const))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "local" (letrec ((local (lambda (name) (let fnrec3455 ((name name)) (let* ((_o$3456 (keyword #f "op")) (_o$3457 (keyword #f "local")) (_o$3458 (keyword #f "name")) (_o$3459 name)) (jolt-hash-map _o$3456 _o$3457 _o$3458 _o$3459)))))) local))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "var-ref" (letrec ((var-ref (lambda (ns name) (let fnrec3460 ((ns ns) (name name)) (let* ((_o$3461 (keyword #f "op")) (_o$3462 (keyword #f "var")) (_o$3463 (keyword #f "ns")) (_o$3464 ns) (_o$3465 (keyword #f "name")) (_o$3466 name)) (jolt-hash-map _o$3461 _o$3462 _o$3463 _o$3464 _o$3465 _o$3466)))))) var-ref))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "the-var" (letrec ((the-var (lambda (ns name) (let fnrec3467 ((ns ns) (name name)) (let* ((_o$3468 (keyword #f "op")) (_o$3469 (keyword #f "the-var")) (_o$3470 (keyword #f "ns")) (_o$3471 ns) (_o$3472 (keyword #f "name")) (_o$3473 name)) (jolt-hash-map _o$3468 _o$3469 _o$3470 _o$3471 _o$3472 _o$3473)))))) the-var))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "rt" (letrec ((rt (lambda (name) (let fnrec3474 ((name name)) (let* ((_o$3475 (keyword #f "op")) (_o$3476 (keyword #f "rt")) (_o$3477 (keyword #f "name")) (_o$3478 name)) (jolt-hash-map _o$3475 _o$3476 _o$3477 _o$3478)))))) rt))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "host-ref" (letrec ((host-ref (lambda (name) (let fnrec3479 ((name name)) (let* ((_o$3480 (keyword #f "op")) (_o$3481 (keyword #f "host")) (_o$3482 (keyword #f "name")) (_o$3483 name)) (jolt-hash-map _o$3480 _o$3481 _o$3482 _o$3483)))))) host-ref))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "host-static" (letrec ((host-static (lambda (class member) (let fnrec3484 ((class class) (member member)) (let* ((_o$3485 (keyword #f "op")) (_o$3486 (keyword #f "host-static")) (_o$3487 (keyword #f "class")) (_o$3488 class) (_o$3489 (keyword #f "member")) (_o$3490 member)) (jolt-hash-map _o$3485 _o$3486 _o$3487 _o$3488 _o$3489 _o$3490)))))) host-static))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "host-new" (letrec ((host-new (lambda (class args) (let fnrec3491 ((class class) (args args)) (let* ((_o$3492 (keyword #f "op")) (_o$3493 (keyword #f "host-new")) (_o$3494 (keyword #f "class")) (_o$3495 class) (_o$3496 (keyword #f "args")) (_o$3497 args)) (jolt-hash-map _o$3492 _o$3493 _o$3494 _o$3495 _o$3496 _o$3497)))))) host-new))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "if-node" (letrec ((if-node (lambda (test then _else) (let fnrec3498 ((test test) (then then) (_else _else)) (let* ((_o$3499 (keyword #f "op")) (_o$3500 (keyword #f "if")) (_o$3501 (keyword #f "test")) (_o$3502 test) (_o$3503 (keyword #f "then")) (_o$3504 then) (_o$3505 (keyword #f "else")) (_o$3506 _else)) (jolt-hash-map _o$3499 _o$3500 _o$3501 _o$3502 _o$3503 _o$3504 _o$3505 _o$3506)))))) if-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "do-node" (letrec ((do-node (lambda (statements ret) (let fnrec3507 ((statements statements) (ret ret)) (let* ((_o$3508 (keyword #f "op")) (_o$3509 (keyword #f "do")) (_o$3510 (keyword #f "statements")) (_o$3511 statements) (_o$3512 (keyword #f "ret")) (_o$3513 ret)) (jolt-hash-map _o$3508 _o$3509 _o$3510 _o$3511 _o$3512 _o$3513)))))) do-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "invoke" (letrec ((invoke (lambda (f args) (let fnrec3514 ((f f) (args args)) (let* ((_o$3515 (keyword #f "op")) (_o$3516 (keyword #f "invoke")) (_o$3517 (keyword #f "fn")) (_o$3518 f) (_o$3519 (keyword #f "args")) (_o$3520 args)) (jolt-hash-map _o$3515 _o$3516 _o$3517 _o$3518 _o$3519 _o$3520)))))) invoke))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "def-node" (letrec ((def-node (case-lambda ((ns name init) (let fnrec3521 ((ns ns) (name name) (init init)) (let* ((_o$3522 (keyword #f "op")) (_o$3523 (keyword #f "def")) (_o$3524 (keyword #f "ns")) (_o$3525 ns) (_o$3526 (keyword #f "name")) (_o$3527 name) (_o$3528 (keyword #f "init")) (_o$3529 init)) (jolt-hash-map _o$3522 _o$3523 _o$3524 _o$3525 _o$3526 _o$3527 _o$3528 _o$3529)))) ((ns name init meta) (let fnrec3530 ((ns ns) (name name) (init init) (meta meta)) (if (jolt-truthy? meta) (let* ((_o$3531 (keyword #f "op")) (_o$3532 (keyword #f "def")) (_o$3533 (keyword #f "ns")) (_o$3534 ns) (_o$3535 (keyword #f "name")) (_o$3536 name) (_o$3537 (keyword #f "init")) (_o$3538 init) (_o$3539 (keyword #f "meta")) (_o$3540 meta)) (jolt-hash-map _o$3531 _o$3532 _o$3533 _o$3534 _o$3535 _o$3536 _o$3537 _o$3538 _o$3539 _o$3540)) (let* ((_o$3541 (keyword #f "op")) (_o$3542 (keyword #f "def")) (_o$3543 (keyword #f "ns")) (_o$3544 ns) (_o$3545 (keyword #f "name")) (_o$3546 name) (_o$3547 (keyword #f "init")) (_o$3548 init)) (jolt-hash-map _o$3541 _o$3542 _o$3543 _o$3544 _o$3545 _o$3546 _o$3547 _o$3548)))))))) def-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "let-node" (letrec ((let-node (lambda (bindings body) (let fnrec3549 ((bindings bindings) (body body)) (let* ((_o$3550 (keyword #f "op")) (_o$3551 (keyword #f "let")) (_o$3552 (keyword #f "bindings")) (_o$3553 bindings) (_o$3554 (keyword #f "body")) (_o$3555 body)) (jolt-hash-map _o$3550 _o$3551 _o$3552 _o$3553 _o$3554 _o$3555)))))) let-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "fn-node" (letrec ((fn-node (lambda (name arities) (let fnrec3556 ((name name) (arities arities)) (if (jolt-truthy? name) (let* ((_o$3557 (keyword #f "op")) (_o$3558 (keyword #f "fn")) (_o$3559 (keyword #f "name")) (_o$3560 name) (_o$3561 (keyword #f "arities")) (_o$3562 arities)) (jolt-hash-map _o$3557 _o$3558 _o$3559 _o$3560 _o$3561 _o$3562)) (let* ((_o$3563 (keyword #f "op")) (_o$3564 (keyword #f "fn")) (_o$3565 (keyword #f "arities")) (_o$3566 arities)) (jolt-hash-map _o$3563 _o$3564 _o$3565 _o$3566))))))) fn-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "vector-node" (letrec ((vector-node (lambda (items) (let fnrec3567 ((items items)) (let* ((_o$3568 (keyword #f "op")) (_o$3569 (keyword #f "vector")) (_o$3570 (keyword #f "items")) (_o$3571 items)) (jolt-hash-map _o$3568 _o$3569 _o$3570 _o$3571)))))) vector-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "map-node" (letrec ((map-node (lambda (pairs) (let fnrec3572 ((pairs pairs)) (let* ((_o$3573 (keyword #f "op")) (_o$3574 (keyword #f "map")) (_o$3575 (keyword #f "pairs")) (_o$3576 pairs)) (jolt-hash-map _o$3573 _o$3574 _o$3575 _o$3576)))))) map-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "set-node" (letrec ((set-node (lambda (items) (let fnrec3577 ((items items)) (let* ((_o$3578 (keyword #f "op")) (_o$3579 (keyword #f "set")) (_o$3580 (keyword #f "items")) (_o$3581 items)) (jolt-hash-map _o$3578 _o$3579 _o$3580 _o$3581)))))) set-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "quote-node" (letrec ((quote-node (lambda (form) (let fnrec3582 ((form form)) (let* ((_o$3583 (keyword #f "op")) (_o$3584 (keyword #f "quote")) (_o$3585 (keyword #f "form")) (_o$3586 form)) (jolt-hash-map _o$3583 _o$3584 _o$3585 _o$3586)))))) quote-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "throw-node" (letrec ((throw-node (lambda (expr) (let fnrec3587 ((expr expr)) (let* ((_o$3588 (keyword #f "op")) (_o$3589 (keyword #f "throw")) (_o$3590 (keyword #f "expr")) (_o$3591 expr)) (jolt-hash-map _o$3588 _o$3589 _o$3590 _o$3591)))))) throw-node))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "op" (letrec ((op (lambda (node) (let fnrec3592 ((node node)) (jolt-get node (keyword #f "op")))))) op))) +(guard (e (#t #f)) + (def-var! "jolt.ir" "map-ir-children" (letrec ((map-ir-children (lambda (f node) (let fnrec3593 ((f f) (node node)) (let* ((op (jolt-get node (keyword #f "op")))) (if (jolt= op (keyword #f "if")) (let* ((_a$3594 node) (_a$3595 (keyword #f "test")) (_a$3596 (jolt-invoke f (jolt-get node (keyword #f "test")))) (_a$3597 (keyword #f "then")) (_a$3598 (jolt-invoke f (jolt-get node (keyword #f "then")))) (_a$3599 (keyword #f "else")) (_a$3600 (jolt-invoke f (jolt-get node (keyword #f "else"))))) (jolt-assoc _a$3594 _a$3595 _a$3596 _a$3597 _a$3598 _a$3599 _a$3600)) (if (jolt= op (keyword #f "do")) (let* ((_a$3601 node) (_a$3602 (keyword #f "statements")) (_a$3603 (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "statements")))) (_a$3604 (keyword #f "ret")) (_a$3605 (jolt-invoke f (jolt-get node (keyword #f "ret"))))) (jolt-assoc _a$3601 _a$3602 _a$3603 _a$3604 _a$3605)) (if (jolt= op (keyword #f "throw")) (jolt-assoc node (keyword #f "expr") (jolt-invoke f (jolt-get node (keyword #f "expr")))) (if (jolt= op (keyword #f "set-var")) (jolt-assoc node (keyword #f "val") (jolt-invoke f (jolt-get node (keyword #f "val")))) (if (jolt= op (keyword #f "set-field")) (let* ((_a$3606 node) (_a$3607 (keyword #f "obj")) (_a$3608 (jolt-invoke f (jolt-get node (keyword #f "obj")))) (_a$3609 (keyword #f "val")) (_a$3610 (jolt-invoke f (jolt-get node (keyword #f "val"))))) (jolt-assoc _a$3606 _a$3607 _a$3608 _a$3609 _a$3610)) (if (jolt= op (keyword #f "defmacro")) (jolt-assoc node (keyword #f "fn") (jolt-invoke f (jolt-get node (keyword #f "fn")))) (if (jolt= op (keyword #f "invoke")) (let* ((_a$3611 node) (_a$3612 (keyword #f "fn")) (_a$3613 (jolt-invoke f (jolt-get node (keyword #f "fn")))) (_a$3614 (keyword #f "args")) (_a$3615 (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "args"))))) (jolt-assoc _a$3611 _a$3612 _a$3613 _a$3614 _a$3615)) (if (jolt= op (keyword #f "vector")) (jolt-assoc node (keyword #f "items") (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "items")))) (if (jolt= op (keyword #f "set")) (jolt-assoc node (keyword #f "items") (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "items")))) (if (jolt= op (keyword #f "map")) (jolt-assoc node (keyword #f "pairs") (let* ((_a$3619 (var-deref "clojure.core" "mapv")) (_a$3620 (lambda (pr) (let fnrec3616 ((pr pr)) (let* ((_o$3617 (jolt-invoke f (jolt-nth pr 0))) (_o$3618 (jolt-invoke f (jolt-nth pr 1)))) (jolt-vector _o$3617 _o$3618))))) (_a$3621 (jolt-get node (keyword #f "pairs")))) (jolt-invoke _a$3619 _a$3620 _a$3621))) (if (jolt= op (keyword #f "let")) (let* ((_a$3628 node) (_a$3629 (keyword #f "bindings")) (_a$3630 (let* ((_a$3625 (var-deref "clojure.core" "mapv")) (_a$3626 (lambda (b) (let fnrec3622 ((b b)) (let* ((_o$3623 (jolt-nth b 0)) (_o$3624 (jolt-invoke f (jolt-nth b 1)))) (jolt-vector _o$3623 _o$3624))))) (_a$3627 (jolt-get node (keyword #f "bindings")))) (jolt-invoke _a$3625 _a$3626 _a$3627))) (_a$3631 (keyword #f "body")) (_a$3632 (jolt-invoke f (jolt-get node (keyword #f "body"))))) (jolt-assoc _a$3628 _a$3629 _a$3630 _a$3631 _a$3632)) (if (jolt= op (keyword #f "loop")) (let* ((_a$3639 node) (_a$3640 (keyword #f "bindings")) (_a$3641 (let* ((_a$3636 (var-deref "clojure.core" "mapv")) (_a$3637 (lambda (b) (let fnrec3633 ((b b)) (let* ((_o$3634 (jolt-nth b 0)) (_o$3635 (jolt-invoke f (jolt-nth b 1)))) (jolt-vector _o$3634 _o$3635))))) (_a$3638 (jolt-get node (keyword #f "bindings")))) (jolt-invoke _a$3636 _a$3637 _a$3638))) (_a$3642 (keyword #f "body")) (_a$3643 (jolt-invoke f (jolt-get node (keyword #f "body"))))) (jolt-assoc _a$3639 _a$3640 _a$3641 _a$3642 _a$3643)) (if (jolt= op (keyword #f "recur")) (jolt-assoc node (keyword #f "args") (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "args")))) (if (jolt= op (keyword #f "fn")) (jolt-assoc node (keyword #f "arities") (let* ((_a$3645 (var-deref "clojure.core" "mapv")) (_a$3646 (lambda (a) (let fnrec3644 ((a a)) (jolt-assoc a (keyword #f "body") (jolt-invoke f (jolt-get a (keyword #f "body"))))))) (_a$3647 (jolt-get node (keyword #f "arities")))) (jolt-invoke _a$3645 _a$3646 _a$3647))) (if (jolt= op (keyword #f "def")) (jolt-assoc node (keyword #f "init") (jolt-invoke f (jolt-get node (keyword #f "init")))) (if (jolt= op (keyword #f "host-call")) (let* ((_a$3648 node) (_a$3649 (keyword #f "target")) (_a$3650 (jolt-invoke f (jolt-get node (keyword #f "target")))) (_a$3651 (keyword #f "args")) (_a$3652 (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "args"))))) (jolt-assoc _a$3648 _a$3649 _a$3650 _a$3651 _a$3652)) (if (jolt= op (keyword #f "host-new")) (jolt-assoc node (keyword #f "args") (jolt-invoke (var-deref "clojure.core" "mapv") f (jolt-get node (keyword #f "args")))) (if (jolt= op (keyword #f "try")) (let* ((n (jolt-assoc node (keyword #f "body") (jolt-invoke f (jolt-get node (keyword #f "body"))))) (n (if (jolt-truthy? (jolt-get node (keyword #f "catch-body"))) (jolt-assoc n (keyword #f "catch-body") (jolt-invoke f (jolt-get node (keyword #f "catch-body")))) n)) (n (if (jolt-truthy? (jolt-get node (keyword #f "finally"))) (jolt-assoc n (keyword #f "finally") (jolt-invoke f (jolt-get node (keyword #f "finally")))) n))) n) (if (jolt-truthy? (keyword #f "else")) node jolt-nil)))))))))))))))))))))))) map-ir-children))) +(guard (e (#t #f)) + (declare-var! "jolt.analyzer" "analyze")) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.analyzer" "handled" (let* ((_o$3653 "quote") (_o$3654 "if") (_o$3655 "do") (_o$3656 "def") (_o$3657 "fn*") (_o$3658 "let*") (_o$3659 "loop*") (_o$3660 "recur") (_o$3661 "throw") (_o$3662 "try") (_o$3663 "syntax-quote") (_o$3664 "var") (_o$3665 "letfn") (_o$3666 "set!") (_o$3667 "defmacro")) (jolt-hash-set _o$3653 _o$3654 _o$3655 _o$3656 _o$3657 _o$3658 _o$3659 _o$3660 _o$3661 _o$3662 _o$3663 _o$3664 _o$3665 _o$3666 _o$3667)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "uncompilable" (letrec ((uncompilable (lambda (why) (let fnrec3668 ((why why)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "jolt/uncompilable: " why)))))) uncompilable))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.analyzer" "gensym-counter" (jolt-invoke (var-deref "clojure.core" "atom") 0) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "gen-name" (letrec ((gen-name (lambda (prefix) (let fnrec3669 ((prefix prefix)) (let* ((n (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.analyzer" "gensym-counter")))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.analyzer" "gensym-counter") jolt-inc) (jolt-invoke (var-deref "clojure.core" "str") "_r$" prefix n))))))) gen-name))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "empty-env" (letrec ((empty-env (lambda () (let fnrec3670 () (let* ((_o$3671 (keyword #f "locals")) (_o$3672 (jolt-hash-set)) (_o$3673 (keyword #f "hints")) (_o$3674 (jolt-hash-map))) (jolt-hash-map _o$3671 _o$3672 _o$3673 _o$3674)))))) empty-env))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "local?" (letrec ((local? (lambda (env nm) (let fnrec3675 ((env env) (nm nm)) (jolt-contains? (jolt-get env (keyword #f "locals")) nm))))) local?))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "add-locals" (letrec ((add-locals (lambda (env names) (let fnrec3676 ((env env) (names names)) (jolt-invoke (var-deref "clojure.core" "update") env (keyword #f "locals") (lambda (p__47_) (let fnrec3677 ((p__47_ p__47_)) (jolt-reduce jolt-conj p__47_ names)))))))) add-locals))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "with-recur" (letrec ((with-recur (lambda (env name) (let fnrec3678 ((env env) (name name)) (jolt-assoc env (keyword #f "recur") name))))) with-recur))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "hint-of" (letrec ((hint-of (lambda (ctx sym) (let fnrec3679 ((ctx ctx) (sym sym)) (let* ((m (jolt-invoke (var-deref "jolt.host" "form-sym-meta") sym))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") m)) jolt-nil (if (jolt-truthy? (jolt-get m (keyword #f "struct"))) (keyword #f "struct") (if (jolt-truthy? (keyword #f "else")) (let* ((t (jolt-get m (keyword #f "tag")))) (if (jolt-truthy? (let* ((and__13__auto t)) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.host" "record-type?") ctx t) and__13__auto))) (keyword #f "struct") jolt-nil)) jolt-nil)))))))) hint-of))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "add-hint" (letrec ((add-hint (lambda (env nm h) (let fnrec3680 ((env env) (nm nm) (h h)) (if (jolt-truthy? h) (jolt-assoc env (keyword #f "hints") (jolt-assoc (jolt-get env (keyword #f "hints")) nm h)) env))))) add-hint))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "phint-of" (letrec ((phint-of (lambda (ctx sym) (let fnrec3681 ((ctx ctx) (sym sym)) (let* ((m (jolt-invoke (var-deref "jolt.host" "form-sym-meta") sym))) (if (jolt-truthy? m) (let* ((t (jolt-get m (keyword #f "tag")))) (if (jolt-truthy? t) (jolt-invoke (var-deref "jolt.host" "record-ctor-key") ctx t) jolt-nil)) jolt-nil)))))) phint-of))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-seq" (letrec ((analyze-seq (lambda (ctx forms env) (let fnrec3682 ((ctx ctx) (forms forms) (env env)) (let* ((v (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (p__48_) (let fnrec3683 ((p__48_ p__48_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__48_ env))) forms)) (n (jolt-count v))) (if (jolt-zero? n) (jolt-invoke (var-deref "jolt.ir" "const") jolt-nil) (if (jolt= 1 n) (jolt-first v) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$3684 (var-deref "jolt.ir" "do-node")) (_a$3685 (jolt-invoke (var-deref "clojure.core" "subvec") v 0 (jolt-dec n))) (_a$3686 (jolt-peek v))) (jolt-invoke _a$3684 _a$3685 _a$3686)) jolt-nil)))))))) analyze-seq))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-bindings" (letrec ((analyze-bindings (lambda (ctx bvec env) (let fnrec3687 ((ctx ctx) (bvec bvec) (env env)) (let* ((i 0) (env env) (pairs (jolt-vector))) (let loop3688 ((i i) (env env) (pairs pairs)) (if (< i (jolt-count bvec)) (let* ((bsym (jolt-nth bvec i))) (begin (if (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") bsym)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "destructuring binding") jolt-nil) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") bsym)) (init (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth bvec (jolt-inc i)) env))) (let* ((_a$3695 (+ i 2)) (_a$3696 (let* ((_a$3689 (var-deref "jolt.analyzer" "add-hint")) (_a$3690 (jolt-invoke (var-deref "jolt.analyzer" "add-locals") env (jolt-vector nm))) (_a$3691 nm) (_a$3692 (jolt-invoke (var-deref "jolt.analyzer" "hint-of") ctx bsym))) (jolt-invoke _a$3689 _a$3690 _a$3691 _a$3692))) (_a$3697 (jolt-conj pairs (let* ((_o$3693 nm) (_o$3694 init)) (jolt-vector _o$3693 _o$3694))))) (loop3688 _a$3695 _a$3696 _a$3697))))) (let* ((_o$3698 pairs) (_o$3699 env)) (jolt-vector _o$3698 _o$3699))))))))) analyze-bindings))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "parse-params" (letrec ((parse-params (lambda (ctx pvec) (let fnrec3700 ((ctx ctx) (pvec pvec)) (let* ((i 0) (fixed (jolt-vector)) (rest-name jolt-nil) (hints (jolt-vector)) (phints (jolt-vector))) (let loop3701 ((i i) (fixed fixed) (rest-name rest-name) (hints hints) (phints phints)) (if (< i (jolt-count pvec)) (let* ((p (jolt-nth pvec i))) (begin (if (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") p)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "destructuring fn param") jolt-nil) (if (jolt= "&" (jolt-invoke (var-deref "jolt.host" "form-sym-name") p)) (let* ((r (jolt-nth pvec (jolt-inc i)))) (begin (if (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") r)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "destructuring fn rest") jolt-nil) (let* ((_a$3702 (+ i 2)) (_a$3703 fixed) (_a$3704 (jolt-invoke (var-deref "jolt.host" "form-sym-name") r)) (_a$3705 hints) (_a$3706 phints)) (loop3701 _a$3702 _a$3703 _a$3704 _a$3705 _a$3706)))) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") p)) (h (jolt-invoke (var-deref "jolt.analyzer" "hint-of") ctx p)) (ph (jolt-invoke (var-deref "jolt.analyzer" "phint-of") ctx p))) (let* ((_a$3711 (jolt-inc i)) (_a$3712 (jolt-conj fixed nm)) (_a$3713 rest-name) (_a$3714 (if (jolt-truthy? h) (jolt-conj hints (let* ((_o$3707 nm) (_o$3708 h)) (jolt-vector _o$3707 _o$3708))) hints)) (_a$3715 (if (jolt-truthy? ph) (jolt-conj phints (let* ((_o$3709 nm) (_o$3710 ph)) (jolt-vector _o$3709 _o$3710))) phints))) (loop3701 _a$3711 _a$3712 _a$3713 _a$3714 _a$3715)))))) (let* ((_o$3716 (keyword #f "fixed")) (_o$3717 fixed) (_o$3718 (keyword #f "rest")) (_o$3719 rest-name) (_o$3720 (keyword #f "hints")) (_o$3721 hints) (_o$3722 (keyword #f "phints")) (_o$3723 phints)) (jolt-hash-map _o$3716 _o$3717 _o$3718 _o$3719 _o$3720 _o$3721 _o$3722 _o$3723))))))))) parse-params))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "uniquify-params" (letrec ((uniquify-params (lambda (names) (let fnrec3724 ((names names)) (let* ((n (jolt-count names))) (let* ((i 0) (out (jolt-vector))) (let loop3725 ((i i) (out out)) (if (< i n) (let* ((nm (jolt-nth names i)) (dup? (let* ((j (jolt-inc i))) (let loop3726 ((j j)) (if (>= j n) #f (if (jolt= nm (jolt-nth names j)) #t (if (jolt-truthy? (keyword #f "else")) (loop3726 (jolt-inc j)) jolt-nil))))))) (let* ((_a$3727 (jolt-inc i)) (_a$3728 (jolt-conj out (if (jolt-truthy? dup?) (jolt-invoke (var-deref "jolt.analyzer" "gen-name") (jolt-invoke (var-deref "clojure.core" "str") nm "_")) nm)))) (loop3725 _a$3727 _a$3728))) out)))))))) uniquify-params))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-arity" (letrec ((analyze-arity (lambda (ctx pvec body env fn-name) (let fnrec3729 ((ctx ctx) (pvec pvec) (body body) (env env) (fn-name fn-name)) (let* ((pp (jolt-invoke (var-deref "jolt.analyzer" "parse-params") ctx (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-vec-items") pvec)))) (fixed (jolt-invoke (var-deref "jolt.analyzer" "uniquify-params") (jolt-get pp (keyword #f "fixed")))) (rst (jolt-get pp (keyword #f "rest"))) (rname (jolt-invoke (var-deref "jolt.analyzer" "gen-name") (let* ((_a$3730 (var-deref "clojure.core" "str")) (_a$3731 (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx)) (_a$3732 "/") (_a$3733 (let* ((or__14__auto fn-name)) (if (jolt-truthy? or__14__auto) or__14__auto "fn"))) (_a$3734 "--")) (jolt-invoke _a$3730 _a$3731 _a$3732 _a$3733 _a$3734)))) (names (let* ((G__40 (jolt-invoke (var-deref "clojure.core" "vec") fixed))) (let* ((G__41 (if (jolt-truthy? rst) (jolt-conj G__40 rst) G__40))) (let* ((G__42 (if (jolt-truthy? fn-name) (jolt-conj G__41 fn-name) G__41))) G__42)))) (env0 (jolt-invoke (var-deref "jolt.analyzer" "with-recur") (jolt-invoke (var-deref "jolt.analyzer" "add-locals") env names) rname)) (env* (let* ((_a$3740 (lambda (e pr) (let fnrec3735 ((e e) (pr pr)) (let* ((_a$3736 (var-deref "jolt.analyzer" "add-hint")) (_a$3737 e) (_a$3738 (jolt-nth pr 0)) (_a$3739 (jolt-nth pr 1))) (jolt-invoke _a$3736 _a$3737 _a$3738 _a$3739))))) (_a$3741 env0) (_a$3742 (jolt-get pp (keyword #f "hints")))) (jolt-reduce _a$3740 _a$3741 _a$3742))) (arity (let* ((_o$3743 (keyword #f "params")) (_o$3744 fixed) (_o$3745 (keyword #f "recur-name")) (_o$3746 rname) (_o$3747 (keyword #f "body")) (_o$3748 (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx body env*))) (jolt-hash-map _o$3743 _o$3744 _o$3745 _o$3746 _o$3747 _o$3748))) (arity (if (jolt-truthy? (jolt-seq (jolt-get pp (keyword #f "phints")))) (jolt-assoc arity (keyword #f "phints") (jolt-get pp (keyword #f "phints"))) arity))) (if (jolt-truthy? rst) (jolt-assoc arity (keyword #f "rest") rst) arity)))))) analyze-arity))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "strip-arglist-meta" (letrec ((strip-arglist-meta (lambda (form) (let fnrec3749 ((form form)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") form)) (let* ((es (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") form)))) (if (jolt-truthy? (let* ((and__13__auto (jolt= 3 (jolt-count es)))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-first es)))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt= "with-meta" (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-first es))))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.host" "form-vec?") (jolt-nth es 1)) and__13__auto)) and__13__auto)) and__13__auto))) (jolt-nth es 1) form)) form))))) strip-arglist-meta))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-fn" (letrec ((analyze-fn (lambda (ctx items env) (let fnrec3750 ((ctx ctx) (items items) (env env)) (let* ((named (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-nth items 1))) (fn-name (if (jolt-truthy? named) (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-nth items 1)) jolt-nil)) (rest-items (if (jolt-truthy? named) (jolt-drop 2 items) (jolt-drop 1 items))) (first* (jolt-invoke (var-deref "jolt.analyzer" "strip-arglist-meta") (jolt-first rest-items)))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-vec?") first*)) (jolt-invoke (var-deref "jolt.ir" "fn-node") fn-name (jolt-vector (jolt-invoke (var-deref "jolt.analyzer" "analyze-arity") ctx first* (jolt-rest rest-items) env fn-name))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") first*)) (jolt-invoke (var-deref "jolt.ir" "fn-node") fn-name (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (clause) (let fnrec3751 ((clause clause)) (let* ((cl (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") clause)))) (let* ((_a$3752 (var-deref "jolt.analyzer" "analyze-arity")) (_a$3753 ctx) (_a$3754 (jolt-invoke (var-deref "jolt.analyzer" "strip-arglist-meta") (jolt-first cl))) (_a$3755 (jolt-rest cl)) (_a$3756 env) (_a$3757 fn-name)) (jolt-invoke _a$3752 _a$3753 _a$3754 _a$3755 _a$3756 _a$3757))))) rest-items)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "fn: bad params") jolt-nil)))))))) analyze-fn))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-try" (letrec ((analyze-try (lambda (ctx items env) (let fnrec3758 ((ctx ctx) (items items) (env env)) (let* ((clauses (jolt-rest items)) (body (jolt-invoke (var-deref "clojure.core" "atom") (jolt-vector))) (catch-sym (jolt-invoke (var-deref "clojure.core" "atom") jolt-nil)) (catch-body (jolt-invoke (var-deref "clojure.core" "atom") jolt-nil)) (finally-body (jolt-invoke (var-deref "clojure.core" "atom") jolt-nil))) (begin (begin (jolt-count (jolt-map (lambda (c) (let fnrec3759 ((c c)) (begin (let* ((head (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") c)) (jolt-first (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") c))) jolt-nil)) (hname (if (jolt-truthy? (let* ((and__13__auto head)) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.host" "form-sym?") head) and__13__auto))) (jolt-invoke (var-deref "jolt.host" "form-sym-name") head) jolt-nil))) (if (jolt= hname "catch") (let* ((cl (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") c)))) (begin (if (jolt-truthy? (let* ((or__14__auto (< (jolt-count cl) 3))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-nth cl 2)))))) (jolt-throw "Unable to parse catch clause; expected (catch class binding body*)") jolt-nil) (jolt-invoke (var-deref "clojure.core" "reset!") catch-sym (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-nth cl 2))) (jolt-invoke (var-deref "clojure.core" "reset!") catch-body (jolt-drop 3 cl)))) (if (jolt= hname "finally") (jolt-invoke (var-deref "clojure.core" "reset!") finally-body (jolt-rest (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") c)))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "swap!") body jolt-conj c) jolt-nil)))) jolt-nil))) clauses)) jolt-nil) (let* ((n (let* ((_o$3760 (keyword #f "op")) (_o$3761 (keyword #f "try")) (_o$3762 (keyword #f "body")) (_o$3763 (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-invoke (var-deref "clojure.core" "deref") body) env))) (jolt-hash-map _o$3760 _o$3761 _o$3762 _o$3763))) (n (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "deref") catch-body)) (let* ((_a$3768 n) (_a$3769 (keyword #f "catch-sym")) (_a$3770 (jolt-invoke (var-deref "clojure.core" "deref") catch-sym)) (_a$3771 (keyword #f "catch-body")) (_a$3772 (let* ((_a$3764 (var-deref "jolt.analyzer" "analyze-seq")) (_a$3765 ctx) (_a$3766 (jolt-invoke (var-deref "clojure.core" "deref") catch-body)) (_a$3767 (jolt-invoke (var-deref "jolt.analyzer" "add-locals") env (jolt-vector (jolt-invoke (var-deref "clojure.core" "deref") catch-sym))))) (jolt-invoke _a$3764 _a$3765 _a$3766 _a$3767)))) (jolt-assoc _a$3768 _a$3769 _a$3770 _a$3771 _a$3772)) n)) (n (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "deref") finally-body)) (jolt-assoc n (keyword #f "finally") (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-invoke (var-deref "clojure.core" "deref") finally-body) env)) n))) n))))))) analyze-try))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-letfn" (letrec ((analyze-letfn (lambda (ctx items env) (let fnrec3773 ((ctx ctx) (items items) (env env)) (let* ((specs (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-vec-items") (jolt-nth items 1)))) (names (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (p__49_) (let fnrec3774 ((p__49_ p__49_)) (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-first (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") p__49_)))))) specs)) (env* (jolt-invoke (var-deref "jolt.analyzer" "add-locals") env names)) (binds (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (spec) (let fnrec3775 ((spec spec)) (let* ((cl (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") spec)))) (let* ((_o$3776 (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-first cl))) (_o$3777 (jolt-invoke (var-deref "jolt.analyzer" "analyze-fn") ctx (jolt-invoke (var-deref "clojure.core" "vec") (jolt-cons (jolt-first cl) cl)) env*))) (jolt-vector _o$3776 _o$3777))))) specs))) (let* ((_o$3778 (keyword #f "op")) (_o$3779 (keyword #f "let")) (_o$3780 (keyword #f "letrec")) (_o$3781 #t) (_o$3782 (keyword #f "bindings")) (_o$3783 binds) (_o$3784 (keyword #f "body")) (_o$3785 (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-drop 2 items) env*))) (jolt-hash-map _o$3778 _o$3779 _o$3780 _o$3781 _o$3782 _o$3783 _o$3784 _o$3785))))))) analyze-letfn))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-special" (letrec ((analyze-special (lambda (ctx op items env) (let fnrec3786 ((ctx ctx) (op op) (items items) (env env)) (let* ((G__43 op)) (if (jolt= G__43 "quote") (jolt-invoke (var-deref "jolt.ir" "quote-node") (jolt-invoke (var-deref "clojure.core" "second") items)) (if (jolt= G__43 "if") (begin (if (jolt-truthy? (let* ((or__14__auto (< (jolt-count items) 3))) (if (jolt-truthy? or__14__auto) or__14__auto (> (jolt-count items) 4)))) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Wrong number of args (" (jolt-dec (jolt-count items)) ") passed to: if")) jolt-nil) (let* ((_a$3787 (var-deref "jolt.ir" "if-node")) (_a$3788 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (_a$3789 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 2) env)) (_a$3790 (if (> (jolt-count items) 3) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 3) env) (jolt-invoke (var-deref "jolt.ir" "const") jolt-nil)))) (jolt-invoke _a$3787 _a$3788 _a$3789 _a$3790))) (if (jolt= G__43 "do") (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-rest items) env) (if (jolt= G__43 "throw") (jolt-invoke (var-deref "jolt.ir" "throw-node") (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (if (jolt= G__43 "def") (let* ((name-sym (jolt-nth items 1))) (begin (if (jolt-not (jolt-invoke (var-deref "jolt.host" "form-sym?") name-sym)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "def name with map metadata") jolt-nil) (if (< (jolt-count items) 3) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") name-sym)) (cur (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx))) (begin (jolt-invoke (var-deref "jolt.host" "host-intern!") ctx cur nm) (let* ((_o$3791 (keyword #f "op")) (_o$3792 (keyword #f "def")) (_o$3793 (keyword #f "ns")) (_o$3794 cur) (_o$3795 (keyword #f "name")) (_o$3796 nm) (_o$3797 (keyword #f "no-init")) (_o$3798 #t)) (jolt-hash-map _o$3791 _o$3792 _o$3793 _o$3794 _o$3795 _o$3796 _o$3797 _o$3798)))) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") name-sym)) (cur (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx)) (has-doc (let* ((and__13__auto (> (jolt-count items) 3))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "string?") (jolt-nth items 2)) and__13__auto))) (val-form (jolt-nth items (if (jolt-truthy? has-doc) 3 2))) (base0 (let* ((or__14__auto (jolt-invoke (var-deref "jolt.host" "form-sym-meta") name-sym))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-hash-map)))) (tag (jolt-get base0 (keyword #f "tag"))) (tag-name (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") tag)) (jolt-invoke (var-deref "jolt.host" "form-sym-name") tag) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") tag)) tag (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))) (base-meta (if (jolt-truthy? tag-name) (let* ((c (jolt-invoke (var-deref "jolt.host" "resolve-class-hint") tag-name))) (if (jolt-truthy? c) (jolt-assoc base0 (keyword #f "tag") c) base0)) base0)) (node-meta (if (jolt-truthy? has-doc) (jolt-assoc base-meta (keyword #f "doc") (jolt-nth items 2)) base-meta))) (begin (jolt-invoke (var-deref "jolt.host" "host-intern!") ctx cur nm) (jolt-invoke (var-deref "jolt.ir" "def-node") cur nm (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx val-form env) node-meta)))))) (if (jolt= G__43 "let*") (let* ((bvec (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-vec-items") (jolt-nth items 1)))) (r (jolt-invoke (var-deref "jolt.analyzer" "analyze-bindings") ctx bvec env))) (let* ((_a$3803 (var-deref "jolt.ir" "let-node")) (_a$3804 (jolt-first r)) (_a$3805 (let* ((_a$3799 (var-deref "jolt.analyzer" "analyze-seq")) (_a$3800 ctx) (_a$3801 (jolt-drop 2 items)) (_a$3802 (jolt-invoke (var-deref "clojure.core" "second") r))) (jolt-invoke _a$3799 _a$3800 _a$3801 _a$3802)))) (jolt-invoke _a$3803 _a$3804 _a$3805))) (if (jolt= G__43 "loop*") (let* ((bvec (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-vec-items") (jolt-nth items 1)))) (rname (jolt-invoke (var-deref "jolt.analyzer" "gen-name") "loop")) (r (jolt-invoke (var-deref "jolt.analyzer" "analyze-bindings") ctx bvec env)) (env** (jolt-invoke (var-deref "jolt.analyzer" "with-recur") (jolt-invoke (var-deref "clojure.core" "second") r) rname))) (let* ((_o$3806 (keyword #f "op")) (_o$3807 (keyword #f "loop")) (_o$3808 (keyword #f "recur-name")) (_o$3809 rname) (_o$3810 (keyword #f "bindings")) (_o$3811 (jolt-first r)) (_o$3812 (keyword #f "body")) (_o$3813 (jolt-invoke (var-deref "jolt.analyzer" "analyze-seq") ctx (jolt-drop 2 items) env**))) (jolt-hash-map _o$3806 _o$3807 _o$3808 _o$3809 _o$3810 _o$3811 _o$3812 _o$3813))) (if (jolt= G__43 "recur") (let* ((rt (jolt-get env (keyword #f "recur")))) (begin (if (jolt-not rt) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "recur outside loop/fn") jolt-nil) (let* ((_o$3818 (keyword #f "op")) (_o$3819 (keyword #f "recur")) (_o$3820 (keyword #f "recur-name")) (_o$3821 rt) (_o$3822 (keyword #f "args")) (_o$3823 (let* ((_a$3815 (var-deref "clojure.core" "mapv")) (_a$3816 (lambda (p__50_) (let fnrec3814 ((p__50_ p__50_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__50_ env)))) (_a$3817 (jolt-rest items))) (jolt-invoke _a$3815 _a$3816 _a$3817)))) (jolt-hash-map _o$3818 _o$3819 _o$3820 _o$3821 _o$3822 _o$3823)))) (if (jolt= G__43 "try") (jolt-invoke (var-deref "jolt.analyzer" "analyze-try") ctx items env) (if (jolt= G__43 "letfn") (jolt-invoke (var-deref "jolt.analyzer" "analyze-letfn") ctx items env) (if (jolt= G__43 "fn*") (jolt-invoke (var-deref "jolt.analyzer" "analyze-fn") ctx items env) (if (jolt= G__43 "syntax-quote") (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-invoke (var-deref "jolt.host" "form-syntax-quote-lower") ctx (jolt-invoke (var-deref "clojure.core" "second") items)) env) (if (jolt= G__43 "var") (let* ((sym (jolt-invoke (var-deref "clojure.core" "second") items)) (r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx sym))) (if (jolt= (keyword #f "var") (jolt-get r (keyword #f "kind"))) (let* ((_a$3824 (var-deref "jolt.ir" "the-var")) (_a$3825 (jolt-get r (keyword #f "ns"))) (_a$3826 (jolt-get r (keyword #f "name")))) (jolt-invoke _a$3824 _a$3825 _a$3826)) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") (jolt-invoke (var-deref "clojure.core" "str") "var of non-var " (jolt-invoke (var-deref "jolt.host" "form-sym-name") sym))))) (if (jolt= G__43 "defmacro") (let* ((name-sym (jolt-nth items 1)) (nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") name-sym)) (cur (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx)) (after (jolt-drop 2 items)) (after (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") (jolt-first after))) (jolt-rest after) after)) (after (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-map?") (jolt-first after))) (jolt-rest after) after)) (fn-form (jolt-cons (jolt-invoke (var-deref "clojure.core" "symbol") "fn") after))) (begin (jolt-invoke (var-deref "jolt.host" "host-intern!") ctx cur nm) (let* ((_o$3827 (keyword #f "op")) (_o$3828 (keyword #f "defmacro")) (_o$3829 (keyword #f "ns")) (_o$3830 cur) (_o$3831 (keyword #f "name")) (_o$3832 nm) (_o$3833 (keyword #f "fn")) (_o$3834 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx fn-form env))) (jolt-hash-map _o$3827 _o$3828 _o$3829 _o$3830 _o$3831 _o$3832 _o$3833 _o$3834)))) (if (jolt= G__43 "set!") (let* ((target (jolt-nth items 1)) (val-node (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 2) env)) (ti (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") target)) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") target)) jolt-nil)) (thead (if (jolt-truthy? (let* ((and__13__auto ti)) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-pos? (jolt-count ti)))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-first ti)) and__13__auto)) and__13__auto))) (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-first ti)) jolt-nil))) (if (jolt-truthy? (let* ((and__13__auto thead)) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.analyzer" "field-head?") thead) and__13__auto))) (let* ((_o$3835 (keyword #f "op")) (_o$3836 (keyword #f "set-field")) (_o$3837 (keyword #f "obj")) (_o$3838 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth ti 1) env)) (_o$3839 (keyword #f "field")) (_o$3840 (jolt-invoke (var-deref "clojure.core" "subs") thead 2)) (_o$3841 (keyword #f "val")) (_o$3842 val-node)) (jolt-hash-map _o$3835 _o$3836 _o$3837 _o$3838 _o$3839 _o$3840 _o$3841 _o$3842)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") target)) (begin (if (jolt-truthy? (jolt-invoke (var-deref "jolt.analyzer" "local?") env (jolt-invoke (var-deref "jolt.host" "form-sym-name") target))) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "set! of a local") jolt-nil) (let* ((r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx target))) (begin (if (jolt-not (jolt= (keyword #f "var") (jolt-get r (keyword #f "kind")))) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "set! of a non-var") jolt-nil) (let* ((_o$3846 (keyword #f "op")) (_o$3847 (keyword #f "set-var")) (_o$3848 (keyword #f "the-var")) (_o$3849 (let* ((_a$3843 (var-deref "jolt.ir" "the-var")) (_a$3844 (jolt-get r (keyword #f "ns"))) (_a$3845 (jolt-get r (keyword #f "name")))) (jolt-invoke _a$3843 _a$3844 _a$3845))) (_o$3850 (keyword #f "val")) (_o$3851 val-node)) (jolt-hash-map _o$3846 _o$3847 _o$3848 _o$3849 _o$3850 _o$3851))))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "set! of an unsupported target") jolt-nil)))) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") (jolt-invoke (var-deref "clojure.core" "str") "special form " op)))))))))))))))))))))) analyze-special))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "method-head?" (letrec ((method-head? (lambda (nm) (let fnrec3852 ((nm nm)) (let* ((and__13__auto (> (jolt-count nm) 1))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt= "." (jolt-invoke (var-deref "clojure.core" "subs") nm 0 1)))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-not (jolt= "-" (jolt-invoke (var-deref "clojure.core" "subs") nm 1 2))))) (if (jolt-truthy? and__13__auto) (jolt-not (jolt= "." (jolt-invoke (var-deref "clojure.core" "subs") nm 1 2))) and__13__auto)) and__13__auto)) and__13__auto)))))) method-head?))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-host-call" (letrec ((analyze-host-call (lambda (ctx hname items env) (let fnrec3853 ((ctx ctx) (hname hname) (items items) (env env)) (begin (if (< (jolt-count items) 2) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Malformed member expression, expecting (.method target ...): " hname)) jolt-nil) (let* ((_o$3858 (keyword #f "op")) (_o$3859 (keyword #f "host-call")) (_o$3860 (keyword #f "method")) (_o$3861 (jolt-invoke (var-deref "clojure.core" "subs") hname 1)) (_o$3862 (keyword #f "target")) (_o$3863 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (_o$3864 (keyword #f "args")) (_o$3865 (let* ((_a$3855 (var-deref "clojure.core" "mapv")) (_a$3856 (lambda (p__51_) (let fnrec3854 ((p__51_ p__51_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__51_ env)))) (_a$3857 (jolt-drop 2 items))) (jolt-invoke _a$3855 _a$3856 _a$3857)))) (jolt-hash-map _o$3858 _o$3859 _o$3860 _o$3861 _o$3862 _o$3863 _o$3864 _o$3865))))))) analyze-host-call))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "ctor-head?" (letrec ((ctor-head? (lambda (nm) (let fnrec3866 ((nm nm)) (let* ((and__13__auto (> (jolt-count nm) 1))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt= "." (let* ((_a$3867 (var-deref "clojure.core" "subs")) (_a$3868 nm) (_a$3869 (jolt-dec (jolt-count nm))) (_a$3870 (jolt-count nm))) (jolt-invoke _a$3867 _a$3868 _a$3869 _a$3870))))) (if (jolt-truthy? and__13__auto) (jolt-not (jolt= "." (jolt-invoke (var-deref "clojure.core" "subs") nm 0 1))) and__13__auto)) and__13__auto)))))) ctor-head?))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-ctor" (letrec ((analyze-ctor (lambda (ctx class args env) (let fnrec3871 ((ctx ctx) (class class) (args args) (env env)) (jolt-invoke (var-deref "jolt.ir" "host-new") class (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (p__52_) (let fnrec3872 ((p__52_ p__52_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__52_ env))) args)))))) analyze-ctor))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-dot" (letrec ((analyze-dot (lambda (ctx items env) (let fnrec3873 ((ctx ctx) (items items) (env env)) (begin (if (< (jolt-count items) 3) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Malformed (. target member ...) form")) jolt-nil) (let* ((member (jolt-nth items 2))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") member)) (let* ((_o$3878 (keyword #f "op")) (_o$3879 (keyword #f "host-call")) (_o$3880 (keyword #f "method")) (_o$3881 (jolt-invoke (var-deref "jolt.host" "form-sym-name") member)) (_o$3882 (keyword #f "target")) (_o$3883 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (_o$3884 (keyword #f "args")) (_o$3885 (let* ((_a$3875 (var-deref "clojure.core" "mapv")) (_a$3876 (lambda (p__53_) (let fnrec3874 ((p__53_ p__53_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__53_ env)))) (_a$3877 (jolt-drop 3 items))) (jolt-invoke _a$3875 _a$3876 _a$3877)))) (jolt-hash-map _o$3878 _o$3879 _o$3880 _o$3881 _o$3882 _o$3883 _o$3884 _o$3885)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-keyword?") member)) (let* ((_a$3886 (var-deref "jolt.ir" "invoke")) (_a$3887 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx member env)) (_a$3888 (jolt-vector (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)))) (jolt-invoke _a$3886 _a$3887 _a$3888)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "special form . (non-symbol member)") jolt-nil))))))))) analyze-dot))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "field-head?" (letrec ((field-head? (lambda (nm) (let fnrec3889 ((nm nm)) (let* ((and__13__auto (> (jolt-count nm) 2))) (if (jolt-truthy? and__13__auto) (jolt= ".-" (jolt-invoke (var-deref "clojure.core" "subs") nm 0 2)) and__13__auto)))))) field-head?))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-field" (letrec ((analyze-field (lambda (ctx hname items env) (let fnrec3890 ((ctx ctx) (hname hname) (items items) (env env)) (begin (if (< (jolt-count items) 2) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Malformed (.-field target) form")) jolt-nil) (let* ((_o$3891 (keyword #f "op")) (_o$3892 (keyword #f "host-call")) (_o$3893 (keyword #f "method")) (_o$3894 (jolt-invoke (var-deref "clojure.core" "subs") hname 1)) (_o$3895 (keyword #f "target")) (_o$3896 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-nth items 1) env)) (_o$3897 (keyword #f "args")) (_o$3898 (jolt-vector))) (jolt-hash-map _o$3891 _o$3892 _o$3893 _o$3894 _o$3895 _o$3896 _o$3897 _o$3898))))))) analyze-field))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-symbol" (letrec ((analyze-symbol (lambda (ctx form env) (let fnrec3899 ((ctx ctx) (form form) (env env)) (let* ((nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") form)) (ns (jolt-invoke (var-deref "jolt.host" "form-sym-ns") form))) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "nil?") ns))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.analyzer" "local?") env nm) and__13__auto))) (let* ((h (jolt-get (jolt-get env (keyword #f "hints")) nm))) (if (jolt-truthy? h) (jolt-assoc (jolt-invoke (var-deref "jolt.ir" "local") nm) (keyword #f "hint") h) (jolt-invoke (var-deref "jolt.ir" "local") nm))) (if (jolt-truthy? ns) (let* ((r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx form))) (if (jolt= (keyword #f "var") (jolt-get r (keyword #f "kind"))) (let* ((_a$3900 (var-deref "jolt.ir" "var-ref")) (_a$3901 (jolt-get r (keyword #f "ns"))) (_a$3902 (jolt-get r (keyword #f "name")))) (jolt-invoke _a$3900 _a$3901 _a$3902)) (jolt-invoke (var-deref "jolt.ir" "host-static") ns nm))) (if (jolt-truthy? (keyword #f "else")) (let* ((r (jolt-invoke (var-deref "jolt.host" "resolve-global") ctx form))) (let* ((G__44 (jolt-get r (keyword #f "kind")))) (if (jolt= G__44 (keyword #f "var")) (let* ((_a$3903 (var-deref "jolt.ir" "var-ref")) (_a$3904 (jolt-get r (keyword #f "ns"))) (_a$3905 (jolt-get r (keyword #f "name")))) (jolt-invoke _a$3903 _a$3904 _a$3905)) (if (jolt= G__44 (keyword #f "host")) (jolt-invoke (var-deref "jolt.ir" "host-ref") (jolt-get r (keyword #f "name"))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "late-bind?") ctx)) (jolt-invoke (var-deref "jolt.ir" "var-ref") (jolt-invoke (var-deref "jolt.host" "compile-ns") ctx) nm) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") (jolt-invoke (var-deref "clojure.core" "str") "Unable to resolve symbol: " nm " in this context"))))))) jolt-nil)))))))) analyze-symbol))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze-list" (letrec ((analyze-list (lambda (ctx form env) (let fnrec3906 ((ctx ctx) (form form) (env env)) (let* ((items (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "jolt.host" "form-elements") form)))) (if (jolt-zero? (jolt-count items)) (jolt-invoke (var-deref "jolt.ir" "quote-node") form) (let* ((head (jolt-first items)) (hname (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") head))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-invoke (var-deref "jolt.host" "form-sym-ns") head)) and__13__auto))) (jolt-invoke (var-deref "jolt.host" "form-sym-name") head) jolt-nil)) (shadowed (let* ((and__13__auto hname)) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.analyzer" "local?") env hname) and__13__auto)))) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "jolt.host" "form-sym?") head))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-not shadowed))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.host" "form-macro?") ctx head) and__13__auto)) and__13__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx (jolt-invoke (var-deref "jolt.host" "form-expand-1") ctx form) env) (if (jolt-truthy? (let* ((and__13__auto hname)) (if (jolt-truthy? and__13__auto) (jolt-contains? (var-deref "jolt.analyzer" "handled") hname) and__13__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze-special") ctx hname items env) (if (jolt-truthy? (let* ((and__13__auto hname)) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-not shadowed))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.analyzer" "method-head?") hname) and__13__auto)) and__13__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze-host-call") ctx hname items env) (if (jolt-truthy? (let* ((and__13__auto hname)) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-not shadowed))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.analyzer" "ctor-head?") hname) and__13__auto)) and__13__auto))) (let* ((_a$3907 (var-deref "jolt.analyzer" "analyze-ctor")) (_a$3908 ctx) (_a$3909 (jolt-invoke (var-deref "clojure.core" "subs") hname 0 (jolt-dec (jolt-count hname)))) (_a$3910 (jolt-rest items)) (_a$3911 env)) (jolt-invoke _a$3907 _a$3908 _a$3909 _a$3910 _a$3911)) (if (jolt-truthy? (let* ((and__13__auto (jolt= hname "new"))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-not shadowed))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (>= (jolt-count items) 2))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.host" "form-sym?") (jolt-nth items 1)) and__13__auto)) and__13__auto)) and__13__auto))) (let* ((_a$3912 (var-deref "jolt.analyzer" "analyze-ctor")) (_a$3913 ctx) (_a$3914 (jolt-invoke (var-deref "jolt.host" "form-sym-name") (jolt-nth items 1))) (_a$3915 (jolt-drop 2 items)) (_a$3916 env)) (jolt-invoke _a$3912 _a$3913 _a$3914 _a$3915 _a$3916)) (if (jolt-truthy? (let* ((and__13__auto (jolt= hname "."))) (if (jolt-truthy? and__13__auto) (jolt-not shadowed) and__13__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze-dot") ctx items env) (if (jolt-truthy? (let* ((and__13__auto hname)) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-not shadowed))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.analyzer" "field-head?") hname) and__13__auto)) and__13__auto))) (jolt-invoke (var-deref "jolt.analyzer" "analyze-field") ctx hname items env) (if (jolt-truthy? (let* ((and__13__auto hname)) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-not shadowed))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.host" "form-special?") hname) and__13__auto)) and__13__auto))) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") (jolt-invoke (var-deref "clojure.core" "str") "special form " hname)) (if (jolt-truthy? (keyword #f "else")) (let* ((n (let* ((_a$3921 (var-deref "jolt.ir" "invoke")) (_a$3922 (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx head env)) (_a$3923 (let* ((_a$3918 (var-deref "clojure.core" "mapv")) (_a$3919 (lambda (p__54_) (let fnrec3917 ((p__54_ p__54_)) (jolt-invoke (var-deref "jolt.analyzer" "analyze") ctx p__54_ env)))) (_a$3920 (jolt-rest items))) (jolt-invoke _a$3918 _a$3919 _a$3920)))) (jolt-invoke _a$3921 _a$3922 _a$3923))) (p (jolt-invoke (var-deref "jolt.host" "form-position") form))) (if (jolt-truthy? p) (jolt-assoc n (keyword #f "pos") p) n)) jolt-nil)))))))))))))))) analyze-list))) +(guard (e (#t #f)) + (def-var! "jolt.analyzer" "analyze" (letrec ((analyze (case-lambda ((ctx form) (let fnrec3924 ((ctx ctx) (form form)) (jolt-invoke analyze ctx form (jolt-invoke (var-deref "jolt.analyzer" "empty-env"))))) ((ctx form env) (let fnrec3925 ((ctx ctx) (form form) (env env)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-literal?") form)) (jolt-invoke (var-deref "jolt.ir" "const") form) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") form)) (jolt-invoke (var-deref "jolt.analyzer" "analyze-symbol") ctx form env) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-vec?") form)) (jolt-invoke (var-deref "jolt.ir" "vector-node") (let* ((_a$3927 (var-deref "clojure.core" "mapv")) (_a$3928 (lambda (p__55_) (let fnrec3926 ((p__55_ p__55_)) (jolt-invoke analyze ctx p__55_ env)))) (_a$3929 (jolt-invoke (var-deref "jolt.host" "form-vec-items") form))) (jolt-invoke _a$3927 _a$3928 _a$3929))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-map?") form)) (jolt-invoke (var-deref "jolt.ir" "map-node") (let* ((_a$3933 (var-deref "clojure.core" "mapv")) (_a$3934 (lambda (p) (let fnrec3930 ((p p)) (let* ((_o$3931 (jolt-invoke analyze ctx (jolt-first p) env)) (_o$3932 (jolt-invoke analyze ctx (jolt-invoke (var-deref "clojure.core" "second") p) env))) (jolt-vector _o$3931 _o$3932))))) (_a$3935 (jolt-invoke (var-deref "jolt.host" "form-map-pairs") form))) (jolt-invoke _a$3933 _a$3934 _a$3935))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-set?") form)) (jolt-invoke (var-deref "jolt.ir" "set-node") (let* ((_a$3937 (var-deref "clojure.core" "mapv")) (_a$3938 (lambda (p__56_) (let fnrec3936 ((p__56_ p__56_)) (jolt-invoke analyze ctx p__56_ env)))) (_a$3939 (jolt-invoke (var-deref "jolt.host" "form-set-items") form))) (jolt-invoke _a$3937 _a$3938 _a$3939))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") form)) (jolt-invoke (var-deref "jolt.analyzer" "analyze-list") ctx form env) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-regex?") form)) (let* ((_o$3940 (keyword #f "op")) (_o$3941 (keyword #f "regex")) (_o$3942 (keyword #f "source")) (_o$3943 (jolt-invoke (var-deref "jolt.host" "form-regex-source") form))) (jolt-hash-map _o$3940 _o$3941 _o$3942 _o$3943)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-inst?") form)) (let* ((_o$3944 (keyword #f "op")) (_o$3945 (keyword #f "inst")) (_o$3946 (keyword #f "source")) (_o$3947 (jolt-invoke (var-deref "jolt.host" "form-inst-source") form))) (jolt-hash-map _o$3944 _o$3945 _o$3946 _o$3947)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-uuid?") form)) (let* ((_o$3948 (keyword #f "op")) (_o$3949 (keyword #f "uuid")) (_o$3950 (keyword #f "source")) (_o$3951 (jolt-invoke (var-deref "jolt.host" "form-uuid-source") form))) (jolt-hash-map _o$3948 _o$3949 _o$3950 _o$3951)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-bigdec?") form)) (let* ((_o$3952 (keyword #f "op")) (_o$3953 (keyword #f "bigdec")) (_o$3954 (keyword #f "source")) (_o$3955 (jolt-invoke (var-deref "jolt.host" "form-bigdec-source") form))) (jolt-hash-map _o$3952 _o$3953 _o$3954 _o$3955)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-ns-value?") form)) (let* ((_o$3956 (keyword #f "op")) (_o$3957 (keyword #f "the-ns")) (_o$3958 (keyword #f "name")) (_o$3959 (jolt-invoke (var-deref "jolt.host" "form-ns-value-name") form))) (jolt-hash-map _o$3956 _o$3957 _o$3958 _o$3959)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "jolt.analyzer" "uncompilable") "unsupported form") jolt-nil))))))))))))))))) analyze))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "native-ops" (let* ((_o$2876 "+") (_o$2877 "+") (_o$2878 "-") (_o$2879 "-") (_o$2880 "*") (_o$2881 "*") (_o$2882 "/") (_o$2883 "/") (_o$2884 "<") (_o$2885 "<") (_o$2886 ">") (_o$2887 ">") (_o$2888 "<=") (_o$2889 "<=") (_o$2890 ">=") (_o$2891 ">=") (_o$2892 "=") (_o$2893 "jolt=") (_o$2894 "inc") (_o$2895 "jolt-inc") (_o$2896 "dec") (_o$2897 "jolt-dec") (_o$2898 "not") (_o$2899 "jolt-not") (_o$2900 "min") (_o$2901 "min") (_o$2902 "max") (_o$2903 "max") (_o$2904 "mod") (_o$2905 "modulo") (_o$2906 "rem") (_o$2907 "remainder") (_o$2908 "quot") (_o$2909 "quotient") (_o$2910 "vector") (_o$2911 "jolt-vector") (_o$2912 "hash-map") (_o$2913 "jolt-hash-map") (_o$2914 "hash-set") (_o$2915 "jolt-hash-set") (_o$2916 "conj") (_o$2917 "jolt-conj") (_o$2918 "get") (_o$2919 "jolt-get") (_o$2920 "nth") (_o$2921 "jolt-nth") (_o$2922 "count") (_o$2923 "jolt-count") (_o$2924 "assoc") (_o$2925 "jolt-assoc") (_o$2926 "dissoc") (_o$2927 "jolt-dissoc") (_o$2928 "contains?") (_o$2929 "jolt-contains?") (_o$2930 "empty?") (_o$2931 "jolt-empty?") (_o$2932 "peek") (_o$2933 "jolt-peek") (_o$2934 "pop") (_o$2935 "jolt-pop") (_o$2936 "first") (_o$2937 "jolt-first") (_o$2938 "rest") (_o$2939 "jolt-rest") (_o$2940 "next") (_o$2941 "jolt-next") (_o$2942 "seq") (_o$2943 "jolt-seq") (_o$2944 "cons") (_o$2945 "jolt-cons") (_o$2946 "list") (_o$2947 "jolt-list") (_o$2948 "reverse") (_o$2949 "jolt-reverse") (_o$2950 "last") (_o$2951 "jolt-last") (_o$2952 "map") (_o$2953 "jolt-map") (_o$2954 "filter") (_o$2955 "jolt-filter") (_o$2956 "remove") (_o$2957 "jolt-remove") (_o$2958 "reduce") (_o$2959 "jolt-reduce") (_o$2960 "into") (_o$2961 "jolt-into") (_o$2962 "concat") (_o$2963 "jolt-concat") (_o$2964 "apply") (_o$2965 "jolt-apply") (_o$2966 "range") (_o$2967 "jolt-range") (_o$2968 "take") (_o$2969 "jolt-take") (_o$2970 "drop") (_o$2971 "jolt-drop") (_o$2972 "keys") (_o$2973 "jolt-keys") (_o$2974 "vals") (_o$2975 "jolt-vals") (_o$2976 "even?") (_o$2977 "jolt-even?") (_o$2978 "odd?") (_o$2979 "jolt-odd?") (_o$2980 "pos?") (_o$2981 "jolt-pos?") (_o$2982 "neg?") (_o$2983 "jolt-neg?") (_o$2984 "zero?") (_o$2985 "jolt-zero?") (_o$2986 "identity") (_o$2987 "jolt-identity") (_o$2988 "ex-info") (_o$2989 "jolt-ex-info")) (jolt-hash-map _o$2876 _o$2877 _o$2878 _o$2879 _o$2880 _o$2881 _o$2882 _o$2883 _o$2884 _o$2885 _o$2886 _o$2887 _o$2888 _o$2889 _o$2890 _o$2891 _o$2892 _o$2893 _o$2894 _o$2895 _o$2896 _o$2897 _o$2898 _o$2899 _o$2900 _o$2901 _o$2902 _o$2903 _o$2904 _o$2905 _o$2906 _o$2907 _o$2908 _o$2909 _o$2910 _o$2911 _o$2912 _o$2913 _o$2914 _o$2915 _o$2916 _o$2917 _o$2918 _o$2919 _o$2920 _o$2921 _o$2922 _o$2923 _o$2924 _o$2925 _o$2926 _o$2927 _o$2928 _o$2929 _o$2930 _o$2931 _o$2932 _o$2933 _o$2934 _o$2935 _o$2936 _o$2937 _o$2938 _o$2939 _o$2940 _o$2941 _o$2942 _o$2943 _o$2944 _o$2945 _o$2946 _o$2947 _o$2948 _o$2949 _o$2950 _o$2951 _o$2952 _o$2953 _o$2954 _o$2955 _o$2956 _o$2957 _o$2958 _o$2959 _o$2960 _o$2961 _o$2962 _o$2963 _o$2964 _o$2965 _o$2966 _o$2967 _o$2968 _o$2969 _o$2970 _o$2971 _o$2972 _o$2973 _o$2974 _o$2975 _o$2976 _o$2977 _o$2978 _o$2979 _o$2980 _o$2981 _o$2982 _o$2983 _o$2984 _o$2985 _o$2986 _o$2987 _o$2988 _o$2989)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "core-value-procs" (jolt-invoke (var-deref "clojure.core" "merge") (var-deref "jolt.backend-scheme" "native-ops") (let* ((_o$2990 "+") (_o$2991 "jolt-add") (_o$2992 "-") (_o$2993 "jolt-sub") (_o$2994 "*") (_o$2995 "jolt-mul") (_o$2996 "/") (_o$2997 "jolt-div")) (jolt-hash-map _o$2990 _o$2991 _o$2992 _o$2993 _o$2994 _o$2995 _o$2996 _o$2997))) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "op-arity" (let* ((_o$3039 "inc") (_o$3040 (lambda (p__4_) (let fnrec2998 ((p__4_ p__4_)) (jolt= p__4_ 1)))) (_o$3041 "dec") (_o$3042 (lambda (p__5_) (let fnrec2999 ((p__5_ p__5_)) (jolt= p__5_ 1)))) (_o$3043 "not") (_o$3044 (lambda (p__6_) (let fnrec3000 ((p__6_ p__6_)) (jolt= p__6_ 1)))) (_o$3045 "count") (_o$3046 (lambda (p__7_) (let fnrec3001 ((p__7_ p__7_)) (jolt= p__7_ 1)))) (_o$3047 "empty?") (_o$3048 (lambda (p__8_) (let fnrec3002 ((p__8_ p__8_)) (jolt= p__8_ 1)))) (_o$3049 "peek") (_o$3050 (lambda (p__9_) (let fnrec3003 ((p__9_ p__9_)) (jolt= p__9_ 1)))) (_o$3051 "pop") (_o$3052 (lambda (p__10_) (let fnrec3004 ((p__10_ p__10_)) (jolt= p__10_ 1)))) (_o$3053 "mod") (_o$3054 (lambda (p__11_) (let fnrec3005 ((p__11_ p__11_)) (jolt= p__11_ 2)))) (_o$3055 "rem") (_o$3056 (lambda (p__12_) (let fnrec3006 ((p__12_ p__12_)) (jolt= p__12_ 2)))) (_o$3057 "quot") (_o$3058 (lambda (p__13_) (let fnrec3007 ((p__13_ p__13_)) (jolt= p__13_ 2)))) (_o$3059 "contains?") (_o$3060 (lambda (p__14_) (let fnrec3008 ((p__14_ p__14_)) (jolt= p__14_ 2)))) (_o$3061 "get") (_o$3062 (lambda (p__15_) (let fnrec3009 ((p__15_ p__15_)) (let* ((or__14__auto (jolt= p__15_ 2))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= p__15_ 3)))))) (_o$3063 "nth") (_o$3064 (lambda (p__16_) (let fnrec3010 ((p__16_ p__16_)) (let* ((or__14__auto (jolt= p__16_ 2))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= p__16_ 3)))))) (_o$3065 "assoc") (_o$3066 (lambda (p__17_) (let fnrec3011 ((p__17_ p__17_)) (let* ((and__13__auto (>= p__17_ 3))) (if (jolt-truthy? and__13__auto) (jolt-odd? p__17_) and__13__auto))))) (_o$3067 "dissoc") (_o$3068 (lambda (p__18_) (let fnrec3012 ((p__18_ p__18_)) (>= p__18_ 1)))) (_o$3069 "conj") (_o$3070 (lambda (p__19_) (let fnrec3013 ((p__19_ p__19_)) (>= p__19_ 1)))) (_o$3071 "first") (_o$3072 (lambda (p__20_) (let fnrec3014 ((p__20_ p__20_)) (jolt= p__20_ 1)))) (_o$3073 "rest") (_o$3074 (lambda (p__21_) (let fnrec3015 ((p__21_ p__21_)) (jolt= p__21_ 1)))) (_o$3075 "next") (_o$3076 (lambda (p__22_) (let fnrec3016 ((p__22_ p__22_)) (jolt= p__22_ 1)))) (_o$3077 "seq") (_o$3078 (lambda (p__23_) (let fnrec3017 ((p__23_ p__23_)) (jolt= p__23_ 1)))) (_o$3079 "reverse") (_o$3080 (lambda (p__24_) (let fnrec3018 ((p__24_ p__24_)) (jolt= p__24_ 1)))) (_o$3081 "last") (_o$3082 (lambda (p__25_) (let fnrec3019 ((p__25_ p__25_)) (jolt= p__25_ 1)))) (_o$3083 "keys") (_o$3084 (lambda (p__26_) (let fnrec3020 ((p__26_ p__26_)) (jolt= p__26_ 1)))) (_o$3085 "vals") (_o$3086 (lambda (p__27_) (let fnrec3021 ((p__27_ p__27_)) (jolt= p__27_ 1)))) (_o$3087 "even?") (_o$3088 (lambda (p__28_) (let fnrec3022 ((p__28_ p__28_)) (jolt= p__28_ 1)))) (_o$3089 "odd?") (_o$3090 (lambda (p__29_) (let fnrec3023 ((p__29_ p__29_)) (jolt= p__29_ 1)))) (_o$3091 "pos?") (_o$3092 (lambda (p__30_) (let fnrec3024 ((p__30_ p__30_)) (jolt= p__30_ 1)))) (_o$3093 "neg?") (_o$3094 (lambda (p__31_) (let fnrec3025 ((p__31_ p__31_)) (jolt= p__31_ 1)))) (_o$3095 "zero?") (_o$3096 (lambda (p__32_) (let fnrec3026 ((p__32_ p__32_)) (jolt= p__32_ 1)))) (_o$3097 "identity") (_o$3098 (lambda (p__33_) (let fnrec3027 ((p__33_ p__33_)) (jolt= p__33_ 1)))) (_o$3099 "cons") (_o$3100 (lambda (p__34_) (let fnrec3028 ((p__34_ p__34_)) (jolt= p__34_ 2)))) (_o$3101 "filter") (_o$3102 (lambda (p__35_) (let fnrec3029 ((p__35_ p__35_)) (jolt= p__35_ 2)))) (_o$3103 "remove") (_o$3104 (lambda (p__36_) (let fnrec3030 ((p__36_ p__36_)) (jolt= p__36_ 2)))) (_o$3105 "into") (_o$3106 (lambda (p__37_) (let fnrec3031 ((p__37_ p__37_)) (jolt= p__37_ 2)))) (_o$3107 "take") (_o$3108 (lambda (p__38_) (let fnrec3032 ((p__38_ p__38_)) (jolt= p__38_ 2)))) (_o$3109 "drop") (_o$3110 (lambda (p__39_) (let fnrec3033 ((p__39_ p__39_)) (jolt= p__39_ 2)))) (_o$3111 "map") (_o$3112 (lambda (p__40_) (let fnrec3034 ((p__40_ p__40_)) (>= p__40_ 2)))) (_o$3113 "apply") (_o$3114 (lambda (p__41_) (let fnrec3035 ((p__41_ p__41_)) (>= p__41_ 2)))) (_o$3115 "reduce") (_o$3116 (lambda (p__42_) (let fnrec3036 ((p__42_ p__42_)) (let* ((or__14__auto (jolt= p__42_ 2))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= p__42_ 3)))))) (_o$3117 "range") (_o$3118 (lambda (p__43_) (let fnrec3037 ((p__43_ p__43_)) (let* ((and__13__auto (>= p__43_ 0))) (if (jolt-truthy? and__13__auto) (<= p__43_ 3) and__13__auto))))) (_o$3119 "ex-info") (_o$3120 (lambda (p__44_) (let fnrec3038 ((p__44_ p__44_)) (let* ((or__14__auto (jolt= p__44_ 2))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= p__44_ 3))))))) (jolt-hash-map _o$3039 _o$3040 _o$3041 _o$3042 _o$3043 _o$3044 _o$3045 _o$3046 _o$3047 _o$3048 _o$3049 _o$3050 _o$3051 _o$3052 _o$3053 _o$3054 _o$3055 _o$3056 _o$3057 _o$3058 _o$3059 _o$3060 _o$3061 _o$3062 _o$3063 _o$3064 _o$3065 _o$3066 _o$3067 _o$3068 _o$3069 _o$3070 _o$3071 _o$3072 _o$3073 _o$3074 _o$3075 _o$3076 _o$3077 _o$3078 _o$3079 _o$3080 _o$3081 _o$3082 _o$3083 _o$3084 _o$3085 _o$3086 _o$3087 _o$3088 _o$3089 _o$3090 _o$3091 _o$3092 _o$3093 _o$3094 _o$3095 _o$3096 _o$3097 _o$3098 _o$3099 _o$3100 _o$3101 _o$3102 _o$3103 _o$3104 _o$3105 _o$3106 _o$3107 _o$3108 _o$3109 _o$3110 _o$3111 _o$3112 _o$3113 _o$3114 _o$3115 _o$3116 _o$3117 _o$3118 _o$3119 _o$3120)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "cmp1-ops" (let* ((_o$3121 "<") (_o$3122 ">") (_o$3123 "<=") (_o$3124 ">=")) (jolt-hash-set _o$3121 _o$3122 _o$3123 _o$3124)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "supported-host-methods" (let* ((_o$3125 "isDirectory") (_o$3126 "listFiles")) (jolt-hash-set _o$3125 _o$3126)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "bool-returning-ops" (let* ((_o$3127 "<") (_o$3128 "<=") (_o$3129 ">") (_o$3130 ">=") (_o$3131 "jolt=") (_o$3132 "jolt-not") (_o$3133 "jolt-even?") (_o$3134 "jolt-odd?") (_o$3135 "jolt-pos?") (_o$3136 "jolt-neg?") (_o$3137 "jolt-zero?") (_o$3138 "jolt-empty?") (_o$3139 "jolt-contains?")) (jolt-hash-set _o$3127 _o$3128 _o$3129 _o$3130 _o$3131 _o$3132 _o$3133 _o$3134 _o$3135 _o$3136 _o$3137 _o$3138 _o$3139)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "prelude-mode?" (jolt-invoke (var-deref "clojure.core" "atom") #f))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "set-prelude-mode!" (letrec ((set-prelude-mode! (lambda (on) (let fnrec3140 ((on on)) (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "jolt.backend-scheme" "prelude-mode?") on))))) set-prelude-mode!))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "*recur-target*" jolt-nil (jolt-hash-map (keyword #f "dynamic") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "*known-procs*" (jolt-hash-set) (jolt-hash-map (keyword #f "dynamic") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "gensym-counter" (jolt-invoke (var-deref "clojure.core" "atom") 0) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "fresh-label" (letrec ((fresh-label (lambda (prefix) (let fnrec3141 ((prefix prefix)) (jolt-invoke (var-deref "clojure.core" "str") prefix (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "jolt.backend-scheme" "gensym-counter") jolt-inc)))))) fresh-label))) +(guard (e (#t #f)) + (def-var-with-meta! "jolt.backend-scheme" "scheme-reserved" (let* ((_o$3142 "if") (_o$3143 "begin") (_o$3144 "lambda") (_o$3145 "let") (_o$3146 "let*") (_o$3147 "letrec") (_o$3148 "letrec*") (_o$3149 "quote") (_o$3150 "quasiquote") (_o$3151 "unquote") (_o$3152 "set!") (_o$3153 "define") (_o$3154 "define-syntax") (_o$3155 "cond") (_o$3156 "case") (_o$3157 "when") (_o$3158 "unless") (_o$3159 "and") (_o$3160 "or") (_o$3161 "do") (_o$3162 "else") (_o$3163 "guard") (_o$3164 "parameterize") (_o$3165 "delay") (_o$3166 "values")) (jolt-hash-set _o$3142 _o$3143 _o$3144 _o$3145 _o$3146 _o$3147 _o$3148 _o$3149 _o$3150 _o$3151 _o$3152 _o$3153 _o$3154 _o$3155 _o$3156 _o$3157 _o$3158 _o$3159 _o$3160 _o$3161 _o$3162 _o$3163 _o$3164 _o$3165 _o$3166)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "munge-name" (letrec ((munge-name (lambda (s) (let fnrec3167 ((s s)) (let* ((s (jolt-invoke (var-deref "clojure.string" "replace") (jolt-invoke (var-deref "clojure.string" "replace") s "#" "_") "'" "_PRIME_"))) (if (jolt-contains? (var-deref "jolt.backend-scheme" "scheme-reserved") s) (jolt-invoke (var-deref "clojure.core" "str") "_" s) s)))))) munge-name))) +(guard (e (#t #f)) + (declare-var! "jolt.backend-scheme" "emit")) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "char-escape" (letrec ((char-escape (lambda (cp) (let fnrec3168 ((cp cp)) (if (jolt= cp 34) "\\\"" (if (jolt= cp 92) "\\\\" (if (jolt= cp 10) "\\n" (if (jolt= cp 9) "\\t" (if (jolt= cp 13) "\\r" (if (jolt-truthy? (let* ((and__13__auto (>= cp 32))) (if (jolt-truthy? and__13__auto) (< cp 127) and__13__auto))) (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "char") cp)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "str") "\\x" (jolt-invoke (var-deref "clojure.core" "format") "%x" cp) ";") jolt-nil))))))))))) char-escape))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "chez-str-lit" (letrec ((chez-str-lit (lambda (s) (let fnrec3169 ((s s)) (jolt-invoke (var-deref "clojure.core" "str") "\"" (jolt-apply (var-deref "clojure.core" "str") (jolt-map (lambda (c) (let fnrec3170 ((c c)) (jolt-invoke (var-deref "jolt.backend-scheme" "char-escape") (jolt-invoke (var-deref "clojure.core" "int") c)))) s)) "\""))))) chez-str-lit))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-const" (letrec ((emit-const (lambda (v) (let fnrec3171 ((v v)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") v)) "jolt-nil" (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "boolean?") v)) (if (jolt-truthy? v) "#t" "#f") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") v)) (if (jolt= v +inf.0) "+inf.0" (if (jolt= v -inf.0) "-inf.0" (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "not=") v v)) "+nan.0" (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "float?") v)) (let* ((s (jolt-invoke (var-deref "clojure.core" "str") v))) (if (jolt-truthy? (let* ((or__14__auto (jolt-invoke (var-deref "clojure.string" "includes?") s "."))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.string" "includes?") s "e")))) s (jolt-invoke (var-deref "clojure.core" "str") s ".0"))) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "str") v) jolt-nil))))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") v)) (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") v) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") v)) (let* ((temp__4__auto (jolt-invoke (var-deref "clojure.core" "namespace") v))) (if (jolt-truthy? temp__4__auto) (let* ((kns temp__4__auto)) (let* ((_a$3172 (var-deref "clojure.core" "str")) (_a$3173 "(keyword ") (_a$3174 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") kns)) (_a$3175 " ") (_a$3176 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-invoke (var-deref "clojure.core" "name") v))) (_a$3177 ")")) (jolt-invoke _a$3172 _a$3173 _a$3174 _a$3175 _a$3176 _a$3177))) (jolt-invoke (var-deref "clojure.core" "str") "(keyword #f " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-invoke (var-deref "clojure.core" "name") v)) ")"))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-char?") v)) (jolt-invoke (var-deref "clojure.core" "str") "(integer->char " (jolt-invoke (var-deref "jolt.host" "form-char-code") v) ")") (if (jolt-truthy? (keyword #f "else")) (jolt-throw (let* ((_a$3178 (jolt-invoke (var-deref "clojure.core" "str") "emit-const: unsupported literal " (jolt-invoke (var-deref "clojure.core" "pr-str") v))) (_a$3179 (jolt-hash-map))) (jolt-ex-info _a$3178 _a$3179))) jolt-nil))))))))))) emit-const))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-ordered" (letrec ((emit-ordered (lambda (ctor arg-strs) (let fnrec3180 ((ctor ctor) (arg-strs arg-strs)) (if (< (jolt-count arg-strs) 2) (jolt-invoke (var-deref "clojure.core" "str") "(" ctor (if (jolt-empty? arg-strs) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " arg-strs))) ")") (let* ((tmps (jolt-map (lambda (_) (let fnrec3181 ((_ _)) (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "_o$"))) arg-strs)) (binds (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (t a) (let fnrec3182 ((t t) (a a)) (jolt-invoke (var-deref "clojure.core" "str") "(" t " " a ")"))) tmps arg-strs)))) (jolt-invoke (var-deref "clojure.core" "str") "(let* (" binds ") (" ctor " " (jolt-invoke (var-deref "clojure.string" "join") " " tmps) "))"))))))) emit-ordered))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "side-effect-free?" (letrec ((side-effect-free? (lambda (n) (let fnrec3183 ((n n)) (let* ((_a$3189 (let* ((_o$3184 (keyword #f "const")) (_o$3185 (keyword #f "local")) (_o$3186 (keyword #f "var")) (_o$3187 (keyword #f "the-var")) (_o$3188 (keyword #f "quote"))) (jolt-hash-set _o$3184 _o$3185 _o$3186 _o$3187 _o$3188))) (_a$3190 (jolt-get n (keyword #f "op")))) (jolt-contains? _a$3189 _a$3190)))))) side-effect-free?))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "needs-order?" (letrec ((needs-order? (lambda (nodes) (let fnrec3191 ((nodes nodes)) (> (jolt-count (jolt-remove (var-deref "jolt.backend-scheme" "side-effect-free?") nodes)) 1))))) needs-order?))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "ordered-call" (letrec ((ordered-call (lambda (nodes strs build) (let fnrec3192 ((nodes nodes) (strs strs) (build build)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "needs-order?") nodes)) (let* ((tmps (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (_) (let fnrec3193 ((_ _)) (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "_a$"))) strs)) (binds (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (t a) (let fnrec3194 ((t t) (a a)) (jolt-invoke (var-deref "clojure.core" "str") "(" t " " a ")"))) tmps strs)))) (jolt-invoke (var-deref "clojure.core" "str") "(let* (" binds ") " (jolt-invoke build tmps) ")")) (jolt-invoke build strs)))))) ordered-call))) +(guard (e (#t #f)) + (declare-var! "jolt.backend-scheme" "emit-quoted")) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-quoted-map" (letrec ((emit-quoted-map (lambda (pairs) (let fnrec3195 ((pairs pairs)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-hash-map " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-invoke (var-deref "clojure.core" "mapcat") (lambda (p) (let fnrec3196 ((p p)) (let* ((_o$3197 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-nth p 0))) (_o$3198 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-nth p 1)))) (jolt-vector _o$3197 _o$3198)))) pairs)) ")"))))) emit-quoted-map))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-quoted-map-value" (letrec ((emit-quoted-map-value (lambda (m) (let fnrec3199 ((m m)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-hash-map " (jolt-invoke (var-deref "clojure.string" "join") " " (let* ((_a$3203 (var-deref "clojure.core" "mapcat")) (_a$3204 (lambda (k) (let fnrec3200 ((k k)) (let* ((_o$3201 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") k)) (_o$3202 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-get m k)))) (jolt-vector _o$3201 _o$3202))))) (_a$3205 (jolt-keys m))) (jolt-invoke _a$3203 _a$3204 _a$3205))) ")"))))) emit-quoted-map-value))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-quoted" (letrec ((emit-quoted (lambda (form) (let fnrec3206 ((form form)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-char?") form)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-const") form) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-literal?") form)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-const") form) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-sym?") form)) (let* ((m (jolt-invoke (var-deref "jolt.host" "form-sym-meta") form)) (sns (jolt-invoke (var-deref "jolt.host" "form-sym-ns") form)) (nm (jolt-invoke (var-deref "jolt.host" "form-sym-name") form))) (if (jolt-truthy? (let* ((and__13__auto m)) (if (jolt-truthy? and__13__auto) (jolt-pos? (jolt-count m)) and__13__auto))) (let* ((_a$3207 (var-deref "clojure.core" "str")) (_a$3208 "(jolt-symbol/meta ") (_a$3209 (if (jolt-truthy? sns) (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") sns) "#f")) (_a$3210 " ") (_a$3211 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$3212 " ") (_a$3213 (jolt-invoke emit-quoted m)) (_a$3214 ")")) (jolt-invoke _a$3207 _a$3208 _a$3209 _a$3210 _a$3211 _a$3212 _a$3213 _a$3214)) (let* ((_a$3215 (var-deref "clojure.core" "str")) (_a$3216 "(jolt-symbol ") (_a$3217 (if (jolt-truthy? sns) (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") sns) "#f")) (_a$3218 " ") (_a$3219 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") nm)) (_a$3220 ")")) (jolt-invoke _a$3215 _a$3216 _a$3217 _a$3218 _a$3219 _a$3220)))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-set?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-hash-set " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted (jolt-invoke (var-deref "jolt.host" "form-set-items") form))) ")") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-list?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-list " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted (jolt-invoke (var-deref "jolt.host" "form-elements") form))) ")") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-vec?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-vector " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted (jolt-invoke (var-deref "jolt.host" "form-vec-items") form))) ")") (if (jolt-truthy? (jolt-invoke (var-deref "jolt.host" "form-map?") form)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted-map") (jolt-invoke (var-deref "jolt.host" "form-map-pairs") form)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") form)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted-map-value") form) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-vector " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted form)) ")") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "set?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-hash-set " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted form)) ")") (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-list " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit-quoted form)) ")") (if (jolt-truthy? (keyword #f "else")) (jolt-throw (let* ((_a$3221 (jolt-invoke (var-deref "clojure.core" "str") "emit-quoted: unsupported quoted form " (jolt-invoke (var-deref "clojure.core" "pr-str") form))) (_a$3222 (jolt-hash-map))) (jolt-ex-info _a$3221 _a$3222))) jolt-nil)))))))))))))))) emit-quoted))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "jmeta-nonempty?" (letrec ((jmeta-nonempty? (lambda (m) (let fnrec3223 ((m m)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "map?") m))) (if (jolt-truthy? and__13__auto) (jolt-pos? (jolt-count m)) and__13__auto)))))) jmeta-nonempty?))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-binding" (letrec ((emit-binding (lambda (b) (let fnrec3224 ((b b)) (let* ((_a$3225 (var-deref "clojure.core" "str")) (_a$3226 "(") (_a$3227 (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-nth b 0))) (_a$3228 " ") (_a$3229 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-nth b 1))) (_a$3230 ")")) (jolt-invoke _a$3225 _a$3226 _a$3227 _a$3228 _a$3229 _a$3230)))))) emit-binding))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-let" (letrec ((emit-let (lambda (node) (let fnrec3231 ((node node)) (let* ((kw (if (jolt-truthy? (jolt-get node (keyword #f "letrec"))) "letrec*" "let*"))) (let* ((_a$3232 (var-deref "clojure.core" "str")) (_a$3233 "(") (_a$3234 kw) (_a$3235 " (") (_a$3236 (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (var-deref "jolt.backend-scheme" "emit-binding") (jolt-get node (keyword #f "bindings"))))) (_a$3237 ") ") (_a$3238 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "body")))) (_a$3239 ")")) (jolt-invoke _a$3232 _a$3233 _a$3234 _a$3235 _a$3236 _a$3237 _a$3238 _a$3239))))))) emit-let))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-loop" (letrec ((emit-loop (lambda (node) (let fnrec3240 ((node node)) (let* ((label (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "loop")) (pairs (jolt-get node (keyword #f "bindings"))) (names (jolt-map (lambda (p__45_) (let fnrec3241 ((p__45_ p__45_)) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-nth p__45_ 0)))) pairs)) (inits (jolt-map (lambda (p__46_) (let fnrec3242 ((p__46_ p__46_)) (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-nth p__46_ 1)))) pairs)) (seq-bs (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (n i) (let fnrec3243 ((n n) (i i)) (jolt-invoke (var-deref "clojure.core" "str") "(" n " " i ")"))) names inits))) (rebinds (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (n) (let fnrec3244 ((n n)) (jolt-invoke (var-deref "clojure.core" "str") "(" n " " n ")"))) names))) (body (let* ((frame__8__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*recur-target*") label))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__8__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "body")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings")))))))) (jolt-invoke (var-deref "clojure.core" "str") "(let* (" seq-bs ") (let " label " (" rebinds ") " body "))")))))) emit-loop))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-recur" (letrec ((emit-recur (lambda (node) (let fnrec3245 ((node node)) (begin (if (jolt-not (var-deref "jolt.backend-scheme" "*recur-target*")) (jolt-throw (jolt-ex-info "emit: recur outside a loop/fn target" (jolt-hash-map))) jolt-nil) (let* ((arg-nodes (jolt-get node (keyword #f "args")))) (let* ((_a$3247 (var-deref "jolt.backend-scheme" "ordered-call")) (_a$3248 arg-nodes) (_a$3249 (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "jolt.backend-scheme" "emit") arg-nodes)) (_a$3250 (lambda (as) (let fnrec3246 ((as as)) (jolt-invoke (var-deref "clojure.core" "str") "(" (var-deref "jolt.backend-scheme" "*recur-target*") " " (jolt-invoke (var-deref "clojure.string" "join") " " as) ")"))))) (jolt-invoke _a$3247 _a$3248 _a$3249 _a$3250)))))))) emit-recur))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-arity-clause" (letrec ((emit-arity-clause (lambda (a) (let fnrec3251 ((a a)) (let* ((params (jolt-map (var-deref "jolt.backend-scheme" "munge-name") (jolt-get a (keyword #f "params")))) (restp (let* ((temp__15__auto (jolt-get a (keyword #f "rest")))) (if (jolt-truthy? temp__15__auto) (let* ((r temp__15__auto)) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") r)) jolt-nil))) (label (jolt-invoke (var-deref "jolt.backend-scheme" "fresh-label") "fnrec")) (body (let* ((frame__8__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*recur-target*") label))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__8__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get a (keyword #f "body")))) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) (paramlist (if (jolt-truthy? (let* ((and__13__auto restp)) (if (jolt-truthy? and__13__auto) (jolt-empty? params) and__13__auto))) restp (if (jolt-truthy? restp) (jolt-invoke (var-deref "clojure.core" "str") "(" (jolt-invoke (var-deref "clojure.string" "join") " " params) " . " restp ")") (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "str") "(" (jolt-invoke (var-deref "clojure.string" "join") " " params) ")") jolt-nil)))) (binds (if (jolt-truthy? restp) (let* ((_a$3253 (jolt-map (lambda (p) (let fnrec3252 ((p p)) (jolt-invoke (var-deref "clojure.core" "str") "(" p " " p ")"))) params)) (_a$3254 (jolt-vector (jolt-invoke (var-deref "clojure.core" "str") "(" restp " (list->cseq " restp "))")))) (jolt-concat _a$3253 _a$3254)) (jolt-map (lambda (p) (let fnrec3255 ((p p)) (jolt-invoke (var-deref "clojure.core" "str") "(" p " " p ")"))) params)))) (let* ((_o$3256 paramlist) (_o$3257 (jolt-invoke (var-deref "clojure.core" "str") "(let " label " (" (jolt-invoke (var-deref "clojure.string" "join") " " binds) ") " body ")"))) (jolt-vector _o$3256 _o$3257))))))) emit-arity-clause))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-fn" (letrec ((emit-fn (lambda (node) (let fnrec3258 ((node node)) (let* ((arities (jolt-get node (keyword #f "arities"))) (self (let* ((temp__15__auto (jolt-get node (keyword #f "name")))) (if (jolt-truthy? temp__15__auto) (let* ((nm temp__15__auto)) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") nm)) jolt-nil))) (clauses (let* ((frame__8__auto (jolt-invoke (var-deref "clojure.core" "array-map") (jolt-var "jolt.backend-scheme" "*known-procs*") (if (jolt-truthy? self) (jolt-conj (var-deref "jolt.backend-scheme" "*known-procs*") self) (var-deref "jolt.backend-scheme" "*known-procs*"))))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") frame__8__auto) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "jolt.backend-scheme" "emit-arity-clause") arities)) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))) (_lambda (if (jolt= 1 (jolt-count clauses)) (let* ((c (jolt-first clauses))) (let* ((_a$3259 (var-deref "clojure.core" "str")) (_a$3260 "(lambda ") (_a$3261 (jolt-nth c 0)) (_a$3262 " ") (_a$3263 (jolt-nth c 1)) (_a$3264 ")")) (jolt-invoke _a$3259 _a$3260 _a$3261 _a$3262 _a$3263 _a$3264))) (jolt-invoke (var-deref "clojure.core" "str") "(case-lambda " (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map (lambda (c) (let fnrec3265 ((c c)) (let* ((_a$3266 (var-deref "clojure.core" "str")) (_a$3267 "(") (_a$3268 (jolt-nth c 0)) (_a$3269 " ") (_a$3270 (jolt-nth c 1)) (_a$3271 ")")) (jolt-invoke _a$3266 _a$3267 _a$3268 _a$3269 _a$3270 _a$3271)))) clauses)) ")")))) (let* ((temp__4__auto (jolt-get node (keyword #f "name")))) (if (jolt-truthy? temp__4__auto) (let* ((nm temp__4__auto)) (let* ((m (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") nm))) (jolt-invoke (var-deref "clojure.core" "str") "(letrec ((" m " " _lambda ")) " m ")"))) _lambda))))))) emit-fn))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "native-op" (letrec ((native-op (lambda (fnode nargs) (let fnrec3272 ((fnode fnode) (nargs nargs)) (let* ((nm (let* ((G__33 (jolt-get fnode (keyword #f "op")))) (if (jolt= G__33 (keyword #f "var")) (if (jolt= "clojure.core" (jolt-get fnode (keyword #f "ns"))) (jolt-get fnode (keyword #f "name")) jolt-nil) (if (jolt= G__33 (keyword #f "host")) (jolt-get fnode (keyword #f "name")) jolt-nil)))) (op (if (jolt-truthy? nm) (jolt-invoke (var-deref "jolt.backend-scheme" "native-ops") nm) jolt-nil)) (arity-ok (if (jolt-truthy? nm) (jolt-invoke (var-deref "jolt.backend-scheme" "op-arity") nm) jolt-nil))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") op)) jolt-nil (if (jolt-truthy? (let* ((and__13__auto arity-ok)) (if (jolt-truthy? and__13__auto) (jolt-not (jolt-invoke arity-ok nargs)) and__13__auto))) jolt-nil (if (jolt-truthy? (keyword #f "else")) op jolt-nil)))))))) native-op))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "ifn-kind" (letrec ((ifn-kind (lambda (fnode) (let fnrec3273 ((fnode fnode)) (let* ((G__34 (jolt-get fnode (keyword #f "op")))) (if (jolt= G__34 (keyword #f "const")) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") (jolt-get fnode (keyword #f "val")))) (keyword #f "keyword") jolt-nil) (if (jolt-truthy? (let* ((or__14__auto (jolt= G__34 (keyword #f "map")))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt= G__34 (keyword #f "set")))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= G__34 (keyword #f "vector"))))))) (keyword #f "coll") jolt-nil))))))) ifn-kind))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "stdlib-var?" (letrec ((stdlib-var? (lambda (n) (let fnrec3274 ((n n)) (let* ((and__13__auto (jolt= (keyword #f "var") (jolt-get n (keyword #f "op"))))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.string" "starts-with?") (let* ((or__14__auto (jolt-get n (keyword #f "ns")))) (if (jolt-truthy? or__14__auto) or__14__auto "")) "clojure.") and__13__auto)))))) stdlib-var?))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-invoke" (letrec ((emit-invoke (lambda (node) (let fnrec3275 ((node node)) (let* ((fnode (jolt-get node (keyword #f "fn"))) (arg-nodes (jolt-get node (keyword #f "args"))) (args (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "jolt.backend-scheme" "emit") arg-nodes)) (nop (jolt-invoke (var-deref "jolt.backend-scheme" "native-op") fnode (jolt-count args))) (kind (jolt-invoke (var-deref "jolt.backend-scheme" "ifn-kind") fnode)) (order-args (lambda (build) (let fnrec3276 ((build build)) (jolt-invoke (var-deref "jolt.backend-scheme" "ordered-call") arg-nodes args build)))) (defstr (lambda (as) (let fnrec3277 ((as as)) (if (> (jolt-count as) 1) (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-nth as 1)) "")))) (invoke (lambda () (let fnrec3278 () (let* ((_a$3280 (var-deref "jolt.backend-scheme" "ordered-call")) (_a$3281 (jolt-cons fnode arg-nodes)) (_a$3282 (jolt-cons (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fnode) args)) (_a$3283 (lambda (G__35) (let fnrec3279 ((G__35 G__35)) (let* ((G__36 G__35) (f (jolt-nth G__36 0 jolt-nil)) (as (jolt-invoke (var-deref "clojure.core" "nthnext") G__36 1))) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-invoke " f (if (jolt-truthy? (jolt-seq as)) (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " as)) "") ")")))))) (jolt-invoke _a$3280 _a$3281 _a$3282 _a$3283)))))) (if (jolt-truthy? (let* ((and__13__auto nop)) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-empty? args))) (if (jolt-truthy? and__13__auto) (jolt= nop "+") and__13__auto)) and__13__auto))) "0" (if (jolt-truthy? (let* ((and__13__auto nop)) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-empty? args))) (if (jolt-truthy? and__13__auto) (jolt= nop "*") and__13__auto)) and__13__auto))) "1" (if (jolt-truthy? (let* ((and__13__auto nop)) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt= 1 (jolt-count args)))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.backend-scheme" "cmp1-ops") nop) and__13__auto)) and__13__auto))) (jolt-invoke (var-deref "clojure.core" "str") "(begin " (jolt-first args) " #t)") (if (jolt-truthy? nop) (jolt-invoke order-args (lambda (as) (let fnrec3284 ((as as)) (jolt-invoke (var-deref "clojure.core" "str") "(" nop " " (jolt-invoke (var-deref "clojure.string" "join") " " as) ")")))) (if (jolt= kind (keyword #f "keyword")) (jolt-invoke order-args (lambda (as) (let fnrec3285 ((as as)) (let* ((_a$3286 (var-deref "clojure.core" "str")) (_a$3287 "(jolt-get ") (_a$3288 (jolt-first as)) (_a$3289 " ") (_a$3290 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fnode)) (_a$3291 (jolt-invoke defstr as)) (_a$3292 ")")) (jolt-invoke _a$3286 _a$3287 _a$3288 _a$3289 _a$3290 _a$3291 _a$3292))))) (if (jolt= kind (keyword #f "coll")) (let* ((_a$3294 (var-deref "jolt.backend-scheme" "ordered-call")) (_a$3295 (jolt-cons fnode arg-nodes)) (_a$3296 (jolt-cons (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fnode) args)) (_a$3297 (lambda (G__37) (let fnrec3293 ((G__37 G__37)) (let* ((G__38 G__37) (c (jolt-nth G__38 0 jolt-nil)) (as (jolt-invoke (var-deref "clojure.core" "nthnext") G__38 1))) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-get " c " " (jolt-invoke (var-deref "clojure.string" "join") " " as) ")")))))) (jolt-invoke _a$3294 _a$3295 _a$3296 _a$3297)) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "jolt.backend-scheme" "stdlib-var?") fnode))) (if (jolt-truthy? and__13__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "prelude-mode?"))) and__13__auto))) (jolt-throw (let* ((_a$3304 (let* ((_a$3298 (var-deref "clojure.core" "str")) (_a$3299 "emit: unsupported stdlib fn `") (_a$3300 (jolt-get fnode (keyword #f "ns"))) (_a$3301 "/") (_a$3302 (jolt-get fnode (keyword #f "name"))) (_a$3303 "` (no core on Chez yet)")) (jolt-invoke _a$3298 _a$3299 _a$3300 _a$3301 _a$3302 _a$3303))) (_a$3305 (jolt-hash-map))) (jolt-ex-info _a$3304 _a$3305))) (if (jolt= (keyword #f "host-static") (jolt-get fnode (keyword #f "op"))) (jolt-invoke order-args (lambda (as) (let fnrec3306 ((as as)) (let* ((_a$3307 (var-deref "clojure.core" "str")) (_a$3308 "(host-static-call ") (_a$3309 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get fnode (keyword #f "class")))) (_a$3310 " ") (_a$3311 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get fnode (keyword #f "member")))) (_a$3312 (if (jolt-empty? as) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " as)))) (_a$3313 ")")) (jolt-invoke _a$3307 _a$3308 _a$3309 _a$3310 _a$3311 _a$3312 _a$3313))))) (if (jolt= (keyword #f "host") (jolt-get fnode (keyword #f "op"))) (jolt-throw (let* ((_a$3314 (jolt-invoke (var-deref "clojure.core" "str") "emit: unsupported host call `" (jolt-get fnode (keyword #f "name")) "`")) (_a$3315 (jolt-hash-map))) (jolt-ex-info _a$3314 _a$3315))) (if (jolt-truthy? (let* ((and__13__auto (jolt= (keyword #f "local") (jolt-get fnode (keyword #f "op"))))) (if (jolt-truthy? and__13__auto) (jolt-not (jolt-invoke (var-deref "jolt.backend-scheme" "*known-procs*") (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-get fnode (keyword #f "name"))))) and__13__auto))) (jolt-invoke invoke) (if (jolt= (keyword #f "var") (jolt-get fnode (keyword #f "op"))) (jolt-invoke invoke) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke invoke) jolt-nil))))))))))))))))) emit-invoke))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit-try" (letrec ((emit-try (lambda (node) (let fnrec3316 ((node node)) (let* ((core (let* ((temp__4__auto (jolt-get node (keyword #f "catch-sym")))) (if (jolt-truthy? temp__4__auto) (let* ((cs temp__4__auto)) (let* ((_a$3317 (var-deref "clojure.core" "str")) (_a$3318 "(guard (") (_a$3319 (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") cs)) (_a$3320 " (else ") (_a$3321 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "catch-body")))) (_a$3322 ")) ") (_a$3323 (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "body")))) (_a$3324 ")")) (jolt-invoke _a$3317 _a$3318 _a$3319 _a$3320 _a$3321 _a$3322 _a$3323 _a$3324))) (jolt-invoke (var-deref "jolt.backend-scheme" "emit") (jolt-get node (keyword #f "body"))))))) (let* ((temp__4__auto (jolt-get node (keyword #f "finally")))) (if (jolt-truthy? temp__4__auto) (let* ((fin temp__4__auto)) (jolt-invoke (var-deref "clojure.core" "str") "(dynamic-wind (lambda () #f) (lambda () " core ") (lambda () " (jolt-invoke (var-deref "jolt.backend-scheme" "emit") fin) "))")) core))))))) emit-try))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "returns-scheme-bool?" (letrec ((returns-scheme-bool? (lambda (node) (let fnrec3325 ((node node)) (if (jolt-truthy? (let* ((and__13__auto (jolt= (keyword #f "const") (jolt-get node (keyword #f "op"))))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "boolean?") (jolt-get node (keyword #f "val"))) and__13__auto))) #t (if (jolt= (keyword #f "invoke") (jolt-get node (keyword #f "op"))) (let* ((nop (let* ((_a$3326 (var-deref "jolt.backend-scheme" "native-op")) (_a$3327 (jolt-get node (keyword #f "fn"))) (_a$3328 (jolt-count (jolt-get node (keyword #f "args"))))) (jolt-invoke _a$3326 _a$3327 _a$3328)))) (if (jolt-truthy? (let* ((and__13__auto nop)) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.backend-scheme" "bool-returning-ops") nop) and__13__auto))) #t #f)) (if (jolt-truthy? (keyword #f "else")) #f jolt-nil))))))) returns-scheme-bool?))) +(guard (e (#t #f)) + (def-var! "jolt.backend-scheme" "emit" (letrec ((emit (lambda (node) (let fnrec3329 ((node node)) (let* ((G__39 (jolt-get node (keyword #f "op")))) (if (jolt= G__39 (keyword #f "const")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-const") (jolt-get node (keyword #f "val"))) (if (jolt= G__39 (keyword #f "local")) (jolt-invoke (var-deref "jolt.backend-scheme" "munge-name") (jolt-get node (keyword #f "name"))) (if (jolt= G__39 (keyword #f "var")) (let* ((core-proc (let* ((and__13__auto (jolt= "clojure.core" (jolt-get node (keyword #f "ns"))))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "jolt.backend-scheme" "core-value-procs") (jolt-get node (keyword #f "name"))) and__13__auto)))) (if (jolt-truthy? core-proc) core-proc (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "jolt.backend-scheme" "stdlib-var?") node))) (if (jolt-truthy? and__13__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "jolt.backend-scheme" "prelude-mode?"))) and__13__auto))) (jolt-throw (let* ((_a$3336 (let* ((_a$3330 (var-deref "clojure.core" "str")) (_a$3331 "emit: unsupported stdlib ref `") (_a$3332 (jolt-get node (keyword #f "ns"))) (_a$3333 "/") (_a$3334 (jolt-get node (keyword #f "name"))) (_a$3335 "` (no core on Chez yet)")) (jolt-invoke _a$3330 _a$3331 _a$3332 _a$3333 _a$3334 _a$3335))) (_a$3337 (jolt-hash-map))) (jolt-ex-info _a$3336 _a$3337))) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$3338 (var-deref "clojure.core" "str")) (_a$3339 "(var-deref ") (_a$3340 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$3341 " ") (_a$3342 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$3343 ")")) (jolt-invoke _a$3338 _a$3339 _a$3340 _a$3341 _a$3342 _a$3343)) jolt-nil)))) (if (jolt= G__39 (keyword #f "the-var")) (let* ((_a$3344 (var-deref "clojure.core" "str")) (_a$3345 "(jolt-var ") (_a$3346 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$3347 " ") (_a$3348 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$3349 ")")) (jolt-invoke _a$3344 _a$3345 _a$3346 _a$3347 _a$3348 _a$3349)) (if (jolt= G__39 (keyword #f "set-var")) (let* ((_a$3350 (var-deref "clojure.core" "str")) (_a$3351 "(jolt-var-set ") (_a$3352 (jolt-invoke emit (jolt-get node (keyword #f "the-var")))) (_a$3353 " ") (_a$3354 (jolt-invoke emit (jolt-get node (keyword #f "val")))) (_a$3355 ")")) (jolt-invoke _a$3350 _a$3351 _a$3352 _a$3353 _a$3354 _a$3355)) (if (jolt= G__39 (keyword #f "set-field")) (let* ((_a$3356 (var-deref "clojure.core" "str")) (_a$3357 "(jolt-set-field! ") (_a$3358 (jolt-invoke emit (jolt-get node (keyword #f "obj")))) (_a$3359 " (keyword #f ") (_a$3360 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "field")))) (_a$3361 ") ") (_a$3362 (jolt-invoke emit (jolt-get node (keyword #f "val")))) (_a$3363 ")")) (jolt-invoke _a$3356 _a$3357 _a$3358 _a$3359 _a$3360 _a$3361 _a$3362 _a$3363)) (if (jolt= G__39 (keyword #f "defmacro")) (let* ((_a$3364 (var-deref "clojure.core" "str")) (_a$3365 "(begin (def-var! ") (_a$3366 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$3367 " ") (_a$3368 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$3369 " ") (_a$3370 (jolt-invoke emit (jolt-get node (keyword #f "fn")))) (_a$3371 ") (mark-macro! ") (_a$3372 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$3373 " ") (_a$3374 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$3375 ") jolt-nil)")) (jolt-invoke _a$3364 _a$3365 _a$3366 _a$3367 _a$3368 _a$3369 _a$3370 _a$3371 _a$3372 _a$3373 _a$3374 _a$3375)) (if (jolt= G__39 (keyword #f "host")) (jolt-throw (let* ((_a$3376 (jolt-invoke (var-deref "clojure.core" "str") "emit: unsupported host ref `" (jolt-get node (keyword #f "name")) "`")) (_a$3377 (jolt-hash-map))) (jolt-ex-info _a$3376 _a$3377))) (if (jolt= G__39 (keyword #f "host-static")) (let* ((_a$3378 (var-deref "clojure.core" "str")) (_a$3379 "(host-static-ref ") (_a$3380 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "class")))) (_a$3381 " ") (_a$3382 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "member")))) (_a$3383 ")")) (jolt-invoke _a$3378 _a$3379 _a$3380 _a$3381 _a$3382 _a$3383)) (if (jolt= G__39 (keyword #f "host-new")) (let* ((_a$3384 (var-deref "clojure.core" "str")) (_a$3385 "(host-new ") (_a$3386 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "class")))) (_a$3387 (let* ((args (jolt-map emit (jolt-get node (keyword #f "args"))))) (if (jolt-empty? args) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " args))))) (_a$3388 ")")) (jolt-invoke _a$3384 _a$3385 _a$3386 _a$3387 _a$3388)) (if (jolt= G__39 (keyword #f "if")) (let* ((test (jolt-get node (keyword #f "test"))) (t (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "returns-scheme-bool?") test)) (jolt-invoke emit test) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-truthy? " (jolt-invoke emit test) ")")))) (let* ((_a$3389 (var-deref "clojure.core" "str")) (_a$3390 "(if ") (_a$3391 t) (_a$3392 " ") (_a$3393 (jolt-invoke emit (jolt-get node (keyword #f "then")))) (_a$3394 " ") (_a$3395 (jolt-invoke emit (jolt-get node (keyword #f "else")))) (_a$3396 ")")) (jolt-invoke _a$3389 _a$3390 _a$3391 _a$3392 _a$3393 _a$3394 _a$3395 _a$3396))) (if (jolt= G__39 (keyword #f "do")) (let* ((_a$3397 (var-deref "clojure.core" "str")) (_a$3398 "(begin ") (_a$3399 (jolt-invoke (var-deref "clojure.string" "join") " " (jolt-map emit (jolt-get node (keyword #f "statements"))))) (_a$3400 (if (jolt-empty? (jolt-get node (keyword #f "statements"))) "" " ")) (_a$3401 (jolt-invoke emit (jolt-get node (keyword #f "ret")))) (_a$3402 ")")) (jolt-invoke _a$3397 _a$3398 _a$3399 _a$3400 _a$3401 _a$3402)) (if (jolt= G__39 (keyword #f "invoke")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-invoke") node) (if (jolt= G__39 (keyword #f "vector")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-ordered") "jolt-vector" (jolt-map emit (jolt-get node (keyword #f "items")))) (if (jolt= G__39 (keyword #f "set")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-ordered") "jolt-hash-set" (jolt-map emit (jolt-get node (keyword #f "items")))) (if (jolt= G__39 (keyword #f "map")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-ordered") "jolt-hash-map" (let* ((_a$3406 (var-deref "clojure.core" "mapcat")) (_a$3407 (lambda (p) (let fnrec3403 ((p p)) (let* ((_o$3404 (jolt-invoke emit (jolt-nth p 0))) (_o$3405 (jolt-invoke emit (jolt-nth p 1)))) (jolt-vector _o$3404 _o$3405))))) (_a$3408 (jolt-get node (keyword #f "pairs")))) (jolt-invoke _a$3406 _a$3407 _a$3408))) (if (jolt= G__39 (keyword #f "quote")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-get node (keyword #f "form"))) (if (jolt= G__39 (keyword #f "throw")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-throw " (jolt-invoke emit (jolt-get node (keyword #f "expr"))) ")") (if (jolt= G__39 (keyword #f "try")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-try") node) (if (jolt= G__39 (keyword #f "regex")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-regex " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "source"))) ")") (if (jolt= G__39 (keyword #f "inst")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-inst-from-string " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "source"))) ")") (if (jolt= G__39 (keyword #f "uuid")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-uuid-from-string " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "source"))) ")") (if (jolt= G__39 (keyword #f "bigdec")) (jolt-invoke (var-deref "clojure.core" "str") "(jolt-bigdec-from-string " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "source"))) ")") (if (jolt= G__39 (keyword #f "the-ns")) (jolt-invoke (var-deref "clojure.core" "str") "(intern-ns! " (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name"))) ")") (if (jolt= G__39 (keyword #f "host-call")) (let* ((m (jolt-get node (keyword #f "method"))) (target (jolt-invoke emit (jolt-get node (keyword #f "target")))) (args (jolt-map emit (jolt-get node (keyword #f "args"))))) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "supported-host-methods") m)) (let* ((_a$3409 (var-deref "clojure.core" "str")) (_a$3410 "(jolt-host-call ") (_a$3411 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") m)) (_a$3412 " ") (_a$3413 target) (_a$3414 (if (jolt-empty? args) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " args)))) (_a$3415 ")")) (jolt-invoke _a$3409 _a$3410 _a$3411 _a$3412 _a$3413 _a$3414 _a$3415)) (let* ((_a$3416 (var-deref "clojure.core" "str")) (_a$3417 "(record-method-dispatch ") (_a$3418 target) (_a$3419 " ") (_a$3420 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") m)) (_a$3421 " (jolt-vector") (_a$3422 (if (jolt-empty? args) "" (jolt-invoke (var-deref "clojure.core" "str") " " (jolt-invoke (var-deref "clojure.string" "join") " " args)))) (_a$3423 "))")) (jolt-invoke _a$3416 _a$3417 _a$3418 _a$3419 _a$3420 _a$3421 _a$3422 _a$3423)))) (if (jolt= G__39 (keyword #f "let")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-let") node) (if (jolt= G__39 (keyword #f "loop")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-loop") node) (if (jolt= G__39 (keyword #f "recur")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-recur") node) (if (jolt= G__39 (keyword #f "fn")) (jolt-invoke (var-deref "jolt.backend-scheme" "emit-fn") node) (if (jolt= G__39 (keyword #f "def")) (if (jolt-truthy? (jolt-get node (keyword #f "no-init"))) (let* ((_a$3424 (var-deref "clojure.core" "str")) (_a$3425 "(declare-var! ") (_a$3426 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$3427 " ") (_a$3428 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$3429 ")")) (jolt-invoke _a$3424 _a$3425 _a$3426 _a$3427 _a$3428 _a$3429)) (if (jolt-truthy? (jolt-invoke (var-deref "jolt.backend-scheme" "jmeta-nonempty?") (jolt-get node (keyword #f "meta")))) (let* ((_a$3430 (var-deref "clojure.core" "str")) (_a$3431 "(def-var-with-meta! ") (_a$3432 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$3433 " ") (_a$3434 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$3435 " ") (_a$3436 (jolt-invoke emit (jolt-get node (keyword #f "init")))) (_a$3437 " ") (_a$3438 (jolt-invoke (var-deref "jolt.backend-scheme" "emit-quoted") (jolt-get node (keyword #f "meta")))) (_a$3439 ")")) (jolt-invoke _a$3430 _a$3431 _a$3432 _a$3433 _a$3434 _a$3435 _a$3436 _a$3437 _a$3438 _a$3439)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$3440 (var-deref "clojure.core" "str")) (_a$3441 "(def-var! ") (_a$3442 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "ns")))) (_a$3443 " ") (_a$3444 (jolt-invoke (var-deref "jolt.backend-scheme" "chez-str-lit") (jolt-get node (keyword #f "name")))) (_a$3445 " ") (_a$3446 (jolt-invoke emit (jolt-get node (keyword #f "init")))) (_a$3447 ")")) (jolt-invoke _a$3440 _a$3441 _a$3442 _a$3443 _a$3444 _a$3445 _a$3446 _a$3447)) jolt-nil))) (jolt-throw (let* ((_a$3448 (jolt-invoke (var-deref "clojure.core" "str") "emit: op not yet ported / unhandled: " (jolt-invoke (var-deref "clojure.core" "pr-str") (jolt-get node (keyword #f "op"))))) (_a$3449 (jolt-hash-map))) (jolt-ex-info _a$3448 _a$3449)))))))))))))))))))))))))))))))))))))) emit))) \ No newline at end of file diff --git a/host/chez/seed/prelude.ss b/host/chez/seed/prelude.ss new file mode 100644 index 0000000..f59e9f6 --- /dev/null +++ b/host/chez/seed/prelude.ss @@ -0,0 +1,1104 @@ +(guard (e (#t #f)) + (def-var! "clojure.core" "zero?" (letrec ((zero? (lambda (x) (let fnrec2316 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) (jolt= x 0) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "zero? requires a number, got: " x))))))) zero?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "pos?" (letrec ((pos? (lambda (x) (let fnrec2317 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) (> x 0) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "pos? requires a number, got: " x))))))) pos?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "every?" (letrec ((every? (lambda (pred coll) (let fnrec2318 ((pred pred) (coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-seq coll))) #t (if (jolt-truthy? (jolt-invoke pred (jolt-first coll))) (fnrec2318 pred (jolt-next coll)) #f)))))) every?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "empty?" (letrec ((empty? (lambda (coll) (let fnrec2319 ((coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") coll)) #t (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (jolt-zero? (jolt-count coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") coll)) (jolt-zero? (jolt-count coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "set?") coll)) (jolt-zero? (jolt-count coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") coll)) (jolt-zero? (jolt-count coll)) (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-seq coll))))))))))) empty?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "keys" (letrec ((keys (lambda (m) (let fnrec2320 ((m m)) (let* ((s (jolt-seq m))) (if (jolt-truthy? s) (jolt-map (lambda (e) (let fnrec2321 ((e e)) (jolt-nth e 0))) s) jolt-nil)))))) keys))) +(guard (e (#t #f)) + (def-var! "clojure.core" "vals" (letrec ((vals (lambda (m) (let fnrec2322 ((m m)) (let* ((s (jolt-seq m))) (if (jolt-truthy? s) (jolt-map (lambda (e) (let fnrec2323 ((e e)) (jolt-nth e 1))) s) jolt-nil)))))) vals))) +(guard (e (#t #f)) + (def-var! "clojure.core" "when" + (lambda (test . body) (let fnrec2324 ((test test) (body (list->cseq body))) (let* ((_a$2325 (var-deref "clojure.core" "__sqcat")) (_a$2326 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2327 (jolt-invoke (var-deref "clojure.core" "__sq1") test)) (_a$2328 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body)))) (jolt-invoke _a$2325 _a$2326 _a$2327 _a$2328))))) + (mark-macro! "clojure.core" "when")) +(guard (e (#t #f)) + (def-var! "clojure.core" "when-not" + (lambda (test . body) (let fnrec2329 ((test test) (body (list->cseq body))) (let* ((_a$2333 (var-deref "clojure.core" "__sqcat")) (_a$2334 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2335 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2330 (var-deref "clojure.core" "__sqcat")) (_a$2331 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "not"))) (_a$2332 (jolt-invoke (var-deref "clojure.core" "__sq1") test))) (jolt-invoke _a$2330 _a$2331 _a$2332)))) (_a$2336 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body)))) (jolt-invoke _a$2333 _a$2334 _a$2335 _a$2336))))) + (mark-macro! "clojure.core" "when-not")) +(guard (e (#t #f)) + (def-var! "clojure.core" "and" + (lambda exprs (let fnrec2337 ((exprs (list->cseq exprs))) (if (jolt-empty? exprs) #t (if (jolt-empty? (jolt-rest exprs)) (jolt-first exprs) (let* ((_a$2349 (var-deref "clojure.core" "__sqcat")) (_a$2350 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$2351 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2338 (var-deref "clojure.core" "__sqvec")) (_a$2339 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "and__13__auto"))) (_a$2340 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first exprs)))) (jolt-invoke _a$2338 _a$2339 _a$2340)))) (_a$2352 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2344 (var-deref "clojure.core" "__sqcat")) (_a$2345 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2346 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "and__13__auto"))) (_a$2347 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2341 (var-deref "clojure.core" "__sqcat")) (_a$2342 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "and"))) (_a$2343 (jolt-rest exprs))) (jolt-invoke _a$2341 _a$2342 _a$2343)))) (_a$2348 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "and__13__auto")))) (jolt-invoke _a$2344 _a$2345 _a$2346 _a$2347 _a$2348))))) (jolt-invoke _a$2349 _a$2350 _a$2351 _a$2352))))))) + (mark-macro! "clojure.core" "and")) +(guard (e (#t #f)) + (def-var! "clojure.core" "or" + (lambda exprs (let fnrec2353 ((exprs (list->cseq exprs))) (if (jolt-empty? exprs) jolt-nil (if (jolt-empty? (jolt-rest exprs)) (jolt-first exprs) (let* ((_a$2365 (var-deref "clojure.core" "__sqcat")) (_a$2366 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$2367 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2354 (var-deref "clojure.core" "__sqvec")) (_a$2355 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "or__14__auto"))) (_a$2356 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first exprs)))) (jolt-invoke _a$2354 _a$2355 _a$2356)))) (_a$2368 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2360 (var-deref "clojure.core" "__sqcat")) (_a$2361 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2362 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "or__14__auto"))) (_a$2363 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "or__14__auto"))) (_a$2364 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2357 (var-deref "clojure.core" "__sqcat")) (_a$2358 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "or"))) (_a$2359 (jolt-rest exprs))) (jolt-invoke _a$2357 _a$2358 _a$2359))))) (jolt-invoke _a$2360 _a$2361 _a$2362 _a$2363 _a$2364))))) (jolt-invoke _a$2365 _a$2366 _a$2367 _a$2368))))))) + (mark-macro! "clojure.core" "or")) +(guard (e (#t #f)) + (def-var! "clojure.core" "cond" + (lambda clauses (let fnrec2369 ((clauses (list->cseq clauses))) (if (jolt-empty? clauses) jolt-nil (let* ((_a$2373 (var-deref "clojure.core" "__sqcat")) (_a$2374 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2375 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first clauses))) (_a$2376 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth clauses 1))) (_a$2377 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2370 (var-deref "clojure.core" "__sqcat")) (_a$2371 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "cond"))) (_a$2372 (jolt-drop 2 clauses))) (jolt-invoke _a$2370 _a$2371 _a$2372))))) (jolt-invoke _a$2373 _a$2374 _a$2375 _a$2376 _a$2377)))))) + (mark-macro! "clojure.core" "cond")) +(guard (e (#t #f)) + (def-var! "clojure.core" "ns" + (lambda (nm . clauses) (let fnrec2378 ((nm nm) (clauses (list->cseq clauses))) (let* ((nm (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "seq?") nm))) (if (jolt-truthy? and__13__auto) (jolt= (jolt-symbol #f "with-meta") (jolt-first nm)) and__13__auto))) (jolt-invoke (var-deref "clojure.core" "second") nm) nm)) (calls (let* ((_a$2408 (lambda (acc clause) (let fnrec2379 ((acc acc) (clause clause)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") clause)) (let* ((head (jolt-first clause)) (args (jolt-rest clause))) (if (jolt= head (keyword #f "require")) (jolt-conj acc (let* ((_a$2384 (var-deref "clojure.core" "__sqcat")) (_a$2385 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "require"))) (_a$2386 (jolt-map (lambda (s) (let fnrec2380 ((s s)) (let* ((_a$2381 (var-deref "clojure.core" "__sqcat")) (_a$2382 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$2383 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$2381 _a$2382 _a$2383)))) args))) (jolt-invoke _a$2384 _a$2385 _a$2386))) (if (jolt= head (keyword #f "use")) (jolt-conj acc (let* ((_a$2391 (var-deref "clojure.core" "__sqcat")) (_a$2392 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "use"))) (_a$2393 (jolt-map (lambda (s) (let fnrec2387 ((s s)) (let* ((_a$2388 (var-deref "clojure.core" "__sqcat")) (_a$2389 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$2390 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$2388 _a$2389 _a$2390)))) args))) (jolt-invoke _a$2391 _a$2392 _a$2393))) (if (jolt= head (keyword #f "import")) (jolt-conj acc (let* ((_a$2398 (var-deref "clojure.core" "__sqcat")) (_a$2399 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "import"))) (_a$2400 (jolt-map (lambda (s) (let fnrec2394 ((s s)) (let* ((_a$2395 (var-deref "clojure.core" "__sqcat")) (_a$2396 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$2397 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$2395 _a$2396 _a$2397)))) args))) (jolt-invoke _a$2398 _a$2399 _a$2400))) (if (jolt= head (keyword #f "refer-clojure")) (jolt-conj acc (let* ((_a$2405 (var-deref "clojure.core" "__sqcat")) (_a$2406 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "refer-clojure"))) (_a$2407 (jolt-map (lambda (s) (let fnrec2401 ((s s)) (let* ((_a$2402 (var-deref "clojure.core" "__sqcat")) (_a$2403 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$2404 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$2402 _a$2403 _a$2404)))) args))) (jolt-invoke _a$2405 _a$2406 _a$2407))) (if (jolt-truthy? (keyword #f "else")) acc jolt-nil)))))) acc)))) (_a$2409 (jolt-vector)) (_a$2410 clauses)) (jolt-reduce _a$2408 _a$2409 _a$2410)))) (let* ((_a$2417 (var-deref "clojure.core" "__sqcat")) (_a$2418 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$2419 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2414 (var-deref "clojure.core" "__sqcat")) (_a$2415 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "in-ns"))) (_a$2416 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2411 (var-deref "clojure.core" "__sqcat")) (_a$2412 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$2413 (jolt-invoke (var-deref "clojure.core" "__sq1") nm))) (jolt-invoke _a$2411 _a$2412 _a$2413))))) (jolt-invoke _a$2414 _a$2415 _a$2416)))) (_a$2420 calls)) (jolt-invoke _a$2417 _a$2418 _a$2419 _a$2420)))))) + (mark-macro! "clojure.core" "ns")) +(guard (e (#t #f)) + (def-var! "clojure.core" "->" + (lambda (x . forms) (let fnrec2421 ((x x) (forms (list->cseq forms))) (if (jolt-empty? forms) x (let* ((form (jolt-first forms)) (threaded (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (let* ((_a$2422 (var-deref "clojure.core" "__sqcat")) (_a$2423 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first form))) (_a$2424 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$2425 (jolt-rest form))) (jolt-invoke _a$2422 _a$2423 _a$2424 _a$2425)) (let* ((_a$2426 (var-deref "clojure.core" "__sqcat")) (_a$2427 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$2428 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$2426 _a$2427 _a$2428))))) (let* ((_a$2429 (var-deref "clojure.core" "__sqcat")) (_a$2430 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->"))) (_a$2431 (jolt-invoke (var-deref "clojure.core" "__sq1") threaded)) (_a$2432 (jolt-rest forms))) (jolt-invoke _a$2429 _a$2430 _a$2431 _a$2432))))))) + (mark-macro! "clojure.core" "->")) +(guard (e (#t #f)) + (def-var! "clojure.core" "->>" + (lambda (x . forms) (let fnrec2433 ((x x) (forms (list->cseq forms))) (if (jolt-empty? forms) x (let* ((form (jolt-first forms)) (threaded (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (let* ((_a$2434 (var-deref "clojure.core" "__sqcat")) (_a$2435 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first form))) (_a$2436 (jolt-rest form)) (_a$2437 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$2434 _a$2435 _a$2436 _a$2437)) (let* ((_a$2438 (var-deref "clojure.core" "__sqcat")) (_a$2439 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$2440 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$2438 _a$2439 _a$2440))))) (let* ((_a$2441 (var-deref "clojure.core" "__sqcat")) (_a$2442 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->>"))) (_a$2443 (jolt-invoke (var-deref "clojure.core" "__sq1") threaded)) (_a$2444 (jolt-rest forms))) (jolt-invoke _a$2441 _a$2442 _a$2443 _a$2444))))))) + (mark-macro! "clojure.core" "->>")) +(guard (e (#t #f)) + (def-var! "clojure.core" "declare" + (lambda syms (let fnrec2445 ((syms (list->cseq syms))) (let* ((_a$2450 (var-deref "clojure.core" "__sqcat")) (_a$2451 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$2452 (jolt-map (lambda (s) (let fnrec2446 ((s s)) (let* ((_a$2447 (var-deref "clojure.core" "__sqcat")) (_a$2448 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$2449 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$2447 _a$2448 _a$2449)))) syms))) (jolt-invoke _a$2450 _a$2451 _a$2452))))) + (mark-macro! "clojure.core" "declare")) +(guard (e (#t #f)) + (def-var! "clojure.core" "destructure" (letrec ((destructure (lambda (bindings) (let fnrec2453 ((bindings bindings)) (let* ((find-or (lambda (or-map nm) (let fnrec2454 ((or-map or-map) (nm nm)) (let* ((_a$2460 (lambda (acc k) (let fnrec2455 ((acc acc) (k k)) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "symbol?") k))) (if (jolt-truthy? and__13__auto) (jolt= nm (jolt-invoke (var-deref "clojure.core" "name") k)) and__13__auto))) (let* ((_o$2456 #t) (_o$2457 (jolt-get or-map k))) (jolt-vector _o$2456 _o$2457)) acc)))) (_a$2461 (let* ((_o$2458 #f) (_o$2459 jolt-nil)) (jolt-vector _o$2458 _o$2459))) (_a$2462 (if (jolt-truthy? or-map) (jolt-keys or-map) (jolt-vector)))) (jolt-reduce _a$2460 _a$2461 _a$2462))))) (amp? (lambda (x) (let fnrec2463 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? and__13__auto) (jolt= "&" (jolt-invoke (var-deref "clojure.core" "name") x)) and__13__auto))))) (proc (letrec ((proc (lambda (pat init acc) (let fnrec2464 ((pat pat) (init init) (acc acc)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") pat)) (jolt-conj (jolt-conj acc pat) init) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") pat)) (let* ((g (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))) (n (jolt-count pat)) (vloop (letrec ((vloop (lambda (i idx a) (let fnrec2465 ((i i) (idx idx) (a a)) (if (< i n) (let* ((elem (jolt-nth pat i))) (if (jolt-truthy? (jolt-invoke amp? elem)) (let* ((_a$2474 vloop) (_a$2475 (+ i 2)) (_a$2476 idx) (_a$2477 (let* ((_a$2470 proc) (_a$2471 (jolt-nth pat (jolt-inc i))) (_a$2472 (let* ((_a$2466 (var-deref "clojure.core" "__sqcat")) (_a$2467 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "nthnext"))) (_a$2468 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$2469 (jolt-invoke (var-deref "clojure.core" "__sq1") idx))) (jolt-invoke _a$2466 _a$2467 _a$2468 _a$2469))) (_a$2473 a)) (jolt-invoke _a$2470 _a$2471 _a$2472 _a$2473)))) (jolt-invoke _a$2474 _a$2475 _a$2476 _a$2477)) (if (jolt= elem (keyword #f "as")) (let* ((_a$2478 vloop) (_a$2479 (+ i 2)) (_a$2480 idx) (_a$2481 (jolt-invoke proc (jolt-nth pat (jolt-inc i)) g a))) (jolt-invoke _a$2478 _a$2479 _a$2480 _a$2481)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$2487 vloop) (_a$2488 (jolt-inc i)) (_a$2489 (jolt-inc idx)) (_a$2490 (jolt-invoke proc elem (let* ((_a$2482 (var-deref "clojure.core" "__sqcat")) (_a$2483 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "nth"))) (_a$2484 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$2485 (jolt-invoke (var-deref "clojure.core" "__sq1") idx)) (_a$2486 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$2482 _a$2483 _a$2484 _a$2485 _a$2486)) a))) (jolt-invoke _a$2487 _a$2488 _a$2489 _a$2490)) jolt-nil)))) a))))) vloop))) (jolt-invoke vloop 0 0 (jolt-conj (jolt-conj acc g) init))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") pat)) (let* ((g (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))) (gm (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))) (coerce (let* ((_a$2523 (var-deref "clojure.core" "__sqcat")) (_a$2524 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2525 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2491 (var-deref "clojure.core" "__sqcat")) (_a$2492 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "sequential?"))) (_a$2493 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$2491 _a$2492 _a$2493)))) (_a$2526 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2518 (var-deref "clojure.core" "__sqcat")) (_a$2519 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2520 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2507 (var-deref "clojure.core" "__sqcat")) (_a$2508 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "and"))) (_a$2509 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2497 (var-deref "clojure.core" "__sqcat")) (_a$2498 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "="))) (_a$2499 (jolt-invoke (var-deref "clojure.core" "__sq1") 1)) (_a$2500 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2494 (var-deref "clojure.core" "__sqcat")) (_a$2495 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "count"))) (_a$2496 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$2494 _a$2495 _a$2496))))) (jolt-invoke _a$2497 _a$2498 _a$2499 _a$2500)))) (_a$2510 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2504 (var-deref "clojure.core" "__sqcat")) (_a$2505 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "map?"))) (_a$2506 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2501 (var-deref "clojure.core" "__sqcat")) (_a$2502 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "first"))) (_a$2503 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$2501 _a$2502 _a$2503))))) (jolt-invoke _a$2504 _a$2505 _a$2506))))) (jolt-invoke _a$2507 _a$2508 _a$2509 _a$2510)))) (_a$2521 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2511 (var-deref "clojure.core" "__sqcat")) (_a$2512 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "first"))) (_a$2513 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$2511 _a$2512 _a$2513)))) (_a$2522 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2514 (var-deref "clojure.core" "__sqcat")) (_a$2515 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "apply"))) (_a$2516 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "hash-map"))) (_a$2517 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$2514 _a$2515 _a$2516 _a$2517))))) (jolt-invoke _a$2518 _a$2519 _a$2520 _a$2521 _a$2522)))) (_a$2527 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$2523 _a$2524 _a$2525 _a$2526 _a$2527))) (or-map (jolt-get pat (keyword #f "or"))) (as-sym (jolt-get pat (keyword #f "as"))) (bound (jolt-conj (jolt-conj (jolt-conj (jolt-conj acc g) init) gm) coerce)) (base (if (jolt-truthy? as-sym) (jolt-conj (jolt-conj bound as-sym) gm) bound)) (group (lambda (a kw kind) (let fnrec2528 ((a a) (kw kw) (kind kind)) (let* ((names (jolt-get pat kw))) (if (jolt-truthy? names) (jolt-reduce (lambda (aa s) (let fnrec2529 ((aa aa) (s s)) (let* ((local (jolt-invoke (var-deref "clojure.core" "name") s)) (nsp (jolt-invoke (var-deref "clojure.core" "namespace") s)) (keyform (if (jolt= kind (keyword #f "kw")) (jolt-invoke (var-deref "clojure.core" "keyword") (if (jolt-truthy? nsp) (jolt-invoke (var-deref "clojure.core" "str") nsp "/" local) local)) (if (jolt= kind (keyword #f "str")) local (if (jolt-truthy? (keyword #f "else")) (let* ((_a$2530 (var-deref "clojure.core" "__sqcat")) (_a$2531 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$2532 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "symbol") nsp local)))) (jolt-invoke _a$2530 _a$2531 _a$2532)) jolt-nil)))) (fo (jolt-invoke find-or or-map local))) (let* ((_a$2542 (jolt-conj aa (jolt-invoke (var-deref "clojure.core" "symbol") local))) (_a$2543 (if (jolt-truthy? (jolt-nth fo 0)) (let* ((_a$2533 (var-deref "clojure.core" "__sqcat")) (_a$2534 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$2535 (jolt-invoke (var-deref "clojure.core" "__sq1") gm)) (_a$2536 (jolt-invoke (var-deref "clojure.core" "__sq1") keyform)) (_a$2537 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth fo 1)))) (jolt-invoke _a$2533 _a$2534 _a$2535 _a$2536 _a$2537)) (let* ((_a$2538 (var-deref "clojure.core" "__sqcat")) (_a$2539 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$2540 (jolt-invoke (var-deref "clojure.core" "__sq1") gm)) (_a$2541 (jolt-invoke (var-deref "clojure.core" "__sq1") keyform))) (jolt-invoke _a$2538 _a$2539 _a$2540 _a$2541))))) (jolt-conj _a$2542 _a$2543))))) a names) a))))) (g1 (jolt-invoke group base (keyword #f "keys") (keyword #f "kw"))) (g2 (jolt-invoke group g1 (keyword #f "strs") (keyword #f "str"))) (g3 (jolt-invoke group g2 (keyword #f "syms") (keyword #f "sym")))) (let* ((_a$2549 (lambda (a k) (let fnrec2544 ((a a) (k k)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") k)) a (jolt-invoke proc k (let* ((_a$2545 (var-deref "clojure.core" "__sqcat")) (_a$2546 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$2547 (jolt-invoke (var-deref "clojure.core" "__sq1") gm)) (_a$2548 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-get pat k)))) (jolt-invoke _a$2545 _a$2546 _a$2547 _a$2548)) a))))) (_a$2550 g3) (_a$2551 (jolt-keys pat))) (jolt-reduce _a$2549 _a$2550 _a$2551))) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "unsupported destructuring pattern: " (jolt-invoke (var-deref "clojure.core" "pr-str") pat))) jolt-nil)))))))) proc)) (ploop (letrec ((ploop (lambda (i acc) (let fnrec2552 ((i i) (acc acc)) (if (< i (jolt-count bindings)) (let* ((_a$2557 ploop) (_a$2558 (+ i 2)) (_a$2559 (let* ((_a$2553 proc) (_a$2554 (jolt-nth bindings i)) (_a$2555 (jolt-nth bindings (jolt-inc i))) (_a$2556 acc)) (jolt-invoke _a$2553 _a$2554 _a$2555 _a$2556)))) (jolt-invoke _a$2557 _a$2558 _a$2559)) acc))))) ploop))) (jolt-invoke ploop 0 (jolt-vector))))))) destructure))) +(guard (e (#t #f)) + (def-var! "clojure.core" "let" + (lambda (bindings . body) (let fnrec2560 ((bindings bindings) (body (list->cseq body))) (let* ((_a$2561 (var-deref "clojure.core" "__sqcat")) (_a$2562 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$2563 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "destructure") bindings)))) (_a$2564 body)) (jolt-invoke _a$2561 _a$2562 _a$2563 _a$2564))))) + (mark-macro! "clojure.core" "let")) +(guard (e (#t #f)) + (def-var! "clojure.core" "loop" + (lambda (bindings . body) (let fnrec2565 ((bindings bindings) (body (list->cseq body))) (let* ((d (jolt-invoke (var-deref "clojure.core" "destructure") bindings))) (if (jolt= d bindings) (let* ((_a$2566 (var-deref "clojure.core" "__sqcat")) (_a$2567 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "loop*"))) (_a$2568 (jolt-invoke (var-deref "clojure.core" "__sq1") bindings)) (_a$2569 body)) (jolt-invoke _a$2566 _a$2567 _a$2568 _a$2569)) (let* ((bs (jolt-invoke (var-deref "clojure.core" "take-nth") 2 bindings)) (vs (jolt-invoke (var-deref "clojure.core" "take-nth") 2 (jolt-drop 1 bindings))) (gs (jolt-map (lambda (b) (let fnrec2570 ((b b)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") b)) b (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym"))))))) bs)) (outer (let* ((_a$2572 (lambda (acc t) (let fnrec2571 ((acc acc) (t t)) (let* ((b (jolt-nth t 0)) (v (jolt-nth t 1)) (g (jolt-nth t 2))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") b)) (jolt-conj (jolt-conj acc g) v) (jolt-conj (jolt-conj (jolt-conj (jolt-conj acc g) v) b) g)))))) (_a$2573 (jolt-vector)) (_a$2574 (jolt-map jolt-vector bs vs gs))) (jolt-reduce _a$2572 _a$2573 _a$2574))) (inner (let* ((_a$2578 (lambda (acc t) (let fnrec2575 ((acc acc) (t t)) (let* ((_a$2576 (jolt-conj acc (jolt-nth t 0))) (_a$2577 (jolt-nth t 1))) (jolt-conj _a$2576 _a$2577))))) (_a$2579 (jolt-vector)) (_a$2580 (jolt-map jolt-vector bs gs))) (jolt-reduce _a$2578 _a$2579 _a$2580))) (loopv (let* ((_a$2582 (lambda (acc g) (let fnrec2581 ((acc acc) (g g)) (jolt-conj (jolt-conj acc g) g)))) (_a$2583 (jolt-vector)) (_a$2584 gs)) (jolt-reduce _a$2582 _a$2583 _a$2584)))) (let* ((_a$2593 (var-deref "clojure.core" "__sqcat")) (_a$2594 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$2595 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") outer))) (_a$2596 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2589 (var-deref "clojure.core" "__sqcat")) (_a$2590 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "loop*"))) (_a$2591 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") loopv))) (_a$2592 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2585 (var-deref "clojure.core" "__sqcat")) (_a$2586 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$2587 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") inner))) (_a$2588 body)) (jolt-invoke _a$2585 _a$2586 _a$2587 _a$2588))))) (jolt-invoke _a$2589 _a$2590 _a$2591 _a$2592))))) (jolt-invoke _a$2593 _a$2594 _a$2595 _a$2596)))))))) + (mark-macro! "clojure.core" "loop")) +(guard (e (#t #f)) + (def-var! "clojure.core" "fn" + (lambda raw (let fnrec2597 ((raw (list->cseq raw))) (let* ((nm (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first raw))) (jolt-first raw) jolt-nil)) (aftn (if (jolt-truthy? nm) (jolt-next raw) raw)) (unhint (lambda (x) (let fnrec2598 ((x x)) (if (jolt-truthy? (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") x)) (jolt= (jolt-symbol #f "with-meta") (jolt-first x)) #f)) (jolt-nth x 1) x)))) (md (letrec ((go (lambda (ps nps lets) (let fnrec2599 ((ps ps) (nps nps) (lets lets)) (if (jolt-truthy? (jolt-seq ps)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first ps))) (let* ((_a$2600 go) (_a$2601 (jolt-next ps)) (_a$2602 (jolt-conj nps (jolt-first ps))) (_a$2603 lets)) (jolt-invoke _a$2600 _a$2601 _a$2602 _a$2603)) (let* ((g (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym")))))) (let* ((_a$2604 go) (_a$2605 (jolt-next ps)) (_a$2606 (jolt-conj nps g)) (_a$2607 (jolt-conj (jolt-conj lets (jolt-first ps)) g))) (jolt-invoke _a$2604 _a$2605 _a$2606 _a$2607)))) (let* ((_o$2608 nps) (_o$2609 lets)) (jolt-vector _o$2608 _o$2609))))))) go)) (mk (lambda (sig) (let fnrec2610 ((sig sig)) (let* ((ps (jolt-invoke unhint (jolt-first sig))) (hinted (jolt-not (jolt= ps (jolt-first sig)))) (r (let* ((_a$2611 md) (_a$2612 (jolt-seq ps)) (_a$2613 (jolt-vector)) (_a$2614 (jolt-vector))) (jolt-invoke _a$2611 _a$2612 _a$2613 _a$2614)))) (if (jolt-truthy? (if (jolt-empty? (jolt-nth r 1)) (jolt-not hinted) #f)) sig (let* ((pv (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-nth r 0))) (lv (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-nth r 1)))) (if (jolt-empty? (jolt-nth r 1)) (let* ((_a$2615 (var-deref "clojure.core" "__sqcat")) (_a$2616 (jolt-invoke (var-deref "clojure.core" "__sq1") pv)) (_a$2617 (jolt-rest sig))) (jolt-invoke _a$2615 _a$2616 _a$2617)) (let* ((_a$2622 (var-deref "clojure.core" "__sqcat")) (_a$2623 (jolt-invoke (var-deref "clojure.core" "__sq1") pv)) (_a$2624 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2618 (var-deref "clojure.core" "__sqcat")) (_a$2619 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$2620 (jolt-invoke (var-deref "clojure.core" "__sq1") lv)) (_a$2621 (jolt-rest sig))) (jolt-invoke _a$2618 _a$2619 _a$2620 _a$2621))))) (jolt-invoke _a$2622 _a$2623 _a$2624)))))))))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") (jolt-invoke unhint (jolt-first aftn)))) (let* ((a (jolt-invoke mk aftn))) (if (jolt-truthy? nm) (let* ((_a$2625 (var-deref "clojure.core" "__sqcat")) (_a$2626 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$2627 (jolt-invoke (var-deref "clojure.core" "__sq1") nm)) (_a$2628 a)) (jolt-invoke _a$2625 _a$2626 _a$2627 _a$2628)) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*")) a))) (let* ((as (jolt-invoke (var-deref "clojure.core" "vec") (jolt-map mk aftn)))) (if (jolt-truthy? nm) (let* ((_a$2629 (var-deref "clojure.core" "__sqcat")) (_a$2630 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$2631 (jolt-invoke (var-deref "clojure.core" "__sq1") nm)) (_a$2632 as)) (jolt-invoke _a$2629 _a$2630 _a$2631 _a$2632)) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*")) as)))))))) + (mark-macro! "clojure.core" "fn")) +(guard (e (#t #f)) + (def-var! "clojure.core" "defn" + (lambda (fn-name . body) (let fnrec2633 ((fn-name fn-name) (body (list->cseq body))) (let* ((body (if (jolt-truthy? (let* ((and__13__auto (jolt-seq body))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "string?") (jolt-first body)) and__13__auto))) (jolt-rest body) body)) (body (if (jolt-truthy? (let* ((and__13__auto (jolt-seq body))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "map?") (jolt-first body)))) (if (jolt-truthy? and__13__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first body))) and__13__auto)) and__13__auto))) (jolt-rest body) body)) (fn-only-name (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") fn-name)) fn-name (jolt-first (jolt-rest fn-name))))) (let* ((_a$2638 (var-deref "clojure.core" "__sqcat")) (_a$2639 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$2640 (jolt-invoke (var-deref "clojure.core" "__sq1") fn-name)) (_a$2641 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2634 (var-deref "clojure.core" "__sqcat")) (_a$2635 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$2636 (jolt-invoke (var-deref "clojure.core" "__sq1") fn-only-name)) (_a$2637 body)) (jolt-invoke _a$2634 _a$2635 _a$2636 _a$2637))))) (jolt-invoke _a$2638 _a$2639 _a$2640 _a$2641)))))) + (mark-macro! "clojure.core" "defn")) +(guard (e (#t #f)) + (def-var! "clojure.core" "defn-" + (lambda (fn-name . body) (let fnrec2642 ((fn-name fn-name) (body (list->cseq body))) (let* ((_a$2643 (var-deref "clojure.core" "__sqcat")) (_a$2644 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defn"))) (_a$2645 (jolt-invoke (var-deref "clojure.core" "__sq1") fn-name)) (_a$2646 body)) (jolt-invoke _a$2643 _a$2644 _a$2645 _a$2646))))) + (mark-macro! "clojure.core" "defn-")) +(guard (e (#t #f)) + (def-var! "clojure.core" "fresh-sym" (letrec ((fresh-sym (lambda () (let fnrec2647 () (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym")))))))) fresh-sym))) +(guard (e (#t #f)) + (def-var! "clojure.core" "cond->" + (lambda (expr . clauses) (let fnrec2648 ((expr expr) (clauses (list->cseq clauses))) (let* ((step (letrec ((step (lambda (prev cls) (let fnrec2649 ((prev prev) (cls cls)) (if (jolt-empty? cls) prev (let* ((t (jolt-first cls)) (f (jolt-nth cls 1)) (gn (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (call (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") f)) (let* ((_a$2650 (var-deref "clojure.core" "__sqcat")) (_a$2651 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first f))) (_a$2652 (jolt-invoke (var-deref "clojure.core" "__sq1") prev)) (_a$2653 (jolt-rest f))) (jolt-invoke _a$2650 _a$2651 _a$2652 _a$2653)) (let* ((_a$2654 (var-deref "clojure.core" "__sqcat")) (_a$2655 (jolt-invoke (var-deref "clojure.core" "__sq1") f)) (_a$2656 (jolt-invoke (var-deref "clojure.core" "__sq1") prev))) (jolt-invoke _a$2654 _a$2655 _a$2656))))) (let* ((_a$2665 (var-deref "clojure.core" "__sqcat")) (_a$2666 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$2667 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2662 (var-deref "clojure.core" "__sqvec")) (_a$2663 (jolt-invoke (var-deref "clojure.core" "__sq1") gn)) (_a$2664 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2657 (var-deref "clojure.core" "__sqcat")) (_a$2658 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2659 (jolt-invoke (var-deref "clojure.core" "__sq1") t)) (_a$2660 (jolt-invoke (var-deref "clojure.core" "__sq1") call)) (_a$2661 (jolt-invoke (var-deref "clojure.core" "__sq1") prev))) (jolt-invoke _a$2657 _a$2658 _a$2659 _a$2660 _a$2661))))) (jolt-invoke _a$2662 _a$2663 _a$2664)))) (_a$2668 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke step gn (jolt-drop 2 cls))))) (jolt-invoke _a$2665 _a$2666 _a$2667 _a$2668)))))))) step)) (g0 (jolt-invoke (var-deref "clojure.core" "fresh-sym")))) (let* ((_a$2672 (var-deref "clojure.core" "__sqcat")) (_a$2673 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$2674 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2669 (var-deref "clojure.core" "__sqvec")) (_a$2670 (jolt-invoke (var-deref "clojure.core" "__sq1") g0)) (_a$2671 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$2669 _a$2670 _a$2671)))) (_a$2675 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke step g0 clauses)))) (jolt-invoke _a$2672 _a$2673 _a$2674 _a$2675)))))) + (mark-macro! "clojure.core" "cond->")) +(guard (e (#t #f)) + (def-var! "clojure.core" "case" + (lambda (expr . clauses) (let fnrec2676 ((expr expr) (clauses (list->cseq clauses))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (mk-const (lambda (c) (let fnrec2677 ((c c)) (if (jolt-truthy? (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "symbol?") c))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "seq?") c)))) (let* ((_a$2678 (var-deref "clojure.core" "__sqcat")) (_a$2679 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$2680 (jolt-invoke (var-deref "clojure.core" "__sq1") c))) (jolt-invoke _a$2678 _a$2679 _a$2680)) c)))) (mk-test (lambda (c) (let fnrec2681 ((c c)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") c)) (let* ((_a$2687 (var-deref "clojure.core" "__sqcat")) (_a$2688 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "or"))) (_a$2689 (jolt-map (lambda (v) (let fnrec2682 ((v v)) (let* ((_a$2683 (var-deref "clojure.core" "__sqcat")) (_a$2684 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "="))) (_a$2685 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$2686 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke mk-const v)))) (jolt-invoke _a$2683 _a$2684 _a$2685 _a$2686)))) c))) (jolt-invoke _a$2687 _a$2688 _a$2689)) (let* ((_a$2690 (var-deref "clojure.core" "__sqcat")) (_a$2691 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "="))) (_a$2692 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$2693 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke mk-const c)))) (jolt-invoke _a$2690 _a$2691 _a$2692 _a$2693)))))) (collect (letrec ((collect (lambda (cls acc) (let fnrec2694 ((cls cls) (acc acc)) (if (jolt-truthy? (let* ((or__14__auto (jolt-empty? cls))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-empty? (jolt-rest cls))))) acc (let* ((t (jolt-first cls)) (acc (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") t)) (jolt-reduce jolt-conj acc t) (jolt-conj acc t)))) (jolt-invoke collect (jolt-drop 2 cls) acc))))))) collect)) (first-dup (letrec ((fd (lambda (items seen) (let fnrec2695 ((items items) (seen seen)) (if (jolt-empty? items) jolt-nil (let* ((x (jolt-first items))) (if (jolt-truthy? (jolt-reduce (lambda (f s) (let fnrec2696 ((f f) (s s)) (let* ((or__14__auto f)) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= s x))))) #f seen)) (jolt-vector x) (let* ((_a$2697 fd) (_a$2698 (jolt-rest items)) (_a$2699 (jolt-conj seen x))) (jolt-invoke _a$2697 _a$2698 _a$2699))))))))) fd)) (dup (let* ((_a$2700 first-dup) (_a$2701 (jolt-invoke collect clauses (jolt-vector))) (_a$2702 (jolt-vector))) (jolt-invoke _a$2700 _a$2701 _a$2702))) (build (letrec ((build (lambda (cls) (let fnrec2703 ((cls cls)) (if (jolt-empty? cls) (let* ((_a$2712 (var-deref "clojure.core" "__sqcat")) (_a$2713 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "throw"))) (_a$2714 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2708 (var-deref "clojure.core" "__sqcat")) (_a$2709 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "ex-info"))) (_a$2710 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2704 (var-deref "clojure.core" "__sqcat")) (_a$2705 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "str"))) (_a$2706 (jolt-invoke (var-deref "clojure.core" "__sq1") "No matching clause: ")) (_a$2707 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$2704 _a$2705 _a$2706 _a$2707)))) (_a$2711 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqmap"))))) (jolt-invoke _a$2708 _a$2709 _a$2710 _a$2711))))) (jolt-invoke _a$2712 _a$2713 _a$2714)) (if (jolt-empty? (jolt-rest cls)) (jolt-first cls) (let* ((_a$2715 (var-deref "clojure.core" "__sqcat")) (_a$2716 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2717 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke mk-test (jolt-first cls)))) (_a$2718 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth cls 1))) (_a$2719 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke build (jolt-drop 2 cls))))) (jolt-invoke _a$2715 _a$2716 _a$2717 _a$2718 _a$2719)))))))) build))) (if (jolt-truthy? dup) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Duplicate case test constant: " (jolt-first dup))) (let* ((_a$2723 (var-deref "clojure.core" "__sqcat")) (_a$2724 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$2725 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2720 (var-deref "clojure.core" "__sqvec")) (_a$2721 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$2722 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$2720 _a$2721 _a$2722)))) (_a$2726 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke build clauses)))) (jolt-invoke _a$2723 _a$2724 _a$2725 _a$2726))))))) + (mark-macro! "clojure.core" "case")) +(guard (e (#t #f)) + (def-var! "clojure.core" "for" + (lambda (bindings body) (let fnrec2727 ((bindings bindings) (body body)) (let* ((scan (letrec ((scan (lambda (bvec i bind coll mods) (let fnrec2728 ((bvec bvec) (i i) (bind bind) (coll coll) (mods mods)) (if (jolt-truthy? (let* ((and__13__auto (< i (jolt-count bvec)))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "keyword?") (jolt-nth bvec i)) and__13__auto))) (let* ((k (jolt-nth bvec i)) (v (jolt-nth bvec (jolt-inc i)))) (if (jolt= k (keyword #f "when")) (let* ((_a$2731 scan) (_a$2732 bvec) (_a$2733 (+ i 2)) (_a$2734 bind) (_a$2735 coll) (_a$2736 (jolt-conj mods (let* ((_o$2729 (keyword #f "when")) (_o$2730 v)) (jolt-vector _o$2729 _o$2730))))) (jolt-invoke _a$2731 _a$2732 _a$2733 _a$2734 _a$2735 _a$2736)) (if (jolt= k (keyword #f "let")) (let* ((_a$2739 scan) (_a$2740 bvec) (_a$2741 (+ i 2)) (_a$2742 bind) (_a$2743 coll) (_a$2744 (jolt-conj mods (let* ((_o$2737 (keyword #f "let")) (_o$2738 v)) (jolt-vector _o$2737 _o$2738))))) (jolt-invoke _a$2739 _a$2740 _a$2741 _a$2742 _a$2743 _a$2744)) (if (jolt= k (keyword #f "while")) (let* ((_a$2753 scan) (_a$2754 bvec) (_a$2755 (+ i 2)) (_a$2756 bind) (_a$2757 (let* ((_a$2749 (var-deref "clojure.core" "__sqcat")) (_a$2750 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "take-while"))) (_a$2751 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2745 (var-deref "clojure.core" "__sqcat")) (_a$2746 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$2747 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") bind)))) (_a$2748 (jolt-invoke (var-deref "clojure.core" "__sq1") v))) (jolt-invoke _a$2745 _a$2746 _a$2747 _a$2748)))) (_a$2752 (jolt-invoke (var-deref "clojure.core" "__sq1") coll))) (jolt-invoke _a$2749 _a$2750 _a$2751 _a$2752))) (_a$2758 mods)) (jolt-invoke _a$2753 _a$2754 _a$2755 _a$2756 _a$2757 _a$2758)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke scan bvec (jolt-inc i) bind coll mods) jolt-nil))))) (let* ((_o$2759 i) (_o$2760 bind) (_o$2761 coll) (_o$2762 mods)) (jolt-vector _o$2759 _o$2760 _o$2761 _o$2762))))))) scan)) (parse-groups (letrec ((parse-groups (lambda (bvec i groups) (let fnrec2763 ((bvec bvec) (i i) (groups groups)) (if (>= i (jolt-count bvec)) groups (let* ((r (let* ((_a$2764 scan) (_a$2765 bvec) (_a$2766 (+ i 2)) (_a$2767 (jolt-nth bvec i)) (_a$2768 (jolt-nth bvec (jolt-inc i))) (_a$2769 (jolt-vector))) (jolt-invoke _a$2764 _a$2765 _a$2766 _a$2767 _a$2768 _a$2769)))) (let* ((_a$2773 parse-groups) (_a$2774 bvec) (_a$2775 (jolt-nth r 0)) (_a$2776 (jolt-conj groups (let* ((_o$2770 (jolt-nth r 1)) (_o$2771 (jolt-nth r 2)) (_o$2772 (jolt-nth r 3))) (jolt-vector _o$2770 _o$2771 _o$2772))))) (jolt-invoke _a$2773 _a$2774 _a$2775 _a$2776)))))))) parse-groups)) (wrap-mods (letrec ((wrap-mods (lambda (mods inner) (let fnrec2777 ((mods mods) (inner inner)) (if (jolt-empty? mods) inner (let* ((m (jolt-first mods)) (sub (jolt-invoke wrap-mods (jolt-rest mods) inner))) (if (jolt= (jolt-first m) (keyword #f "when")) (let* ((_a$2778 (var-deref "clojure.core" "__sqcat")) (_a$2779 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2780 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth m 1))) (_a$2781 (jolt-invoke (var-deref "clojure.core" "__sq1") sub)) (_a$2782 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec"))))) (jolt-invoke _a$2778 _a$2779 _a$2780 _a$2781 _a$2782)) (let* ((_a$2783 (var-deref "clojure.core" "__sqcat")) (_a$2784 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$2785 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth m 1))) (_a$2786 (jolt-invoke (var-deref "clojure.core" "__sq1") sub))) (jolt-invoke _a$2783 _a$2784 _a$2785 _a$2786))))))))) wrap-mods)) (build (letrec ((build (lambda (idx groups) (let fnrec2787 ((idx idx) (groups groups)) (let* ((g (jolt-nth groups idx)) (my-bind (jolt-nth g 0)) (my-coll (jolt-nth g 1)) (my-mods (jolt-nth g 2)) (is-last (jolt= idx (jolt-dec (jolt-count groups))))) (if (jolt-truthy? (let* ((and__13__auto is-last)) (if (jolt-truthy? and__13__auto) (jolt-empty? my-mods) and__13__auto))) (let* ((_a$2792 (var-deref "clojure.core" "__sqcat")) (_a$2793 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "map"))) (_a$2794 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2788 (var-deref "clojure.core" "__sqcat")) (_a$2789 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$2790 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") my-bind)))) (_a$2791 (jolt-invoke (var-deref "clojure.core" "__sq1") body))) (jolt-invoke _a$2788 _a$2789 _a$2790 _a$2791)))) (_a$2795 (jolt-invoke (var-deref "clojure.core" "__sq1") my-coll))) (jolt-invoke _a$2792 _a$2793 _a$2794 _a$2795)) (let* ((base (if (jolt-truthy? is-last) (let* ((_a$2796 (var-deref "clojure.core" "__sqcat")) (_a$2797 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "list"))) (_a$2798 (jolt-invoke (var-deref "clojure.core" "__sq1") body))) (jolt-invoke _a$2796 _a$2797 _a$2798)) (jolt-invoke build (jolt-inc idx) groups)))) (let* ((_a$2803 (var-deref "clojure.core" "__sqcat")) (_a$2804 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "mapcat"))) (_a$2805 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2799 (var-deref "clojure.core" "__sqcat")) (_a$2800 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$2801 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") my-bind)))) (_a$2802 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke wrap-mods my-mods base)))) (jolt-invoke _a$2799 _a$2800 _a$2801 _a$2802)))) (_a$2806 (jolt-invoke (var-deref "clojure.core" "__sq1") my-coll))) (jolt-invoke _a$2803 _a$2804 _a$2805 _a$2806))))))))) build))) (if (>= (jolt-count bindings) 2) (jolt-invoke build 0 (jolt-invoke parse-groups bindings 0 (jolt-vector))) body))))) + (mark-macro! "clojure.core" "for")) +(guard (e (#t #f)) + (def-var! "clojure.core" "doseq" + (lambda (bindings . body) (let fnrec2807 ((bindings bindings) (body (list->cseq body))) (let* ((_a$2819 (var-deref "clojure.core" "__sqcat")) (_a$2820 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$2821 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2816 (var-deref "clojure.core" "__sqcat")) (_a$2817 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "count"))) (_a$2818 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2812 (var-deref "clojure.core" "__sqcat")) (_a$2813 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "for"))) (_a$2814 (jolt-invoke (var-deref "clojure.core" "__sq1") bindings)) (_a$2815 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2808 (var-deref "clojure.core" "__sqcat")) (_a$2809 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$2810 body) (_a$2811 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$2808 _a$2809 _a$2810 _a$2811))))) (jolt-invoke _a$2812 _a$2813 _a$2814 _a$2815))))) (jolt-invoke _a$2816 _a$2817 _a$2818)))) (_a$2822 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$2819 _a$2820 _a$2821 _a$2822))))) + (mark-macro! "clojure.core" "doseq")) +(guard (e (#t #f)) + (def-var! "clojure.core" "when-let" + (lambda (bindings . body) (let fnrec2823 ((bindings bindings) (body (list->cseq body))) (let* ((form (jolt-invoke bindings 0)) (tst (jolt-invoke bindings 1))) (let* ((_a$2839 (var-deref "clojure.core" "__sqcat")) (_a$2840 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$2841 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2824 (var-deref "clojure.core" "__sqvec")) (_a$2825 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__15__auto"))) (_a$2826 (jolt-invoke (var-deref "clojure.core" "__sq1") tst))) (jolt-invoke _a$2824 _a$2825 _a$2826)))) (_a$2842 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2834 (var-deref "clojure.core" "__sqcat")) (_a$2835 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$2836 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__15__auto"))) (_a$2837 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2830 (var-deref "clojure.core" "__sqcat")) (_a$2831 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$2832 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2827 (var-deref "clojure.core" "__sqvec")) (_a$2828 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$2829 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__15__auto")))) (jolt-invoke _a$2827 _a$2828 _a$2829)))) (_a$2833 body)) (jolt-invoke _a$2830 _a$2831 _a$2832 _a$2833)))) (_a$2838 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$2834 _a$2835 _a$2836 _a$2837 _a$2838))))) (jolt-invoke _a$2839 _a$2840 _a$2841 _a$2842)))))) + (mark-macro! "clojure.core" "when-let")) +(guard (e (#t #f)) + (def-var! "clojure.core" "lazy-seq" + (lambda body (let fnrec2843 ((body (list->cseq body))) (let* ((_a$2851 (var-deref "clojure.core" "__sqcat")) (_a$2852 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-lazy-seq"))) (_a$2853 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2847 (var-deref "clojure.core" "__sqcat")) (_a$2848 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$2849 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$2850 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$2844 (var-deref "clojure.core" "__sqcat")) (_a$2845 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "coll->cells"))) (_a$2846 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body)))) (jolt-invoke _a$2844 _a$2845 _a$2846))))) (jolt-invoke _a$2847 _a$2848 _a$2849 _a$2850))))) (jolt-invoke _a$2851 _a$2852 _a$2853))))) + (mark-macro! "clojure.core" "lazy-seq")) +(guard (e (#t #f)) + (def-var! "clojure.core" "lazy-cat" + (lambda colls (let fnrec2854 ((colls (list->cseq colls))) (let* ((_a$2859 (var-deref "clojure.core" "__sqcat")) (_a$2860 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "concat"))) (_a$2861 (jolt-map (lambda (c) (let fnrec2855 ((c c)) (let* ((_a$2856 (var-deref "clojure.core" "__sqcat")) (_a$2857 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "lazy-seq"))) (_a$2858 (jolt-invoke (var-deref "clojure.core" "__sq1") c))) (jolt-invoke _a$2856 _a$2857 _a$2858)))) colls))) (jolt-invoke _a$2859 _a$2860 _a$2861))))) + (mark-macro! "clojure.core" "lazy-cat")) +(guard (e (#t #f)) + (def-var! "clojure.core" "not=" (letrec ((not= (case-lambda ((x) (let fnrec2862 ((x x)) #f)) ((x y) (let fnrec2863 ((x x) (y y)) (jolt-not (jolt= x y)))) ((x y . more) (let fnrec2864 ((x x) (y y) (more (list->cseq more))) (jolt-not (jolt-apply jolt= x y more))))))) not=))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unreduced" (letrec ((unreduced (lambda (x) (let fnrec2865 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "reduced?") x)) (jolt-invoke (var-deref "clojure.core" "deref") x) x))))) unreduced))) +(guard (e (#t #f)) + (def-var! "clojure.core" "second" (letrec ((second (lambda (coll) (let fnrec2866 ((coll coll)) (jolt-first (jolt-next coll)))))) second))) +(guard (e (#t #f)) + (def-var! "clojure.core" "peek" (letrec ((peek (lambda (coll) (let fnrec2867 ((coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") coll)) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (if (jolt-zero? (jolt-count coll)) jolt-nil (jolt-nth coll (jolt-dec (jolt-count coll)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") coll)) (jolt-first coll) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "peek not supported on: " coll)) jolt-nil)))))))) peek))) +(guard (e (#t #f)) + (def-var! "clojure.core" "subvec" (letrec ((subvec (case-lambda ((v start) (let fnrec2868 ((v v) (start start)) (jolt-invoke subvec v start (jolt-count v)))) ((v start end) (let fnrec2869 ((v v) (start start) (end end)) (begin (if (jolt-not (jolt-invoke (var-deref "clojure.core" "vector?") v)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "subvec requires a vector")) jolt-nil) (let* ((coerce (lambda (x) (let fnrec2870 ((x x)) (if (jolt-not (jolt-invoke (var-deref "clojure.core" "number?") x)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "subvec index must be a number")) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "not=") x x)) 0 (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "long") x) jolt-nil)))))) (s (jolt-invoke coerce start)) (e (jolt-invoke coerce end))) (begin (if (jolt-truthy? (let* ((or__14__auto (< s 0))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (< e s))) (if (jolt-truthy? or__14__auto) or__14__auto (< (jolt-count v) e)))))) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "subvec index out of range: " s " " e)) jolt-nil) (let* ((i s) (acc (jolt-vector))) (let loop2871 ((i i) (acc acc)) (if (< i e) (let* ((_a$2872 (jolt-inc i)) (_a$2873 (jolt-conj acc (jolt-nth v i)))) (loop2871 _a$2872 _a$2873)) acc))))))))))) subvec))) +(guard (e (#t #f)) + (def-var! "clojure.core" "mapv" (letrec ((mapv (lambda (f . colls) (let fnrec2874 ((f f) (colls (list->cseq colls))) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-apply jolt-map f colls)))))) mapv))) +(guard (e (#t #f)) + (def-var! "clojure.core" "update" (letrec ((update (lambda (m k f . args) (let fnrec2875 ((m m) (k k) (f f) (args (list->cseq args))) (jolt-assoc m k (jolt-apply f (jolt-get m k) args)))))) update))) +(guard (e (#t #f)) + (def-var! "clojure.core" "vreset!" (letrec ((vreset! (lambda (vol newval) (let fnrec1680 ((vol vol) (newval newval)) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") vol (keyword #f "val") newval) newval))))) vreset!))) +(guard (e (#t #f)) + (def-var! "clojure.core" "vswap!" (letrec ((vswap! (lambda (vol f . args) (let fnrec1681 ((vol vol) (f f) (args (list->cseq args))) (jolt-invoke (var-deref "clojure.core" "vreset!") vol (jolt-apply f (jolt-get vol (keyword #f "val")) args)))))) vswap!))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ffirst" (letrec ((ffirst (lambda (coll) (let fnrec1682 ((coll coll)) (jolt-first (jolt-first coll)))))) ffirst))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nfirst" (letrec ((nfirst (lambda (coll) (let fnrec1683 ((coll coll)) (jolt-next (jolt-first coll)))))) nfirst))) +(guard (e (#t #f)) + (def-var! "clojure.core" "fnext" (letrec ((fnext (lambda (coll) (let fnrec1684 ((coll coll)) (jolt-first (jolt-next coll)))))) fnext))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nnext" (letrec ((nnext (lambda (coll) (let fnrec1685 ((coll coll)) (jolt-next (jolt-next coll)))))) nnext))) +(guard (e (#t #f)) + (def-var! "clojure.core" "last" (letrec ((last (lambda (s) (let fnrec1686 ((s s)) (if (jolt-truthy? (jolt-next s)) (fnrec1686 (jolt-next s)) (jolt-first s)))))) last))) +(guard (e (#t #f)) + (def-var! "clojure.core" "butlast" (letrec ((butlast (lambda (s) (let fnrec1687 ((s s)) (let* ((ret (jolt-vector)) (s s)) (let loop1688 ((ret ret) (s s)) (if (jolt-truthy? (jolt-next s)) (let* ((_a$1689 (jolt-conj ret (jolt-first s))) (_a$1690 (jolt-next s))) (loop1688 _a$1689 _a$1690)) (jolt-seq ret)))))))) butlast))) +(guard (e (#t #f)) + (def-var! "clojure.core" "partition-by" (letrec ((partition-by (case-lambda ((f) (let fnrec1691 ((f f)) (lambda (rf) (let fnrec1692 ((rf rf)) (let* ((buf (jolt-invoke (var-deref "clojure.core" "volatile!") (jolt-vector))) (pv (jolt-invoke (var-deref "clojure.core" "volatile!") jolt-nil)) (started (jolt-invoke (var-deref "clojure.core" "volatile!") #f))) (case-lambda (() (let fnrec1693 () (jolt-invoke rf))) ((result) (let fnrec1694 ((result result)) (let* ((b (jolt-invoke (var-deref "clojure.core" "deref") buf)) (result (if (jolt-zero? (jolt-count b)) result (begin (jolt-invoke (var-deref "clojure.core" "vreset!") buf (jolt-vector)) (jolt-invoke (var-deref "clojure.core" "unreduced") (jolt-invoke rf result b)))))) (jolt-invoke rf result)))) ((result input) (let fnrec1695 ((result result) (input input)) (let* ((val (jolt-invoke f input))) (if (jolt-truthy? (let* ((or__14__auto (jolt-not (jolt-invoke (var-deref "clojure.core" "deref") started)))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= val (jolt-invoke (var-deref "clojure.core" "deref") pv))))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") started #t) (jolt-invoke (var-deref "clojure.core" "vreset!") pv val) (jolt-invoke (var-deref "clojure.core" "vswap!") buf jolt-conj input) result) (let* ((b (jolt-invoke (var-deref "clojure.core" "deref") buf))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") buf (jolt-vector)) (jolt-invoke (var-deref "clojure.core" "vreset!") pv val) (let* ((ret (jolt-invoke rf result b))) (begin (if (jolt-not (jolt-invoke (var-deref "clojure.core" "reduced?") ret)) (jolt-invoke (var-deref "clojure.core" "vswap!") buf jolt-conj input) jolt-nil) ret)))))))))))))) ((f coll) (let fnrec1696 ((f f) (coll coll)) (let* ((step (letrec ((step (lambda (s) (let fnrec1697 ((s s)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec1698 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((s (jolt-seq s))) (if (jolt-truthy? s) (let* ((fst (jolt-first s)) (fv (jolt-invoke f fst)) (run (jolt-cons fst (let* ((_a$1700 (var-deref "clojure.core" "take-while")) (_a$1701 (lambda (x) (let fnrec1699 ((x x)) (jolt= fv (jolt-invoke f x))))) (_a$1702 (jolt-rest s))) (jolt-invoke _a$1700 _a$1701 _a$1702))))) (jolt-cons run (jolt-invoke step (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec1703 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-drop (jolt-count run) s)))))))) jolt-nil)))))))))) step))) (jolt-invoke step coll))))))) partition-by))) +(guard (e (#t #f)) + (def-var! "clojure.core" "some?" (letrec ((some? (lambda (x) (let fnrec1704 ((x x)) (jolt-not (jolt-invoke (var-deref "clojure.core" "nil?") x)))))) some?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "identity" (letrec ((identity (lambda (x) (let fnrec1705 ((x x)) x)))) identity))) +(guard (e (#t #f)) + (def-var! "clojure.core" "constantly" (letrec ((constantly (lambda (x) (let fnrec1706 ((x x)) (lambda args (let fnrec1707 ((args (list->cseq args))) x)))))) constantly))) +(guard (e (#t #f)) + (def-var! "clojure.core" "neg?" (letrec ((neg? (lambda (x) (let fnrec1708 ((x x)) (< x 0))))) neg?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "bit-and" (letrec ((bit-and (case-lambda ((x y) (let fnrec1709 ((x x) (y y)) (jolt-invoke (var-deref "clojure.core" "__bit-and") x y))) ((x y . more) (let fnrec1710 ((x x) (y y) (more (list->cseq more))) (jolt-reduce (var-deref "clojure.core" "__bit-and") (jolt-invoke (var-deref "clojure.core" "__bit-and") x y) more)))))) bit-and))) +(guard (e (#t #f)) + (def-var! "clojure.core" "bit-or" (letrec ((bit-or (case-lambda ((x y) (let fnrec1711 ((x x) (y y)) (jolt-invoke (var-deref "clojure.core" "__bit-or") x y))) ((x y . more) (let fnrec1712 ((x x) (y y) (more (list->cseq more))) (jolt-reduce (var-deref "clojure.core" "__bit-or") (jolt-invoke (var-deref "clojure.core" "__bit-or") x y) more)))))) bit-or))) +(guard (e (#t #f)) + (def-var! "clojure.core" "bit-xor" (letrec ((bit-xor (case-lambda ((x y) (let fnrec1713 ((x x) (y y)) (jolt-invoke (var-deref "clojure.core" "__bit-xor") x y))) ((x y . more) (let fnrec1714 ((x x) (y y) (more (list->cseq more))) (jolt-reduce (var-deref "clojure.core" "__bit-xor") (jolt-invoke (var-deref "clojure.core" "__bit-xor") x y) more)))))) bit-xor))) +(guard (e (#t #f)) + (def-var! "clojure.core" "bit-and-not" (letrec ((bit-and-not (case-lambda ((x y) (let fnrec1715 ((x x) (y y)) (jolt-invoke (var-deref "clojure.core" "__bit-and-not") x y))) ((x y . more) (let fnrec1716 ((x x) (y y) (more (list->cseq more))) (jolt-reduce (var-deref "clojure.core" "__bit-and-not") (jolt-invoke (var-deref "clojure.core" "__bit-and-not") x y) more)))))) bit-and-not))) +(guard (e (#t #f)) + (def-var! "clojure.core" "pr-str" (letrec ((pr-str (lambda xs (let fnrec1717 ((xs (list->cseq xs))) (let* ((out "") (s (jolt-seq xs)) (first? #t)) (let loop1718 ((out out) (s s) (first? first?)) (if (jolt-truthy? s) (let* ((_a$1723 (let* ((_a$1719 (var-deref "clojure.core" "str")) (_a$1720 out) (_a$1721 (if (jolt-truthy? first?) "" " ")) (_a$1722 (jolt-invoke (var-deref "clojure.core" "__pr-str1") (jolt-first s)))) (jolt-invoke _a$1719 _a$1720 _a$1721 _a$1722))) (_a$1724 (jolt-next s)) (_a$1725 #f)) (loop1718 _a$1723 _a$1724 _a$1725)) out))))))) pr-str))) +(guard (e (#t #f)) + (def-var! "clojure.core" "pr" (letrec ((pr (lambda xs (let fnrec1726 ((xs (list->cseq xs))) (begin (jolt-invoke (var-deref "clojure.core" "__write") (jolt-apply (var-deref "clojure.core" "pr-str") xs)) jolt-nil))))) pr))) +(guard (e (#t #f)) + (def-var! "clojure.core" "prn" (letrec ((prn (lambda xs (let fnrec1727 ((xs (list->cseq xs))) (begin (jolt-apply (var-deref "clojure.core" "pr") xs) (jolt-invoke (var-deref "clojure.core" "__write") "\n") jolt-nil))))) prn))) +(guard (e (#t #f)) + (def-var! "clojure.core" "print" (letrec ((print (lambda xs (let fnrec1728 ((xs (list->cseq xs))) (begin (jolt-invoke (var-deref "clojure.core" "__write") (let* ((out "") (s (jolt-seq xs)) (first? #t)) (let loop1729 ((out out) (s s) (first? first?)) (if (jolt-truthy? s) (let* ((x (jolt-first s)) (r (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") x)) "nil" (jolt-invoke (var-deref "clojure.core" "str") x)))) (let* ((_a$1730 (jolt-invoke (var-deref "clojure.core" "str") out (if (jolt-truthy? first?) "" " ") r)) (_a$1731 (jolt-next s)) (_a$1732 #f)) (loop1729 _a$1730 _a$1731 _a$1732))) out)))) jolt-nil))))) print))) +(guard (e (#t #f)) + (def-var! "clojure.core" "println" (letrec ((println (lambda xs (let fnrec1733 ((xs (list->cseq xs))) (begin (jolt-apply (var-deref "clojure.core" "print") xs) (jolt-invoke (var-deref "clojure.core" "__write") "\n") jolt-nil))))) println))) +(guard (e (#t #f)) + (def-var! "clojure.core" "frequencies" (letrec ((frequencies (lambda (coll) (let fnrec1734 ((coll coll)) (jolt-invoke (var-deref "clojure.core" "persistent!") (let* ((_a$1736 (lambda (counts x) (let fnrec1735 ((counts counts) (x x)) (jolt-invoke (var-deref "clojure.core" "assoc!") counts x (jolt-inc (jolt-get counts x 0)))))) (_a$1737 (jolt-invoke (var-deref "clojure.core" "transient") (jolt-hash-map))) (_a$1738 coll)) (jolt-reduce _a$1736 _a$1737 _a$1738))))))) frequencies))) +(guard (e (#t #f)) + (def-var! "clojure.core" "group-by" (letrec ((group-by (lambda (f coll) (let fnrec1739 ((f f) (coll coll)) (let* ((tm (jolt-invoke (var-deref "clojure.core" "transient") (jolt-hash-map))) (ks (let* ((_a$1741 (lambda (ks x) (let fnrec1740 ((ks ks) (x x)) (let* ((k (jolt-invoke f x)) (b (jolt-get tm k))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") b)) (begin (jolt-invoke (var-deref "clojure.core" "assoc!") tm k (jolt-vector x)) (jolt-invoke (var-deref "clojure.core" "conj!") ks k)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") b)) (begin (jolt-invoke (var-deref "clojure.core" "assoc!") tm k (jolt-invoke (var-deref "clojure.core" "conj!") (jolt-invoke (var-deref "clojure.core" "transient") b) x)) ks) (begin (jolt-invoke (var-deref "clojure.core" "conj!") b x) ks))))))) (_a$1742 (jolt-invoke (var-deref "clojure.core" "transient") (jolt-vector))) (_a$1743 coll)) (jolt-reduce _a$1741 _a$1742 _a$1743)))) (begin (let* ((_a$1745 (lambda (_ k) (let fnrec1744 ((_ _) (k k)) (let* ((b (jolt-get tm k))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") b)) jolt-nil (jolt-invoke (var-deref "clojure.core" "assoc!") tm k (jolt-invoke (var-deref "clojure.core" "persistent!") b))))))) (_a$1746 jolt-nil) (_a$1747 (jolt-invoke (var-deref "clojure.core" "persistent!") ks))) (jolt-reduce _a$1745 _a$1746 _a$1747)) (jolt-invoke (var-deref "clojure.core" "persistent!") tm))))))) group-by))) +(guard (e (#t #f)) + (def-var! "clojure.core" "not-empty" (letrec ((not-empty (lambda (coll) (let fnrec1748 ((coll coll)) (if (jolt-truthy? (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "nil?") coll))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-zero? (jolt-count coll))))) jolt-nil coll))))) not-empty))) +(guard (e (#t #f)) + (def-var! "clojure.core" "filterv" (letrec ((filterv (lambda (pred coll) (let fnrec1749 ((pred pred) (coll coll)) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-filter pred coll)))))) filterv))) +(guard (e (#t #f)) + (def-var! "clojure.core" "max-key" (letrec ((max-key (case-lambda ((k x) (let fnrec1750 ((k k) (x x)) x)) ((k x y) (let fnrec1751 ((k k) (x x) (y y)) (if (let* ((_a$1752 (jolt-invoke k x)) (_a$1753 (jolt-invoke k y))) (> _a$1752 _a$1753)) x y))) ((k x y . more) (let fnrec1754 ((k k) (x x) (y y) (more (list->cseq more))) (let* ((kx (jolt-invoke k x)) (ky (jolt-invoke k y)) (v (if (> kx ky) x y)) (kv (if (> kx ky) kx ky))) (let* ((v v) (kv kv) (more more)) (let loop1755 ((v v) (kv kv) (more more)) (if (jolt-truthy? (jolt-seq more)) (let* ((w (jolt-first more)) (kw (jolt-invoke k w))) (if (>= kw kv) (loop1755 w kw (jolt-next more)) (loop1755 v kv (jolt-next more)))) v))))))))) max-key))) +(guard (e (#t #f)) + (def-var! "clojure.core" "min-key" (letrec ((min-key (case-lambda ((k x) (let fnrec1756 ((k k) (x x)) x)) ((k x y) (let fnrec1757 ((k k) (x x) (y y)) (if (let* ((_a$1758 (jolt-invoke k x)) (_a$1759 (jolt-invoke k y))) (< _a$1758 _a$1759)) x y))) ((k x y . more) (let fnrec1760 ((k k) (x x) (y y) (more (list->cseq more))) (let* ((kx (jolt-invoke k x)) (ky (jolt-invoke k y)) (v (if (< kx ky) x y)) (kv (if (< kx ky) kx ky))) (let* ((v v) (kv kv) (more more)) (let loop1761 ((v v) (kv kv) (more more)) (if (jolt-truthy? (jolt-seq more)) (let* ((w (jolt-first more)) (kw (jolt-invoke k w))) (if (<= kw kv) (loop1761 w kw (jolt-next more)) (loop1761 v kv (jolt-next more)))) v))))))))) min-key))) +(guard (e (#t #f)) + (def-var! "clojure.core" "juxt" (letrec ((juxt (lambda fs (let fnrec1762 ((fs (list->cseq fs))) (lambda args (let fnrec1763 ((args (list->cseq args))) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (f) (let fnrec1764 ((f f)) (jolt-apply f args))) fs))))))) juxt))) +(guard (e (#t #f)) + (def-var! "clojure.core" "every-pred" (letrec ((every-pred (lambda preds (let fnrec1765 ((preds (list->cseq preds))) (lambda xs (let fnrec1766 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (p) (let fnrec1767 ((p p)) (jolt-invoke (var-deref "clojure.core" "every?") p xs))) preds))))))) every-pred))) +(guard (e (#t #f)) + (def-var! "clojure.core" "some" (letrec ((some (lambda (pred coll) (let fnrec1768 ((pred pred) (coll coll)) (let* ((temp__15__auto (jolt-seq coll))) (if (jolt-truthy? temp__15__auto) (let* ((s temp__15__auto)) (let* ((or__14__auto (jolt-invoke pred (jolt-first s)))) (if (jolt-truthy? or__14__auto) or__14__auto (fnrec1768 pred (jolt-next s))))) jolt-nil)))))) some))) +(guard (e (#t #f)) + (def-var! "clojure.core" "some-fn" (letrec ((some-fn (lambda preds (let fnrec1769 ((preds (list->cseq preds))) (lambda xs (let fnrec1770 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "some") (lambda (p) (let fnrec1771 ((p p)) (jolt-invoke (var-deref "clojure.core" "some") p xs))) preds))))))) some-fn))) +(guard (e (#t #f)) + (def-var! "clojure.core" "not-any?" (letrec ((not-any? (lambda (pred coll) (let fnrec1772 ((pred pred) (coll coll)) (jolt-not (jolt-invoke (var-deref "clojure.core" "some") pred coll)))))) not-any?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "not-every?" (letrec ((not-every? (lambda (pred coll) (let fnrec1773 ((pred pred) (coll coll)) (jolt-not (jolt-invoke (var-deref "clojure.core" "every?") pred coll)))))) not-every?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "split-at" (letrec ((split-at (lambda (n coll) (let fnrec1774 ((n n) (coll coll)) (let* ((_o$1775 (jolt-take n coll)) (_o$1776 (jolt-drop n coll))) (jolt-vector _o$1775 _o$1776)))))) split-at))) +(guard (e (#t #f)) + (def-var! "clojure.core" "split-with" (letrec ((split-with (lambda (pred coll) (let fnrec1777 ((pred pred) (coll coll)) (let* ((_o$1778 (jolt-invoke (var-deref "clojure.core" "take-while") pred coll)) (_o$1779 (jolt-invoke (var-deref "clojure.core" "drop-while") pred coll))) (jolt-vector _o$1778 _o$1779)))))) split-with))) +(guard (e (#t #f)) + (def-var! "clojure.core" "qualified-keyword?" (letrec ((qualified-keyword? (lambda (x) (let fnrec1780 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "keyword?") x))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "some?") (jolt-invoke (var-deref "clojure.core" "namespace") x)) and__13__auto)))))) qualified-keyword?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "simple-keyword?" (letrec ((simple-keyword? (lambda (x) (let fnrec1781 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "keyword?") x))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-invoke (var-deref "clojure.core" "namespace") x)) and__13__auto)))))) simple-keyword?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "qualified-symbol?" (letrec ((qualified-symbol? (lambda (x) (let fnrec1782 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "some?") (jolt-invoke (var-deref "clojure.core" "namespace") x)) and__13__auto)))))) qualified-symbol?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "simple-symbol?" (letrec ((simple-symbol? (lambda (x) (let fnrec1783 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-invoke (var-deref "clojure.core" "namespace") x)) and__13__auto)))))) simple-symbol?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ident?" (letrec ((ident? (lambda (x) (let fnrec1784 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "keyword?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))))))) ident?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "qualified-ident?" (letrec ((qualified-ident? (lambda (x) (let fnrec1785 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "qualified-symbol?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "qualified-keyword?") x))))))) qualified-ident?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "simple-ident?" (letrec ((simple-ident? (lambda (x) (let fnrec1786 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "simple-symbol?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "simple-keyword?") x))))))) simple-ident?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ratio?" (letrec ((ratio? (lambda (x) (let fnrec1787 ((x x)) #f)))) ratio?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "decimal?" (letrec ((decimal? (lambda (x) (let fnrec1788 ((x x)) #f)))) decimal?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "class?" (letrec ((class? (lambda (x) (let fnrec1789 ((x x)) #f)))) class?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "rational?" (letrec ((rational? (lambda (x) (let fnrec1790 ((x x)) (jolt-invoke (var-deref "clojure.core" "int?") x))))) rational?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nat-int?" (letrec ((nat-int? (lambda (x) (let fnrec1791 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "int?") x))) (if (jolt-truthy? and__13__auto) (>= x 0) and__13__auto)))))) nat-int?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "neg-int?" (letrec ((neg-int? (lambda (x) (let fnrec1792 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "int?") x))) (if (jolt-truthy? and__13__auto) (jolt-neg? x) and__13__auto)))))) neg-int?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "pos-int?" (letrec ((pos-int? (lambda (x) (let fnrec1793 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "int?") x))) (if (jolt-truthy? and__13__auto) (jolt-pos? x) and__13__auto)))))) pos-int?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "replicate" (letrec ((replicate (lambda (n x) (let fnrec1794 ((n n) (x x)) (let* ((_a$1796 (lambda (_) (let fnrec1795 ((_ _)) x))) (_a$1797 (jolt-range n))) (jolt-map _a$1796 _a$1797)))))) replicate))) +(guard (e (#t #f)) + (def-var! "clojure.core" "take-last" (letrec ((take-last (lambda (n coll) (let fnrec1798 ((n n) (coll coll)) (let* ((c (jolt-invoke (var-deref "clojure.core" "vec") coll)) (len (jolt-count c))) (if (jolt-pos? len) (jolt-invoke (var-deref "clojure.core" "subvec") c (max 0 (- len n))) jolt-nil)))))) take-last))) +(guard (e (#t #f)) + (def-var! "clojure.core" "drop-last" (letrec ((drop-last (case-lambda ((coll) (let fnrec1799 ((coll coll)) (jolt-invoke drop-last 1 coll))) ((n coll) (let fnrec1800 ((n n) (coll coll)) (let* ((c (jolt-invoke (var-deref "clojure.core" "vec") coll))) (jolt-invoke (var-deref "clojure.core" "subvec") c 0 (max 0 (- (jolt-count c) n))))))))) drop-last))) +(guard (e (#t #f)) + (def-var! "clojure.core" "distinct?" (letrec ((distinct? (case-lambda ((x) (let fnrec1801 ((x x)) #t)) ((x y) (let fnrec1802 ((x x) (y y)) (jolt-not (jolt= x y)))) ((x y . more) (let fnrec1803 ((x x) (y y) (more (list->cseq more))) (if (jolt-not (jolt= x y)) (let* ((s (let* ((_o$1805 x) (_o$1806 y)) (jolt-hash-set _o$1805 _o$1806))) (xs more)) (let loop1804 ((s s) (xs xs)) (if (jolt-truthy? xs) (let* ((x (jolt-first xs))) (if (jolt-contains? s x) #f (let* ((_a$1807 (jolt-conj s x)) (_a$1808 (jolt-next xs))) (loop1804 _a$1807 _a$1808)))) #t))) #f)))))) distinct?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "replace" (letrec ((replace (lambda (smap coll) (let fnrec1809 ((smap smap) (coll coll)) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (x) (let fnrec1810 ((x x)) (jolt-get smap x x))) coll))))) replace))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nthnext" (letrec ((nthnext (lambda (coll n) (let fnrec1811 ((coll coll) (n n)) (let* ((n n) (xs (jolt-seq coll))) (let loop1812 ((n n) (xs xs)) (if (jolt-truthy? (let* ((and__13__auto xs)) (if (jolt-truthy? and__13__auto) (jolt-pos? n) and__13__auto))) (let* ((_a$1813 (jolt-dec n)) (_a$1814 (jolt-next xs))) (loop1812 _a$1813 _a$1814)) xs))))))) nthnext))) +(guard (e (#t #f)) + (def-var! "clojure.core" "bounded-count" (letrec ((bounded-count (lambda (n coll) (let fnrec1815 ((n n) (coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "counted?") coll)) (jolt-count coll) (let* ((i 0) (s (jolt-seq coll))) (let loop1816 ((i i) (s s)) (if (jolt-truthy? (let* ((and__13__auto s)) (if (jolt-truthy? and__13__auto) (< i n) and__13__auto))) (let* ((_a$1817 (jolt-inc i)) (_a$1818 (jolt-next s))) (loop1816 _a$1817 _a$1818)) i)))))))) bounded-count))) +(guard (e (#t #f)) + (def-var! "clojure.core" "run!" (letrec ((run! (lambda (proc coll) (let fnrec1819 ((proc proc) (coll coll)) (begin (jolt-reduce (lambda (_ x) (let fnrec1820 ((_ _) (x x)) (begin (jolt-invoke proc x) jolt-nil))) jolt-nil coll) jolt-nil))))) run!))) +(guard (e (#t #f)) + (def-var! "clojure.core" "completing" (letrec ((completing (case-lambda ((f) (let fnrec1821 ((f f)) (jolt-invoke completing f jolt-identity))) ((f cf) (let fnrec1822 ((f f) (cf cf)) (case-lambda (() (let fnrec1823 () (jolt-invoke f))) ((x) (let fnrec1824 ((x x)) (jolt-invoke cf x))) ((x y) (let fnrec1825 ((x x) (y y)) (jolt-invoke f x y))))))))) completing))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nthrest" (letrec ((nthrest (lambda (coll n) (let fnrec1826 ((coll coll) (n n)) (if (jolt-pos? n) (let* ((or__14__auto (let* ((n n) (xs coll)) (let loop1827 ((n n) (xs xs)) (let* ((s (let* ((and__13__auto (jolt-pos? n))) (if (jolt-truthy? and__13__auto) (jolt-seq xs) and__13__auto)))) (if (jolt-truthy? s) (let* ((_a$1828 (jolt-dec n)) (_a$1829 (jolt-rest s))) (loop1827 _a$1828 _a$1829)) (jolt-seq xs))))))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-list ))) coll))))) nthrest))) +(guard (e (#t #f)) + (def-var! "clojure.core" "abs" (letrec ((abs (lambda (x) (let fnrec1830 ((x x)) (if (jolt-neg? x) (- 0 x) x))))) abs))) +(guard (e (#t #f)) + (def-var! "clojure.core" "NaN?" (letrec ((NaN? (lambda (x) (let fnrec1831 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) (jolt-not (jolt= x x)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "NaN? requires a number"))))))) NaN?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "object?" (letrec ((object? (lambda (x) (let fnrec1832 ((x x)) #f)))) object?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "undefined?" (letrec ((undefined? (lambda (x) (let fnrec1833 ((x x)) #f)))) undefined?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "keyword-identical?" (letrec ((keyword-identical? (lambda (a b) (let fnrec1834 ((a a) (b b)) (jolt= a b))))) keyword-identical?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "any?" (letrec ((any? (lambda (x) (let fnrec1835 ((x x)) #t)))) any?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "printf" (letrec ((printf (lambda (fmt . args) (let fnrec1836 ((fmt fmt) (args (list->cseq args))) (jolt-invoke (var-deref "clojure.core" "print") (jolt-apply (var-deref "clojure.core" "format") fmt args)))))) printf))) +(guard (e (#t #f)) + (def-var! "clojure.core" "bound?" (letrec ((bound? (lambda vars (let fnrec1837 ((vars (list->cseq vars))) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (v) (let fnrec1838 ((v v)) (jolt-invoke (var-deref "clojure.core" "some?") (jolt-get v (keyword #f "root"))))) vars))))) bound?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-bindings*" (letrec ((with-bindings* (lambda (binding-map f . args) (let fnrec1839 ((binding-map binding-map) (f f) (args (list->cseq args))) (begin (jolt-invoke (var-deref "clojure.core" "push-thread-bindings") binding-map) (dynamic-wind (lambda () #f) (lambda () (jolt-apply f args)) (lambda () (jolt-invoke (var-deref "clojure.core" "pop-thread-bindings"))))))))) with-bindings*))) +(guard (e (#t #f)) + (def-var! "clojure.core" "bound-fn*" (letrec ((bound-fn* (lambda (f) (let fnrec1840 ((f f)) (let* ((bs (jolt-invoke (var-deref "clojure.core" "get-thread-bindings")))) (lambda args (let fnrec1841 ((args (list->cseq args))) (jolt-apply (var-deref "clojure.core" "with-bindings*") bs f args)))))))) bound-fn*))) +(guard (e (#t #f)) + (def-var! "clojure.core" "thread-bound?" (letrec ((thread-bound? (lambda vars (let fnrec1842 ((vars (list->cseq vars))) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (v) (let fnrec1843 ((v v)) (jolt-invoke (var-deref "clojure.core" "__thread-bound?") v))) vars))))) thread-bound?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "key" (letrec ((key (lambda (e) (let fnrec1844 ((e e)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map-entry?") e)) (jolt-nth e 0) (jolt-throw (jolt-ex-info "key requires a map entry" (jolt-hash-map)))))))) key))) +(guard (e (#t #f)) + (def-var! "clojure.core" "val" (letrec ((val (lambda (e) (let fnrec1845 ((e e)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map-entry?") e)) (jolt-nth e 1) (jolt-throw (jolt-ex-info "val requires a map entry" (jolt-hash-map)))))))) val))) +(guard (e (#t #f)) + (def-var! "clojure.core" "make-hierarchy" (letrec ((make-hierarchy (lambda () (let fnrec1846 () (let* ((_o$1847 (keyword #f "parents")) (_o$1848 (jolt-hash-map)) (_o$1849 (keyword #f "descendants")) (_o$1850 (jolt-hash-map)) (_o$1851 (keyword #f "ancestors")) (_o$1852 (jolt-hash-map))) (jolt-hash-map _o$1847 _o$1848 _o$1849 _o$1850 _o$1851 _o$1852)))))) make-hierarchy))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "global-hierarchy" (jolt-invoke (var-deref "clojure.core" "atom") (jolt-invoke (var-deref "clojure.core" "make-hierarchy"))) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "clojure.core" "isa?" (letrec ((isa? (case-lambda ((child parent) (let fnrec1853 ((child child) (parent parent)) (jolt-invoke isa? (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "global-hierarchy")) child parent))) ((h child parent) (let fnrec1854 ((h h) (child child) (parent parent)) (let* ((or__14__auto (jolt= child parent))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-contains? (let* ((_a$1855 (jolt-get h (keyword #f "ancestors"))) (_a$1856 child) (_a$1857 (jolt-hash-set))) (jolt-get _a$1855 _a$1856 _a$1857)) parent))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "vector?") parent))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "vector?") child))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (let* ((_a$1858 (jolt-count parent)) (_a$1859 (jolt-count child))) (jolt= _a$1858 _a$1859)))) (if (jolt-truthy? and__13__auto) (let* ((ret #t) (i 0)) (let loop1860 ((ret ret) (i i)) (if (jolt-truthy? (let* ((or__14__auto (jolt-not ret))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= i (jolt-count parent))))) ret (let* ((_a$1865 (let* ((_a$1861 isa?) (_a$1862 h) (_a$1863 (jolt-nth child i)) (_a$1864 (jolt-nth parent i))) (jolt-invoke _a$1861 _a$1862 _a$1863 _a$1864))) (_a$1866 (jolt-inc i))) (loop1860 _a$1865 _a$1866))))) and__13__auto)) and__13__auto)) and__13__auto))))))))))) isa?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "parents" (letrec ((parents (case-lambda ((tag) (let fnrec1867 ((tag tag)) (jolt-invoke parents (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "global-hierarchy")) tag))) ((h tag) (let fnrec1868 ((h h) (tag tag)) (jolt-invoke (var-deref "clojure.core" "not-empty") (jolt-get (jolt-get h (keyword #f "parents")) tag))))))) parents))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ancestors" (letrec ((ancestors (case-lambda ((tag) (let fnrec1869 ((tag tag)) (jolt-invoke ancestors (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "global-hierarchy")) tag))) ((h tag) (let fnrec1870 ((h h) (tag tag)) (jolt-invoke (var-deref "clojure.core" "not-empty") (jolt-get (jolt-get h (keyword #f "ancestors")) tag))))))) ancestors))) +(guard (e (#t #f)) + (def-var! "clojure.core" "descendants" (letrec ((descendants (case-lambda ((tag) (let fnrec1871 ((tag tag)) (jolt-invoke descendants (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "global-hierarchy")) tag))) ((h tag) (let fnrec1872 ((h h) (tag tag)) (jolt-invoke (var-deref "clojure.core" "not-empty") (jolt-get (jolt-get h (keyword #f "descendants")) tag))))))) descendants))) +(guard (e (#t #f)) + (def-var! "clojure.core" "derive" (letrec ((derive (case-lambda ((tag parent) (let fnrec1873 ((tag tag) (parent parent)) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "clojure.core" "global-hierarchy") derive tag parent) jolt-nil))) ((h tag parent) (let fnrec1874 ((h h) (tag tag) (parent parent)) (let* ((tp (jolt-get h (keyword #f "parents"))) (td (jolt-get h (keyword #f "descendants"))) (ta (jolt-get h (keyword #f "ancestors"))) (tf (lambda (m source sources target targets) (let fnrec1875 ((m m) (source source) (sources sources) (target target) (targets targets)) (let* ((_a$1880 (lambda (ret k) (let fnrec1876 ((ret ret) (k k)) (jolt-assoc ret k (let* ((_a$1877 jolt-conj) (_a$1878 (jolt-get targets k (jolt-hash-set))) (_a$1879 (jolt-cons target (jolt-get targets target)))) (jolt-reduce _a$1877 _a$1878 _a$1879)))))) (_a$1881 m) (_a$1882 (jolt-cons source (jolt-get sources source)))) (jolt-reduce _a$1880 _a$1881 _a$1882)))))) (let* ((or__14__auto (if (jolt-not (jolt-contains? (jolt-get tp tag (jolt-hash-set)) parent)) (begin (if (jolt-contains? (jolt-get ta tag (jolt-hash-set)) parent) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") tag " already has " parent " as ancestor")) jolt-nil) (if (jolt-contains? (jolt-get ta parent (jolt-hash-set)) tag) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Cyclic derivation: " parent " has " tag " as ancestor")) jolt-nil) (let* ((_o$1883 (keyword #f "parents")) (_o$1884 (jolt-assoc tp tag (jolt-conj (jolt-get tp tag (jolt-hash-set)) parent))) (_o$1885 (keyword #f "ancestors")) (_o$1886 (jolt-invoke tf ta tag td parent ta)) (_o$1887 (keyword #f "descendants")) (_o$1888 (jolt-invoke tf td parent ta tag td))) (jolt-hash-map _o$1883 _o$1884 _o$1885 _o$1886 _o$1887 _o$1888))) jolt-nil))) (if (jolt-truthy? or__14__auto) or__14__auto h)))))))) derive))) +(guard (e (#t #f)) + (def-var! "clojure.core" "underive" (letrec ((underive (case-lambda ((tag parent) (let fnrec1889 ((tag tag) (parent parent)) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "clojure.core" "global-hierarchy") underive tag parent) jolt-nil))) ((h tag parent) (let fnrec1890 ((h h) (tag tag) (parent parent)) (let* ((parent-map (jolt-get h (keyword #f "parents"))) (childs-parents (if (jolt-truthy? (jolt-get parent-map tag)) (jolt-invoke (var-deref "clojure.core" "disj") (jolt-get parent-map tag) parent) (jolt-hash-set))) (new-parents (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "not-empty") childs-parents)) (jolt-assoc parent-map tag childs-parents) (jolt-dissoc parent-map tag))) (deriv-seq (let* ((_a$1897 (var-deref "clojure.core" "mapcat")) (_a$1898 (lambda (e) (let fnrec1891 ((e e)) (let* ((_a$1895 (jolt-invoke (var-deref "clojure.core" "key") e)) (_a$1896 (let* ((_a$1892 (var-deref "clojure.core" "interpose")) (_a$1893 (jolt-invoke (var-deref "clojure.core" "key") e)) (_a$1894 (jolt-invoke (var-deref "clojure.core" "val") e))) (jolt-invoke _a$1892 _a$1893 _a$1894)))) (jolt-cons _a$1895 _a$1896))))) (_a$1899 (jolt-seq new-parents))) (jolt-invoke _a$1897 _a$1898 _a$1899)))) (if (jolt-contains? (jolt-get parent-map tag (jolt-hash-set)) parent) (let* ((_a$1901 (lambda (p G__27) (let fnrec1900 ((p p) (G__27 G__27)) (let* ((G__28 G__27) (t (jolt-nth G__28 0 jolt-nil)) (pr (jolt-nth G__28 1 jolt-nil))) (jolt-invoke (var-deref "clojure.core" "derive") p t pr))))) (_a$1902 (jolt-invoke (var-deref "clojure.core" "make-hierarchy"))) (_a$1903 (jolt-invoke (var-deref "clojure.core" "partition") 2 deriv-seq))) (jolt-reduce _a$1901 _a$1902 _a$1903)) h))))))) underive))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sequential?" (letrec ((sequential? (lambda (x) (let fnrec1904 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "seq?") x))))))) sequential?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "associative?" (letrec ((associative? (lambda (x) (let fnrec1905 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "map?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))))))) associative?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "counted?" (letrec ((counted? (lambda (x) (let fnrec1906 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "map?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "set?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "list?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "string?") x))))))))))))) counted?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "indexed?" (letrec ((indexed? (lambda (x) (let fnrec1907 ((x x)) (jolt-invoke (var-deref "clojure.core" "vector?") x))))) indexed?))) +(guard (e (#t #f)) + (declare-var! "clojure.core" "sorted?")) +(guard (e (#t #f)) + (def-var! "clojure.core" "reversible?" (letrec ((reversible? (lambda (x) (let fnrec1908 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "sorted?") x))))))) reversible?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "seqable?" (letrec ((seqable? (lambda (x) (let fnrec1909 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "nil?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "coll?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "string?") x))))))))) seqable?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "boolean?" (letrec ((boolean? (lambda (x) (let fnrec1910 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "true?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "false?") x))))))) boolean?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "double?" (letrec ((double? (lambda (x) (let fnrec1911 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "number?") x))) (if (jolt-truthy? and__13__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "integer?") x)) and__13__auto)))))) double?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "float?" (letrec ((float? (lambda (x) (let fnrec1912 ((x x)) (jolt-invoke (var-deref "clojure.core" "double?") x))))) float?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "infinite?" (letrec ((infinite? (lambda (x) (let fnrec1913 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "number?") x))) (if (jolt-truthy? and__13__auto) (let* ((or__14__auto (jolt= x +inf.0))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= x -inf.0))) and__13__auto)))))) infinite?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "atom?" (letrec ((atom? (lambda (x) (let fnrec1914 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "atom")))))) atom?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "volatile?" (letrec ((volatile? (lambda (x) (let fnrec1915 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "volatile")))))) volatile?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "reader-conditional?" (letrec ((reader-conditional? (lambda (x) (let fnrec1916 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "reader-conditional")))))) reader-conditional?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "tagged-literal?" (letrec ((tagged-literal? (lambda (x) (let fnrec1917 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "tagged-literal")))))) tagged-literal?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "record?" (letrec ((record? (lambda (x) (let fnrec1918 ((x x)) (jolt-invoke (var-deref "clojure.core" "some?") (jolt-get x (keyword "jolt" "deftype"))))))) record?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "uuid?" (letrec ((uuid? (lambda (x) (let fnrec1919 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "uuid")))))) uuid?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "inst?" (letrec ((inst? (lambda (x) (let fnrec1920 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "inst")))))) inst?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "char?" (letrec ((char? (lambda (x) (let fnrec1921 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "char")))))) char?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "realized?" (letrec ((realized? (lambda (x) (let fnrec1922 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "delay?") x)) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "realized"))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "future?") x)) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "cached"))) (if (jolt= (keyword "jolt" "lazy-seq") (jolt-get x (keyword "jolt" "type"))) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "realized"))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "atom?") x)) #t (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "realized? not supported on: " x)) jolt-nil))))))))) realized?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "force" (letrec ((force (lambda (x) (let fnrec1923 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "delay?") x)) (jolt-invoke (var-deref "clojure.core" "deref") x) x))))) force))) +(guard (e (#t #f)) + (def-var! "clojure.core" "pop" (letrec ((pop (lambda (coll) (let fnrec1924 ((coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") coll)) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (if (jolt-zero? (jolt-count coll)) (jolt-throw "Can't pop empty vector") (jolt-invoke (var-deref "clojure.core" "subvec") coll 0 (jolt-dec (jolt-count coll)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-seq coll))) (jolt-throw "Can't pop empty list") (jolt-rest coll)) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "pop not supported on: " coll)) jolt-nil)))))))) pop))) +(guard (e (#t #f)) + (def-var! "clojure.core" "dorun" (letrec ((dorun (case-lambda ((coll) (let fnrec1925 ((coll coll)) (let* ((s (jolt-seq coll))) (let loop1926 ((s s)) (if (jolt-truthy? s) (loop1926 (jolt-next s)) jolt-nil))))) ((n coll) (let fnrec1927 ((n n) (coll coll)) (let* ((n n) (s (jolt-seq coll))) (let loop1928 ((n n) (s s)) (if (jolt-truthy? (let* ((and__13__auto s)) (if (jolt-truthy? and__13__auto) (jolt-pos? n) and__13__auto))) (let* ((_a$1929 (jolt-dec n)) (_a$1930 (jolt-next s))) (loop1928 _a$1929 _a$1930)) jolt-nil)))))))) dorun))) +(guard (e (#t #f)) + (def-var! "clojure.core" "doall" (letrec ((doall (case-lambda ((coll) (let fnrec1931 ((coll coll)) (begin (jolt-invoke (var-deref "clojure.core" "dorun") coll) coll))) ((n coll) (let fnrec1932 ((n n) (coll coll)) (begin (jolt-invoke (var-deref "clojure.core" "dorun") n coll) coll)))))) doall))) +(guard (e (#t #f)) + (def-var! "clojure.core" "spread" (letrec ((spread (lambda (arglist) (let fnrec1933 ((arglist arglist)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") arglist)) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-next arglist))) (jolt-seq (jolt-first arglist)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$1934 (jolt-first arglist)) (_a$1935 (jolt-invoke spread (jolt-next arglist)))) (jolt-cons _a$1934 _a$1935)) jolt-nil))))))) spread))) +(guard (e (#t #f)) + (def-var! "clojure.core" "list*" (letrec ((list* (case-lambda ((args) (let fnrec1936 ((args args)) (jolt-seq args))) ((a args) (let fnrec1937 ((a a) (args args)) (jolt-cons a args))) ((a b args) (let fnrec1938 ((a a) (b b) (args args)) (jolt-cons a (jolt-cons b args)))) ((a b c args) (let fnrec1939 ((a a) (b b) (c c) (args args)) (jolt-cons a (jolt-cons b (jolt-cons c args))))) ((a b c d . more) (let fnrec1940 ((a a) (b b) (c c) (d d) (more (list->cseq more))) (jolt-cons a (jolt-cons b (jolt-cons c (jolt-cons d (jolt-invoke (var-deref "clojure.core" "spread") more)))))))))) list*))) +(guard (e (#t #f)) + (def-var! "clojure.core" "print-str" (letrec ((print-str (lambda xs (let fnrec1941 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "__with-out-str") (lambda () (let fnrec1942 () (jolt-apply (var-deref "clojure.core" "print") xs)))))))) print-str))) +(guard (e (#t #f)) + (def-var! "clojure.core" "println-str" (letrec ((println-str (lambda xs (let fnrec1943 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "__with-out-str") (lambda () (let fnrec1944 () (jolt-apply (var-deref "clojure.core" "println") xs)))))))) println-str))) +(guard (e (#t #f)) + (def-var! "clojure.core" "prn-str" (letrec ((prn-str (lambda xs (let fnrec1945 ((xs (list->cseq xs))) (jolt-invoke (var-deref "clojure.core" "__with-out-str") (lambda () (let fnrec1946 () (jolt-apply (var-deref "clojure.core" "prn") xs)))))))) prn-str))) +(guard (e (#t #f)) + (def-var! "clojure.core" "rand-int" (letrec ((rand-int (lambda (n) (let fnrec1947 ((n n)) (jolt-invoke (var-deref "clojure.core" "int") (jolt-invoke (var-deref "clojure.core" "rand") n)))))) rand-int))) +(guard (e (#t #f)) + (def-var! "clojure.core" "shuffle" (letrec ((shuffle (lambda (coll) (let fnrec1948 ((coll coll)) (begin (if (jolt-not (jolt-invoke (var-deref "clojure.core" "coll?") coll)) (jolt-throw (let* ((_a$1949 (jolt-invoke (var-deref "clojure.core" "str") "shuffle requires a collection, got: " coll)) (_a$1950 (jolt-hash-map))) (jolt-ex-info _a$1949 _a$1950))) jolt-nil) (let* ((v (jolt-invoke (var-deref "clojure.core" "vec") coll)) (i (jolt-dec (jolt-count v)))) (let loop1951 ((v v) (i i)) (if (jolt-pos? i) (let* ((j (jolt-invoke (var-deref "clojure.core" "rand-int") (jolt-inc i))) (t (jolt-nth v i))) (let* ((_a$1952 (jolt-assoc (jolt-assoc v i (jolt-nth v j)) j t)) (_a$1953 (jolt-dec i))) (loop1951 _a$1952 _a$1953))) v)))))))) shuffle))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sort-by" (letrec ((sort-by (case-lambda ((keyfn coll) (let fnrec1954 ((keyfn keyfn) (coll coll)) (jolt-invoke sort-by keyfn (var-deref "clojure.core" "compare") coll))) ((keyfn comp coll) (let fnrec1955 ((keyfn keyfn) (comp comp) (coll coll)) (jolt-invoke (var-deref "clojure.core" "sort") (lambda (x y) (let fnrec1956 ((x x) (y y)) (let* ((_a$1957 comp) (_a$1958 (jolt-invoke keyfn x)) (_a$1959 (jolt-invoke keyfn y))) (jolt-invoke _a$1957 _a$1958 _a$1959)))) coll)))))) sort-by))) +(guard (e (#t #f)) + (def-var! "clojure.core" "parse-uuid" (letrec ((parse-uuid (lambda (s) (let fnrec1960 ((s s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "re-matches") (jolt-regex "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") s)) (jolt-invoke (var-deref "clojure.core" "__make-uuid") s) jolt-nil) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "parse-uuid requires a string, got: " s))))))) parse-uuid))) +(guard (e (#t #f)) + (def-var! "clojure.core" "random-uuid" (letrec ((random-uuid (lambda () (let fnrec1961 () (let* ((hx4 (lambda () (let fnrec1962 () (jolt-invoke (var-deref "clojure.core" "format") "%04x" (jolt-invoke (var-deref "clojure.core" "rand-int") 65536))))) (hx3 (lambda () (let fnrec1963 () (jolt-invoke (var-deref "clojure.core" "format") "%03x" (jolt-invoke (var-deref "clojure.core" "rand-int") 4096)))))) (jolt-invoke (var-deref "clojure.core" "parse-uuid") (let* ((_a$1964 (var-deref "clojure.core" "str")) (_a$1965 (jolt-invoke hx4)) (_a$1966 (jolt-invoke hx4)) (_a$1967 "-") (_a$1968 (jolt-invoke hx4)) (_a$1969 "-4") (_a$1970 (jolt-invoke hx3)) (_a$1971 "-") (_a$1972 (jolt-invoke (var-deref "clojure.core" "format") "%x" (+ 8 (jolt-invoke (var-deref "clojure.core" "rand-int") 4)))) (_a$1973 (jolt-invoke hx3)) (_a$1974 "-") (_a$1975 (jolt-invoke hx4)) (_a$1976 (jolt-invoke hx4)) (_a$1977 (jolt-invoke hx4))) (jolt-invoke _a$1964 _a$1965 _a$1966 _a$1967 _a$1968 _a$1969 _a$1970 _a$1971 _a$1972 _a$1973 _a$1974 _a$1975 _a$1976 _a$1977)))))))) random-uuid))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "char-escape-strings" (let* ((_o$1978 (integer->char 10)) (_o$1979 "\\n") (_o$1980 (integer->char 9)) (_o$1981 "\\t") (_o$1982 (integer->char 13)) (_o$1983 "\\r") (_o$1984 (integer->char 12)) (_o$1985 "\\f") (_o$1986 (integer->char 8)) (_o$1987 "\\b") (_o$1988 (integer->char 34)) (_o$1989 "\\\"") (_o$1990 (integer->char 92)) (_o$1991 "\\\\")) (jolt-hash-map _o$1978 _o$1979 _o$1980 _o$1981 _o$1982 _o$1983 _o$1984 _o$1985 _o$1986 _o$1987 _o$1988 _o$1989 _o$1990 _o$1991)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "clojure.core" "char-escape-string" (letrec ((char-escape-string (lambda (c) (let fnrec1992 ((c c)) (jolt-get (var-deref "clojure.core" "char-escape-strings") c))))) char-escape-string))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "char-name-strings" (let* ((_o$1993 (integer->char 10)) (_o$1994 "newline") (_o$1995 (integer->char 9)) (_o$1996 "tab") (_o$1997 (integer->char 13)) (_o$1998 "return") (_o$1999 (integer->char 12)) (_o$2000 "formfeed") (_o$2001 (integer->char 8)) (_o$2002 "backspace") (_o$2003 (integer->char 32)) (_o$2004 "space")) (jolt-hash-map _o$1993 _o$1994 _o$1995 _o$1996 _o$1997 _o$1998 _o$1999 _o$2000 _o$2001 _o$2002 _o$2003 _o$2004)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "clojure.core" "char-name-string" (letrec ((char-name-string (lambda (c) (let fnrec2005 ((c c)) (jolt-get (var-deref "clojure.core" "char-name-strings") c))))) char-name-string))) +(guard (e (#t #f)) + (def-var! "clojure.core" "rand-nth" (letrec ((rand-nth (lambda (coll) (let fnrec2006 ((coll coll)) (let* ((v (jolt-invoke (var-deref "clojure.core" "vec") coll))) (jolt-nth v (jolt-invoke (var-deref "clojure.core" "rand-int") (jolt-count v)))))))) rand-nth))) +(guard (e (#t #f)) + (def-var! "clojure.core" "random-sample" (letrec ((random-sample (case-lambda ((prob) (let fnrec2007 ((prob prob)) (jolt-invoke jolt-filter (lambda (_) (let fnrec2008 ((_ _)) (< (jolt-invoke (var-deref "clojure.core" "rand")) prob)))))) ((prob coll) (let fnrec2009 ((prob prob) (coll coll)) (jolt-filter (lambda (_) (let fnrec2010 ((_ _)) (< (jolt-invoke (var-deref "clojure.core" "rand")) prob))) coll)))))) random-sample))) +(guard (e (#t #f)) + (def-var! "clojure.core" "comparator" (letrec ((comparator (lambda (pred) (let fnrec2011 ((pred pred)) (lambda (a b) (let fnrec2012 ((a a) (b b)) (if (jolt-truthy? (jolt-invoke pred a b)) -1 (if (jolt-truthy? (jolt-invoke pred b a)) 1 (if (jolt-truthy? (keyword #f "else")) 0 jolt-nil))))))))) comparator))) +(guard (e (#t #f)) + (def-var! "clojure.core" "reductions" (letrec ((reductions (case-lambda ((f coll) (let fnrec2013 ((f f) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2014 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((s (jolt-seq coll))) (if (jolt-truthy? s) (let* ((_a$2015 reductions) (_a$2016 f) (_a$2017 (jolt-first s)) (_a$2018 (jolt-rest s))) (jolt-invoke _a$2015 _a$2016 _a$2017 _a$2018)) (jolt-list (jolt-invoke f)))))))))) ((f init coll) (let fnrec2019 ((f f) (init init) (coll coll)) (jolt-cons init (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2020 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__15__auto (jolt-seq coll))) (if (jolt-truthy? temp__15__auto) (let* ((s temp__15__auto)) (let* ((_a$2021 reductions) (_a$2022 f) (_a$2023 (jolt-invoke f init (jolt-first s))) (_a$2024 (jolt-rest s))) (jolt-invoke _a$2021 _a$2022 _a$2023 _a$2024))) jolt-nil)))))))))))) reductions))) +(guard (e (#t #f)) + (def-var! "clojure.core" "tree-seq" (letrec ((tree-seq (lambda (branch? children root) (let fnrec2025 ((branch? branch?) (children children) (root root)) (let* ((walk (letrec ((walk (lambda (node) (let fnrec2026 ((node node)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2027 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-cons node (if (jolt-truthy? (jolt-invoke branch? node)) (jolt-invoke (var-deref "clojure.core" "mapcat") walk (jolt-invoke children node)) jolt-nil)))))))))) walk))) (jolt-invoke walk root)))))) tree-seq))) +(guard (e (#t #f)) + (def-var! "clojure.core" "file-seq" (letrec ((file-seq (lambda (root) (let fnrec2028 ((root root)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "__file?") root)) (let* ((_a$2031 (var-deref "clojure.core" "tree-seq")) (_a$2032 (lambda (f) (let fnrec2029 ((f f)) (jolt-host-call "isDirectory" f)))) (_a$2033 (lambda (f) (let fnrec2030 ((f f)) (jolt-seq (jolt-host-call "listFiles" f))))) (_a$2034 root)) (jolt-invoke _a$2031 _a$2032 _a$2033 _a$2034)) (jolt-invoke (var-deref "clojure.core" "tree-seq") (var-deref "clojure.core" "__dir?") (var-deref "clojure.core" "__list-dir") root)))))) file-seq))) +(guard (e (#t #f)) + (def-var! "clojure.core" "flatten" (letrec ((flatten (lambda (coll) (let fnrec2035 ((coll coll)) (let* ((_a$2036 (jolt-invoke (var-deref "clojure.core" "complement") (var-deref "clojure.core" "sequential?"))) (_a$2037 (jolt-rest (jolt-invoke (var-deref "clojure.core" "tree-seq") (var-deref "clojure.core" "sequential?") jolt-seq coll)))) (jolt-filter _a$2036 _a$2037)))))) flatten))) +(guard (e (#t #f)) + (def-var! "clojure.core" "xml-seq" (letrec ((xml-seq (lambda (root) (let fnrec2038 ((root root)) (let* ((_a$2039 (var-deref "clojure.core" "tree-seq")) (_a$2040 (jolt-invoke (var-deref "clojure.core" "complement") (var-deref "clojure.core" "string?"))) (_a$2041 (jolt-invoke (var-deref "clojure.core" "comp") jolt-seq (keyword #f "content"))) (_a$2042 root)) (jolt-invoke _a$2039 _a$2040 _a$2041 _a$2042)))))) xml-seq))) +(guard (e (#t #f)) + (def-var! "clojure.core" "interleave" (letrec ((interleave (case-lambda (() (let fnrec2043 () (jolt-list ))) ((c1) (let fnrec2044 ((c1 c1)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2045 () (jolt-invoke (var-deref "clojure.core" "coll->cells") c1)))))) ((c1 c2) (let fnrec2046 ((c1 c1) (c2 c2)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2047 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((s1 (jolt-seq c1)) (s2 (jolt-seq c2))) (if (jolt-truthy? (let* ((and__13__auto s1)) (if (jolt-truthy? and__13__auto) s2 and__13__auto))) (let* ((_a$2053 (jolt-first s1)) (_a$2054 (let* ((_a$2051 (jolt-first s2)) (_a$2052 (let* ((_a$2048 interleave) (_a$2049 (jolt-rest s1)) (_a$2050 (jolt-rest s2))) (jolt-invoke _a$2048 _a$2049 _a$2050)))) (jolt-cons _a$2051 _a$2052)))) (jolt-cons _a$2053 _a$2054)) jolt-nil)))))))) ((c1 c2 . cs) (let fnrec2055 ((c1 c1) (c2 c2) (cs (list->cseq cs))) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2056 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((ss (jolt-map jolt-seq (jolt-invoke (var-deref "clojure.core" "list*") c1 c2 cs)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "every?") jolt-identity ss)) (let* ((_a$2057 (jolt-map jolt-first ss)) (_a$2058 (jolt-apply interleave (jolt-map jolt-rest ss)))) (jolt-concat _a$2057 _a$2058)) jolt-nil))))))))))) interleave))) +(guard (e (#t #f)) + (def-var! "clojure.core" "rationalize" (letrec ((rationalize (lambda (x) (let fnrec2059 ((x x)) x)))) rationalize))) +(guard (e (#t #f)) + (def-var! "clojure.core" "dedupe" (letrec ((dedupe (case-lambda (() (let fnrec2060 () (lambda (rf) (let fnrec2061 ((rf rf)) (let* ((pv (jolt-invoke (var-deref "clojure.core" "volatile!") (let* ((_o$2062 #f) (_o$2063 jolt-nil)) (jolt-vector _o$2062 _o$2063))))) (case-lambda (() (let fnrec2064 () (jolt-invoke rf))) ((result) (let fnrec2065 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec2066 ((result result) (input input)) (let* ((G__29 (jolt-invoke (var-deref "clojure.core" "deref") pv)) (seen (jolt-nth G__29 0 jolt-nil)) (prior (jolt-nth G__29 1 jolt-nil))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") pv (let* ((_o$2067 #t) (_o$2068 input)) (jolt-vector _o$2067 _o$2068))) (if (jolt-truthy? (let* ((and__13__auto seen)) (if (jolt-truthy? and__13__auto) (jolt= prior input) and__13__auto))) result (jolt-invoke rf result input)))))))))))) ((coll) (let fnrec2069 ((coll coll)) (let* ((step (letrec ((step (lambda (s prev) (let fnrec2070 ((s s) (prev prev)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2071 () (let* ((s (jolt-seq s))) (if (jolt-truthy? s) (let* ((x (jolt-first s))) (if (jolt= x prev) (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-invoke step (jolt-rest s) prev)) (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-cons x (jolt-invoke step (jolt-rest s) x))))) jolt-nil))))))))) step))) (let* ((s (jolt-seq coll))) (if (jolt-truthy? s) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec2072 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((_a$2076 (jolt-first s)) (_a$2077 (let* ((_a$2073 step) (_a$2074 (jolt-rest s)) (_a$2075 (jolt-first s))) (jolt-invoke _a$2073 _a$2074 _a$2075)))) (jolt-cons _a$2076 _a$2077)))))) (jolt-list ))))))))) dedupe))) +(guard (e (#t #f)) + (def-var! "clojure.core" "seq-to-map-for-destructuring" (letrec ((seq-to-map-for-destructuring (lambda (s) (let fnrec2078 ((s s)) (if (jolt-truthy? (jolt-next s)) (let* ((m (jolt-hash-map)) (xs (jolt-seq s))) (let loop2079 ((m m) (xs xs)) (if (jolt-truthy? xs) (if (jolt-truthy? (jolt-next xs)) (let* ((_a$2083 (let* ((_a$2080 m) (_a$2081 (jolt-first xs)) (_a$2082 (jolt-invoke (var-deref "clojure.core" "second") xs))) (jolt-assoc _a$2080 _a$2081 _a$2082))) (_a$2084 (jolt-invoke (var-deref "clojure.core" "nnext") xs))) (loop2079 _a$2083 _a$2084)) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "No value supplied for key: " (jolt-first xs)))) m))) (if (jolt-truthy? (jolt-seq s)) (jolt-first s) (jolt-hash-map))))))) seq-to-map-for-destructuring))) +(guard (e (#t #f)) + (def-var! "clojure.core" "vary-meta" (letrec ((vary-meta (lambda (obj f . args) (let fnrec2085 ((obj obj) (f f) (args (list->cseq args))) (jolt-invoke (var-deref "clojure.core" "with-meta") obj (jolt-apply f (jolt-invoke (var-deref "clojure.core" "meta") obj) args)))))) vary-meta))) +(guard (e (#t #f)) + (def-var! "clojure.core" "namespace-munge" (letrec ((namespace-munge (lambda (s) (let fnrec2086 ((s s)) (jolt-apply (var-deref "clojure.core" "str") (let* ((_a$2088 (lambda (c) (let fnrec2087 ((c c)) (if (jolt= c (integer->char 45)) (integer->char 95) c)))) (_a$2089 (jolt-seq (jolt-invoke (var-deref "clojure.core" "str") s)))) (jolt-map _a$2088 _a$2089))))))) namespace-munge))) +(guard (e (#t #f)) + (def-var! "clojure.core" "reduce-kv" (letrec ((reduce-kv (lambda (f init coll) (let fnrec2090 ((f f) (init init) (coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (let* ((_a$2092 (lambda (acc i) (let fnrec2091 ((acc acc) (i i)) (jolt-invoke f acc i (jolt-nth coll i))))) (_a$2093 init) (_a$2094 (jolt-range (jolt-count coll)))) (jolt-reduce _a$2092 _a$2093 _a$2094)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") coll)) (let* ((_a$2096 (lambda (acc k) (let fnrec2095 ((acc acc) (k k)) (jolt-invoke f acc k (jolt-get coll k))))) (_a$2097 init) (_a$2098 (jolt-keys coll))) (jolt-reduce _a$2096 _a$2097 _a$2098)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") coll)) init (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "reduce-kv not supported on: " coll)) jolt-nil)))))))) reduce-kv))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ex-info-val?" (letrec ((ex-info-val? (lambda (x) (let fnrec2099 ((x x)) (jolt= (jolt-get x (keyword "jolt" "type")) (keyword "jolt" "ex-info")))))) ex-info-val?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ex-unwrap" (letrec ((ex-unwrap (lambda (e) (let fnrec2100 ((e e)) (if (jolt= (jolt-get e (keyword "jolt" "type")) (keyword "jolt" "exception")) (jolt-get e (keyword #f "value")) e))))) ex-unwrap))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ex-data" (letrec ((ex-data (lambda (e) (let fnrec2101 ((e e)) (let* ((e (jolt-invoke (var-deref "clojure.core" "ex-unwrap") e))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "ex-info-val?") e)) (jolt-get e (keyword #f "data")) jolt-nil)))))) ex-data))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ex-message" (letrec ((ex-message (lambda (e) (let fnrec2102 ((e e)) (let* ((e (jolt-invoke (var-deref "clojure.core" "ex-unwrap") e))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "ex-info-val?") e)) (jolt-get e (keyword #f "message")) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))))) ex-message))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ex-cause" (letrec ((ex-cause (lambda (e) (let fnrec2103 ((e e)) (let* ((e (jolt-invoke (var-deref "clojure.core" "ex-unwrap") e))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "ex-info-val?") e)) (jolt-get e (keyword #f "cause")) jolt-nil)))))) ex-cause))) +(guard (e (#t #f)) + (def-var! "clojure.core" "inst-ms" (letrec ((inst-ms (lambda (x) (let fnrec2104 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "inst?") x)) (jolt-get x (keyword #f "ms")) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "inst-ms requires an inst, got: " x))))))) inst-ms))) +(guard (e (#t #f)) + (def-var! "clojure.core" "update-keys" (letrec ((update-keys (lambda (m f) (let fnrec2105 ((m m) (f f)) (let* ((_a$2107 (var-deref "clojure.core" "reduce-kv")) (_a$2108 (lambda (acc k v) (let fnrec2106 ((acc acc) (k k) (v v)) (jolt-assoc acc (jolt-invoke f k) v)))) (_a$2109 (jolt-hash-map )) (_a$2110 m)) (jolt-invoke _a$2107 _a$2108 _a$2109 _a$2110)))))) update-keys))) +(guard (e (#t #f)) + (def-var! "clojure.core" "update-vals" (letrec ((update-vals (lambda (m f) (let fnrec2111 ((m m) (f f)) (let* ((_a$2113 (var-deref "clojure.core" "reduce-kv")) (_a$2114 (lambda (acc k v) (let fnrec2112 ((acc acc) (k k) (v v)) (jolt-assoc acc k (jolt-invoke f v))))) (_a$2115 (jolt-hash-map )) (_a$2116 m)) (jolt-invoke _a$2113 _a$2114 _a$2115 _a$2116)))))) update-vals))) +(guard (e (#t #f)) + (def-var! "clojure.core" "partitionv" (letrec ((partitionv (case-lambda ((n coll) (let fnrec2117 ((n n) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition") n coll)))) ((n step coll) (let fnrec2118 ((n n) (step step) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition") n step coll)))) ((n step pad coll) (let fnrec2119 ((n n) (step step) (pad pad) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition") n step pad coll))))))) partitionv))) +(guard (e (#t #f)) + (declare-var! "clojure.core" "partition-all")) +(guard (e (#t #f)) + (def-var! "clojure.core" "partitionv-all" (letrec ((partitionv-all (case-lambda ((n coll) (let fnrec2120 ((n n) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition-all") n coll)))) ((n step coll) (let fnrec2121 ((n n) (step step) (coll coll)) (jolt-map (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "partition-all") n step coll))))))) partitionv-all))) +(guard (e (#t #f)) + (def-var! "clojure.core" "splitv-at" (letrec ((splitv-at (lambda (n coll) (let fnrec2122 ((n n) (coll coll)) (let* ((_o$2123 (jolt-invoke (var-deref "clojure.core" "vec") (jolt-take n coll))) (_o$2124 (jolt-drop n coll))) (jolt-vector _o$2123 _o$2124)))))) splitv-at))) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-redefs-fn" (letrec ((with-redefs-fn (lambda (binding-map func) (let fnrec2125 ((binding-map binding-map) (func func)) (let* ((vars (jolt-invoke (var-deref "clojure.core" "vec") (jolt-keys binding-map))) (saved (jolt-invoke (var-deref "clojure.core" "mapv") (var-deref "clojure.core" "var-get") vars))) (begin (begin (jolt-count (jolt-map (lambda (v) (let fnrec2126 ((v v)) (begin (jolt-invoke (var-deref "clojure.core" "var-set") v (jolt-get binding-map v)) jolt-nil))) vars)) jolt-nil) (dynamic-wind (lambda () #f) (lambda () (jolt-invoke func)) (lambda () (let* ((i 0)) (let loop2127 ((i i)) (if (< i (jolt-count vars)) (begin (let* ((_a$2128 (var-deref "clojure.core" "var-set")) (_a$2129 (jolt-nth vars i)) (_a$2130 (jolt-nth saved i))) (jolt-invoke _a$2128 _a$2129 _a$2130)) (loop2127 (jolt-inc i))) jolt-nil))))))))))) with-redefs-fn))) +(guard (e (#t #f)) + (def-var! "clojure.core" "chunked-seq?" (letrec ((chunked-seq? (lambda (x) (let fnrec2131 ((x x)) #f)))) chunked-seq?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "swap-vals!" (letrec ((swap-vals! (lambda (a f . args) (let fnrec2132 ((a a) (f f) (args (list->cseq args))) (let* ((old (jolt-invoke (var-deref "clojure.core" "deref") a))) (let* ((_o$2133 old) (_o$2134 (jolt-apply (var-deref "clojure.core" "swap!") a f args))) (jolt-vector _o$2133 _o$2134))))))) swap-vals!))) +(guard (e (#t #f)) + (def-var! "clojure.core" "reset-vals!" (letrec ((reset-vals! (lambda (a newval) (let fnrec2135 ((a a) (newval newval)) (let* ((old (jolt-invoke (var-deref "clojure.core" "deref") a))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") a newval) (let* ((_o$2136 old) (_o$2137 newval)) (jolt-vector _o$2136 _o$2137)))))))) reset-vals!))) +(guard (e (#t #f)) + (def-var! "clojure.core" "compare-and-set!" (letrec ((compare-and-set! (lambda (a oldval newval) (let fnrec2138 ((a a) (oldval oldval) (newval newval)) (if (jolt= oldval (jolt-invoke (var-deref "clojure.core" "deref") a)) (begin (jolt-invoke (var-deref "clojure.core" "reset!") a newval) #t) #f))))) compare-and-set!))) +(guard (e (#t #f)) + (def-var! "clojure.core" "get-validator" (letrec ((get-validator (lambda (a) (let fnrec2139 ((a a)) (jolt-get a (keyword #f "validator")))))) get-validator))) +(guard (e (#t #f)) + (def-var! "clojure.core" "add-watch" (letrec ((add-watch (lambda (a key f) (let fnrec2140 ((a a) (key key) (f f)) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-get a (keyword #f "watches")) key f) a))))) add-watch))) +(guard (e (#t #f)) + (def-var! "clojure.core" "remove-watch" (letrec ((remove-watch (lambda (a key) (let fnrec2141 ((a a) (key key)) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-get a (keyword #f "watches")) key jolt-nil) a))))) remove-watch))) +(guard (e (#t #f)) + (def-var! "clojure.core" "set-validator!" (letrec ((set-validator! (lambda (a f) (let fnrec2142 ((a a) (f f)) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") a (keyword #f "validator") f) jolt-nil))))) set-validator!))) +(guard (e (#t #f)) + (def-var! "clojure.core" "future-done?" (letrec ((future-done? (lambda (x) (let fnrec2143 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "future?") x)) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "cached"))) (jolt-throw "future-done? requires a future")))))) future-done?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "future-cancelled?" (letrec ((future-cancelled? (lambda (x) (let fnrec2144 ((x x)) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "future?") x))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-get x (keyword #f "cancelled"))) and__13__auto)))))) future-cancelled?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ns-name" (letrec ((ns-name (lambda (ns) (let fnrec2145 ((ns ns)) (let* ((nm (jolt-get ns (keyword #f "name")))) (if (jolt-truthy? nm) (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") nm)) jolt-nil)))))) ns-name))) +(guard (e (#t #f)) + (def-var! "clojure.core" "aget" (letrec ((aget (lambda (arr . idxs) (let fnrec2146 ((arr arr) (idxs (list->cseq idxs))) (jolt-reduce (lambda (v i) (let fnrec2147 ((v v) (i i)) (jolt-nth v i))) arr idxs))))) aget))) +(guard (e (#t #f)) + (def-var! "clojure.core" "alength" (letrec ((alength (lambda (arr) (let fnrec2148 ((arr arr)) (jolt-count arr))))) alength))) +(guard (e (#t #f)) + (def-var! "clojure.core" "aset" (letrec ((aset (lambda (arr . idxs+val) (let fnrec2149 ((arr arr) (idxs+val (list->cseq idxs+val))) (let* ((n (jolt-count idxs+val)) (val (jolt-nth idxs+val (jolt-dec n))) (target (let* ((_a$2151 (lambda (t k) (let fnrec2150 ((t t) (k k)) (jolt-nth t k)))) (_a$2152 arr) (_a$2153 (jolt-take (- n 2) idxs+val))) (jolt-reduce _a$2151 _a$2152 _a$2153)))) (begin (jolt-invoke (var-deref "jolt.host" "ref-put!") target (jolt-nth idxs+val (- n 2)) val) val)))))) aset))) +(guard (e (#t #f)) + (def-var! "clojure.core" "complement" (letrec ((complement (lambda (f) (let fnrec2154 ((f f)) (lambda args (let fnrec2155 ((args (list->cseq args))) (jolt-not (jolt-apply f args)))))))) complement))) +(guard (e (#t #f)) + (def-var! "clojure.core" "fnil" (letrec ((fnil (case-lambda ((f x) (let fnrec2156 ((f f) (x x)) (lambda (a . args) (let fnrec2157 ((a a) (args (list->cseq args))) (jolt-apply f (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") a)) x a) args))))) ((f x y) (let fnrec2158 ((f f) (x x) (y y)) (lambda (a b . args) (let fnrec2159 ((a a) (b b) (args (list->cseq args))) (let* ((_a$2160 f) (_a$2161 (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") a)) x a)) (_a$2162 (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") b)) y b)) (_a$2163 args)) (jolt-apply _a$2160 _a$2161 _a$2162 _a$2163)))))) ((f x y z) (let fnrec2164 ((f f) (x x) (y y) (z z)) (lambda (a b c . args) (let fnrec2165 ((a a) (b b) (c c) (args (list->cseq args))) (let* ((_a$2166 f) (_a$2167 (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") a)) x a)) (_a$2168 (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") b)) y b)) (_a$2169 (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") c)) z c)) (_a$2170 args)) (jolt-apply _a$2166 _a$2167 _a$2168 _a$2169 _a$2170))))))))) fnil))) +(guard (e (#t #f)) + (def-var! "clojure.core" "clojure-version" (letrec ((clojure-version (lambda () (let fnrec2171 () "1.11.0-jolt")))) clojure-version))) +(guard (e (#t #f)) + (def-var! "clojure.core" "numerator" (letrec ((numerator (lambda (x) (let fnrec2172 ((x x)) (jolt-throw (jolt-ex-info "numerator requires a ratio (Jolt has no ratios)" (jolt-hash-map))))))) numerator))) +(guard (e (#t #f)) + (def-var! "clojure.core" "denominator" (letrec ((denominator (lambda (x) (let fnrec2173 ((x x)) (jolt-throw (jolt-ex-info "denominator requires a ratio (Jolt has no ratios)" (jolt-hash-map))))))) denominator))) +(guard (e (#t #f)) + (def-var! "clojure.core" "supers" (letrec ((supers (lambda (x) (let fnrec2174 ((x x)) (jolt-hash-set))))) supers))) +(guard (e (#t #f)) + (def-var! "clojure.core" "munge" (letrec ((munge (lambda (s) (let fnrec2175 ((s s)) (let* ((m (jolt-invoke (var-deref "clojure.core" "str-replace-all") "-" "_" (jolt-invoke (var-deref "clojure.core" "str") s)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") s)) (jolt-invoke (var-deref "clojure.core" "symbol") m) m)))))) munge))) +(guard (e (#t #f)) + (def-var! "clojure.core" "test" (letrec ((test (lambda (v) (let fnrec2176 ((v v)) (let* ((t (jolt-get (jolt-invoke (var-deref "clojure.core" "meta") v) (keyword #f "test")))) (if (jolt-truthy? t) (begin (jolt-invoke t) (keyword #f "ok")) (keyword #f "no-test"))))))) test))) +(guard (e (#t #f)) + (def-var! "clojure.core" "find" (letrec ((find (lambda (m k) (let fnrec2177 ((m m) (k k)) (if (jolt-contains? m k) (jolt-first (let* ((_o$2178 k) (_o$2179 (jolt-get m k))) (jolt-hash-map _o$2178 _o$2179))) jolt-nil))))) find))) +(guard (e (#t #f)) + (def-var! "clojure.core" "true?" (letrec ((true? (lambda (x) (let fnrec2180 ((x x)) (jolt= #t x))))) true?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "false?" (letrec ((false? (lambda (x) (let fnrec2181 ((x x)) (jolt= #f x))))) false?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "select-keys" (letrec ((select-keys (lambda (map keyseq) (let fnrec2182 ((map map) (keyseq keyseq)) (let* ((_a$2184 (lambda (m k) (let fnrec2183 ((m m) (k k)) (if (jolt-contains? map k) (jolt-assoc m k (jolt-get map k)) m)))) (_a$2185 (jolt-hash-map )) (_a$2186 keyseq)) (jolt-reduce _a$2184 _a$2185 _a$2186)))))) select-keys))) +(guard (e (#t #f)) + (def-var! "clojure.core" "zipmap" (letrec ((zipmap (lambda (keys vals) (let fnrec2187 ((keys keys) (vals vals)) (let* ((m (jolt-hash-map )) (ks (jolt-seq keys)) (vs (jolt-seq vals))) (let loop2188 ((m m) (ks ks) (vs vs)) (if (jolt-truthy? (let* ((and__13__auto ks)) (if (jolt-truthy? and__13__auto) vs and__13__auto))) (let* ((_a$2192 (let* ((_a$2189 m) (_a$2190 (jolt-first ks)) (_a$2191 (jolt-first vs))) (jolt-assoc _a$2189 _a$2190 _a$2191))) (_a$2193 (jolt-next ks)) (_a$2194 (jolt-next vs))) (loop2188 _a$2192 _a$2193 _a$2194)) m))))))) zipmap))) +(guard (e (#t #f)) + (def-var! "clojure.core" "merge" (letrec ((merge (lambda maps (let fnrec2195 ((maps (list->cseq maps))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "some") jolt-identity maps)) (jolt-reduce (lambda (acc m) (let fnrec2196 ((acc acc) (m m)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") m)) acc (jolt-conj (let* ((or__14__auto acc)) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-hash-map ))) m)))) maps) jolt-nil))))) merge))) +(guard (e (#t #f)) + (def-var! "clojure.core" "merge-with" (letrec ((merge-with (lambda (f . maps) (let fnrec2197 ((f f) (maps (list->cseq maps))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "some") jolt-identity maps)) (let* ((merge-entry (lambda (m e) (let fnrec2198 ((m m) (e e)) (let* ((k (jolt-invoke (var-deref "clojure.core" "key") e)) (v (jolt-invoke (var-deref "clojure.core" "val") e))) (if (jolt-contains? m k) (jolt-assoc m k (jolt-invoke f (jolt-get m k) v)) (jolt-assoc m k v)))))) (merge2 (lambda (m1 m2) (let fnrec2199 ((m1 m1) (m2 m2)) (let* ((_a$2200 merge-entry) (_a$2201 (let* ((or__14__auto m1)) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-hash-map )))) (_a$2202 (jolt-seq m2))) (jolt-reduce _a$2200 _a$2201 _a$2202)))))) (jolt-reduce merge2 maps)) jolt-nil))))) merge-with))) +(guard (e (#t #f)) + (def-var! "clojure.core" "get-in" (letrec ((get-in (case-lambda ((m ks) (let fnrec2203 ((m m) (ks ks)) (jolt-reduce jolt-get m ks))) ((m ks not-found) (let fnrec2204 ((m m) (ks ks) (not-found not-found)) (let* ((sentinel (jolt-hash-map ))) (let* ((m m) (ks (jolt-seq ks))) (let loop2205 ((m m) (ks ks)) (if (jolt-truthy? ks) (let* ((nxt (jolt-get m (jolt-first ks) sentinel))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "identical?") sentinel nxt)) not-found (loop2205 nxt (jolt-next ks)))) m))))))))) get-in))) +(guard (e (#t #f)) + (def-var! "clojure.core" "memoize" (letrec ((memoize (lambda (f) (let fnrec2206 ((f f)) (let* ((mem (jolt-invoke (var-deref "clojure.core" "atom") (jolt-hash-map )))) (lambda args (let fnrec2207 ((args (list->cseq args))) (let* ((e (jolt-invoke (var-deref "clojure.core" "find") (jolt-invoke (var-deref "clojure.core" "deref") mem) args))) (if (jolt-truthy? e) (jolt-invoke (var-deref "clojure.core" "val") e) (let* ((ret (jolt-apply f args))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") mem jolt-assoc args ret) ret))))))))))) memoize))) +(guard (e (#t #f)) + (def-var! "clojure.core" "partial" (letrec ((partial (case-lambda ((f) (let fnrec2208 ((f f)) f)) ((f a) (let fnrec2209 ((f f) (a a)) (lambda args (let fnrec2210 ((args (list->cseq args))) (jolt-apply f a args))))) ((f a b) (let fnrec2211 ((f f) (a a) (b b)) (lambda args (let fnrec2212 ((args (list->cseq args))) (jolt-apply f a b args))))) ((f a b c) (let fnrec2213 ((f f) (a a) (b b) (c c)) (lambda args (let fnrec2214 ((args (list->cseq args))) (jolt-apply f a b c args))))) ((f a b c . more) (let fnrec2215 ((f f) (a a) (b b) (c c) (more (list->cseq more))) (lambda args (let fnrec2216 ((args (list->cseq args))) (jolt-apply f a b c (jolt-concat more args))))))))) partial))) +(guard (e (#t #f)) + (def-var! "clojure.core" "trampoline" (letrec ((trampoline (case-lambda ((f) (let fnrec2217 ((f f)) (let* ((ret (jolt-invoke f))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "fn?") ret)) (jolt-invoke trampoline ret) ret)))) ((f . args) (let fnrec2218 ((f f) (args (list->cseq args))) (jolt-invoke trampoline (lambda () (let fnrec2219 () (jolt-apply f args))))))))) trampoline))) +(guard (e (#t #f)) + (def-var! "clojure.core" "max" (letrec ((max (case-lambda ((x) (let fnrec2220 ((x x)) x)) ((x y) (let fnrec2221 ((x x) (y y)) (if (> x y) x y))) ((x y . more) (let fnrec2222 ((x x) (y y) (more (list->cseq more))) (jolt-reduce max (jolt-invoke max x y) more)))))) max))) +(guard (e (#t #f)) + (def-var! "clojure.core" "min" (letrec ((min (case-lambda ((x) (let fnrec2223 ((x x)) x)) ((x y) (let fnrec2224 ((x x) (y y)) (if (< x y) x y))) ((x y . more) (let fnrec2225 ((x x) (y y) (more (list->cseq more))) (jolt-reduce min (jolt-invoke min x y) more)))))) min))) +(guard (e (#t #f)) + (def-var! "clojure.core" "reverse" (letrec ((reverse (lambda (coll) (let fnrec2226 ((coll coll)) (jolt-reduce jolt-conj (jolt-list ) coll))))) reverse))) +(guard (e (#t #f)) + (def-var! "clojure.core" "empty" (letrec ((empty (lambda (coll) (let fnrec2227 ((coll coll)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") coll)) jolt-nil (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "sorted?") coll)) (jolt-invoke (jolt-get (jolt-invoke (var-deref "jolt.host" "ref-get") coll (keyword #f "ops")) (keyword #f "empty")) coll) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") coll)) (jolt-hash-map) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "set?") coll)) (jolt-hash-set) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") coll)) (jolt-vector) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "coll?") coll)) (jolt-list ) (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))))))))))) empty))) +(guard (e (#t #f)) + (def-var! "clojure.core" "assoc-in" (letrec ((assoc-in (lambda (m G__30 v) (let fnrec2228 ((m m) (G__30 G__30) (v v)) (let* ((G__31 G__30) (k (jolt-nth G__31 0 jolt-nil)) (ks (jolt-invoke (var-deref "clojure.core" "nthnext") G__31 1))) (if (jolt-truthy? ks) (jolt-assoc m k (jolt-invoke assoc-in (jolt-get m k) ks v)) (jolt-assoc m k v))))))) assoc-in))) +(guard (e (#t #f)) + (def-var! "clojure.core" "update-in" (letrec ((update-in (lambda (m ks f . args) (let fnrec2229 ((m m) (ks ks) (f f) (args (list->cseq args))) (let* ((up (letrec ((up (lambda (m ks f args) (let fnrec2230 ((m m) (ks ks) (f f) (args args)) (let* ((G__32 ks) (k (jolt-nth G__32 0 jolt-nil)) (ks (jolt-invoke (var-deref "clojure.core" "nthnext") G__32 1))) (if (jolt-truthy? ks) (jolt-assoc m k (jolt-invoke up (jolt-get m k) ks f args)) (jolt-assoc m k (jolt-apply f (jolt-get m k) args)))))))) up))) (jolt-invoke up m ks f args)))))) update-in))) +(guard (e (#t #f)) + (def-var! "clojure.core" "find-keyword" (letrec ((find-keyword (case-lambda ((nm) (let fnrec2231 ((nm nm)) (jolt-invoke (var-deref "clojure.core" "keyword") nm))) ((ns nm) (let fnrec2232 ((ns ns) (nm nm)) (jolt-invoke (var-deref "clojure.core" "keyword") ns nm)))))) find-keyword))) +(guard (e (#t #f)) + (def-var! "clojure.core" "inst-ms*" (letrec ((inst-ms* (lambda (i) (let fnrec2233 ((i i)) (jolt-invoke (var-deref "clojure.core" "inst-ms") i))))) inst-ms*))) +(guard (e (#t #f)) + (def-var! "clojure.core" "comp" (letrec ((comp (case-lambda (() (let fnrec2234 () jolt-identity)) ((f) (let fnrec2235 ((f f)) f)) ((f g) (let fnrec2236 ((f f) (g g)) (case-lambda (() (let fnrec2237 () (jolt-invoke f (jolt-invoke g)))) ((x) (let fnrec2238 ((x x)) (jolt-invoke f (jolt-invoke g x)))) ((x y) (let fnrec2239 ((x x) (y y)) (jolt-invoke f (jolt-invoke g x y)))) ((x y z) (let fnrec2240 ((x x) (y y) (z z)) (jolt-invoke f (jolt-invoke g x y z)))) ((x y z . args) (let fnrec2241 ((x x) (y y) (z z) (args (list->cseq args))) (jolt-invoke f (jolt-apply g x y z args))))))) ((f g . fs) (let fnrec2242 ((f f) (g g) (fs (list->cseq fs))) (jolt-reduce comp (jolt-invoke comp f g) fs)))))) comp))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ifn?" (letrec ((ifn? (lambda (x) (let fnrec2243 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "fn?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "keyword?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "map?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "set?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "var?") x))))))))))))))))) ifn?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "+'" jolt-add)) +(guard (e (#t #f)) + (def-var! "clojure.core" "-'" jolt-sub)) +(guard (e (#t #f)) + (def-var! "clojure.core" "*'" jolt-mul)) +(guard (e (#t #f)) + (def-var! "clojure.core" "inc'" jolt-inc)) +(guard (e (#t #f)) + (def-var! "clojure.core" "dec'" jolt-dec)) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-add" (letrec ((unchecked-add (lambda (x y) (let fnrec2244 ((x x) (y y)) (+ x y))))) unchecked-add))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-subtract" (letrec ((unchecked-subtract (lambda (x y) (let fnrec2245 ((x x) (y y)) (- x y))))) unchecked-subtract))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-multiply" (letrec ((unchecked-multiply (lambda (x y) (let fnrec2246 ((x x) (y y)) (* x y))))) unchecked-multiply))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-negate" (letrec ((unchecked-negate (lambda (x) (let fnrec2247 ((x x)) (- x))))) unchecked-negate))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-inc" (letrec ((unchecked-inc (lambda (x) (let fnrec2248 ((x x)) (+ x 1))))) unchecked-inc))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-dec" (letrec ((unchecked-dec (lambda (x) (let fnrec2249 ((x x)) (- x 1))))) unchecked-dec))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-add-int" (var-deref "clojure.core" "unchecked-add"))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-subtract-int" (var-deref "clojure.core" "unchecked-subtract"))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-multiply-int" (var-deref "clojure.core" "unchecked-multiply"))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-negate-int" (var-deref "clojure.core" "unchecked-negate"))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-inc-int" (var-deref "clojure.core" "unchecked-inc"))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-dec-int" (var-deref "clojure.core" "unchecked-dec"))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-divide-int" (letrec ((unchecked-divide-int (lambda (x y) (let fnrec2250 ((x x) (y y)) (quotient x y))))) unchecked-divide-int))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-remainder-int" (letrec ((unchecked-remainder-int (lambda (x y) (let fnrec2251 ((x x) (y y)) (remainder x y))))) unchecked-remainder-int))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-int" (letrec ((unchecked-int (lambda (x) (let fnrec2252 ((x x)) (jolt-invoke (var-deref "clojure.core" "int") x))))) unchecked-int))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-long" (var-deref "clojure.core" "unchecked-int"))) +(guard (e (#t #f)) + (def-var! "clojure.core" "int?" (letrec ((int? (lambda (x) (let fnrec2253 ((x x)) (jolt-invoke (var-deref "clojure.core" "integer?") x))))) int?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "num" (letrec ((num (lambda (x) (let fnrec2254 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) x (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "num requires a number, got: " x))))))) num))) +(guard (e (#t #f)) + (def-var! "clojure.core" "==" (letrec ((== (case-lambda ((x) (let fnrec2255 ((x x)) #t)) ((x y) (let fnrec2256 ((x x) (y y)) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "number?") x))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "number?") y) and__13__auto))) (jolt= x y) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "Cannot cast to number: " (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") x)) y x)))))) ((x y . more) (let fnrec2257 ((x x) (y y) (more (list->cseq more))) (if (jolt-truthy? (jolt-invoke == x y)) (jolt-apply == y more) #f)))))) ==))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ensure-reduced" (letrec ((ensure-reduced (lambda (x) (let fnrec2258 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "reduced?") x)) x (jolt-invoke (var-deref "clojure.core" "reduced") x)))))) ensure-reduced))) +(guard (e (#t #f)) + (def-var! "clojure.core" "halt-when" (letrec ((halt-when (case-lambda ((pred) (let fnrec2259 ((pred pred)) (jolt-invoke halt-when pred jolt-nil))) ((pred retf) (let fnrec2260 ((pred pred) (retf retf)) (lambda (rf) (let fnrec2261 ((rf rf)) (case-lambda (() (let fnrec2262 () (jolt-invoke rf))) ((result) (let fnrec2263 ((result result)) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "map?") result))) (if (jolt-truthy? and__13__auto) (jolt-contains? result (keyword #f "halt")) and__13__auto))) (jolt-get result (keyword #f "halt")) (jolt-invoke rf result)))) ((result input) (let fnrec2264 ((result result) (input input)) (if (jolt-truthy? (jolt-invoke pred input)) (jolt-invoke (var-deref "clojure.core" "reduced") (jolt-hash-map (keyword #f "halt") (if (jolt-truthy? retf) (jolt-invoke retf (jolt-invoke rf result) input) input))) (jolt-invoke rf result input)))))))))))) halt-when))) +(guard (e (#t #f)) + (def-var! "clojure.core" "parse-boolean" (letrec ((parse-boolean (lambda (s) (let fnrec2265 ((s s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") s)) (if (jolt= s "true") #t (if (jolt= s "false") #f (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil))) (jolt-throw (jolt-invoke (var-deref "clojure.core" "str") "parse-boolean requires a string, got: " s))))))) parse-boolean))) +(guard (e (#t #f)) + (def-var! "clojure.core" "newline" (letrec ((newline (lambda () (let fnrec2266 () (begin (jolt-invoke (var-deref "clojure.core" "print") "\n") jolt-nil))))) newline))) +(guard (e (#t #f)) + (def-var! "clojure.core" "seque" (letrec ((seque (case-lambda ((s) (let fnrec2267 ((s s)) s)) ((n-or-q s) (let fnrec2268 ((n-or-q n-or-q) (s s)) s))))) seque))) +(guard (e (#t #f)) + (def-var! "clojure.core" "array-seq" (letrec ((array-seq (lambda (arr . _) (let fnrec2269 ((arr arr) (_ (list->cseq _))) (jolt-seq arr))))) array-seq))) +(guard (e (#t #f)) + (def-var! "clojure.core" "to-array-2d" (letrec ((to-array-2d (lambda (coll) (let fnrec2270 ((coll coll)) (jolt-invoke (var-deref "clojure.core" "to-array") (jolt-map (var-deref "clojure.core" "to-array") coll)))))) to-array-2d))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-byte" (letrec ((unchecked-byte (lambda (x) (let fnrec2271 ((x x)) (jolt-invoke (var-deref "clojure.core" "bit-and") (jolt-invoke (var-deref "clojure.core" "int") x) 255))))) unchecked-byte))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-short" (letrec ((unchecked-short (lambda (x) (let fnrec2272 ((x x)) (jolt-invoke (var-deref "clojure.core" "bit-and") (jolt-invoke (var-deref "clojure.core" "int") x) 65535))))) unchecked-short))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-char" (letrec ((unchecked-char (lambda (x) (let fnrec2273 ((x x)) (jolt-invoke (var-deref "clojure.core" "char") (jolt-invoke (var-deref "clojure.core" "bit-and") (jolt-invoke (var-deref "clojure.core" "int") x) 65535)))))) unchecked-char))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-float" (letrec ((unchecked-float (lambda (x) (let fnrec2274 ((x x)) (jolt-invoke (var-deref "clojure.core" "double") x))))) unchecked-float))) +(guard (e (#t #f)) + (def-var! "clojure.core" "unchecked-double" (letrec ((unchecked-double (lambda (x) (let fnrec2275 ((x x)) (jolt-invoke (var-deref "clojure.core" "double") x))))) unchecked-double))) +(guard (e (#t #f)) + (def-var! "clojure.core" "transduce" (letrec ((transduce (case-lambda ((xform f coll) (let fnrec2276 ((xform xform) (f f) (coll coll)) (jolt-invoke transduce xform f (jolt-invoke f) coll))) ((xform f init coll) (let fnrec2277 ((xform xform) (f f) (init init) (coll coll)) (let* ((xf (jolt-invoke xform f))) (jolt-invoke xf (jolt-reduce xf init coll)))))))) transduce))) +(guard (e (#t #f)) + (def-var! "clojure.core" "eduction" (letrec ((eduction (lambda args (let fnrec2278 ((args (list->cseq args))) (let* ((coll (jolt-last args)) (xforms (jolt-invoke (var-deref "clojure.core" "butlast") args))) (if (jolt-truthy? xforms) (let* ((_a$2279 jolt-into) (_a$2280 (jolt-vector)) (_a$2281 (jolt-apply (var-deref "clojure.core" "comp") xforms)) (_a$2282 coll)) (jolt-invoke _a$2279 _a$2280 _a$2281 _a$2282)) (jolt-into (jolt-vector) coll))))))) eduction))) +(guard (e (#t #f)) + (def-var! "clojure.core" "->Eduction" (letrec ((->Eduction (lambda (xform coll) (let fnrec2283 ((xform xform) (coll coll)) (jolt-invoke jolt-into (jolt-vector) xform coll))))) ->Eduction))) +(guard (e (#t #f)) + (def-var! "clojure.core" "enumeration-seq" (letrec ((enumeration-seq (lambda (e) (let fnrec2284 ((e e)) (jolt-seq e))))) enumeration-seq))) +(guard (e (#t #f)) + (def-var! "clojure.core" "iterator-seq" (letrec ((iterator-seq (lambda (i) (let fnrec2285 ((i i)) (jolt-seq i))))) iterator-seq))) +(guard (e (#t #f)) + (def-var! "clojure.core" "promise" (letrec ((promise (lambda () (let fnrec2286 () (jolt-invoke (var-deref "clojure.core" "atom") jolt-nil))))) promise))) +(guard (e (#t #f)) + (def-var! "clojure.core" "deliver" (letrec ((deliver (lambda (p v) (let fnrec2287 ((p p) (v v)) (begin (jolt-invoke (var-deref "clojure.core" "reset!") p v) p))))) deliver))) +(guard (e (#t #f)) + (def-var! "clojure.core" "bean" (letrec ((bean (lambda (x) (let fnrec2288 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) x (jolt-hash-map)))))) bean))) +(guard (e (#t #f)) + (def-var! "clojure.core" "uri?" (letrec ((uri? (lambda (x) (let fnrec2289 ((x x)) #f)))) uri?))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "special-syms" (let* ((_o$2290 (jolt-symbol #f "if")) (_o$2291 (jolt-symbol #f "do")) (_o$2292 (jolt-symbol #f "let*")) (_o$2293 (jolt-symbol #f "fn*")) (_o$2294 (jolt-symbol #f "quote")) (_o$2295 (jolt-symbol #f "var")) (_o$2296 (jolt-symbol #f "def")) (_o$2297 (jolt-symbol #f "loop*")) (_o$2298 (jolt-symbol #f "recur")) (_o$2299 (jolt-symbol #f "throw")) (_o$2300 (jolt-symbol #f "try")) (_o$2301 (jolt-symbol #f "catch")) (_o$2302 (jolt-symbol #f "finally")) (_o$2303 (jolt-symbol #f "new")) (_o$2304 (jolt-symbol #f "set!")) (_o$2305 (jolt-symbol #f ".")) (_o$2306 (jolt-symbol #f "monitor-enter")) (_o$2307 (jolt-symbol #f "monitor-exit"))) (jolt-hash-set _o$2290 _o$2291 _o$2292 _o$2293 _o$2294 _o$2295 _o$2296 _o$2297 _o$2298 _o$2299 _o$2300 _o$2301 _o$2302 _o$2303 _o$2304 _o$2305 _o$2306 _o$2307)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "clojure.core" "special-symbol?" (letrec ((special-symbol? (lambda (s) (let fnrec2308 ((s s)) (jolt-contains? (var-deref "clojure.core" "special-syms") s))))) special-symbol?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "proxy-mappings" (letrec ((proxy-mappings (lambda (p) (let fnrec2309 ((p p)) (jolt-hash-map))))) proxy-mappings))) +(guard (e (#t #f)) + (def-var! "clojure.core" "proxy-call-with-super" (letrec ((proxy-call-with-super (lambda (f p meth) (let fnrec2310 ((f f) (p p) (meth meth)) (jolt-invoke f))))) proxy-call-with-super))) +(guard (e (#t #f)) + (def-var! "clojure.core" "init-proxy" (letrec ((init-proxy (lambda (p mappings) (let fnrec2311 ((p p) (mappings mappings)) p)))) init-proxy))) +(guard (e (#t #f)) + (def-var! "clojure.core" "update-proxy" (letrec ((update-proxy (lambda (p mappings) (let fnrec2312 ((p p) (mappings mappings)) p)))) update-proxy))) +(guard (e (#t #f)) + (def-var! "clojure.core" "proxy-super" (letrec ((proxy-super (lambda args (let fnrec2313 ((args (list->cseq args))) (jolt-throw "proxy-super: JVM proxies are not supported in Jolt"))))) proxy-super))) +(guard (e (#t #f)) + (def-var! "clojure.core" "construct-proxy" (letrec ((construct-proxy (lambda (c . args) (let fnrec2314 ((c c) (args (list->cseq args))) (jolt-throw "construct-proxy: not supported in Jolt"))))) construct-proxy))) +(guard (e (#t #f)) + (def-var! "clojure.core" "get-proxy-class" (letrec ((get-proxy-class (lambda interfaces (let fnrec2315 ((interfaces (list->cseq interfaces))) (jolt-throw "get-proxy-class: not supported in Jolt"))))) get-proxy-class))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sfield" (letrec ((sfield (lambda (sc k) (let fnrec361 ((sc sc) (k k)) (jolt-invoke (var-deref "jolt.host" "ref-get") sc k))))) sfield))) +(guard (e (#t #f)) + (def-var! "clojure.core" "fn->cmp" (letrec ((fn->cmp (lambda (f) (let fnrec362 ((f f)) (lambda (a b) (let fnrec363 ((a a) (b b)) (let* ((r (jolt-invoke f a b))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "number?") r)) r (if (jolt-truthy? r) -1 (if (jolt-truthy? (jolt-invoke f b a)) 1 0)))))))))) fn->cmp))) +(guard (e (#t #f)) + (def-var! "clojure.core" "the-cmp" (letrec ((the-cmp (lambda (sc) (let fnrec364 ((sc sc)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "sfield") sc (keyword #f "cmp")))) (if (jolt-truthy? or__14__auto) or__14__auto (var-deref "clojure.core" "compare"))))))) the-cmp))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nd-key" (letrec ((nd-key (lambda (n) (let fnrec365 ((n n)) (jolt-nth n 1))))) nd-key))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nd-val" (letrec ((nd-val (lambda (n) (let fnrec366 ((n n)) (jolt-nth n 2))))) nd-val))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nd-left" (letrec ((nd-left (lambda (n) (let fnrec367 ((n n)) (jolt-nth n 3))))) nd-left))) +(guard (e (#t #f)) + (def-var! "clojure.core" "nd-right" (letrec ((nd-right (lambda (n) (let fnrec368 ((n n)) (jolt-nth n 4))))) nd-right))) +(guard (e (#t #f)) + (def-var! "clojure.core" "red?" (letrec ((red? (lambda (n) (let fnrec369 ((n n)) (let* ((and__13__auto n)) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "identical?") (keyword #f "red") (jolt-nth n 0)) and__13__auto)))))) red?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "black?" (letrec ((black? (lambda (n) (let fnrec370 ((n n)) (let* ((and__13__auto n)) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "identical?") (keyword #f "black") (jolt-nth n 0)) and__13__auto)))))) black?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "mk-red" (letrec ((mk-red (lambda (k v l r) (let fnrec371 ((k k) (v v) (l l) (r r)) (let* ((_o$372 (keyword #f "red")) (_o$373 k) (_o$374 v) (_o$375 l) (_o$376 r)) (jolt-vector _o$372 _o$373 _o$374 _o$375 _o$376)))))) mk-red))) +(guard (e (#t #f)) + (def-var! "clojure.core" "mk-black" (letrec ((mk-black (lambda (k v l r) (let fnrec377 ((k k) (v v) (l l) (r r)) (let* ((_o$378 (keyword #f "black")) (_o$379 k) (_o$380 v) (_o$381 l) (_o$382 r)) (jolt-vector _o$378 _o$379 _o$380 _o$381 _o$382)))))) mk-black))) +(guard (e (#t #f)) + (def-var! "clojure.core" "blacken" (letrec ((blacken (lambda (n) (let fnrec383 ((n n)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") n)) (let* ((_o$384 (keyword #f "black")) (_o$385 (jolt-invoke (var-deref "clojure.core" "nd-key") n)) (_o$386 (jolt-invoke (var-deref "clojure.core" "nd-val") n)) (_o$387 (jolt-invoke (var-deref "clojure.core" "nd-left") n)) (_o$388 (jolt-invoke (var-deref "clojure.core" "nd-right") n))) (jolt-vector _o$384 _o$385 _o$386 _o$387 _o$388)) n))))) blacken))) +(guard (e (#t #f)) + (def-var! "clojure.core" "redden" (letrec ((redden (lambda (n) (let fnrec389 ((n n)) (let* ((_o$390 (keyword #f "red")) (_o$391 (jolt-invoke (var-deref "clojure.core" "nd-key") n)) (_o$392 (jolt-invoke (var-deref "clojure.core" "nd-val") n)) (_o$393 (jolt-invoke (var-deref "clojure.core" "nd-left") n)) (_o$394 (jolt-invoke (var-deref "clojure.core" "nd-right") n))) (jolt-vector _o$390 _o$391 _o$392 _o$393 _o$394)))))) redden))) +(guard (e (#t #f)) + (def-var! "clojure.core" "replace-node" (letrec ((replace-node (lambda (n k v l r) (let fnrec395 ((n n) (k k) (v v) (l l) (r r)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") n)) (jolt-invoke (var-deref "clojure.core" "mk-red") k v l r) (jolt-invoke (var-deref "clojure.core" "mk-black") k v l r)))))) replace-node))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ins-balance-left" (letrec ((ins-balance-left (lambda (ins parent) (let fnrec396 ((ins ins) (parent parent)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ins)) (let* ((l (jolt-invoke (var-deref "clojure.core" "nd-left") ins)) (r (jolt-invoke (var-deref "clojure.core" "nd-right") ins))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") l)) (let* ((_a$402 (var-deref "clojure.core" "mk-red")) (_a$403 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$404 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$405 (jolt-invoke (var-deref "clojure.core" "blacken") l)) (_a$406 (let* ((_a$397 (var-deref "clojure.core" "mk-black")) (_a$398 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$399 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$400 r) (_a$401 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$397 _a$398 _a$399 _a$400 _a$401)))) (jolt-invoke _a$402 _a$403 _a$404 _a$405 _a$406)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") r)) (let* ((_a$417 (var-deref "clojure.core" "mk-red")) (_a$418 (jolt-invoke (var-deref "clojure.core" "nd-key") r)) (_a$419 (jolt-invoke (var-deref "clojure.core" "nd-val") r)) (_a$420 (let* ((_a$407 (var-deref "clojure.core" "mk-black")) (_a$408 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$409 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$410 l) (_a$411 (jolt-invoke (var-deref "clojure.core" "nd-left") r))) (jolt-invoke _a$407 _a$408 _a$409 _a$410 _a$411))) (_a$421 (let* ((_a$412 (var-deref "clojure.core" "mk-black")) (_a$413 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$414 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$415 (jolt-invoke (var-deref "clojure.core" "nd-right") r)) (_a$416 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$412 _a$413 _a$414 _a$415 _a$416)))) (jolt-invoke _a$417 _a$418 _a$419 _a$420 _a$421)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$422 (var-deref "clojure.core" "mk-black")) (_a$423 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$424 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$425 ins) (_a$426 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$422 _a$423 _a$424 _a$425 _a$426)) jolt-nil)))) (let* ((_a$427 (var-deref "clojure.core" "mk-black")) (_a$428 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$429 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$430 ins) (_a$431 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$427 _a$428 _a$429 _a$430 _a$431))))))) ins-balance-left))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ins-balance-right" (letrec ((ins-balance-right (lambda (ins parent) (let fnrec432 ((ins ins) (parent parent)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ins)) (let* ((l (jolt-invoke (var-deref "clojure.core" "nd-left") ins)) (r (jolt-invoke (var-deref "clojure.core" "nd-right") ins))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") r)) (let* ((_a$438 (var-deref "clojure.core" "mk-red")) (_a$439 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$440 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$441 (let* ((_a$433 (var-deref "clojure.core" "mk-black")) (_a$434 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$435 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$436 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$437 l)) (jolt-invoke _a$433 _a$434 _a$435 _a$436 _a$437))) (_a$442 (jolt-invoke (var-deref "clojure.core" "blacken") r))) (jolt-invoke _a$438 _a$439 _a$440 _a$441 _a$442)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") l)) (let* ((_a$453 (var-deref "clojure.core" "mk-red")) (_a$454 (jolt-invoke (var-deref "clojure.core" "nd-key") l)) (_a$455 (jolt-invoke (var-deref "clojure.core" "nd-val") l)) (_a$456 (let* ((_a$443 (var-deref "clojure.core" "mk-black")) (_a$444 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$445 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$446 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$447 (jolt-invoke (var-deref "clojure.core" "nd-left") l))) (jolt-invoke _a$443 _a$444 _a$445 _a$446 _a$447))) (_a$457 (let* ((_a$448 (var-deref "clojure.core" "mk-black")) (_a$449 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$450 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$451 (jolt-invoke (var-deref "clojure.core" "nd-right") l)) (_a$452 r)) (jolt-invoke _a$448 _a$449 _a$450 _a$451 _a$452)))) (jolt-invoke _a$453 _a$454 _a$455 _a$456 _a$457)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$458 (var-deref "clojure.core" "mk-black")) (_a$459 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$460 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$461 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$462 ins)) (jolt-invoke _a$458 _a$459 _a$460 _a$461 _a$462)) jolt-nil)))) (let* ((_a$463 (var-deref "clojure.core" "mk-black")) (_a$464 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$465 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$466 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$467 ins)) (jolt-invoke _a$463 _a$464 _a$465 _a$466 _a$467))))))) ins-balance-right))) +(guard (e (#t #f)) + (def-var! "clojure.core" "add-left" (letrec ((add-left (lambda (parent ins) (let fnrec468 ((parent parent) (ins ins)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") parent)) (let* ((_a$469 (var-deref "clojure.core" "mk-red")) (_a$470 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$471 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$472 ins) (_a$473 (jolt-invoke (var-deref "clojure.core" "nd-right") parent))) (jolt-invoke _a$469 _a$470 _a$471 _a$472 _a$473)) (jolt-invoke (var-deref "clojure.core" "ins-balance-left") ins parent)))))) add-left))) +(guard (e (#t #f)) + (def-var! "clojure.core" "add-right" (letrec ((add-right (lambda (parent ins) (let fnrec474 ((parent parent) (ins ins)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") parent)) (let* ((_a$475 (var-deref "clojure.core" "mk-red")) (_a$476 (jolt-invoke (var-deref "clojure.core" "nd-key") parent)) (_a$477 (jolt-invoke (var-deref "clojure.core" "nd-val") parent)) (_a$478 (jolt-invoke (var-deref "clojure.core" "nd-left") parent)) (_a$479 ins)) (jolt-invoke _a$475 _a$476 _a$477 _a$478 _a$479)) (jolt-invoke (var-deref "clojure.core" "ins-balance-right") ins parent)))))) add-right))) +(guard (e (#t #f)) + (def-var! "clojure.core" "tree-ins" (letrec ((tree-ins (lambda (cmp tree k v) (let fnrec480 ((cmp cmp) (tree tree) (k k) (v v)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") tree)) (jolt-invoke (var-deref "clojure.core" "mk-red") k v jolt-nil jolt-nil) (if (jolt-neg? (jolt-invoke cmp k (jolt-invoke (var-deref "clojure.core" "nd-key") tree))) (jolt-invoke (var-deref "clojure.core" "add-left") tree (jolt-invoke tree-ins cmp (jolt-invoke (var-deref "clojure.core" "nd-left") tree) k v)) (jolt-invoke (var-deref "clojure.core" "add-right") tree (jolt-invoke tree-ins cmp (jolt-invoke (var-deref "clojure.core" "nd-right") tree) k v)))))))) tree-ins))) +(guard (e (#t #f)) + (def-var! "clojure.core" "tree-replace" (letrec ((tree-replace (lambda (cmp tree k v) (let fnrec481 ((cmp cmp) (tree tree) (k k) (v v)) (let* ((c (jolt-invoke cmp k (jolt-invoke (var-deref "clojure.core" "nd-key") tree)))) (if (jolt-zero? c) (let* ((_a$482 (var-deref "clojure.core" "replace-node")) (_a$483 tree) (_a$484 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$485 v) (_a$486 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$487 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$482 _a$483 _a$484 _a$485 _a$486 _a$487)) (if (jolt-neg? c) (let* ((_a$488 (var-deref "clojure.core" "replace-node")) (_a$489 tree) (_a$490 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$491 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$492 (jolt-invoke tree-replace cmp (jolt-invoke (var-deref "clojure.core" "nd-left") tree) k v)) (_a$493 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$488 _a$489 _a$490 _a$491 _a$492 _a$493)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$494 (var-deref "clojure.core" "replace-node")) (_a$495 tree) (_a$496 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$497 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$498 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$499 (jolt-invoke tree-replace cmp (jolt-invoke (var-deref "clojure.core" "nd-right") tree) k v))) (jolt-invoke _a$494 _a$495 _a$496 _a$497 _a$498 _a$499)) jolt-nil)))))))) tree-replace))) +(guard (e (#t #f)) + (def-var! "clojure.core" "tree-lookup" (letrec ((tree-lookup (lambda (tree cmp k) (let fnrec500 ((tree tree) (cmp cmp) (k k)) (let* ((t tree)) (let loop501 ((t t)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") t)) jolt-nil (let* ((c (jolt-invoke cmp k (jolt-invoke (var-deref "clojure.core" "nd-key") t)))) (if (jolt-zero? c) t (if (jolt-neg? c) (loop501 (jolt-invoke (var-deref "clojure.core" "nd-left") t)) (if (jolt-truthy? (keyword #f "else")) (loop501 (jolt-invoke (var-deref "clojure.core" "nd-right") t)) jolt-nil))))))))))) tree-lookup))) +(guard (e (#t #f)) + (def-var! "clojure.core" "balance-left" (letrec ((balance-left (lambda (k v ins right) (let fnrec502 ((k k) (v v) (ins ins) (right right)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ins)) (let* ((il (jolt-invoke (var-deref "clojure.core" "nd-left") ins)) (ir (jolt-invoke (var-deref "clojure.core" "nd-right") ins))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") il)) (let* ((_a$503 (var-deref "clojure.core" "mk-red")) (_a$504 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$505 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$506 (jolt-invoke (var-deref "clojure.core" "blacken") il)) (_a$507 (jolt-invoke (var-deref "clojure.core" "mk-black") k v ir right))) (jolt-invoke _a$503 _a$504 _a$505 _a$506 _a$507)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ir)) (let* ((_a$513 (var-deref "clojure.core" "mk-red")) (_a$514 (jolt-invoke (var-deref "clojure.core" "nd-key") ir)) (_a$515 (jolt-invoke (var-deref "clojure.core" "nd-val") ir)) (_a$516 (let* ((_a$508 (var-deref "clojure.core" "mk-black")) (_a$509 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$510 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$511 il) (_a$512 (jolt-invoke (var-deref "clojure.core" "nd-left") ir))) (jolt-invoke _a$508 _a$509 _a$510 _a$511 _a$512))) (_a$517 (jolt-invoke (var-deref "clojure.core" "mk-black") k v (jolt-invoke (var-deref "clojure.core" "nd-right") ir) right))) (jolt-invoke _a$513 _a$514 _a$515 _a$516 _a$517)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "mk-black") k v ins right) jolt-nil)))) (jolt-invoke (var-deref "clojure.core" "mk-black") k v ins right)))))) balance-left))) +(guard (e (#t #f)) + (def-var! "clojure.core" "balance-right" (letrec ((balance-right (lambda (k v left ins) (let fnrec518 ((k k) (v v) (left left) (ins ins)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ins)) (let* ((il (jolt-invoke (var-deref "clojure.core" "nd-left") ins)) (ir (jolt-invoke (var-deref "clojure.core" "nd-right") ins))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") ir)) (let* ((_a$519 (var-deref "clojure.core" "mk-red")) (_a$520 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$521 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$522 (jolt-invoke (var-deref "clojure.core" "mk-black") k v left il)) (_a$523 (jolt-invoke (var-deref "clojure.core" "blacken") ir))) (jolt-invoke _a$519 _a$520 _a$521 _a$522 _a$523)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") il)) (let* ((_a$529 (var-deref "clojure.core" "mk-red")) (_a$530 (jolt-invoke (var-deref "clojure.core" "nd-key") il)) (_a$531 (jolt-invoke (var-deref "clojure.core" "nd-val") il)) (_a$532 (jolt-invoke (var-deref "clojure.core" "mk-black") k v left (jolt-invoke (var-deref "clojure.core" "nd-left") il))) (_a$533 (let* ((_a$524 (var-deref "clojure.core" "mk-black")) (_a$525 (jolt-invoke (var-deref "clojure.core" "nd-key") ins)) (_a$526 (jolt-invoke (var-deref "clojure.core" "nd-val") ins)) (_a$527 (jolt-invoke (var-deref "clojure.core" "nd-right") il)) (_a$528 ir)) (jolt-invoke _a$524 _a$525 _a$526 _a$527 _a$528)))) (jolt-invoke _a$529 _a$530 _a$531 _a$532 _a$533)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "mk-black") k v left ins) jolt-nil)))) (jolt-invoke (var-deref "clojure.core" "mk-black") k v left ins)))))) balance-right))) +(guard (e (#t #f)) + (def-var! "clojure.core" "balance-left-del" (letrec ((balance-left-del (lambda (k v del right) (let fnrec534 ((k k) (v v) (del del) (right right)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") del)) (jolt-invoke (var-deref "clojure.core" "mk-red") k v (jolt-invoke (var-deref "clojure.core" "blacken") del) right) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "black?") right)) (jolt-invoke (var-deref "clojure.core" "balance-right") k v del (jolt-invoke (var-deref "clojure.core" "redden") right)) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "red?") right))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "black?") (jolt-invoke (var-deref "clojure.core" "nd-left") right)) and__13__auto))) (let* ((_a$540 (var-deref "clojure.core" "mk-red")) (_a$541 (jolt-invoke (var-deref "clojure.core" "nd-key") (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (_a$542 (jolt-invoke (var-deref "clojure.core" "nd-val") (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (_a$543 (jolt-invoke (var-deref "clojure.core" "mk-black") k v del (jolt-invoke (var-deref "clojure.core" "nd-left") (jolt-invoke (var-deref "clojure.core" "nd-left") right)))) (_a$544 (let* ((_a$535 (var-deref "clojure.core" "balance-right")) (_a$536 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$537 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$538 (jolt-invoke (var-deref "clojure.core" "nd-right") (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (_a$539 (jolt-invoke (var-deref "clojure.core" "redden") (jolt-invoke (var-deref "clojure.core" "nd-right") right)))) (jolt-invoke _a$535 _a$536 _a$537 _a$538 _a$539)))) (jolt-invoke _a$540 _a$541 _a$542 _a$543 _a$544)) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-ex-info "red-black tree invariant violation" (jolt-hash-map))) jolt-nil)))))))) balance-left-del))) +(guard (e (#t #f)) + (def-var! "clojure.core" "balance-right-del" (letrec ((balance-right-del (lambda (k v left del) (let fnrec545 ((k k) (v v) (left left) (del del)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") del)) (jolt-invoke (var-deref "clojure.core" "mk-red") k v left (jolt-invoke (var-deref "clojure.core" "blacken") del)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "black?") left)) (jolt-invoke (var-deref "clojure.core" "balance-left") k v (jolt-invoke (var-deref "clojure.core" "redden") left) del) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "red?") left))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "black?") (jolt-invoke (var-deref "clojure.core" "nd-right") left)) and__13__auto))) (let* ((_a$551 (var-deref "clojure.core" "mk-red")) (_a$552 (jolt-invoke (var-deref "clojure.core" "nd-key") (jolt-invoke (var-deref "clojure.core" "nd-right") left))) (_a$553 (jolt-invoke (var-deref "clojure.core" "nd-val") (jolt-invoke (var-deref "clojure.core" "nd-right") left))) (_a$554 (let* ((_a$546 (var-deref "clojure.core" "balance-left")) (_a$547 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$548 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$549 (jolt-invoke (var-deref "clojure.core" "redden") (jolt-invoke (var-deref "clojure.core" "nd-left") left))) (_a$550 (jolt-invoke (var-deref "clojure.core" "nd-left") (jolt-invoke (var-deref "clojure.core" "nd-right") left)))) (jolt-invoke _a$546 _a$547 _a$548 _a$549 _a$550))) (_a$555 (jolt-invoke (var-deref "clojure.core" "mk-black") k v (jolt-invoke (var-deref "clojure.core" "nd-right") (jolt-invoke (var-deref "clojure.core" "nd-right") left)) del))) (jolt-invoke _a$551 _a$552 _a$553 _a$554 _a$555)) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-ex-info "red-black tree invariant violation" (jolt-hash-map))) jolt-nil)))))))) balance-right-del))) +(guard (e (#t #f)) + (def-var! "clojure.core" "tree-append" (letrec ((tree-append (lambda (left right) (let fnrec556 ((left left) (right right)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") left)) right (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") right)) left (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") left)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") right)) (let* ((app (let* ((_a$557 tree-append) (_a$558 (jolt-invoke (var-deref "clojure.core" "nd-right") left)) (_a$559 (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (jolt-invoke _a$557 _a$558 _a$559)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") app)) (let* ((_a$570 (var-deref "clojure.core" "mk-red")) (_a$571 (jolt-invoke (var-deref "clojure.core" "nd-key") app)) (_a$572 (jolt-invoke (var-deref "clojure.core" "nd-val") app)) (_a$573 (let* ((_a$560 (var-deref "clojure.core" "mk-red")) (_a$561 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$562 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$563 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$564 (jolt-invoke (var-deref "clojure.core" "nd-left") app))) (jolt-invoke _a$560 _a$561 _a$562 _a$563 _a$564))) (_a$574 (let* ((_a$565 (var-deref "clojure.core" "mk-red")) (_a$566 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$567 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$568 (jolt-invoke (var-deref "clojure.core" "nd-right") app)) (_a$569 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$565 _a$566 _a$567 _a$568 _a$569)))) (jolt-invoke _a$570 _a$571 _a$572 _a$573 _a$574)) (let* ((_a$580 (var-deref "clojure.core" "mk-red")) (_a$581 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$582 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$583 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$584 (let* ((_a$575 (var-deref "clojure.core" "mk-red")) (_a$576 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$577 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$578 app) (_a$579 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$575 _a$576 _a$577 _a$578 _a$579)))) (jolt-invoke _a$580 _a$581 _a$582 _a$583 _a$584)))) (let* ((_a$585 (var-deref "clojure.core" "mk-red")) (_a$586 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$587 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$588 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$589 (jolt-invoke tree-append (jolt-invoke (var-deref "clojure.core" "nd-right") left) right))) (jolt-invoke _a$585 _a$586 _a$587 _a$588 _a$589))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") right)) (let* ((_a$590 (var-deref "clojure.core" "mk-red")) (_a$591 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$592 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$593 (jolt-invoke tree-append left (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (_a$594 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$590 _a$591 _a$592 _a$593 _a$594)) (if (jolt-truthy? (keyword #f "else")) (let* ((app (let* ((_a$595 tree-append) (_a$596 (jolt-invoke (var-deref "clojure.core" "nd-right") left)) (_a$597 (jolt-invoke (var-deref "clojure.core" "nd-left") right))) (jolt-invoke _a$595 _a$596 _a$597)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "red?") app)) (let* ((_a$608 (var-deref "clojure.core" "mk-red")) (_a$609 (jolt-invoke (var-deref "clojure.core" "nd-key") app)) (_a$610 (jolt-invoke (var-deref "clojure.core" "nd-val") app)) (_a$611 (let* ((_a$598 (var-deref "clojure.core" "mk-black")) (_a$599 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$600 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$601 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$602 (jolt-invoke (var-deref "clojure.core" "nd-left") app))) (jolt-invoke _a$598 _a$599 _a$600 _a$601 _a$602))) (_a$612 (let* ((_a$603 (var-deref "clojure.core" "mk-black")) (_a$604 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$605 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$606 (jolt-invoke (var-deref "clojure.core" "nd-right") app)) (_a$607 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$603 _a$604 _a$605 _a$606 _a$607)))) (jolt-invoke _a$608 _a$609 _a$610 _a$611 _a$612)) (let* ((_a$618 (var-deref "clojure.core" "balance-left-del")) (_a$619 (jolt-invoke (var-deref "clojure.core" "nd-key") left)) (_a$620 (jolt-invoke (var-deref "clojure.core" "nd-val") left)) (_a$621 (jolt-invoke (var-deref "clojure.core" "nd-left") left)) (_a$622 (let* ((_a$613 (var-deref "clojure.core" "mk-black")) (_a$614 (jolt-invoke (var-deref "clojure.core" "nd-key") right)) (_a$615 (jolt-invoke (var-deref "clojure.core" "nd-val") right)) (_a$616 app) (_a$617 (jolt-invoke (var-deref "clojure.core" "nd-right") right))) (jolt-invoke _a$613 _a$614 _a$615 _a$616 _a$617)))) (jolt-invoke _a$618 _a$619 _a$620 _a$621 _a$622)))) jolt-nil))))))))) tree-append))) +(guard (e (#t #f)) + (def-var! "clojure.core" "tree-del" (letrec ((tree-del (lambda (cmp tree k) (let fnrec623 ((cmp cmp) (tree tree) (k k)) (let* ((c (jolt-invoke cmp k (jolt-invoke (var-deref "clojure.core" "nd-key") tree)))) (if (jolt-zero? c) (let* ((_a$624 (var-deref "clojure.core" "tree-append")) (_a$625 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$626 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$624 _a$625 _a$626)) (if (jolt-neg? c) (let* ((del (jolt-invoke tree-del cmp (jolt-invoke (var-deref "clojure.core" "nd-left") tree) k))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "black?") (jolt-invoke (var-deref "clojure.core" "nd-left") tree))) (let* ((_a$627 (var-deref "clojure.core" "balance-left-del")) (_a$628 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$629 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$630 del) (_a$631 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$627 _a$628 _a$629 _a$630 _a$631)) (let* ((_a$632 (var-deref "clojure.core" "mk-red")) (_a$633 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$634 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$635 del) (_a$636 (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (jolt-invoke _a$632 _a$633 _a$634 _a$635 _a$636)))) (if (jolt-truthy? (keyword #f "else")) (let* ((del (jolt-invoke tree-del cmp (jolt-invoke (var-deref "clojure.core" "nd-right") tree) k))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "black?") (jolt-invoke (var-deref "clojure.core" "nd-right") tree))) (let* ((_a$637 (var-deref "clojure.core" "balance-right-del")) (_a$638 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$639 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$640 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$641 del)) (jolt-invoke _a$637 _a$638 _a$639 _a$640 _a$641)) (let* ((_a$642 (var-deref "clojure.core" "mk-red")) (_a$643 (jolt-invoke (var-deref "clojure.core" "nd-key") tree)) (_a$644 (jolt-invoke (var-deref "clojure.core" "nd-val") tree)) (_a$645 (jolt-invoke (var-deref "clojure.core" "nd-left") tree)) (_a$646 del)) (jolt-invoke _a$642 _a$643 _a$644 _a$645 _a$646)))) jolt-nil)))))))) tree-del))) +(guard (e (#t #f)) + (def-var! "clojure.core" "tree-collect" (letrec ((tree-collect (lambda (t proj acc) (let fnrec647 ((t t) (proj proj) (acc acc)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") t)) acc (let* ((_a$650 tree-collect) (_a$651 (jolt-invoke (var-deref "clojure.core" "nd-right") t)) (_a$652 proj) (_a$653 (let* ((_a$648 (jolt-invoke tree-collect (jolt-invoke (var-deref "clojure.core" "nd-left") t) proj acc)) (_a$649 (jolt-invoke proj t))) (jolt-conj _a$648 _a$649)))) (jolt-invoke _a$650 _a$651 _a$652 _a$653))))))) tree-collect))) +(guard (e (#t #f)) + (def-var! "clojure.core" "make-sorted" (letrec ((make-sorted (lambda (tag tree cnt cmp ops) (let fnrec654 ((tag tag) (tree tree) (cnt cnt) (cmp cmp) (ops ops)) (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-invoke (var-deref "jolt.host" "ref-put!") (jolt-invoke (var-deref "jolt.host" "tagged-table") tag) (keyword #f "tree") tree) (keyword #f "cnt") cnt) (keyword #f "cmp") cmp) (keyword #f "ops") ops))))) make-sorted))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sc-entries" (letrec ((sc-entries (lambda (sc proj) (let fnrec655 ((sc sc) (proj proj)) (let* ((_a$656 (var-deref "clojure.core" "tree-collect")) (_a$657 (jolt-invoke (var-deref "clojure.core" "sfield") sc (keyword #f "tree"))) (_a$658 proj) (_a$659 (jolt-vector))) (jolt-invoke _a$656 _a$657 _a$658 _a$659)))))) sc-entries))) +(guard (e (#t #f)) + (def-var! "clojure.core" "map-entry" (letrec ((map-entry (lambda (t) (let fnrec660 ((t t)) (let* ((_a$661 (var-deref "jolt.host" "map-entry")) (_a$662 (jolt-invoke (var-deref "clojure.core" "nd-key") t)) (_a$663 (jolt-invoke (var-deref "clojure.core" "nd-val") t))) (jolt-invoke _a$661 _a$662 _a$663)))))) map-entry))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sm-get" (letrec ((sm-get (lambda (sm k not-found) (let fnrec664 ((sm sm) (k k) (not-found not-found)) (let* ((n (let* ((_a$665 (var-deref "clojure.core" "tree-lookup")) (_a$666 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "tree"))) (_a$667 (jolt-invoke (var-deref "clojure.core" "the-cmp") sm)) (_a$668 k)) (jolt-invoke _a$665 _a$666 _a$667 _a$668)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") n)) not-found (jolt-invoke (var-deref "clojure.core" "nd-val") n))))))) sm-get))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sm-assoc-1" (letrec ((sm-assoc-1 (lambda (sm k v) (let fnrec669 ((sm sm) (k k) (v v)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") sm)) (tree (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "tree"))) (node (jolt-invoke (var-deref "clojure.core" "tree-lookup") tree cmp k))) (if (jolt-truthy? (let* ((and__13__auto node)) (if (jolt-truthy? and__13__auto) (jolt= v (jolt-invoke (var-deref "clojure.core" "nd-val") node)) and__13__auto))) sm (if (jolt-truthy? node) (let* ((_a$670 (var-deref "clojure.core" "make-sorted")) (_a$671 (keyword "jolt" "sorted-map")) (_a$672 (jolt-invoke (var-deref "clojure.core" "tree-replace") cmp tree k v)) (_a$673 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cnt"))) (_a$674 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cmp"))) (_a$675 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "ops")))) (jolt-invoke _a$670 _a$671 _a$672 _a$673 _a$674 _a$675)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$676 (var-deref "clojure.core" "make-sorted")) (_a$677 (keyword "jolt" "sorted-map")) (_a$678 (jolt-invoke (var-deref "clojure.core" "blacken") (jolt-invoke (var-deref "clojure.core" "tree-ins") cmp tree k v))) (_a$679 (jolt-inc (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cnt")))) (_a$680 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cmp"))) (_a$681 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "ops")))) (jolt-invoke _a$676 _a$677 _a$678 _a$679 _a$680 _a$681)) jolt-nil)))))))) sm-assoc-1))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sm-assoc-many" (letrec ((sm-assoc-many (lambda (sm kvs) (let fnrec682 ((sm sm) (kvs kvs)) (let* ((n (jolt-count kvs))) (begin (if (jolt-odd? n) (jolt-throw (jolt-ex-info "sorted-map assoc expects an even number of key/values" (let* ((_o$683 (keyword #f "count")) (_o$684 n)) (jolt-hash-map _o$683 _o$684)))) jolt-nil) (let* ((m sm) (i 0)) (let loop685 ((m m) (i i)) (if (< i n) (let* ((_a$690 (let* ((_a$686 (var-deref "clojure.core" "sm-assoc-1")) (_a$687 m) (_a$688 (jolt-nth kvs i)) (_a$689 (jolt-nth kvs (jolt-inc i)))) (jolt-invoke _a$686 _a$687 _a$688 _a$689))) (_a$691 (+ i 2))) (loop685 _a$690 _a$691)) m))))))))) sm-assoc-many))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sm-dissoc-1" (letrec ((sm-dissoc-1 (lambda (sm k) (let fnrec692 ((sm sm) (k k)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") sm)) (tree (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "tree")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-invoke (var-deref "clojure.core" "tree-lookup") tree cmp k))) sm (let* ((t (jolt-invoke (var-deref "clojure.core" "tree-del") cmp tree k))) (let* ((_a$693 (var-deref "clojure.core" "make-sorted")) (_a$694 (keyword "jolt" "sorted-map")) (_a$695 (if (jolt-truthy? t) (jolt-invoke (var-deref "clojure.core" "blacken") t) jolt-nil)) (_a$696 (jolt-dec (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cnt")))) (_a$697 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cmp"))) (_a$698 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "ops")))) (jolt-invoke _a$693 _a$694 _a$695 _a$696 _a$697 _a$698))))))))) sm-dissoc-1))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sm-dissoc-many" (letrec ((sm-dissoc-many (lambda (sm ks) (let fnrec699 ((sm sm) (ks ks)) (jolt-reduce (var-deref "clojure.core" "sm-dissoc-1") sm ks))))) sm-dissoc-many))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sm-conj-1" (letrec ((sm-conj-1 (lambda (sm x) (let fnrec700 ((sm sm) (x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") x)) sm (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) (let* ((_a$706 (lambda (m e) (let fnrec701 ((m m) (e e)) (let* ((_a$702 (var-deref "clojure.core" "sm-assoc-1")) (_a$703 m) (_a$704 (jolt-first e)) (_a$705 (jolt-invoke (var-deref "clojure.core" "second") e))) (jolt-invoke _a$702 _a$703 _a$704 _a$705))))) (_a$707 sm) (_a$708 (jolt-seq x))) (jolt-reduce _a$706 _a$707 _a$708)) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "vector?") x))) (if (jolt-truthy? and__13__auto) (jolt= 2 (jolt-count x)) and__13__auto))) (let* ((_a$709 (var-deref "clojure.core" "sm-assoc-1")) (_a$710 sm) (_a$711 (jolt-nth x 0)) (_a$712 (jolt-nth x 1))) (jolt-invoke _a$709 _a$710 _a$711 _a$712)) (if (jolt-truthy? (keyword #f "else")) (jolt-throw (jolt-ex-info "conj on a sorted-map requires a [key value] pair or a map" (jolt-hash-map))) jolt-nil)))))))) sm-conj-1))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sm-conj-many" (letrec ((sm-conj-many (lambda (sm xs) (let fnrec713 ((sm sm) (xs xs)) (jolt-reduce (var-deref "clojure.core" "sm-conj-1") sm xs))))) sm-conj-many))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ss-get" (letrec ((ss-get (lambda (ss x not-found) (let fnrec714 ((ss ss) (x x) (not-found not-found)) (let* ((n (let* ((_a$715 (var-deref "clojure.core" "tree-lookup")) (_a$716 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "tree"))) (_a$717 (jolt-invoke (var-deref "clojure.core" "the-cmp") ss)) (_a$718 x)) (jolt-invoke _a$715 _a$716 _a$717 _a$718)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") n)) not-found (jolt-invoke (var-deref "clojure.core" "nd-key") n))))))) ss-get))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ss-conj-1" (letrec ((ss-conj-1 (lambda (ss x) (let fnrec719 ((ss ss) (x x)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") ss)) (tree (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "tree")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "tree-lookup") tree cmp x)) ss (let* ((_a$720 (var-deref "clojure.core" "make-sorted")) (_a$721 (keyword "jolt" "sorted-set")) (_a$722 (jolt-invoke (var-deref "clojure.core" "blacken") (jolt-invoke (var-deref "clojure.core" "tree-ins") cmp tree x jolt-nil))) (_a$723 (jolt-inc (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cnt")))) (_a$724 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cmp"))) (_a$725 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "ops")))) (jolt-invoke _a$720 _a$721 _a$722 _a$723 _a$724 _a$725)))))))) ss-conj-1))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ss-conj-many" (letrec ((ss-conj-many (lambda (ss xs) (let fnrec726 ((ss ss) (xs xs)) (jolt-reduce (var-deref "clojure.core" "ss-conj-1") ss xs))))) ss-conj-many))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ss-disj-1" (letrec ((ss-disj-1 (lambda (ss x) (let fnrec727 ((ss ss) (x x)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") ss)) (tree (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "tree")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-invoke (var-deref "clojure.core" "tree-lookup") tree cmp x))) ss (let* ((t (jolt-invoke (var-deref "clojure.core" "tree-del") cmp tree x))) (let* ((_a$728 (var-deref "clojure.core" "make-sorted")) (_a$729 (keyword "jolt" "sorted-set")) (_a$730 (if (jolt-truthy? t) (jolt-invoke (var-deref "clojure.core" "blacken") t) jolt-nil)) (_a$731 (jolt-dec (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cnt")))) (_a$732 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cmp"))) (_a$733 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "ops")))) (jolt-invoke _a$728 _a$729 _a$730 _a$731 _a$732 _a$733))))))))) ss-disj-1))) +(guard (e (#t #f)) + (def-var! "clojure.core" "ss-disj-many" (letrec ((ss-disj-many (lambda (ss xs) (let fnrec734 ((ss ss) (xs xs)) (jolt-reduce (var-deref "clojure.core" "ss-disj-1") ss xs))))) ss-disj-many))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "sm-ops" (let* ((_o$752 (keyword #f "count")) (_o$753 (lambda (sm) (let fnrec735 ((sm sm)) (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cnt"))))) (_o$754 (keyword #f "entries")) (_o$755 (lambda (sm) (let fnrec736 ((sm sm)) (jolt-invoke (var-deref "clojure.core" "sc-entries") sm (var-deref "clojure.core" "map-entry"))))) (_o$756 (keyword #f "seq")) (_o$757 (lambda (sm) (let fnrec737 ((sm sm)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "sc-entries") sm (var-deref "clojure.core" "map-entry")))))) (_o$758 (keyword #f "rseq")) (_o$759 (lambda (sm) (let fnrec738 ((sm sm)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "vec") (jolt-reverse (jolt-invoke (var-deref "clojure.core" "sc-entries") sm (var-deref "clojure.core" "map-entry")))))))) (_o$760 (keyword #f "first")) (_o$761 (lambda (sm) (let fnrec739 ((sm sm)) (jolt-first (jolt-invoke (var-deref "clojure.core" "sc-entries") sm (var-deref "clojure.core" "map-entry")))))) (_o$762 (keyword #f "get")) (_o$763 (var-deref "clojure.core" "sm-get")) (_o$764 (keyword #f "contains")) (_o$765 (lambda (sm k) (let fnrec740 ((sm sm) (k k)) (jolt-not (jolt-invoke (var-deref "clojure.core" "nil?") (let* ((_a$741 (var-deref "clojure.core" "tree-lookup")) (_a$742 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "tree"))) (_a$743 (jolt-invoke (var-deref "clojure.core" "the-cmp") sm)) (_a$744 k)) (jolt-invoke _a$741 _a$742 _a$743 _a$744))))))) (_o$766 (keyword #f "assoc")) (_o$767 (var-deref "clojure.core" "sm-assoc-many")) (_o$768 (keyword #f "dissoc")) (_o$769 (var-deref "clojure.core" "sm-dissoc-many")) (_o$770 (keyword #f "conj")) (_o$771 (var-deref "clojure.core" "sm-conj-many")) (_o$772 (keyword #f "empty")) (_o$773 (lambda (sm) (let fnrec745 ((sm sm)) (let* ((_a$746 (var-deref "clojure.core" "make-sorted")) (_a$747 (keyword "jolt" "sorted-map")) (_a$748 jolt-nil) (_a$749 0) (_a$750 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "cmp"))) (_a$751 (jolt-invoke (var-deref "clojure.core" "sfield") sm (keyword #f "ops")))) (jolt-invoke _a$746 _a$747 _a$748 _a$749 _a$750 _a$751)))))) (jolt-hash-map _o$752 _o$753 _o$754 _o$755 _o$756 _o$757 _o$758 _o$759 _o$760 _o$761 _o$762 _o$763 _o$764 _o$765 _o$766 _o$767 _o$768 _o$769 _o$770 _o$771 _o$772 _o$773)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "ss-ops" (let* ((_o$791 (keyword #f "count")) (_o$792 (lambda (ss) (let fnrec774 ((ss ss)) (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cnt"))))) (_o$793 (keyword #f "entries")) (_o$794 (lambda (ss) (let fnrec775 ((ss ss)) (jolt-invoke (var-deref "clojure.core" "sc-entries") ss (var-deref "clojure.core" "nd-key"))))) (_o$795 (keyword #f "seq")) (_o$796 (lambda (ss) (let fnrec776 ((ss ss)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "sc-entries") ss (var-deref "clojure.core" "nd-key")))))) (_o$797 (keyword #f "rseq")) (_o$798 (lambda (ss) (let fnrec777 ((ss ss)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "vec") (jolt-reverse (jolt-invoke (var-deref "clojure.core" "sc-entries") ss (var-deref "clojure.core" "nd-key")))))))) (_o$799 (keyword #f "first")) (_o$800 (lambda (ss) (let fnrec778 ((ss ss)) (jolt-first (jolt-invoke (var-deref "clojure.core" "sc-entries") ss (var-deref "clojure.core" "nd-key")))))) (_o$801 (keyword #f "get")) (_o$802 (var-deref "clojure.core" "ss-get")) (_o$803 (keyword #f "contains")) (_o$804 (lambda (ss x) (let fnrec779 ((ss ss) (x x)) (jolt-not (jolt-invoke (var-deref "clojure.core" "nil?") (let* ((_a$780 (var-deref "clojure.core" "tree-lookup")) (_a$781 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "tree"))) (_a$782 (jolt-invoke (var-deref "clojure.core" "the-cmp") ss)) (_a$783 x)) (jolt-invoke _a$780 _a$781 _a$782 _a$783))))))) (_o$805 (keyword #f "conj")) (_o$806 (var-deref "clojure.core" "ss-conj-many")) (_o$807 (keyword #f "disj")) (_o$808 (var-deref "clojure.core" "ss-disj-many")) (_o$809 (keyword #f "empty")) (_o$810 (lambda (ss) (let fnrec784 ((ss ss)) (let* ((_a$785 (var-deref "clojure.core" "make-sorted")) (_a$786 (keyword "jolt" "sorted-set")) (_a$787 jolt-nil) (_a$788 0) (_a$789 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "cmp"))) (_a$790 (jolt-invoke (var-deref "clojure.core" "sfield") ss (keyword #f "ops")))) (jolt-invoke _a$785 _a$786 _a$787 _a$788 _a$789 _a$790)))))) (jolt-hash-map _o$791 _o$792 _o$793 _o$794 _o$795 _o$796 _o$797 _o$798 _o$799 _o$800 _o$801 _o$802 _o$803 _o$804 _o$805 _o$806 _o$807 _o$808 _o$809 _o$810)) (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sorted-map" (letrec ((sorted-map (lambda kvs (let fnrec811 ((kvs (list->cseq kvs))) (let* ((_a$812 (var-deref "clojure.core" "sm-assoc-many")) (_a$813 (jolt-invoke (var-deref "clojure.core" "make-sorted") (keyword "jolt" "sorted-map") jolt-nil 0 jolt-nil (var-deref "clojure.core" "sm-ops"))) (_a$814 (jolt-invoke (var-deref "clojure.core" "vec") kvs))) (jolt-invoke _a$812 _a$813 _a$814)))))) sorted-map))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sorted-map-by" (letrec ((sorted-map-by (lambda (comparator . kvs) (let fnrec815 ((comparator comparator) (kvs (list->cseq kvs))) (let* ((_a$816 (var-deref "clojure.core" "sm-assoc-many")) (_a$817 (jolt-invoke (var-deref "clojure.core" "make-sorted") (keyword "jolt" "sorted-map") jolt-nil 0 (jolt-invoke (var-deref "clojure.core" "fn->cmp") comparator) (var-deref "clojure.core" "sm-ops"))) (_a$818 (jolt-invoke (var-deref "clojure.core" "vec") kvs))) (jolt-invoke _a$816 _a$817 _a$818)))))) sorted-map-by))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sorted-set" (letrec ((sorted-set (lambda xs (let fnrec819 ((xs (list->cseq xs))) (let* ((_a$820 (var-deref "clojure.core" "ss-conj-many")) (_a$821 (jolt-invoke (var-deref "clojure.core" "make-sorted") (keyword "jolt" "sorted-set") jolt-nil 0 jolt-nil (var-deref "clojure.core" "ss-ops"))) (_a$822 (jolt-invoke (var-deref "clojure.core" "vec") xs))) (jolt-invoke _a$820 _a$821 _a$822)))))) sorted-set))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sorted-set-by" (letrec ((sorted-set-by (lambda (comparator . xs) (let fnrec823 ((comparator comparator) (xs (list->cseq xs))) (let* ((_a$824 (var-deref "clojure.core" "ss-conj-many")) (_a$825 (jolt-invoke (var-deref "clojure.core" "make-sorted") (keyword "jolt" "sorted-set") jolt-nil 0 (jolt-invoke (var-deref "clojure.core" "fn->cmp") comparator) (var-deref "clojure.core" "ss-ops"))) (_a$826 (jolt-invoke (var-deref "clojure.core" "vec") xs))) (jolt-invoke _a$824 _a$825 _a$826)))))) sorted-set-by))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sorted-map?" (letrec ((sorted-map? (lambda (x) (let fnrec827 ((x x)) (jolt= (keyword "jolt" "sorted-map") (jolt-invoke (var-deref "clojure.core" "sfield") x (keyword "jolt" "type"))))))) sorted-map?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sorted-set?" (letrec ((sorted-set? (lambda (x) (let fnrec828 ((x x)) (jolt= (keyword "jolt" "sorted-set") (jolt-invoke (var-deref "clojure.core" "sfield") x (keyword "jolt" "type"))))))) sorted-set?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sorted?" (letrec ((sorted? (lambda (x) (let fnrec829 ((x x)) (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "sorted-map?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "sorted-set?") x))))))) sorted?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sc-keyf" (letrec ((sc-keyf (lambda (sc) (let fnrec830 ((sc sc)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "sorted-map?") sc)) jolt-first jolt-identity))))) sc-keyf))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sc-proj" (letrec ((sc-proj (lambda (sc) (let fnrec831 ((sc sc)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "sorted-map?") sc)) (var-deref "clojure.core" "map-entry") (var-deref "clojure.core" "nd-key")))))) sc-proj))) +(guard (e (#t #f)) + (def-var! "clojure.core" "sub-filter" (letrec ((sub-filter (lambda (sc tests) (let fnrec832 ((sc sc) (tests tests)) (let* ((cmp (jolt-invoke (var-deref "clojure.core" "the-cmp") sc)) (keyf (jolt-invoke (var-deref "clojure.core" "sc-keyf") sc))) (let* ((_a$835 (var-deref "clojure.core" "filterv")) (_a$836 (lambda (e) (let fnrec833 ((e e)) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (G__15) (let fnrec834 ((G__15 G__15)) (let* ((G__16 G__15) (test (jolt-nth G__16 0 jolt-nil)) (k (jolt-nth G__16 1 jolt-nil))) (jolt-invoke test (jolt-invoke cmp (jolt-invoke keyf e) k) 0)))) tests)))) (_a$837 (jolt-invoke (var-deref "clojure.core" "sc-entries") sc (jolt-invoke (var-deref "clojure.core" "sc-proj") sc)))) (jolt-invoke _a$835 _a$836 _a$837))))))) sub-filter))) +(guard (e (#t #f)) + (def-var! "clojure.core" "subseq" (letrec ((subseq (case-lambda ((sc test k) (let fnrec838 ((sc sc) (test test) (k k)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "sub-filter") sc (jolt-vector (let* ((_o$839 test) (_o$840 k)) (jolt-vector _o$839 _o$840))))))) ((sc start-test start-k end-test end-k) (let fnrec841 ((sc sc) (start-test start-test) (start-k start-k) (end-test end-test) (end-k end-k)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "sub-filter") sc (let* ((_o$846 (let* ((_o$842 start-test) (_o$843 start-k)) (jolt-vector _o$842 _o$843))) (_o$847 (let* ((_o$844 end-test) (_o$845 end-k)) (jolt-vector _o$844 _o$845)))) (jolt-vector _o$846 _o$847))))))))) subseq))) +(guard (e (#t #f)) + (def-var! "clojure.core" "rsubseq" (letrec ((rsubseq (case-lambda ((sc test k) (let fnrec848 ((sc sc) (test test) (k k)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "vec") (jolt-reverse (jolt-invoke (var-deref "clojure.core" "sub-filter") sc (jolt-vector (let* ((_o$849 test) (_o$850 k)) (jolt-vector _o$849 _o$850))))))))) ((sc start-test start-k end-test end-k) (let fnrec851 ((sc sc) (start-test start-test) (start-k start-k) (end-test end-test) (end-k end-k)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "vec") (jolt-reverse (jolt-invoke (var-deref "clojure.core" "sub-filter") sc (let* ((_o$856 (let* ((_o$852 start-test) (_o$853 start-k)) (jolt-vector _o$852 _o$853))) (_o$857 (let* ((_o$854 end-test) (_o$855 end-k)) (jolt-vector _o$854 _o$855)))) (jolt-vector _o$856 _o$857))))))))))) rsubseq))) +(guard (e (#t #f)) + (def-var! "clojure.core" "comment" + (lambda body (let fnrec858 ((body (list->cseq body))) jolt-nil))) + (mark-macro! "clojure.core" "comment")) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-out-str" + (lambda body (let fnrec859 ((body (list->cseq body))) (let* ((_a$864 (var-deref "clojure.core" "__sqcat")) (_a$865 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__with-out-str"))) (_a$866 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$860 (var-deref "clojure.core" "__sqcat")) (_a$861 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$862 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$863 body)) (jolt-invoke _a$860 _a$861 _a$862 _a$863))))) (jolt-invoke _a$864 _a$865 _a$866))))) + (mark-macro! "clojure.core" "with-out-str")) +(guard (e (#t #f)) + (def-var! "clojure.core" "defmulti" + (lambda (name . args) (let fnrec867 ((name name) (args (list->cseq args))) (let* ((args (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") (jolt-first args))) (jolt-rest args) args)) (args (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "map?") (jolt-first args)))) (if (jolt-truthy? and__13__auto) (jolt-not (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first args))) and__13__auto))) (jolt-rest args) args)) (dispatch (jolt-first args)) (opts (jolt-rest args))) (let* ((_a$871 (var-deref "clojure.core" "__sqcat")) (_a$872 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defmulti-setup"))) (_a$873 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$868 (var-deref "clojure.core" "__sqcat")) (_a$869 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$870 (jolt-invoke (var-deref "clojure.core" "__sq1") name))) (jolt-invoke _a$868 _a$869 _a$870)))) (_a$874 (jolt-invoke (var-deref "clojure.core" "__sq1") dispatch)) (_a$875 opts)) (jolt-invoke _a$871 _a$872 _a$873 _a$874 _a$875)))))) + (mark-macro! "clojure.core" "defmulti")) +(guard (e (#t #f)) + (def-var! "clojure.core" "defmethod" + (lambda (mm dispatch-val . fn-tail) (let fnrec876 ((mm mm) (dispatch-val dispatch-val) (fn-tail (list->cseq fn-tail))) (let* ((_a$880 (var-deref "clojure.core" "__sqcat")) (_a$881 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "defmethod-setup"))) (_a$882 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$877 (var-deref "clojure.core" "__sqcat")) (_a$878 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$879 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$877 _a$878 _a$879)))) (_a$883 (jolt-invoke (var-deref "clojure.core" "__sq1") dispatch-val)) (_a$884 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn")) fn-tail)))) (jolt-invoke _a$880 _a$881 _a$882 _a$883 _a$884))))) + (mark-macro! "clojure.core" "defmethod")) +(guard (e (#t #f)) + (def-var! "clojure.core" "prefer-method" + (lambda (mm dval-a dval-b) (let fnrec885 ((mm mm) (dval-a dval-a) (dval-b dval-b)) (let* ((_a$889 (var-deref "clojure.core" "__sqcat")) (_a$890 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "prefer-method-setup"))) (_a$891 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$886 (var-deref "clojure.core" "__sqcat")) (_a$887 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$888 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$886 _a$887 _a$888)))) (_a$892 (jolt-invoke (var-deref "clojure.core" "__sq1") dval-a)) (_a$893 (jolt-invoke (var-deref "clojure.core" "__sq1") dval-b))) (jolt-invoke _a$889 _a$890 _a$891 _a$892 _a$893))))) + (mark-macro! "clojure.core" "prefer-method")) +(guard (e (#t #f)) + (def-var! "clojure.core" "remove-method" + (lambda (mm dval) (let fnrec894 ((mm mm) (dval dval)) (let* ((_a$898 (var-deref "clojure.core" "__sqcat")) (_a$899 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "remove-method-setup"))) (_a$900 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$895 (var-deref "clojure.core" "__sqcat")) (_a$896 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$897 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$895 _a$896 _a$897)))) (_a$901 (jolt-invoke (var-deref "clojure.core" "__sq1") dval))) (jolt-invoke _a$898 _a$899 _a$900 _a$901))))) + (mark-macro! "clojure.core" "remove-method")) +(guard (e (#t #f)) + (def-var! "clojure.core" "remove-all-methods" + (lambda (mm) (let fnrec902 ((mm mm)) (let* ((_a$906 (var-deref "clojure.core" "__sqcat")) (_a$907 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "remove-all-methods-setup"))) (_a$908 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$903 (var-deref "clojure.core" "__sqcat")) (_a$904 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$905 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$903 _a$904 _a$905))))) (jolt-invoke _a$906 _a$907 _a$908))))) + (mark-macro! "clojure.core" "remove-all-methods")) +(guard (e (#t #f)) + (def-var! "clojure.core" "get-method" + (lambda (mm dval) (let fnrec909 ((mm mm) (dval dval)) (let* ((_a$910 (var-deref "clojure.core" "__sqcat")) (_a$911 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get-method-setup"))) (_a$912 (jolt-invoke (var-deref "clojure.core" "__sq1") mm)) (_a$913 (jolt-invoke (var-deref "clojure.core" "__sq1") dval))) (jolt-invoke _a$910 _a$911 _a$912 _a$913))))) + (mark-macro! "clojure.core" "get-method")) +(guard (e (#t #f)) + (def-var! "clojure.core" "methods" + (lambda (mm) (let fnrec914 ((mm mm)) (let* ((_a$915 (var-deref "clojure.core" "__sqcat")) (_a$916 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "methods-setup"))) (_a$917 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$915 _a$916 _a$917))))) + (mark-macro! "clojure.core" "methods")) +(guard (e (#t #f)) + (def-var! "clojure.core" "prefers" + (lambda (mm) (let fnrec918 ((mm mm)) (let* ((_a$922 (var-deref "clojure.core" "__sqcat")) (_a$923 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "prefers-setup"))) (_a$924 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$919 (var-deref "clojure.core" "__sqcat")) (_a$920 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$921 (jolt-invoke (var-deref "clojure.core" "__sq1") mm))) (jolt-invoke _a$919 _a$920 _a$921))))) (jolt-invoke _a$922 _a$923 _a$924))))) + (mark-macro! "clojure.core" "prefers")) +(guard (e (#t #f)) + (def-var! "clojure.core" "instance?" + (lambda (t x) (let fnrec925 ((t t) (x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") t)) (let* ((_a$926 (var-deref "clojure.core" "__sqcat")) (_a$927 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "instance-check"))) (_a$928 (jolt-invoke (var-deref "clojure.core" "__sq1") t)) (_a$929 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$926 _a$927 _a$928 _a$929)) (let* ((_a$933 (var-deref "clojure.core" "__sqcat")) (_a$934 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "instance-check"))) (_a$935 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$930 (var-deref "clojure.core" "__sqcat")) (_a$931 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$932 (jolt-invoke (var-deref "clojure.core" "__sq1") t))) (jolt-invoke _a$930 _a$931 _a$932)))) (_a$936 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$933 _a$934 _a$935 _a$936)))))) + (mark-macro! "clojure.core" "instance?")) +(guard (e (#t #f)) + (def-var! "clojure.core" "locking" + (lambda (x . body) (let fnrec937 ((x x) (body (list->cseq body))) (let* ((_a$938 (var-deref "clojure.core" "__sqcat")) (_a$939 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$940 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$941 body)) (jolt-invoke _a$938 _a$939 _a$940 _a$941))))) + (mark-macro! "clojure.core" "locking")) +(guard (e (#t #f)) + (def-var! "clojure.core" "time" + (lambda (expr) (let fnrec942 ((expr expr)) (let* ((_a$960 (var-deref "clojure.core" "__sqcat")) (_a$961 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$962 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$943 (var-deref "clojure.core" "__sqvec")) (_a$944 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "start__1__auto"))) (_a$945 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "current-time-ms"))))) (_a$946 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "ret__2__auto"))) (_a$947 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$943 _a$944 _a$945 _a$946 _a$947)))) (_a$963 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$957 (var-deref "clojure.core" "__sqcat")) (_a$958 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "println"))) (_a$959 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$952 (var-deref "clojure.core" "__sqcat")) (_a$953 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "str"))) (_a$954 (jolt-invoke (var-deref "clojure.core" "__sq1") "Elapsed time: ")) (_a$955 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$948 (var-deref "clojure.core" "__sqcat")) (_a$949 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "-"))) (_a$950 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "current-time-ms"))))) (_a$951 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "start__1__auto")))) (jolt-invoke _a$948 _a$949 _a$950 _a$951)))) (_a$956 (jolt-invoke (var-deref "clojure.core" "__sq1") " msecs"))) (jolt-invoke _a$952 _a$953 _a$954 _a$955 _a$956))))) (jolt-invoke _a$957 _a$958 _a$959)))) (_a$964 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "ret__2__auto")))) (jolt-invoke _a$960 _a$961 _a$962 _a$963 _a$964))))) + (mark-macro! "clojure.core" "time")) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-redefs" + (lambda (bindings . body) (let fnrec965 ((bindings bindings) (body (list->cseq body))) (let* ((pairs (let* ((_a$972 (lambda (acc p) (let fnrec966 ((acc acc) (p p)) (let* ((_a$970 (jolt-conj acc (let* ((_a$967 (var-deref "clojure.core" "__sqcat")) (_a$968 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "var"))) (_a$969 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first p)))) (jolt-invoke _a$967 _a$968 _a$969)))) (_a$971 (jolt-invoke (var-deref "clojure.core" "second") p))) (jolt-conj _a$970 _a$971))))) (_a$973 (jolt-vector)) (_a$974 (jolt-invoke (var-deref "clojure.core" "partition") 2 bindings))) (jolt-reduce _a$972 _a$973 _a$974)))) (let* ((_a$979 (var-deref "clojure.core" "__sqcat")) (_a$980 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "with-redefs-fn"))) (_a$981 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "hash-map")) pairs))) (_a$982 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$975 (var-deref "clojure.core" "__sqcat")) (_a$976 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$977 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$978 body)) (jolt-invoke _a$975 _a$976 _a$977 _a$978))))) (jolt-invoke _a$979 _a$980 _a$981 _a$982)))))) + (mark-macro! "clojure.core" "with-redefs")) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-local-vars" + (lambda (bindings . body) (let fnrec983 ((bindings bindings) (body (list->cseq body))) (let* ((binds (let* ((_a$990 (lambda (acc p) (let fnrec984 ((acc acc) (p p)) (let* ((_a$988 (jolt-conj acc (jolt-first p))) (_a$989 (let* ((_a$985 (var-deref "clojure.core" "__sqcat")) (_a$986 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__local-var"))) (_a$987 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "second") p)))) (jolt-invoke _a$985 _a$986 _a$987)))) (jolt-conj _a$988 _a$989))))) (_a$991 (jolt-vector)) (_a$992 (jolt-invoke (var-deref "clojure.core" "partition") 2 bindings))) (jolt-reduce _a$990 _a$991 _a$992)))) (let* ((_a$993 (var-deref "clojure.core" "__sqcat")) (_a$994 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$995 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") binds))) (_a$996 body)) (jolt-invoke _a$993 _a$994 _a$995 _a$996)))))) + (mark-macro! "clojure.core" "with-local-vars")) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-open" + (lambda (bindings . body) (let fnrec997 ((bindings bindings) (body (list->cseq body))) (if (jolt-zero? (jolt-count bindings)) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body) (let* ((_a$1015 (var-deref "clojure.core" "__sqcat")) (_a$1016 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1017 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$998 (var-deref "clojure.core" "__sqvec")) (_a$999 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first bindings))) (_a$1000 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "second") bindings)))) (jolt-invoke _a$998 _a$999 _a$1000)))) (_a$1018 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1011 (var-deref "clojure.core" "__sqcat")) (_a$1012 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "try"))) (_a$1013 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1001 (var-deref "clojure.core" "__sqcat")) (_a$1002 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "with-open"))) (_a$1003 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "vec") (jolt-drop 2 bindings)))) (_a$1004 body)) (jolt-invoke _a$1001 _a$1002 _a$1003 _a$1004)))) (_a$1014 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1008 (var-deref "clojure.core" "__sqcat")) (_a$1009 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "finally"))) (_a$1010 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1005 (var-deref "clojure.core" "__sqcat")) (_a$1006 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__close"))) (_a$1007 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first bindings)))) (jolt-invoke _a$1005 _a$1006 _a$1007))))) (jolt-invoke _a$1008 _a$1009 _a$1010))))) (jolt-invoke _a$1011 _a$1012 _a$1013 _a$1014))))) (jolt-invoke _a$1015 _a$1016 _a$1017 _a$1018)))))) + (mark-macro! "clojure.core" "with-open")) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-precision" + (lambda (precision . exprs) (let fnrec1019 ((precision precision) (exprs (list->cseq exprs))) (let* ((body (if (jolt= (keyword #f "rounding") (jolt-first exprs)) (jolt-drop 2 exprs) exprs))) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body))))) + (mark-macro! "clojure.core" "with-precision")) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-bindings" + (lambda (binding-map . body) (let fnrec1020 ((binding-map binding-map) (body (list->cseq body))) (let* ((_a$1025 (var-deref "clojure.core" "__sqcat")) (_a$1026 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "with-bindings*"))) (_a$1027 (jolt-invoke (var-deref "clojure.core" "__sq1") binding-map)) (_a$1028 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1021 (var-deref "clojure.core" "__sqcat")) (_a$1022 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1023 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$1024 body)) (jolt-invoke _a$1021 _a$1022 _a$1023 _a$1024))))) (jolt-invoke _a$1025 _a$1026 _a$1027 _a$1028))))) + (mark-macro! "clojure.core" "with-bindings")) +(guard (e (#t #f)) + (def-var! "clojure.core" "bound-fn" + (lambda fntail (let fnrec1029 ((fntail (list->cseq fntail))) (let* ((_a$1030 (var-deref "clojure.core" "__sqcat")) (_a$1031 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "bound-fn*"))) (_a$1032 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn")) fntail)))) (jolt-invoke _a$1030 _a$1031 _a$1032))))) + (mark-macro! "clojure.core" "bound-fn")) +(guard (e (#t #f)) + (def-var! "clojure.core" "defonce" + (lambda (name expr) (let fnrec1033 ((name name) (expr expr)) (let* ((_a$1059 (var-deref "clojure.core" "__sqcat")) (_a$1060 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1061 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1040 (var-deref "clojure.core" "__sqvec")) (_a$1041 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "v__3__auto"))) (_a$1042 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1037 (var-deref "clojure.core" "__sqcat")) (_a$1038 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "resolve"))) (_a$1039 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1034 (var-deref "clojure.core" "__sqcat")) (_a$1035 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$1036 (jolt-invoke (var-deref "clojure.core" "__sq1") name))) (jolt-invoke _a$1034 _a$1035 _a$1036))))) (jolt-invoke _a$1037 _a$1038 _a$1039))))) (jolt-invoke _a$1040 _a$1041 _a$1042)))) (_a$1062 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1054 (var-deref "clojure.core" "__sqcat")) (_a$1055 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1056 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1046 (var-deref "clojure.core" "__sqcat")) (_a$1047 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "and"))) (_a$1048 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "v__3__auto"))) (_a$1049 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1043 (var-deref "clojure.core" "__sqcat")) (_a$1044 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "bound?"))) (_a$1045 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "v__3__auto")))) (jolt-invoke _a$1043 _a$1044 _a$1045))))) (jolt-invoke _a$1046 _a$1047 _a$1048 _a$1049)))) (_a$1057 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "v__3__auto"))) (_a$1058 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1050 (var-deref "clojure.core" "__sqcat")) (_a$1051 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$1052 (jolt-invoke (var-deref "clojure.core" "__sq1") name)) (_a$1053 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$1050 _a$1051 _a$1052 _a$1053))))) (jolt-invoke _a$1054 _a$1055 _a$1056 _a$1057 _a$1058))))) (jolt-invoke _a$1059 _a$1060 _a$1061 _a$1062))))) + (mark-macro! "clojure.core" "defonce")) +(guard (e (#t #f)) + (def-var! "clojure.core" "if-not" + (lambda (test then . G__17) (let fnrec1063 ((test test) (then then) (G__17 (list->cseq G__17))) (let* ((G__18 G__17) (_else (jolt-nth G__18 0 jolt-nil))) (let* ((_a$1067 (var-deref "clojure.core" "__sqcat")) (_a$1068 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1069 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1064 (var-deref "clojure.core" "__sqcat")) (_a$1065 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "not"))) (_a$1066 (jolt-invoke (var-deref "clojure.core" "__sq1") test))) (jolt-invoke _a$1064 _a$1065 _a$1066)))) (_a$1070 (jolt-invoke (var-deref "clojure.core" "__sq1") then)) (_a$1071 (jolt-invoke (var-deref "clojure.core" "__sq1") _else))) (jolt-invoke _a$1067 _a$1068 _a$1069 _a$1070 _a$1071)))))) + (mark-macro! "clojure.core" "if-not")) +(guard (e (#t #f)) + (def-var! "clojure.core" "if-let" + (lambda (bindings then . G__19) (let fnrec1072 ((bindings bindings) (then then) (G__19 (list->cseq G__19))) (let* ((G__20 G__19) (_else (jolt-nth G__20 0 jolt-nil))) (let* ((form (jolt-invoke bindings 0)) (tst (jolt-invoke bindings 1))) (let* ((_a$1088 (var-deref "clojure.core" "__sqcat")) (_a$1089 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1090 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1073 (var-deref "clojure.core" "__sqvec")) (_a$1074 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__4__auto"))) (_a$1075 (jolt-invoke (var-deref "clojure.core" "__sq1") tst))) (jolt-invoke _a$1073 _a$1074 _a$1075)))) (_a$1091 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1083 (var-deref "clojure.core" "__sqcat")) (_a$1084 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1085 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__4__auto"))) (_a$1086 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1079 (var-deref "clojure.core" "__sqcat")) (_a$1080 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1081 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1076 (var-deref "clojure.core" "__sqvec")) (_a$1077 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$1078 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__4__auto")))) (jolt-invoke _a$1076 _a$1077 _a$1078)))) (_a$1082 (jolt-invoke (var-deref "clojure.core" "__sq1") then))) (jolt-invoke _a$1079 _a$1080 _a$1081 _a$1082)))) (_a$1087 (jolt-invoke (var-deref "clojure.core" "__sq1") _else))) (jolt-invoke _a$1083 _a$1084 _a$1085 _a$1086 _a$1087))))) (jolt-invoke _a$1088 _a$1089 _a$1090 _a$1091))))))) + (mark-macro! "clojure.core" "if-let")) +(guard (e (#t #f)) + (def-var! "clojure.core" "if-some" + (lambda (bindings then . G__21) (let fnrec1092 ((bindings bindings) (then then) (G__21 (list->cseq G__21))) (let* ((G__22 G__21) (_else (jolt-nth G__22 0 jolt-nil))) (let* ((form (jolt-invoke bindings 0)) (tst (jolt-invoke bindings 1))) (let* ((_a$1111 (var-deref "clojure.core" "__sqcat")) (_a$1112 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1113 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1093 (var-deref "clojure.core" "__sqvec")) (_a$1094 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__5__auto"))) (_a$1095 (jolt-invoke (var-deref "clojure.core" "__sq1") tst))) (jolt-invoke _a$1093 _a$1094 _a$1095)))) (_a$1114 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1106 (var-deref "clojure.core" "__sqcat")) (_a$1107 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1108 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1096 (var-deref "clojure.core" "__sqcat")) (_a$1097 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "some?"))) (_a$1098 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__5__auto")))) (jolt-invoke _a$1096 _a$1097 _a$1098)))) (_a$1109 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1102 (var-deref "clojure.core" "__sqcat")) (_a$1103 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1104 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1099 (var-deref "clojure.core" "__sqvec")) (_a$1100 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$1101 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__5__auto")))) (jolt-invoke _a$1099 _a$1100 _a$1101)))) (_a$1105 (jolt-invoke (var-deref "clojure.core" "__sq1") then))) (jolt-invoke _a$1102 _a$1103 _a$1104 _a$1105)))) (_a$1110 (jolt-invoke (var-deref "clojure.core" "__sq1") _else))) (jolt-invoke _a$1106 _a$1107 _a$1108 _a$1109 _a$1110))))) (jolt-invoke _a$1111 _a$1112 _a$1113 _a$1114))))))) + (mark-macro! "clojure.core" "if-some")) +(guard (e (#t #f)) + (def-var! "clojure.core" "when-some" + (lambda (bindings . body) (let fnrec1115 ((bindings bindings) (body (list->cseq body))) (let* ((form (jolt-invoke bindings 0)) (tst (jolt-invoke bindings 1))) (let* ((_a$1134 (var-deref "clojure.core" "__sqcat")) (_a$1135 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1136 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1116 (var-deref "clojure.core" "__sqvec")) (_a$1117 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__6__auto"))) (_a$1118 (jolt-invoke (var-deref "clojure.core" "__sq1") tst))) (jolt-invoke _a$1116 _a$1117 _a$1118)))) (_a$1137 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1129 (var-deref "clojure.core" "__sqcat")) (_a$1130 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1131 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1119 (var-deref "clojure.core" "__sqcat")) (_a$1120 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "some?"))) (_a$1121 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__6__auto")))) (jolt-invoke _a$1119 _a$1120 _a$1121)))) (_a$1132 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1125 (var-deref "clojure.core" "__sqcat")) (_a$1126 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1127 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1122 (var-deref "clojure.core" "__sqvec")) (_a$1123 (jolt-invoke (var-deref "clojure.core" "__sq1") form)) (_a$1124 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "temp__6__auto")))) (jolt-invoke _a$1122 _a$1123 _a$1124)))) (_a$1128 body)) (jolt-invoke _a$1125 _a$1126 _a$1127 _a$1128)))) (_a$1133 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil))) (jolt-invoke _a$1129 _a$1130 _a$1131 _a$1132 _a$1133))))) (jolt-invoke _a$1134 _a$1135 _a$1136 _a$1137)))))) + (mark-macro! "clojure.core" "when-some")) +(guard (e (#t #f)) + (def-var! "clojure.core" "while" + (lambda (test . body) (let fnrec1138 ((test test) (body (list->cseq body))) (let* ((_a$1144 (var-deref "clojure.core" "__sqcat")) (_a$1145 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "loop"))) (_a$1146 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$1147 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1139 (var-deref "clojure.core" "__sqcat")) (_a$1140 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "when"))) (_a$1141 (jolt-invoke (var-deref "clojure.core" "__sq1") test)) (_a$1142 body) (_a$1143 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "recur")))))) (jolt-invoke _a$1139 _a$1140 _a$1141 _a$1142 _a$1143))))) (jolt-invoke _a$1144 _a$1145 _a$1146 _a$1147))))) + (mark-macro! "clojure.core" "while")) +(guard (e (#t #f)) + (def-var! "clojure.core" "dotimes" + (lambda (bindings . body) (let fnrec1148 ((bindings bindings) (body (list->cseq body))) (let* ((i (jolt-invoke bindings 0)) (n (jolt-invoke bindings 1))) (let* ((_a$1174 (var-deref "clojure.core" "__sqcat")) (_a$1175 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1176 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1149 (var-deref "clojure.core" "__sqvec")) (_a$1150 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "n__7__auto"))) (_a$1151 (jolt-invoke (var-deref "clojure.core" "__sq1") n))) (jolt-invoke _a$1149 _a$1150 _a$1151)))) (_a$1177 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1170 (var-deref "clojure.core" "__sqcat")) (_a$1171 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "loop"))) (_a$1172 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1152 (var-deref "clojure.core" "__sqvec")) (_a$1153 (jolt-invoke (var-deref "clojure.core" "__sq1") i)) (_a$1154 (jolt-invoke (var-deref "clojure.core" "__sq1") 0))) (jolt-invoke _a$1152 _a$1153 _a$1154)))) (_a$1173 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1165 (var-deref "clojure.core" "__sqcat")) (_a$1166 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "when"))) (_a$1167 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1155 (var-deref "clojure.core" "__sqcat")) (_a$1156 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "<"))) (_a$1157 (jolt-invoke (var-deref "clojure.core" "__sq1") i)) (_a$1158 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "n__7__auto")))) (jolt-invoke _a$1155 _a$1156 _a$1157 _a$1158)))) (_a$1168 body) (_a$1169 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1162 (var-deref "clojure.core" "__sqcat")) (_a$1163 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "recur"))) (_a$1164 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1159 (var-deref "clojure.core" "__sqcat")) (_a$1160 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "inc"))) (_a$1161 (jolt-invoke (var-deref "clojure.core" "__sq1") i))) (jolt-invoke _a$1159 _a$1160 _a$1161))))) (jolt-invoke _a$1162 _a$1163 _a$1164))))) (jolt-invoke _a$1165 _a$1166 _a$1167 _a$1168 _a$1169))))) (jolt-invoke _a$1170 _a$1171 _a$1172 _a$1173))))) (jolt-invoke _a$1174 _a$1175 _a$1176 _a$1177)))))) + (mark-macro! "clojure.core" "dotimes")) +(guard (e (#t #f)) + (def-var! "clojure.core" "fresh-sym" (letrec ((fresh-sym (lambda () (let fnrec1178 () (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") (jolt-invoke (var-deref "clojure.core" "gensym")))))))) fresh-sym))) +(guard (e (#t #f)) + (def-var! "clojure.core" "when-first" + (lambda (bindings . body) (let fnrec1179 ((bindings bindings) (body (list->cseq body))) (let* ((x (jolt-invoke bindings 0)) (coll (jolt-invoke bindings 1))) (let* ((_a$1186 (var-deref "clojure.core" "__sqcat")) (_a$1187 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "when-let"))) (_a$1188 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1183 (var-deref "clojure.core" "__sqvec")) (_a$1184 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$1185 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1180 (var-deref "clojure.core" "__sqcat")) (_a$1181 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "first"))) (_a$1182 (jolt-invoke (var-deref "clojure.core" "__sq1") coll))) (jolt-invoke _a$1180 _a$1181 _a$1182))))) (jolt-invoke _a$1183 _a$1184 _a$1185)))) (_a$1189 body)) (jolt-invoke _a$1186 _a$1187 _a$1188 _a$1189)))))) + (mark-macro! "clojure.core" "when-first")) +(guard (e (#t #f)) + (def-var! "clojure.core" "doto" + (lambda (x . forms) (let fnrec1190 ((x x) (forms (list->cseq forms))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (steps (jolt-map (lambda (f) (let fnrec1191 ((f f)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") f)) (let* ((_a$1192 jolt-list) (_a$1193 (jolt-first f)) (_a$1194 g) (_a$1195 (jolt-rest f))) (jolt-apply _a$1192 _a$1193 _a$1194 _a$1195)) (jolt-list f g)))) forms))) (let* ((_a$1199 (var-deref "clojure.core" "__sqcat")) (_a$1200 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1201 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1196 (var-deref "clojure.core" "__sqvec")) (_a$1197 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$1198 (jolt-invoke (var-deref "clojure.core" "__sq1") x))) (jolt-invoke _a$1196 _a$1197 _a$1198)))) (_a$1202 steps) (_a$1203 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$1199 _a$1200 _a$1201 _a$1202 _a$1203)))))) + (mark-macro! "clojure.core" "doto")) +(guard (e (#t #f)) + (def-var! "clojure.core" "thread-binds" (letrec ((thread-binds (lambda (g steps) (let fnrec1204 ((g g) (steps steps)) (let* ((_a$1206 (lambda (acc s) (let fnrec1205 ((acc acc) (s s)) (jolt-conj (jolt-conj acc g) s)))) (_a$1207 (jolt-vector)) (_a$1208 (jolt-invoke (var-deref "clojure.core" "butlast") steps))) (jolt-reduce _a$1206 _a$1207 _a$1208)))))) thread-binds))) +(guard (e (#t #f)) + (def-var! "clojure.core" "as->" + (lambda (expr name . forms) (let fnrec1209 ((expr expr) (name name) (forms (list->cseq forms))) (let* ((pairs (let* ((_a$1211 (lambda (acc f) (let fnrec1210 ((acc acc) (f f)) (jolt-conj (jolt-conj acc name) f)))) (_a$1212 (jolt-vector)) (_a$1213 (jolt-invoke (var-deref "clojure.core" "butlast") forms))) (jolt-reduce _a$1211 _a$1212 _a$1213)))) (let* ((_a$1218 (var-deref "clojure.core" "__sqcat")) (_a$1219 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1220 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1214 (var-deref "clojure.core" "__sqvec")) (_a$1215 (jolt-invoke (var-deref "clojure.core" "__sq1") name)) (_a$1216 (jolt-invoke (var-deref "clojure.core" "__sq1") expr)) (_a$1217 pairs)) (jolt-invoke _a$1214 _a$1215 _a$1216 _a$1217)))) (_a$1221 (jolt-invoke (var-deref "clojure.core" "__sq1") (if (jolt-empty? forms) name (jolt-last forms))))) (jolt-invoke _a$1218 _a$1219 _a$1220 _a$1221)))))) + (mark-macro! "clojure.core" "as->")) +(guard (e (#t #f)) + (def-var! "clojure.core" "some->" + (lambda (expr . forms) (let fnrec1222 ((expr expr) (forms (list->cseq forms))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (steps (jolt-map (lambda (f) (let fnrec1223 ((f f)) (let* ((_a$1231 (var-deref "clojure.core" "__sqcat")) (_a$1232 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1233 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1224 (var-deref "clojure.core" "__sqcat")) (_a$1225 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "nil?"))) (_a$1226 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$1224 _a$1225 _a$1226)))) (_a$1234 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil)) (_a$1235 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1227 (var-deref "clojure.core" "__sqcat")) (_a$1228 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->"))) (_a$1229 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$1230 (jolt-invoke (var-deref "clojure.core" "__sq1") f))) (jolt-invoke _a$1227 _a$1228 _a$1229 _a$1230))))) (jolt-invoke _a$1231 _a$1232 _a$1233 _a$1234 _a$1235)))) forms))) (let* ((_a$1240 (var-deref "clojure.core" "__sqcat")) (_a$1241 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1242 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1236 (var-deref "clojure.core" "__sqvec")) (_a$1237 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$1238 (jolt-invoke (var-deref "clojure.core" "__sq1") expr)) (_a$1239 (jolt-invoke (var-deref "clojure.core" "thread-binds") g steps))) (jolt-invoke _a$1236 _a$1237 _a$1238 _a$1239)))) (_a$1243 (jolt-invoke (var-deref "clojure.core" "__sq1") (if (jolt-empty? steps) g (jolt-last steps))))) (jolt-invoke _a$1240 _a$1241 _a$1242 _a$1243)))))) + (mark-macro! "clojure.core" "some->")) +(guard (e (#t #f)) + (def-var! "clojure.core" "some->>" + (lambda (expr . forms) (let fnrec1244 ((expr expr) (forms (list->cseq forms))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (steps (jolt-map (lambda (f) (let fnrec1245 ((f f)) (let* ((_a$1253 (var-deref "clojure.core" "__sqcat")) (_a$1254 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1255 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1246 (var-deref "clojure.core" "__sqcat")) (_a$1247 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "nil?"))) (_a$1248 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$1246 _a$1247 _a$1248)))) (_a$1256 (jolt-invoke (var-deref "clojure.core" "__sq1") jolt-nil)) (_a$1257 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1249 (var-deref "clojure.core" "__sqcat")) (_a$1250 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->>"))) (_a$1251 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$1252 (jolt-invoke (var-deref "clojure.core" "__sq1") f))) (jolt-invoke _a$1249 _a$1250 _a$1251 _a$1252))))) (jolt-invoke _a$1253 _a$1254 _a$1255 _a$1256 _a$1257)))) forms))) (let* ((_a$1262 (var-deref "clojure.core" "__sqcat")) (_a$1263 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1264 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1258 (var-deref "clojure.core" "__sqvec")) (_a$1259 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$1260 (jolt-invoke (var-deref "clojure.core" "__sq1") expr)) (_a$1261 (jolt-invoke (var-deref "clojure.core" "thread-binds") g steps))) (jolt-invoke _a$1258 _a$1259 _a$1260 _a$1261)))) (_a$1265 (jolt-invoke (var-deref "clojure.core" "__sq1") (if (jolt-empty? steps) g (jolt-last steps))))) (jolt-invoke _a$1262 _a$1263 _a$1264 _a$1265)))))) + (mark-macro! "clojure.core" "some->>")) +(guard (e (#t #f)) + (def-var! "clojure.core" "cond->>" + (lambda (expr . clauses) (let fnrec1266 ((expr expr) (clauses (list->cseq clauses))) (let* ((g (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (steps (let* ((_a$1277 (lambda (pair) (let fnrec1267 ((pair pair)) (let* ((_a$1272 (var-deref "clojure.core" "__sqcat")) (_a$1273 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1274 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first pair))) (_a$1275 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1268 (var-deref "clojure.core" "__sqcat")) (_a$1269 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "->>"))) (_a$1270 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$1271 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "second") pair)))) (jolt-invoke _a$1268 _a$1269 _a$1270 _a$1271)))) (_a$1276 (jolt-invoke (var-deref "clojure.core" "__sq1") g))) (jolt-invoke _a$1272 _a$1273 _a$1274 _a$1275 _a$1276))))) (_a$1278 (jolt-invoke (var-deref "clojure.core" "partition") 2 clauses))) (jolt-map _a$1277 _a$1278)))) (let* ((_a$1283 (var-deref "clojure.core" "__sqcat")) (_a$1284 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1285 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1279 (var-deref "clojure.core" "__sqvec")) (_a$1280 (jolt-invoke (var-deref "clojure.core" "__sq1") g)) (_a$1281 (jolt-invoke (var-deref "clojure.core" "__sq1") expr)) (_a$1282 (jolt-invoke (var-deref "clojure.core" "thread-binds") g steps))) (jolt-invoke _a$1279 _a$1280 _a$1281 _a$1282)))) (_a$1286 (jolt-invoke (var-deref "clojure.core" "__sq1") (if (jolt-empty? steps) g (jolt-last steps))))) (jolt-invoke _a$1283 _a$1284 _a$1285 _a$1286)))))) + (mark-macro! "clojure.core" "cond->>")) +(guard (e (#t #f)) + (def-var! "clojure.core" "assert" + (lambda (x . G__23) (let fnrec1287 ((x x) (G__23 (list->cseq G__23))) (let* ((G__24 G__23) (message (jolt-nth G__24 0 jolt-nil))) (let* ((msg (if (jolt-truthy? message) message (jolt-invoke (var-deref "clojure.core" "str") "Assert failed: " (jolt-invoke (var-deref "clojure.core" "pr-str") x))))) (let* ((_a$1295 (var-deref "clojure.core" "__sqcat")) (_a$1296 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "when-not"))) (_a$1297 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$1298 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1292 (var-deref "clojure.core" "__sqcat")) (_a$1293 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "throw"))) (_a$1294 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1288 (var-deref "clojure.core" "__sqcat")) (_a$1289 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "ex-info"))) (_a$1290 (jolt-invoke (var-deref "clojure.core" "__sq1") msg)) (_a$1291 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqmap"))))) (jolt-invoke _a$1288 _a$1289 _a$1290 _a$1291))))) (jolt-invoke _a$1292 _a$1293 _a$1294))))) (jolt-invoke _a$1295 _a$1296 _a$1297 _a$1298))))))) + (mark-macro! "clojure.core" "assert")) +(guard (e (#t #f)) + (def-var! "clojure.core" "pvalues" + (lambda exprs (let fnrec1299 ((exprs (list->cseq exprs))) (let* ((_a$1305 (var-deref "clojure.core" "__sqcat")) (_a$1306 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "pcalls"))) (_a$1307 (jolt-map (lambda (e) (let fnrec1300 ((e e)) (let* ((_a$1301 (var-deref "clojure.core" "__sqcat")) (_a$1302 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1303 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$1304 (jolt-invoke (var-deref "clojure.core" "__sq1") e))) (jolt-invoke _a$1301 _a$1302 _a$1303 _a$1304)))) exprs))) (jolt-invoke _a$1305 _a$1306 _a$1307))))) + (mark-macro! "clojure.core" "pvalues")) +(guard (e (#t #f)) + (def-var! "clojure.core" "delay" + (lambda body (let fnrec1308 ((body (list->cseq body))) (let* ((_a$1313 (var-deref "clojure.core" "__sqcat")) (_a$1314 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-delay"))) (_a$1315 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1309 (var-deref "clojure.core" "__sqcat")) (_a$1310 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1311 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$1312 body)) (jolt-invoke _a$1309 _a$1310 _a$1311 _a$1312))))) (jolt-invoke _a$1313 _a$1314 _a$1315))))) + (mark-macro! "clojure.core" "delay")) +(guard (e (#t #f)) + (def-var! "clojure.core" "future" + (lambda body (let fnrec1316 ((body (list->cseq body))) (let* ((_a$1321 (var-deref "clojure.core" "__sqcat")) (_a$1322 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "future-call"))) (_a$1323 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1317 (var-deref "clojure.core" "__sqcat")) (_a$1318 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1319 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec")))) (_a$1320 body)) (jolt-invoke _a$1317 _a$1318 _a$1319 _a$1320))))) (jolt-invoke _a$1321 _a$1322 _a$1323))))) + (mark-macro! "clojure.core" "future")) +(guard (e (#t #f)) + (def-var! "clojure.core" "binding" + (lambda (bindings . body) (let fnrec1324 ((bindings bindings) (body (list->cseq body))) (let* ((pairs (let* ((_a$1331 (lambda (acc p) (let fnrec1325 ((acc acc) (p p)) (let* ((_a$1329 (jolt-conj acc (let* ((_a$1326 (var-deref "clojure.core" "__sqcat")) (_a$1327 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "var"))) (_a$1328 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first p)))) (jolt-invoke _a$1326 _a$1327 _a$1328)))) (_a$1330 (jolt-invoke (var-deref "clojure.core" "second") p))) (jolt-conj _a$1329 _a$1330))))) (_a$1332 (jolt-vector)) (_a$1333 (jolt-invoke (var-deref "clojure.core" "partition") 2 bindings))) (jolt-reduce _a$1331 _a$1332 _a$1333)))) (let* ((_a$1347 (var-deref "clojure.core" "__sqcat")) (_a$1348 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "let*"))) (_a$1349 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1334 (var-deref "clojure.core" "__sqvec")) (_a$1335 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "frame__8__auto"))) (_a$1336 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "array-map")) pairs)))) (jolt-invoke _a$1334 _a$1335 _a$1336)))) (_a$1350 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1337 (var-deref "clojure.core" "__sqcat")) (_a$1338 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "push-thread-bindings"))) (_a$1339 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "frame__8__auto")))) (jolt-invoke _a$1337 _a$1338 _a$1339)))) (_a$1351 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1343 (var-deref "clojure.core" "__sqcat")) (_a$1344 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "try"))) (_a$1345 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body))) (_a$1346 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1340 (var-deref "clojure.core" "__sqcat")) (_a$1341 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "finally"))) (_a$1342 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "pop-thread-bindings")))))) (jolt-invoke _a$1340 _a$1341 _a$1342))))) (jolt-invoke _a$1343 _a$1344 _a$1345 _a$1346))))) (jolt-invoke _a$1347 _a$1348 _a$1349 _a$1350 _a$1351)))))) + (mark-macro! "clojure.core" "binding")) +(guard (e (#t #f)) + (def-var! "clojure.core" "condp" + (lambda (pred expr . clauses) (let fnrec1352 ((pred pred) (expr expr) (clauses (list->cseq clauses))) (let* ((gp (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (ge (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (emit (letrec ((emit (lambda (args) (let fnrec1353 ((args args)) (let* ((n (if (jolt= (keyword #f ">>") (jolt-invoke (var-deref "clojure.core" "second") args)) 3 2)) (clause (jolt-take n args)) (more (jolt-drop n args)) (cn (jolt-count clause))) (if (jolt= 0 cn) (let* ((_a$1362 (var-deref "clojure.core" "__sqcat")) (_a$1363 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "throw"))) (_a$1364 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1358 (var-deref "clojure.core" "__sqcat")) (_a$1359 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "ex-info"))) (_a$1360 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1354 (var-deref "clojure.core" "__sqcat")) (_a$1355 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "str"))) (_a$1356 (jolt-invoke (var-deref "clojure.core" "__sq1") "No matching clause: ")) (_a$1357 (jolt-invoke (var-deref "clojure.core" "__sq1") ge))) (jolt-invoke _a$1354 _a$1355 _a$1356 _a$1357)))) (_a$1361 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqmap"))))) (jolt-invoke _a$1358 _a$1359 _a$1360 _a$1361))))) (jolt-invoke _a$1362 _a$1363 _a$1364)) (if (jolt= 1 cn) (jolt-first clause) (if (jolt= 2 cn) (let* ((_a$1369 (var-deref "clojure.core" "__sqcat")) (_a$1370 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "if"))) (_a$1371 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1365 (var-deref "clojure.core" "__sqcat")) (_a$1366 (jolt-invoke (var-deref "clojure.core" "__sq1") gp)) (_a$1367 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first clause))) (_a$1368 (jolt-invoke (var-deref "clojure.core" "__sq1") ge))) (jolt-invoke _a$1365 _a$1366 _a$1367 _a$1368)))) (_a$1372 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "second") clause))) (_a$1373 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke emit more)))) (jolt-invoke _a$1369 _a$1370 _a$1371 _a$1372 _a$1373)) (if (jolt-truthy? (keyword #f "else")) (let* ((_a$1384 (var-deref "clojure.core" "__sqcat")) (_a$1385 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "if-let"))) (_a$1386 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1378 (var-deref "clojure.core" "__sqvec")) (_a$1379 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "p__9__auto"))) (_a$1380 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1374 (var-deref "clojure.core" "__sqcat")) (_a$1375 (jolt-invoke (var-deref "clojure.core" "__sq1") gp)) (_a$1376 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first clause))) (_a$1377 (jolt-invoke (var-deref "clojure.core" "__sq1") ge))) (jolt-invoke _a$1374 _a$1375 _a$1376 _a$1377))))) (jolt-invoke _a$1378 _a$1379 _a$1380)))) (_a$1387 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1381 (var-deref "clojure.core" "__sqcat")) (_a$1382 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth clause 2))) (_a$1383 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "p__9__auto")))) (jolt-invoke _a$1381 _a$1382 _a$1383)))) (_a$1388 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke emit more)))) (jolt-invoke _a$1384 _a$1385 _a$1386 _a$1387 _a$1388)) jolt-nil))))))))) emit))) (let* ((_a$1394 (var-deref "clojure.core" "__sqcat")) (_a$1395 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1396 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1389 (var-deref "clojure.core" "__sqvec")) (_a$1390 (jolt-invoke (var-deref "clojure.core" "__sq1") gp)) (_a$1391 (jolt-invoke (var-deref "clojure.core" "__sq1") pred)) (_a$1392 (jolt-invoke (var-deref "clojure.core" "__sq1") ge)) (_a$1393 (jolt-invoke (var-deref "clojure.core" "__sq1") expr))) (jolt-invoke _a$1389 _a$1390 _a$1391 _a$1392 _a$1393)))) (_a$1397 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke emit clauses)))) (jolt-invoke _a$1394 _a$1395 _a$1396 _a$1397)))))) + (mark-macro! "clojure.core" "condp")) +(guard (e (#t #f)) + (def-var! "clojure.core" "group-by-head" (letrec ((group-by-head (lambda (items) (let fnrec1398 ((items items)) (let* ((_a$1402 (lambda (acc x) (let fnrec1399 ((acc acc) (x x)) (if (jolt-truthy? (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "symbol?") x))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.core" "nil?") x)))) (jolt-conj acc (jolt-vector x)) (let* ((_a$1400 (jolt-pop acc)) (_a$1401 (jolt-conj (jolt-peek acc) x))) (jolt-conj _a$1400 _a$1401)))))) (_a$1403 (jolt-vector)) (_a$1404 items)) (jolt-reduce _a$1402 _a$1403 _a$1404)))))) group-by-head))) +(guard (e (#t #f)) + (def-var! "clojure.core" "deftype" + (lambda (tname fields . body) (let fnrec1405 ((tname tname) (fields fields) (body (list->cseq body))) (let* ((unwrap (lambda (x) (let fnrec1406 ((x x)) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "seq?") x))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first x)))) (if (jolt-truthy? and__13__auto) (jolt= "with-meta" (jolt-invoke (var-deref "clojure.core" "name") (jolt-first x))) and__13__auto)) and__13__auto))) (jolt-invoke (var-deref "clojure.core" "second") x) x)))) (tname (jolt-invoke unwrap tname)) (fields (jolt-map unwrap fields)) (arrow (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "->" (jolt-invoke (var-deref "clojure.core" "name") tname)))) (field-kws (jolt-map (lambda (f) (let fnrec1407 ((f f)) (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f)))) fields)) (field-tags (jolt-map (lambda (f) (let fnrec1408 ((f f)) (let* ((mt (jolt-invoke (var-deref "clojure.core" "meta") f))) (if (jolt-truthy? (let* ((and__13__auto mt)) (if (jolt-truthy? and__13__auto) (jolt-get mt (keyword #f "tag")) and__13__auto))) (jolt-get mt (keyword #f "tag")) (if (jolt-truthy? (let* ((and__13__auto mt)) (if (jolt-truthy? and__13__auto) (jolt-get mt (keyword #f "num")) and__13__auto))) "num" (if (jolt-truthy? (keyword #f "else")) jolt-nil jolt-nil)))))) fields)) (field-muts (jolt-map (lambda (f) (let fnrec1409 ((f f)) (let* ((mt (jolt-invoke (var-deref "clojure.core" "meta") f))) (if (jolt-truthy? (let* ((and__13__auto mt)) (if (jolt-truthy? and__13__auto) (let* ((or__14__auto (jolt-get mt (keyword #f "unsynchronized-mutable")))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-get mt (keyword #f "volatile-mutable")))) and__13__auto))) #t #f)))) fields)) (mutable-syms (jolt-map jolt-first (jolt-filter (var-deref "clojure.core" "second") (jolt-map jolt-vector fields field-muts)))) (mutable? (lambda (s) (let fnrec1410 ((s s)) (jolt-invoke (var-deref "clojure.core" "boolean") (jolt-invoke (var-deref "clojure.core" "some") (lambda (m) (let fnrec1411 ((m m)) (jolt= m s))) mutable-syms))))) (rewrite-set (letrec ((rw (lambda (inst form) (let fnrec1412 ((inst inst) (form form)) (if (jolt-truthy? (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "seq?") form))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-seq form))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-first form)))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt= "set!" (jolt-invoke (var-deref "clojure.core" "name") (jolt-first form))))) (if (jolt-truthy? and__13__auto) (let* ((and__13__auto (jolt-invoke (var-deref "clojure.core" "symbol?") (jolt-invoke (var-deref "clojure.core" "second") form)))) (if (jolt-truthy? and__13__auto) (jolt-invoke mutable? (jolt-invoke (var-deref "clojure.core" "second") form)) and__13__auto)) and__13__auto)) and__13__auto)) and__13__auto)) and__13__auto))) (let* ((_a$1413 (jolt-symbol #f "set!")) (_a$1414 (jolt-list (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") ".-" (jolt-invoke (var-deref "clojure.core" "name") (jolt-invoke (var-deref "clojure.core" "second") form)))) inst)) (_a$1415 (jolt-invoke rw inst (jolt-nth form 2)))) (jolt-list _a$1413 _a$1414 _a$1415)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (jolt-map (lambda (x) (let fnrec1416 ((x x)) (jolt-invoke rw inst x))) form) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") form)) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (x) (let fnrec1417 ((x x)) (jolt-invoke rw inst x))) form) (if (jolt-truthy? (keyword #f "else")) form jolt-nil)))))))) rw)) (impl (lambda (proto specs) (let fnrec1418 ((proto proto) (specs specs)) (let* ((_a$1444 (var-deref "clojure.core" "__sqcat")) (_a$1445 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$1446 (jolt-map (lambda (spec) (let fnrec1419 ((spec spec)) (let* ((argv (jolt-nth spec 1)) (inst (jolt-first argv)) (binds (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "mapcat") (lambda (f) (let fnrec1420 ((f f)) (let* ((_o$1425 f) (_o$1426 (let* ((_a$1421 (var-deref "clojure.core" "__sqcat")) (_a$1422 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$1423 (jolt-invoke (var-deref "clojure.core" "__sq1") inst)) (_a$1424 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f))))) (jolt-invoke _a$1421 _a$1422 _a$1423 _a$1424)))) (jolt-vector _o$1425 _o$1426)))) fields))) (mbody (let* ((_a$1428 (lambda (bf) (let fnrec1427 ((bf bf)) (jolt-invoke rewrite-set inst bf)))) (_a$1429 (jolt-drop 2 spec))) (jolt-map _a$1428 _a$1429)))) (let* ((_a$1438 (var-deref "clojure.core" "__sqcat")) (_a$1439 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-inline-method"))) (_a$1440 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") tname))) (_a$1441 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") proto))) (_a$1442 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first spec)))) (_a$1443 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1434 (var-deref "clojure.core" "__sqcat")) (_a$1435 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1436 (jolt-invoke (var-deref "clojure.core" "__sq1") argv)) (_a$1437 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1430 (var-deref "clojure.core" "__sqcat")) (_a$1431 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1432 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") binds))) (_a$1433 mbody)) (jolt-invoke _a$1430 _a$1431 _a$1432 _a$1433))))) (jolt-invoke _a$1434 _a$1435 _a$1436 _a$1437))))) (jolt-invoke _a$1438 _a$1439 _a$1440 _a$1441 _a$1442 _a$1443))))) specs))) (jolt-invoke _a$1444 _a$1445 _a$1446)))))) (let* ((_a$1470 (var-deref "clojure.core" "__sqcat")) (_a$1471 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$1472 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1456 (var-deref "clojure.core" "__sqcat")) (_a$1457 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$1458 (jolt-invoke (var-deref "clojure.core" "__sq1") tname)) (_a$1459 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1450 (var-deref "clojure.core" "__sqcat")) (_a$1451 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-deftype-ctor"))) (_a$1452 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1447 (var-deref "clojure.core" "__sqcat")) (_a$1448 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$1449 (jolt-invoke (var-deref "clojure.core" "__sq1") tname))) (jolt-invoke _a$1447 _a$1448 _a$1449)))) (_a$1453 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") field-kws))) (_a$1454 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") field-tags))) (_a$1455 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") field-muts)))) (jolt-invoke _a$1450 _a$1451 _a$1452 _a$1453 _a$1454 _a$1455))))) (jolt-invoke _a$1456 _a$1457 _a$1458 _a$1459)))) (_a$1473 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1460 (var-deref "clojure.core" "__sqcat")) (_a$1461 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$1462 (jolt-invoke (var-deref "clojure.core" "__sq1") arrow)) (_a$1463 (jolt-invoke (var-deref "clojure.core" "__sq1") tname))) (jolt-invoke _a$1460 _a$1461 _a$1462 _a$1463)))) (_a$1474 (let* ((_a$1468 (lambda (g) (let fnrec1464 ((g g)) (let* ((_a$1465 impl) (_a$1466 (jolt-first g)) (_a$1467 (jolt-rest g))) (jolt-invoke _a$1465 _a$1466 _a$1467))))) (_a$1469 (jolt-invoke (var-deref "clojure.core" "group-by-head") body))) (jolt-map _a$1468 _a$1469))) (_a$1475 (jolt-invoke (var-deref "clojure.core" "__sq1") tname))) (jolt-invoke _a$1470 _a$1471 _a$1472 _a$1473 _a$1474 _a$1475)))))) + (mark-macro! "clojure.core" "deftype")) +(guard (e (#t #f)) + (def-var! "clojure.core" "defprotocol" + (lambda (pname . sigs) (let fnrec1476 ((pname pname) (sigs (list->cseq sigs))) (let* ((sigs (let* ((s sigs)) (let loop1477 ((s s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") (jolt-first s))) (loop1477 (jolt-rest s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") (jolt-first s))) (loop1477 (jolt-rest (jolt-rest s))) (if (jolt-truthy? (keyword #f "else")) s jolt-nil)))))) (methods (let* ((_a$1484 (lambda (m sig) (let fnrec1478 ((m m) (sig sig)) (let* ((_a$1481 m) (_a$1482 (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first sig)))) (_a$1483 (let* ((_o$1479 (keyword #f "name")) (_o$1480 (jolt-invoke (var-deref "clojure.core" "name") (jolt-first sig)))) (jolt-hash-map _o$1479 _o$1480)))) (jolt-assoc _a$1481 _a$1482 _a$1483))))) (_a$1485 (jolt-hash-map)) (_a$1486 sigs)) (jolt-reduce _a$1484 _a$1485 _a$1486)))) (let* ((_a$1519 (var-deref "clojure.core" "__sqcat")) (_a$1520 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$1521 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1491 (var-deref "clojure.core" "__sqcat")) (_a$1492 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$1493 (jolt-invoke (var-deref "clojure.core" "__sq1") pname)) (_a$1494 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1487 (var-deref "clojure.core" "__sqcat")) (_a$1488 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-protocol"))) (_a$1489 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") pname))) (_a$1490 (jolt-invoke (var-deref "clojure.core" "__sq1") methods))) (jolt-invoke _a$1487 _a$1488 _a$1489 _a$1490))))) (jolt-invoke _a$1491 _a$1492 _a$1493 _a$1494)))) (_a$1522 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1496 (var-deref "clojure.core" "__sqcat")) (_a$1497 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-protocol-methods!"))) (_a$1498 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") pname))) (_a$1499 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-map (lambda (s) (let fnrec1495 ((s s)) (jolt-invoke (var-deref "clojure.core" "name") (jolt-first s)))) sigs))))) (jolt-invoke _a$1496 _a$1497 _a$1498 _a$1499)))) (_a$1523 (jolt-map (lambda (sig) (let fnrec1500 ((sig sig)) (let* ((_a$1515 (var-deref "clojure.core" "__sqcat")) (_a$1516 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$1517 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first sig))) (_a$1518 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1511 (var-deref "clojure.core" "__sqcat")) (_a$1512 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$1513 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1501 (var-deref "clojure.core" "__sqvec")) (_a$1502 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "this__11__auto"))) (_a$1503 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "&"))) (_a$1504 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "rest__10__auto")))) (jolt-invoke _a$1501 _a$1502 _a$1503 _a$1504)))) (_a$1514 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1505 (var-deref "clojure.core" "__sqcat")) (_a$1506 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "protocol-dispatch"))) (_a$1507 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") pname))) (_a$1508 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first sig)))) (_a$1509 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "this__11__auto"))) (_a$1510 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "rest__10__auto")))) (jolt-invoke _a$1505 _a$1506 _a$1507 _a$1508 _a$1509 _a$1510))))) (jolt-invoke _a$1511 _a$1512 _a$1513 _a$1514))))) (jolt-invoke _a$1515 _a$1516 _a$1517 _a$1518)))) sigs))) (jolt-invoke _a$1519 _a$1520 _a$1521 _a$1522 _a$1523)))))) + (mark-macro! "clojure.core" "defprotocol")) +(guard (e (#t #f)) + (def-var! "clojure.core" ".." + (lambda (x form . more) (let fnrec1524 ((x x) (form form) (more (list->cseq more))) (let* ((step (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (let* ((_a$1525 (var-deref "clojure.core" "__sqcat")) (_a$1526 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "."))) (_a$1527 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$1528 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first form))) (_a$1529 (jolt-rest form))) (jolt-invoke _a$1525 _a$1526 _a$1527 _a$1528 _a$1529)) (let* ((_a$1530 (var-deref "clojure.core" "__sqcat")) (_a$1531 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "."))) (_a$1532 (jolt-invoke (var-deref "clojure.core" "__sq1") x)) (_a$1533 (jolt-invoke (var-deref "clojure.core" "__sq1") form))) (jolt-invoke _a$1530 _a$1531 _a$1532 _a$1533))))) (if (jolt-truthy? (jolt-seq more)) (let* ((_a$1534 (var-deref "clojure.core" "__sqcat")) (_a$1535 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" ".."))) (_a$1536 (jolt-invoke (var-deref "clojure.core" "__sq1") step)) (_a$1537 more)) (jolt-invoke _a$1534 _a$1535 _a$1536 _a$1537)) step))))) + (mark-macro! "clojure.core" "..")) +(guard (e (#t #f)) + (def-var! "clojure.core" "extends?" (letrec ((extends? (lambda (protocol atype) (let fnrec1538 ((protocol protocol) (atype atype)) (let* ((want (jolt-invoke (var-deref "clojure.core" "name") atype)) (dotted (jolt-invoke (var-deref "clojure.core" "str") "." want)) (dlen (jolt-count dotted))) (jolt-invoke (var-deref "clojure.core" "boolean") (let* ((_a$1540 (var-deref "clojure.core" "some")) (_a$1541 (lambda (t) (let fnrec1539 ((t t)) (let* ((tn (jolt-invoke (var-deref "clojure.core" "name") t))) (let* ((or__14__auto (jolt= tn want))) (if (jolt-truthy? or__14__auto) or__14__auto (let* ((and__13__auto (> (jolt-count tn) dlen))) (if (jolt-truthy? and__13__auto) (jolt= (jolt-invoke (var-deref "clojure.core" "subs") tn (- (jolt-count tn) dlen)) dotted) and__13__auto)))))))) (_a$1542 (jolt-invoke (var-deref "clojure.core" "extenders") protocol))) (jolt-invoke _a$1540 _a$1541 _a$1542)))))))) extends?))) +(guard (e (#t #f)) + (def-var! "clojure.core" "extend" (letrec ((extend (lambda (atype . proto+mmaps) (let fnrec1543 ((atype atype) (proto+mmaps (list->cseq proto+mmaps))) (let* ((s (jolt-seq proto+mmaps))) (let loop1544 ((s s)) (if (jolt-truthy? s) (begin (let* ((proto (jolt-first s)) (mmap (jolt-invoke (var-deref "clojure.core" "second") s)) (pname (jolt-invoke (var-deref "clojure.core" "name") (jolt-get proto (keyword #f "name"))))) (begin (jolt-count (jolt-map (lambda (G__25) (let fnrec1545 ((G__25 G__25)) (let* ((G__26 G__25) (k (jolt-nth G__26 0 jolt-nil)) (f (jolt-nth G__26 1 jolt-nil))) (begin (let* ((_a$1546 (var-deref "clojure.core" "register-method")) (_a$1547 (jolt-invoke (var-deref "clojure.core" "name") atype)) (_a$1548 pname) (_a$1549 (jolt-invoke (var-deref "clojure.core" "name") k)) (_a$1550 f)) (jolt-invoke _a$1546 _a$1547 _a$1548 _a$1549 _a$1550)) jolt-nil)))) mmap)) jolt-nil)) (loop1544 (jolt-invoke (var-deref "clojure.core" "nnext") s))) jolt-nil))))))) extend))) +(guard (e (#t #f)) + (def-var! "clojure.core" "extend-type" + (lambda (tsym . body) (let fnrec1551 ((tsym tsym) (body (list->cseq body))) (let* ((tname (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") tsym)) "nil" (jolt-invoke (var-deref "clojure.core" "name") tsym)))) (let* ((items (jolt-seq body)) (proto jolt-nil) (forms (jolt-vector))) (let loop1552 ((items items) (proto proto) (forms forms)) (if (jolt-empty? items) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) forms) (let* ((x (jolt-first items))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") x)) (let* ((_a$1553 (jolt-rest items)) (_a$1554 (jolt-invoke (var-deref "clojure.core" "name") x)) (_a$1555 forms)) (loop1552 _a$1553 _a$1554 _a$1555)) (let* ((_a$1566 (jolt-rest items)) (_a$1567 proto) (_a$1568 (jolt-conj forms (let* ((_a$1560 (var-deref "clojure.core" "__sqcat")) (_a$1561 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-method"))) (_a$1562 (jolt-invoke (var-deref "clojure.core" "__sq1") tname)) (_a$1563 (jolt-invoke (var-deref "clojure.core" "__sq1") proto)) (_a$1564 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first x)))) (_a$1565 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1556 (var-deref "clojure.core" "__sqcat")) (_a$1557 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1558 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth x 1))) (_a$1559 (jolt-drop 2 x))) (jolt-invoke _a$1556 _a$1557 _a$1558 _a$1559))))) (jolt-invoke _a$1560 _a$1561 _a$1562 _a$1563 _a$1564 _a$1565))))) (loop1552 _a$1566 _a$1567 _a$1568))))))))))) + (mark-macro! "clojure.core" "extend-type")) +(guard (e (#t #f)) + (def-var! "clojure.core" "extend-protocol" + (lambda (psym . type-impls) (let fnrec1569 ((psym psym) (type-impls (list->cseq type-impls))) (let* ((_a$1578 (var-deref "clojure.core" "__sqcat")) (_a$1579 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$1580 (let* ((_a$1576 (lambda (g) (let fnrec1570 ((g g)) (let* ((_a$1571 (var-deref "clojure.core" "__sqcat")) (_a$1572 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "extend-type"))) (_a$1573 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-first g))) (_a$1574 (jolt-invoke (var-deref "clojure.core" "__sq1") psym)) (_a$1575 (jolt-rest g))) (jolt-invoke _a$1571 _a$1572 _a$1573 _a$1574 _a$1575))))) (_a$1577 (jolt-invoke (var-deref "clojure.core" "group-by-head") type-impls))) (jolt-map _a$1576 _a$1577)))) (jolt-invoke _a$1578 _a$1579 _a$1580))))) + (mark-macro! "clojure.core" "extend-protocol")) +(guard (e (#t #f)) + (def-var! "clojure.core" "proxy" + (lambda args (let fnrec1581 ((args (list->cseq args))) jolt-nil))) + (mark-macro! "clojure.core" "proxy")) +(guard (e (#t #f)) + (def-var! "clojure.core" "definterface" + (lambda (name-sym . body) (let fnrec1582 ((name-sym name-sym) (body (list->cseq body))) (let* ((_a$1590 (var-deref "clojure.core" "__sqcat")) (_a$1591 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$1592 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1583 (var-deref "clojure.core" "__sqcat")) (_a$1584 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$1585 (jolt-invoke (var-deref "clojure.core" "__sq1") name-sym)) (_a$1586 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqmap"))))) (jolt-invoke _a$1583 _a$1584 _a$1585 _a$1586)))) (_a$1593 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1587 (var-deref "clojure.core" "__sqcat")) (_a$1588 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "quote"))) (_a$1589 (jolt-invoke (var-deref "clojure.core" "__sq1") name-sym))) (jolt-invoke _a$1587 _a$1588 _a$1589))))) (jolt-invoke _a$1590 _a$1591 _a$1592 _a$1593))))) + (mark-macro! "clojure.core" "definterface")) +(guard (e (#t #f)) + (def-var! "clojure.core" "reify" + (lambda forms (let fnrec1594 ((forms (list->cseq forms))) (let* ((items (jolt-seq forms)) (protos (jolt-vector)) (methods (jolt-hash-map))) (let loop1595 ((items items) (protos protos) (methods methods)) (if (jolt-empty? items) (let* ((_a$1596 (var-deref "clojure.core" "__sqcat")) (_a$1597 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "make-reified"))) (_a$1598 (jolt-invoke (var-deref "clojure.core" "__sq1") methods)) (_a$1599 (jolt-invoke (var-deref "clojure.core" "vec") (jolt-map (var-deref "clojure.core" "name") protos)))) (jolt-invoke _a$1596 _a$1597 _a$1598 _a$1599)) (let* ((x (jolt-first items))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "symbol?") x)) (let* ((_a$1600 (jolt-rest items)) (_a$1601 (jolt-conj protos x)) (_a$1602 methods)) (loop1595 _a$1600 _a$1601 _a$1602)) (let* ((_a$1610 (jolt-rest items)) (_a$1611 protos) (_a$1612 (let* ((_a$1607 methods) (_a$1608 (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first x)))) (_a$1609 (let* ((_a$1603 (var-deref "clojure.core" "__sqcat")) (_a$1604 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1605 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-nth x 1))) (_a$1606 (jolt-drop 2 x))) (jolt-invoke _a$1603 _a$1604 _a$1605 _a$1606)))) (jolt-assoc _a$1607 _a$1608 _a$1609)))) (loop1595 _a$1610 _a$1611 _a$1612)))))))))) + (mark-macro! "clojure.core" "reify")) +(guard (e (#t #f)) + (def-var! "clojure.core" "defrecord" + (lambda (name-sym fields . body) (let fnrec1613 ((name-sym name-sym) (fields fields) (body (list->cseq body))) (let* ((tn (jolt-invoke (var-deref "clojure.core" "name") name-sym)) (arrow (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "->" tn))) (mapf (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "map->" tn))) (m (jolt-invoke (var-deref "clojure.core" "fresh-sym"))) (impl (lambda (proto specs) (let fnrec1614 ((proto proto) (specs specs)) (let* ((_a$1637 (var-deref "clojure.core" "__sqcat")) (_a$1638 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$1639 (jolt-map (lambda (spec) (let fnrec1615 ((spec spec)) (let* ((argv (jolt-nth spec 1)) (inst (jolt-first argv)) (hinted (jolt-assoc argv 0 (jolt-invoke (var-deref "clojure.core" "vary-meta") inst jolt-assoc (keyword #f "tag") (jolt-invoke (var-deref "clojure.core" "name") name-sym)))) (binds (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "mapcat") (lambda (f) (let fnrec1616 ((f f)) (let* ((_o$1621 f) (_o$1622 (let* ((_a$1617 (var-deref "clojure.core" "__sqcat")) (_a$1618 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$1619 (jolt-invoke (var-deref "clojure.core" "__sq1") inst)) (_a$1620 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f))))) (jolt-invoke _a$1617 _a$1618 _a$1619 _a$1620)))) (jolt-vector _o$1621 _o$1622)))) fields)))) (let* ((_a$1631 (var-deref "clojure.core" "__sqcat")) (_a$1632 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "register-inline-method"))) (_a$1633 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") name-sym))) (_a$1634 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") proto))) (_a$1635 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "name") (jolt-first spec)))) (_a$1636 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1627 (var-deref "clojure.core" "__sqcat")) (_a$1628 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1629 (jolt-invoke (var-deref "clojure.core" "__sq1") hinted)) (_a$1630 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1623 (var-deref "clojure.core" "__sqcat")) (_a$1624 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "let"))) (_a$1625 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") binds))) (_a$1626 (jolt-drop 2 spec))) (jolt-invoke _a$1623 _a$1624 _a$1625 _a$1626))))) (jolt-invoke _a$1627 _a$1628 _a$1629 _a$1630))))) (jolt-invoke _a$1631 _a$1632 _a$1633 _a$1634 _a$1635 _a$1636))))) specs))) (jolt-invoke _a$1637 _a$1638 _a$1639)))))) (let* ((_a$1666 (var-deref "clojure.core" "__sqcat")) (_a$1667 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$1668 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1640 (var-deref "clojure.core" "__sqcat")) (_a$1641 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "deftype"))) (_a$1642 (jolt-invoke (var-deref "clojure.core" "__sq1") name-sym)) (_a$1643 (jolt-invoke (var-deref "clojure.core" "__sq1") fields))) (jolt-invoke _a$1640 _a$1641 _a$1642 _a$1643)))) (_a$1669 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1656 (var-deref "clojure.core" "__sqcat")) (_a$1657 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "def"))) (_a$1658 (jolt-invoke (var-deref "clojure.core" "__sq1") mapf)) (_a$1659 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1652 (var-deref "clojure.core" "__sqcat")) (_a$1653 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "fn*"))) (_a$1654 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") m)))) (_a$1655 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1649 (var-deref "clojure.core" "__sqcat")) (_a$1650 (jolt-invoke (var-deref "clojure.core" "__sq1") arrow)) (_a$1651 (jolt-map (lambda (f) (let fnrec1644 ((f f)) (let* ((_a$1645 (var-deref "clojure.core" "__sqcat")) (_a$1646 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "get"))) (_a$1647 (jolt-invoke (var-deref "clojure.core" "__sq1") m)) (_a$1648 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "keyword") (jolt-invoke (var-deref "clojure.core" "name") f))))) (jolt-invoke _a$1645 _a$1646 _a$1647 _a$1648)))) fields))) (jolt-invoke _a$1649 _a$1650 _a$1651))))) (jolt-invoke _a$1652 _a$1653 _a$1654 _a$1655))))) (jolt-invoke _a$1656 _a$1657 _a$1658 _a$1659)))) (_a$1670 (let* ((_a$1664 (lambda (g) (let fnrec1660 ((g g)) (let* ((_a$1661 impl) (_a$1662 (jolt-first g)) (_a$1663 (jolt-rest g))) (jolt-invoke _a$1661 _a$1662 _a$1663))))) (_a$1665 (jolt-invoke (var-deref "clojure.core" "group-by-head") body))) (jolt-map _a$1664 _a$1665)))) (jolt-invoke _a$1666 _a$1667 _a$1668 _a$1669 _a$1670)))))) + (mark-macro! "clojure.core" "defrecord")) +(guard (e (#t #f)) + (def-var! "clojure.core" "memfn" + (lambda (method-name . args) (let fnrec1671 ((method-name method-name) (args (list->cseq args))) (let* ((_a$1676 (var-deref "clojure.core" "__sqcat")) (_a$1677 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "fn"))) (_a$1678 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "__sqvec") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "target__12__auto")) args))) (_a$1679 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$1672 (var-deref "clojure.core" "__sqcat")) (_a$1673 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-invoke (var-deref "clojure.core" "symbol") (jolt-invoke (var-deref "clojure.core" "str") "." (jolt-invoke (var-deref "clojure.core" "name") method-name))))) (_a$1674 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "target__12__auto"))) (_a$1675 args)) (jolt-invoke _a$1672 _a$1673 _a$1674 _a$1675))))) (jolt-invoke _a$1676 _a$1677 _a$1678 _a$1679))))) + (mark-macro! "clojure.core" "memfn")) +(guard (e (#t #f)) + (def-var! "clojure.core" "distinct" (letrec ((distinct (case-lambda (() (let fnrec173 () (lambda (rf) (let fnrec174 ((rf rf)) (let* ((seen (jolt-invoke (var-deref "clojure.core" "volatile!") (jolt-hash-set)))) (case-lambda (() (let fnrec175 () (jolt-invoke rf))) ((result) (let fnrec176 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec177 ((result result) (input input)) (if (jolt-contains? (jolt-invoke (var-deref "clojure.core" "deref") seen) input) result (begin (jolt-invoke (var-deref "clojure.core" "vswap!") seen jolt-conj input) (jolt-invoke rf result input))))))))))) ((coll) (let fnrec178 ((coll coll)) (let* ((step (letrec ((step (lambda (xs seen) (let fnrec179 ((xs xs) (seen seen)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec180 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-invoke (lambda (G__13 seen) (let fnrec181 ((G__13 G__13) (seen seen)) (let* ((G__14 G__13) (f (jolt-nth G__14 0 jolt-nil)) (xs G__14)) (let* ((temp__15__auto (jolt-seq xs))) (if (jolt-truthy? temp__15__auto) (let* ((s temp__15__auto)) (if (jolt-contains? seen f) (fnrec181 (jolt-rest s) seen) (jolt-cons f (let* ((_a$182 step) (_a$183 (jolt-rest s)) (_a$184 (jolt-conj seen f))) (jolt-invoke _a$182 _a$183 _a$184))))) jolt-nil))))) xs seen))))))))) step))) (jolt-invoke step coll (jolt-hash-set)))))))) distinct))) +(guard (e (#t #f)) + (def-var! "clojure.core" "keep" (letrec ((keep (case-lambda ((f) (let fnrec185 ((f f)) (lambda (rf) (let fnrec186 ((rf rf)) (case-lambda (() (let fnrec187 () (jolt-invoke rf))) ((result) (let fnrec188 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec189 ((result result) (input input)) (let* ((v (jolt-invoke f input))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") v)) result (jolt-invoke rf result v)))))))))) ((f coll) (let fnrec190 ((f f) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec191 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__15__auto (jolt-seq coll))) (if (jolt-truthy? temp__15__auto) (let* ((s temp__15__auto)) (let* ((x (jolt-invoke f (jolt-first s)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") x)) (jolt-invoke keep f (jolt-rest s)) (jolt-cons x (jolt-invoke keep f (jolt-rest s)))))) jolt-nil))))))))))) keep))) +(guard (e (#t #f)) + (def-var! "clojure.core" "keep-indexed" (letrec ((keep-indexed (case-lambda ((f) (let fnrec192 ((f f)) (lambda (rf) (let fnrec193 ((rf rf)) (let* ((ia (jolt-invoke (var-deref "clojure.core" "volatile!") -1))) (case-lambda (() (let fnrec194 () (jolt-invoke rf))) ((result) (let fnrec195 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec196 ((result result) (input input)) (let* ((i (jolt-invoke (var-deref "clojure.core" "vswap!") ia jolt-inc)) (v (jolt-invoke f i input))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") v)) result (jolt-invoke rf result v))))))))))) ((f coll) (let fnrec197 ((f f) (coll coll)) (letrec* ((keepi (letrec ((keepi (lambda (idx coll) (let fnrec198 ((idx idx) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec199 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__15__auto (jolt-seq coll))) (if (jolt-truthy? temp__15__auto) (let* ((s temp__15__auto)) (let* ((x (jolt-invoke f idx (jolt-first s)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") x)) (let* ((_a$200 keepi) (_a$201 (jolt-inc idx)) (_a$202 (jolt-rest s))) (jolt-invoke _a$200 _a$201 _a$202)) (jolt-cons x (let* ((_a$203 keepi) (_a$204 (jolt-inc idx)) (_a$205 (jolt-rest s))) (jolt-invoke _a$203 _a$204 _a$205)))))) jolt-nil)))))))))) keepi))) (jolt-invoke keepi 0 coll))))))) keep-indexed))) +(guard (e (#t #f)) + (def-var! "clojure.core" "map-indexed" (letrec ((map-indexed (case-lambda ((f) (let fnrec206 ((f f)) (lambda (rf) (let fnrec207 ((rf rf)) (let* ((i (jolt-invoke (var-deref "clojure.core" "volatile!") -1))) (case-lambda (() (let fnrec208 () (jolt-invoke rf))) ((result) (let fnrec209 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec210 ((result result) (input input)) (jolt-invoke rf result (jolt-invoke f (jolt-invoke (var-deref "clojure.core" "vswap!") i jolt-inc) input)))))))))) ((f coll) (let fnrec211 ((f f) (coll coll)) (letrec* ((mapi (letrec ((mapi (lambda (idx coll) (let fnrec212 ((idx idx) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec213 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__15__auto (jolt-seq coll))) (if (jolt-truthy? temp__15__auto) (let* ((s temp__15__auto)) (let* ((_a$217 (jolt-invoke f idx (jolt-first s))) (_a$218 (let* ((_a$214 mapi) (_a$215 (jolt-inc idx)) (_a$216 (jolt-rest s))) (jolt-invoke _a$214 _a$215 _a$216)))) (jolt-cons _a$217 _a$218))) jolt-nil)))))))))) mapi))) (jolt-invoke mapi 0 coll))))))) map-indexed))) +(guard (e (#t #f)) + (def-var! "clojure.core" "cycle" (letrec ((cycle (lambda (coll) (let fnrec219 ((coll coll)) (let* ((temp__4__auto (jolt-seq coll))) (if (jolt-truthy? temp__4__auto) (let* ((vals temp__4__auto)) (let* ((n (jolt-count vals))) (letrec* ((cstep (letrec ((cstep (lambda (i) (let fnrec220 ((i i)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec221 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((_a$222 (jolt-nth vals (modulo i n))) (_a$223 (jolt-invoke cstep (jolt-inc i)))) (jolt-cons _a$222 _a$223)))))))))) cstep))) (jolt-invoke cstep 0)))) (jolt-list ))))))) cycle))) +(guard (e (#t #f)) + (def-var! "clojure.core" "repeatedly" (letrec ((repeatedly (case-lambda ((f) (let fnrec224 ((f f)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec225 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((_a$226 (jolt-invoke f)) (_a$227 (jolt-invoke repeatedly f))) (jolt-cons _a$226 _a$227)))))))) ((n f) (let fnrec228 ((n n) (f f)) (jolt-take n (jolt-invoke repeatedly f))))))) repeatedly))) +(guard (e (#t #f)) + (def-var! "clojure.core" "repeat" (letrec ((repeat (case-lambda ((x) (let fnrec229 ((x x)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec230 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-cons x (jolt-invoke repeat x)))))))) ((n x) (let fnrec231 ((n n) (x x)) (jolt-take n (jolt-invoke repeat x))))))) repeat))) +(guard (e (#t #f)) + (def-var! "clojure.core" "iterate" (letrec ((iterate (lambda (f x) (let fnrec232 ((f f) (x x)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec233 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (jolt-cons x (jolt-invoke iterate f (jolt-invoke f x))))))))))) iterate))) +(guard (e (#t #f)) + (def-var! "clojure.core" "partition-all" (letrec ((partition-all (case-lambda ((n) (let fnrec234 ((n n)) (lambda (rf) (let fnrec235 ((rf rf)) (let* ((a (jolt-invoke (var-deref "clojure.core" "volatile!") (jolt-vector)))) (case-lambda (() (let fnrec236 () (jolt-invoke rf))) ((result) (let fnrec237 ((result result)) (let* ((result (if (jolt-zero? (jolt-count (jolt-invoke (var-deref "clojure.core" "deref") a))) result (let* ((v (jolt-invoke (var-deref "clojure.core" "deref") a))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") a (jolt-vector)) (jolt-invoke (var-deref "clojure.core" "unreduced") (jolt-invoke rf result v))))))) (jolt-invoke rf result)))) ((result input) (let fnrec238 ((result result) (input input)) (begin (jolt-invoke (var-deref "clojure.core" "vswap!") a jolt-conj input) (if (jolt= n (jolt-count (jolt-invoke (var-deref "clojure.core" "deref") a))) (let* ((v (jolt-invoke (var-deref "clojure.core" "deref") a))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") a (jolt-vector)) (jolt-invoke rf result v))) result)))))))))) ((n coll) (let fnrec239 ((n n) (coll coll)) (letrec* ((go (letrec ((go (lambda (s) (let fnrec240 ((s s)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec241 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (if (jolt-truthy? (jolt-seq s)) (let* ((i 0) (chunk (jolt-vector)) (cur s)) (let loop242 ((i i) (chunk chunk) (cur cur)) (if (jolt-truthy? (let* ((and__13__auto (< i n))) (if (jolt-truthy? and__13__auto) (jolt-seq cur) and__13__auto))) (let* ((_a$243 (jolt-inc i)) (_a$244 (jolt-conj chunk (jolt-first cur))) (_a$245 (jolt-rest cur))) (loop242 _a$243 _a$244 _a$245)) (jolt-cons chunk (jolt-invoke go cur))))) jolt-nil))))))))) go))) (jolt-invoke go coll)))) ((n step coll) (let fnrec246 ((n n) (step step) (coll coll)) (letrec* ((go (letrec ((go (lambda (s) (let fnrec247 ((s s)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec248 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (if (jolt-truthy? (jolt-seq s)) (let* ((_a$249 (jolt-take n s)) (_a$250 (jolt-invoke go (jolt-invoke (var-deref "clojure.core" "nthrest") s step)))) (jolt-cons _a$249 _a$250)) jolt-nil))))))))) go))) (jolt-invoke go coll))))))) partition-all))) +(guard (e (#t #f)) + (def-var! "clojure.core" "interpose" (letrec ((interpose (case-lambda ((sep) (let fnrec251 ((sep sep)) (lambda (rf) (let fnrec252 ((rf rf)) (let* ((started (jolt-invoke (var-deref "clojure.core" "volatile!") #f))) (case-lambda (() (let fnrec253 () (jolt-invoke rf))) ((result) (let fnrec254 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec255 ((result result) (input input)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "deref") started)) (let* ((sepr (jolt-invoke rf result sep))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "reduced?") sepr)) sepr (jolt-invoke rf sepr input))) (begin (jolt-invoke (var-deref "clojure.core" "vreset!") started #t) (jolt-invoke rf result input))))))))))) ((sep coll) (let fnrec256 ((sep sep) (coll coll)) (jolt-drop 1 (jolt-invoke (var-deref "clojure.core" "interleave") (jolt-invoke (var-deref "clojure.core" "repeat") sep) coll))))))) interpose))) +(guard (e (#t #f)) + (def-var! "clojure.core" "take-nth" (letrec ((take-nth (case-lambda ((n) (let fnrec257 ((n n)) (lambda (rf) (let fnrec258 ((rf rf)) (let* ((iv (jolt-invoke (var-deref "clojure.core" "volatile!") -1))) (case-lambda (() (let fnrec259 () (jolt-invoke rf))) ((result) (let fnrec260 ((result result)) (jolt-invoke rf result))) ((result input) (let fnrec261 ((result result) (input input)) (let* ((i (jolt-invoke (var-deref "clojure.core" "vswap!") iv jolt-inc))) (if (jolt-zero? (remainder i n)) (jolt-invoke rf result input) result)))))))))) ((n coll) (let fnrec262 ((n n) (coll coll)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec263 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((temp__15__auto (jolt-seq coll))) (if (jolt-truthy? temp__15__auto) (let* ((s temp__15__auto)) (let* ((_a$264 (jolt-first s)) (_a$265 (jolt-invoke take-nth n (jolt-drop n s)))) (jolt-cons _a$264 _a$265))) jolt-nil))))))))))) take-nth))) +(guard (e (#t #f)) + (def-var! "clojure.core" "pmap" (letrec ((pmap (case-lambda ((f coll) (let fnrec266 ((f f) (coll coll)) (jolt-map (var-deref "clojure.core" "deref") (jolt-invoke (var-deref "clojure.core" "doall") (jolt-map (lambda (x) (let fnrec267 ((x x)) (jolt-invoke (var-deref "clojure.core" "future-call") (lambda () (let fnrec268 () (jolt-invoke f x)))))) coll))))) ((f coll . colls) (let fnrec269 ((f f) (coll coll) (colls (list->cseq colls))) (let* ((_a$271 pmap) (_a$272 (lambda (xs) (let fnrec270 ((xs xs)) (jolt-apply f xs)))) (_a$273 (jolt-apply jolt-map jolt-vector coll colls))) (jolt-invoke _a$271 _a$272 _a$273))))))) pmap))) +(guard (e (#t #f)) + (def-var! "clojure.core" "pcalls" (letrec ((pcalls (lambda fns (let fnrec274 ((fns (list->cseq fns))) (jolt-invoke (var-deref "clojure.core" "pmap") (lambda (f) (let fnrec275 ((f f)) (jolt-invoke f))) fns))))) pcalls))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "reader-eof" (keyword "jolt" "reader-eof") (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (begin (def-var! "clojure.core" "IReader" (jolt-invoke (var-deref "clojure.core" "make-protocol") "IReader" (let* ((_o$282 (keyword #f "-read+string")) (_o$283 (let* ((_o$276 (keyword #f "name")) (_o$277 "-read+string")) (jolt-hash-map _o$276 _o$277))) (_o$284 (keyword #f "-read-line")) (_o$285 (let* ((_o$278 (keyword #f "name")) (_o$279 "-read-line")) (jolt-hash-map _o$278 _o$279))) (_o$286 (keyword #f "-read-form")) (_o$287 (let* ((_o$280 (keyword #f "name")) (_o$281 "-read-form")) (jolt-hash-map _o$280 _o$281)))) (jolt-hash-map _o$282 _o$283 _o$284 _o$285 _o$286 _o$287)))) (jolt-invoke (var-deref "clojure.core" "register-protocol-methods!") "IReader" (let* ((_o$288 "-read-line") (_o$289 "-read-form") (_o$290 "-read+string")) (jolt-vector _o$288 _o$289 _o$290))) (def-var! "clojure.core" "-read-line" (lambda (this__11__auto . rest__10__auto) (let fnrec291 ((this__11__auto this__11__auto) (rest__10__auto (list->cseq rest__10__auto))) (jolt-invoke (var-deref "clojure.core" "protocol-dispatch") "IReader" "-read-line" this__11__auto rest__10__auto)))) (def-var! "clojure.core" "-read-form" (lambda (this__11__auto . rest__10__auto) (let fnrec292 ((this__11__auto this__11__auto) (rest__10__auto (list->cseq rest__10__auto))) (jolt-invoke (var-deref "clojure.core" "protocol-dispatch") "IReader" "-read-form" this__11__auto rest__10__auto)))) (def-var! "clojure.core" "-read+string" (lambda (this__11__auto . rest__10__auto) (let fnrec293 ((this__11__auto this__11__auto) (rest__10__auto (list->cseq rest__10__auto))) (jolt-invoke (var-deref "clojure.core" "protocol-dispatch") "IReader" "-read+string" this__11__auto rest__10__auto)))))) +(guard (e (#t #f)) + (def-var! "clojure.core" "__string-reader" (letrec ((__string-reader (lambda (s) (let fnrec294 ((s s)) (let* ((buf (jolt-invoke (var-deref "clojure.core" "atom") s))) (jolt-invoke (var-deref "clojure.core" "make-reified") (let* ((_o$304 (keyword #f "-read+string")) (_o$305 (lambda (_ eof-error? eof-value) (let fnrec295 ((_ _) (eof-error? eof-error?) (eof-value eof-value)) (let* ((s (jolt-invoke (var-deref "clojure.core" "deref") buf)) (r (jolt-invoke (var-deref "clojure.core" "__parse-next") s))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") r)) (if (jolt-truthy? eof-error?) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map))) (let* ((_o$296 eof-value) (_o$297 "")) (jolt-vector _o$296 _o$297))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") buf (jolt-nth r 1)) (let* ((_o$300 (jolt-nth r 0)) (_o$301 (jolt-invoke (var-deref "clojure.core" "subs") s 0 (let* ((_a$298 (jolt-count s)) (_a$299 (jolt-count (jolt-nth r 1)))) (- _a$298 _a$299))))) (jolt-vector _o$300 _o$301)))))))) (_o$306 (keyword #f "-read-line")) (_o$307 (lambda (_) (let fnrec302 ((_ _)) (let* ((cur (jolt-invoke (var-deref "clojure.core" "deref") buf))) (if (jolt-pos? (jolt-count cur)) (let* ((i (jolt-invoke (var-deref "clojure.core" "str-find") "\n" cur))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") i)) (begin (jolt-invoke (var-deref "clojure.core" "reset!") buf "") cur) (begin (jolt-invoke (var-deref "clojure.core" "reset!") buf (jolt-invoke (var-deref "clojure.core" "subs") cur (jolt-inc i))) (jolt-invoke (var-deref "clojure.core" "subs") cur 0 i)))) jolt-nil))))) (_o$308 (keyword #f "-read-form")) (_o$309 (lambda (_) (let fnrec303 ((_ _)) (let* ((r (jolt-invoke (var-deref "clojure.core" "__parse-next") (jolt-invoke (var-deref "clojure.core" "deref") buf)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") r)) (var-deref "clojure.core" "reader-eof") (begin (jolt-invoke (var-deref "clojure.core" "reset!") buf (jolt-nth r 1)) (jolt-nth r 0)))))))) (jolt-hash-map _o$304 _o$305 _o$306 _o$307 _o$308 _o$309)) "IReader")))))) __string-reader))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "stdin-buf" (jolt-invoke (var-deref "clojure.core" "atom") "") (jolt-hash-map (keyword #f "private") #t))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.core" "*in*" (jolt-invoke (var-deref "clojure.core" "make-reified") (let* ((_o$323 (keyword #f "-read+string")) (_o$324 (lambda (_ eof-error? eof-value) (let fnrec310 ((_ _) (eof-error? eof-error?) (eof-value eof-value)) (let* () (let loop311 () (let* ((s (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "stdin-buf"))) (r (jolt-invoke (var-deref "clojure.core" "__parse-next") s))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") r)) (let* ((line (jolt-invoke (var-deref "clojure.core" "__stdin-read-line")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") line)) (if (jolt-truthy? eof-error?) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map))) (let* ((_o$312 eof-value) (_o$313 "")) (jolt-vector _o$312 _o$313))) (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "clojure.core" "stdin-buf") (lambda (b) (let fnrec314 ((b b)) (jolt-invoke (var-deref "clojure.core" "str") b line "\n")))) (loop311 )))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "clojure.core" "stdin-buf") (jolt-nth r 1)) (let* ((_o$317 (jolt-nth r 0)) (_o$318 (jolt-invoke (var-deref "clojure.core" "subs") s 0 (let* ((_a$315 (jolt-count s)) (_a$316 (jolt-count (jolt-nth r 1)))) (- _a$315 _a$316))))) (jolt-vector _o$317 _o$318)))))))))) (_o$325 (keyword #f "-read-line")) (_o$326 (lambda (_) (let fnrec319 ((_ _)) (let* ((cur (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "stdin-buf")))) (if (jolt-pos? (jolt-count cur)) (let* ((i (jolt-invoke (var-deref "clojure.core" "str-find") "\n" cur))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") i)) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "clojure.core" "stdin-buf") "") cur) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "clojure.core" "stdin-buf") (jolt-invoke (var-deref "clojure.core" "subs") cur (jolt-inc i))) (jolt-invoke (var-deref "clojure.core" "subs") cur 0 i)))) (jolt-invoke (var-deref "clojure.core" "__stdin-read-line"))))))) (_o$327 (keyword #f "-read-form")) (_o$328 (lambda (_) (let fnrec320 ((_ _)) (let* () (let loop321 () (let* ((r (jolt-invoke (var-deref "clojure.core" "__parse-next") (jolt-invoke (var-deref "clojure.core" "deref") (var-deref "clojure.core" "stdin-buf"))))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") r)) (let* ((line (jolt-invoke (var-deref "clojure.core" "__stdin-read-line")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") line)) (var-deref "clojure.core" "reader-eof") (begin (jolt-invoke (var-deref "clojure.core" "swap!") (var-deref "clojure.core" "stdin-buf") (lambda (b) (let fnrec322 ((b b)) (jolt-invoke (var-deref "clojure.core" "str") b line "\n")))) (loop321 )))) (begin (jolt-invoke (var-deref "clojure.core" "reset!") (var-deref "clojure.core" "stdin-buf") (jolt-nth r 1)) (jolt-nth r 0)))))))))) (jolt-hash-map _o$323 _o$324 _o$325 _o$326 _o$327 _o$328)) "IReader") (jolt-hash-map (keyword #f "dynamic") #t))) +(guard (e (#t #f)) + (def-var! "clojure.core" "read-line" (letrec ((read-line (lambda () (let fnrec329 () (jolt-invoke (var-deref "clojure.core" "-read-line") (var-deref "clojure.core" "*in*")))))) read-line))) +(guard (e (#t #f)) + (def-var! "clojure.core" "read" (letrec ((read (case-lambda (() (let fnrec330 () (jolt-invoke read (var-deref "clojure.core" "*in*")))) ((stream) (let fnrec331 ((stream stream)) (let* ((v (jolt-invoke (var-deref "clojure.core" "-read-form") stream))) (if (jolt= v (var-deref "clojure.core" "reader-eof")) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map))) v)))) ((stream eof-error? eof-value) (let fnrec332 ((stream stream) (eof-error? eof-error?) (eof-value eof-value)) (let* ((v (jolt-invoke (var-deref "clojure.core" "-read-form") stream))) (if (jolt= v (var-deref "clojure.core" "reader-eof")) (if (jolt-truthy? eof-error?) (jolt-throw (jolt-ex-info "EOF while reading" (jolt-hash-map))) eof-value) v))))))) read))) +(guard (e (#t #f)) + (def-var! "clojure.core" "with-in-str" + (lambda (s . body) (let fnrec333 ((s s) (body (list->cseq body))) (let* ((_a$340 (var-deref "clojure.core" "__sqcat")) (_a$341 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "binding"))) (_a$342 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$337 (var-deref "clojure.core" "__sqvec")) (_a$338 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "*in*"))) (_a$339 (jolt-invoke (var-deref "clojure.core" "__sq1") (let* ((_a$334 (var-deref "clojure.core" "__sqcat")) (_a$335 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol "clojure.core" "__string-reader"))) (_a$336 (jolt-invoke (var-deref "clojure.core" "__sq1") s))) (jolt-invoke _a$334 _a$335 _a$336))))) (jolt-invoke _a$337 _a$338 _a$339)))) (_a$343 body)) (jolt-invoke _a$340 _a$341 _a$342 _a$343))))) + (mark-macro! "clojure.core" "with-in-str")) +(guard (e (#t #f)) + (def-var! "clojure.core" "read+string" (letrec ((read+string (case-lambda (() (let fnrec344 () (jolt-invoke read+string (var-deref "clojure.core" "*in*")))) ((stream) (let fnrec345 ((stream stream)) (jolt-invoke read+string stream #t jolt-nil))) ((stream eof-error? eof-value) (let fnrec346 ((stream stream) (eof-error? eof-error?) (eof-value eof-value)) (jolt-invoke (var-deref "clojure.core" "-read+string") stream eof-error? eof-value)))))) read+string))) +(guard (e (#t #f)) + (def-var! "clojure.core" "line-seq" (letrec ((line-seq (lambda (rdr) (let fnrec347 ((rdr rdr)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") rdr)) (jolt-seq (jolt-invoke (var-deref "clojure.core" "str-split") "\n" rdr)) (jolt-invoke (var-deref "clojure.core" "make-lazy-seq") (lambda () (let fnrec348 () (jolt-invoke (var-deref "clojure.core" "coll->cells") (let* ((line (jolt-invoke (var-deref "clojure.core" "-read-line") rdr))) (if (jolt-truthy? line) (jolt-cons line (jolt-invoke line-seq rdr)) jolt-nil))))))))))) line-seq))) +(guard (e (#t #f)) + (jolt-invoke (var-deref "clojure.core" "defmulti-setup") (jolt-symbol #f "print-method") (lambda (x writer) (let fnrec349 ((x x) (writer writer)) (let* ((t (jolt-get (jolt-invoke (var-deref "clojure.core" "meta") x) (keyword #f "type")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") t)) t (jolt-invoke (var-deref "clojure.core" "type") x))))))) +(guard (e (#t #f)) + (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword #f "default") (lambda (o w) (let fnrec350 ((o o) (w w)) (begin (record-method-dispatch w "write" (jolt-vector (jolt-invoke (var-deref "clojure.core" "__pr-str1") o))) jolt-nil))))) +(guard (e (#t #f)) + (jolt-invoke (var-deref "clojure.core" "defmulti-setup") (jolt-symbol #f "print-dup") (lambda (x writer) (let fnrec351 ((x x) (writer writer)) (let* ((t (jolt-get (jolt-invoke (var-deref "clojure.core" "meta") x) (keyword #f "type")))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") t)) t (jolt-invoke (var-deref "clojure.core" "type") x))))))) +(guard (e (#t #f)) + (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-dup") (keyword #f "default") (lambda (o w) (let fnrec352 ((o o) (w w)) (jolt-invoke (var-deref "clojure.core" "print-method") o w))))) +(guard (e (#t #f)) + (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword "jolt" "uuid") (lambda (u w) (let fnrec353 ((u u) (w w)) (begin (record-method-dispatch w "write" (jolt-vector (jolt-invoke (var-deref "clojure.core" "str") "#uuid \"" (jolt-get u (keyword #f "str")) "\""))) jolt-nil))))) +(guard (e (#t #f)) + (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword "jolt" "regex") (lambda (re w) (let fnrec354 ((re re) (w w)) (begin (record-method-dispatch w "write" (jolt-vector (jolt-invoke (var-deref "clojure.core" "str") "#\"" (jolt-get re (keyword #f "source")) "\""))) jolt-nil))))) +(guard (e (#t #f)) + (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword "jolt" "transient") (lambda (t w) (let fnrec355 ((t t) (w w)) (begin (record-method-dispatch w "write" (jolt-vector (jolt-invoke (var-deref "clojure.core" "str") "#"))) jolt-nil))))) +(guard (e (#t #f)) + (jolt-invoke (var-deref "clojure.core" "defmethod-setup") (jolt-symbol #f "print-method") (keyword "jolt" "chan") (lambda (c w) (let fnrec356 ((c c) (w w)) (begin (record-method-dispatch w "write" (jolt-vector "#")) jolt-nil))))) +(guard (e (#t #f)) + (def-var! "clojure.core" "agent" (letrec ((agent (lambda (state . _opts) (let fnrec357 ((state state) (_opts (list->cseq _opts))) (jolt-invoke (var-deref "clojure.core" "atom") state))))) agent))) +(guard (e (#t #f)) + (def-var! "clojure.core" "send-off" (letrec ((send-off (lambda (a f . args) (let fnrec358 ((a a) (f f) (args (list->cseq args))) (begin (jolt-apply (var-deref "clojure.core" "swap!") a f args) a))))) send-off))) +(guard (e (#t #f)) + (def-var! "clojure.core" "send" (letrec ((send (lambda (a f . args) (let fnrec359 ((a a) (f f) (args (list->cseq args))) (begin (jolt-apply (var-deref "clojure.core" "swap!") a f args) a))))) send))) +(guard (e (#t #f)) + (def-var! "clojure.core" "agent-error" (letrec ((agent-error (lambda (_a) (let fnrec360 ((_a _a)) jolt-nil)))) agent-error))) +(guard (e (#t #f)) + (def-var! "clojure.string" "blank?" (letrec ((blank? (lambda (s) (let fnrec101 ((s s)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "nil?") s)) #t (jolt= 0 (jolt-count (jolt-invoke (var-deref "clojure.core" "str-trim") s)))))))) blank?))) +(guard (e (#t #f)) + (def-var! "clojure.string" "capitalize" (letrec ((capitalize (lambda (s) (let fnrec102 ((s s)) (if (< 1 (jolt-count s)) (let* ((_a$103 (var-deref "clojure.core" "str")) (_a$104 (jolt-invoke (var-deref "clojure.core" "str-upper") (jolt-invoke (var-deref "clojure.core" "subs") s 0 1))) (_a$105 (jolt-invoke (var-deref "clojure.core" "str-lower") (jolt-invoke (var-deref "clojure.core" "subs") s 1)))) (jolt-invoke _a$103 _a$104 _a$105)) (jolt-invoke (var-deref "clojure.core" "str-upper") s)))))) capitalize))) +(guard (e (#t #f)) + (def-var! "clojure.string" "lower-case" (letrec ((lower-case (lambda (s) (let fnrec106 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-lower") s))))) lower-case))) +(guard (e (#t #f)) + (def-var! "clojure.string" "upper-case" (letrec ((upper-case (lambda (s) (let fnrec107 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-upper") s))))) upper-case))) +(guard (e (#t #f)) + (def-var! "clojure.string" "includes?" (letrec ((includes? (lambda (s substr) (let fnrec108 ((s s) (substr substr)) (jolt-not (jolt-invoke (var-deref "clojure.core" "nil?") (jolt-invoke (var-deref "clojure.core" "str-find") substr s))))))) includes?))) +(guard (e (#t #f)) + (def-var! "clojure.string" "join" (letrec ((join (case-lambda ((coll) (let fnrec109 ((coll coll)) (jolt-invoke (var-deref "clojure.core" "str-join") coll))) ((separator coll) (let fnrec110 ((separator separator) (coll coll)) (jolt-invoke (var-deref "clojure.core" "str-join") coll separator)))))) join))) +(guard (e (#t #f)) + (def-var! "clojure.string" "replace" (letrec ((replace (lambda (s match replacement) (let fnrec111 ((s s) (match match) (replacement replacement)) (jolt-invoke (var-deref "clojure.core" "str-replace-all") match replacement s))))) replace))) +(guard (e (#t #f)) + (def-var! "clojure.string" "replace-first" (letrec ((replace-first (lambda (s match replacement) (let fnrec112 ((s s) (match match) (replacement replacement)) (jolt-invoke (var-deref "clojure.core" "str-replace") match replacement s))))) replace-first))) +(guard (e (#t #f)) + (def-var! "clojure.string" "reverse" (letrec ((reverse (lambda (s) (let fnrec113 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-reverse-b") s))))) reverse))) +(guard (e (#t #f)) + (def-var! "clojure.string" "str-reverse" (letrec ((str-reverse (lambda (s) (let fnrec114 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-reverse-b") s))))) str-reverse))) +(guard (e (#t #f)) + (def-var! "clojure.string" "split" (letrec ((split (case-lambda ((s re) (let fnrec115 ((s s) (re re)) (jolt-invoke split s re 0))) ((s re limit) (let fnrec116 ((s s) (re re) (limit limit)) (let* ((parts (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "str-split") re s (if (jolt-pos? limit) limit jolt-nil))))) (if (jolt-truthy? (let* ((and__13__auto (jolt-zero? limit))) (if (jolt-truthy? and__13__auto) (> (jolt-count parts) 1) and__13__auto))) (let* ((v parts)) (let loop117 ((v v)) (if (jolt-truthy? (let* ((and__13__auto (jolt-seq v))) (if (jolt-truthy? and__13__auto) (jolt= "" (jolt-peek v)) and__13__auto))) (loop117 (jolt-pop v)) v))) parts))))))) split))) +(guard (e (#t #f)) + (def-var! "clojure.string" "split-lines" (letrec ((split-lines (lambda (s) (let fnrec118 ((s s)) (jolt-invoke (var-deref "clojure.core" "vec") (jolt-invoke (var-deref "clojure.core" "str-split") (jolt-regex "\\r?\\n") s)))))) split-lines))) +(guard (e (#t #f)) + (def-var! "clojure.string" "starts-with?" (letrec ((starts-with? (lambda (s substr) (let fnrec119 ((s s) (substr substr)) (let* ((slen (jolt-count s)) (slen2 (jolt-count substr))) (let* ((and__13__auto (>= slen slen2))) (if (jolt-truthy? and__13__auto) (jolt= (jolt-invoke (var-deref "clojure.core" "subs") s 0 slen2) substr) and__13__auto))))))) starts-with?))) +(guard (e (#t #f)) + (def-var! "clojure.string" "ends-with?" (letrec ((ends-with? (lambda (s substr) (let fnrec120 ((s s) (substr substr)) (let* ((slen (jolt-count s)) (slen2 (jolt-count substr))) (let* ((and__13__auto (>= slen slen2))) (if (jolt-truthy? and__13__auto) (jolt= (jolt-invoke (var-deref "clojure.core" "subs") s (- slen slen2)) substr) and__13__auto))))))) ends-with?))) +(guard (e (#t #f)) + (def-var! "clojure.string" "trim" (letrec ((trim (lambda (s) (let fnrec121 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-trim") s))))) trim))) +(guard (e (#t #f)) + (def-var! "clojure.string" "triml" (letrec ((triml (lambda (s) (let fnrec122 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-triml") s))))) triml))) +(guard (e (#t #f)) + (def-var! "clojure.string" "trimr" (letrec ((trimr (lambda (s) (let fnrec123 ((s s)) (jolt-invoke (var-deref "clojure.core" "str-trimr") s))))) trimr))) +(guard (e (#t #f)) + (def-var! "clojure.string" "escape" (letrec ((escape (lambda (s cmap) (let fnrec124 ((s s) (cmap cmap)) (jolt-apply (var-deref "clojure.core" "str") (jolt-map (lambda (ch) (let fnrec125 ((ch ch)) (let* ((temp__4__auto (jolt-invoke cmap ch))) (if (jolt-truthy? temp__4__auto) (let* ((rep temp__4__auto)) rep) (jolt-invoke (var-deref "clojure.core" "str") ch))))) s)))))) escape))) +(guard (e (#t #f)) + (def-var! "clojure.string" "index-of" (letrec ((index-of (case-lambda ((s value) (let fnrec126 ((s s) (value value)) (jolt-invoke (var-deref "clojure.core" "str-find") value s))) ((s value from) (let fnrec127 ((s s) (value value) (from from)) (let* ((idx (jolt-invoke (var-deref "clojure.core" "str-find") value (jolt-invoke (var-deref "clojure.core" "subs") s from)))) (if (jolt-truthy? idx) (+ from idx) jolt-nil))))))) index-of))) +(guard (e (#t #f)) + (def-var! "clojure.string" "last-index-of" (letrec ((last-index-of (case-lambda ((s value) (let fnrec128 ((s s) (value value)) (let* ((r (jolt-invoke (var-deref "clojure.core" "str-reverse-b") s)) (sval (jolt-invoke (var-deref "clojure.core" "str-reverse-b") value)) (idx (jolt-invoke (var-deref "clojure.core" "str-find") sval r))) (if (jolt-truthy? idx) (let* ((_a$129 (jolt-count s)) (_a$130 (+ idx (jolt-count value)))) (- _a$129 _a$130)) jolt-nil)))) ((s value from) (let fnrec131 ((s s) (value value) (from from)) (let* ((sub (jolt-invoke (var-deref "clojure.core" "subs") s 0 from)) (r (jolt-invoke (var-deref "clojure.core" "str-reverse-b") sub)) (sval (jolt-invoke (var-deref "clojure.core" "str-reverse-b") value)) (idx (jolt-invoke (var-deref "clojure.core" "str-find") sval r))) (if (jolt-truthy? idx) (- from (+ idx (jolt-count value))) jolt-nil))))))) last-index-of))) +(guard (e (#t #f)) + (def-var! "clojure.string" "re-quote-replacement" (letrec ((re-quote-replacement (lambda (replacement) (let fnrec132 ((replacement replacement)) (jolt-apply (var-deref "clojure.core" "str") (let* ((_a$134 (lambda (ch) (let fnrec133 ((ch ch)) (let* ((c (jolt-invoke (var-deref "clojure.core" "str") ch))) (if (jolt-truthy? (let* ((or__14__auto (jolt= c "\\"))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= c "$")))) (jolt-invoke (var-deref "clojure.core" "str") "\\" c) c))))) (_a$135 (jolt-seq replacement))) (jolt-map _a$134 _a$135))))))) re-quote-replacement))) +(guard (e (#t #f)) + (def-var! "clojure.string" "trim-newline" (letrec ((trim-newline (lambda (s) (let fnrec136 ((s s)) (let* ((index (jolt-count s))) (let loop137 ((index index)) (if (jolt-zero? index) "" (let* ((c (jolt-invoke (var-deref "clojure.core" "subs") s (jolt-dec index) index))) (if (jolt-truthy? (let* ((or__14__auto (jolt= c "\n"))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt= c "\r")))) (loop137 (jolt-dec index)) (jolt-invoke (var-deref "clojure.core" "subs") s 0 index)))))))))) trim-newline))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "walk" (letrec ((walk (lambda (inner outer form) (let fnrec138 ((inner inner) (outer outer) (form form)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") form)) (jolt-invoke outer (jolt-invoke (var-deref "clojure.core" "vec") (jolt-map inner form))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") form)) (jolt-invoke outer (let* ((_a$139 (jolt-invoke (var-deref "clojure.core" "empty") form)) (_a$140 (jolt-map inner form))) (jolt-into _a$139 _a$140))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "list?") form)) (jolt-invoke outer (jolt-apply jolt-list (jolt-map inner form))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") form)) (jolt-invoke outer (jolt-map inner form)) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke outer form) jolt-nil))))))))) walk))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "postwalk" (letrec ((postwalk (lambda (f form) (let fnrec141 ((f f) (form form)) (jolt-invoke (var-deref "clojure.walk" "walk") (jolt-invoke (var-deref "clojure.core" "partial") postwalk f) f form))))) postwalk))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "prewalk" (letrec ((prewalk (lambda (f form) (let fnrec142 ((f f) (form form)) (let* ((_a$143 (var-deref "clojure.walk" "walk")) (_a$144 (jolt-invoke (var-deref "clojure.core" "partial") prewalk f)) (_a$145 jolt-identity) (_a$146 (jolt-invoke f form))) (jolt-invoke _a$143 _a$144 _a$145 _a$146)))))) prewalk))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "postwalk-demo" (letrec ((postwalk-demo (lambda (form) (let fnrec147 ((form form)) (jolt-invoke (var-deref "clojure.walk" "postwalk") (lambda (x) (let fnrec148 ((x x)) (begin (jolt-invoke (var-deref "clojure.core" "print") "Walked: ") (jolt-invoke (var-deref "clojure.core" "prn") x) x))) form))))) postwalk-demo))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "prewalk-demo" (letrec ((prewalk-demo (lambda (form) (let fnrec149 ((form form)) (jolt-invoke (var-deref "clojure.walk" "prewalk") (lambda (x) (let fnrec150 ((x x)) (begin (jolt-invoke (var-deref "clojure.core" "print") "Walked: ") (jolt-invoke (var-deref "clojure.core" "prn") x) x))) form))))) prewalk-demo))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "postwalk-replace" (letrec ((postwalk-replace (lambda (smap form) (let fnrec151 ((smap smap) (form form)) (jolt-invoke (var-deref "clojure.walk" "postwalk") (lambda (x) (let fnrec152 ((x x)) (if (jolt-contains? smap x) (jolt-get smap x) x))) form))))) postwalk-replace))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "prewalk-replace" (letrec ((prewalk-replace (lambda (smap form) (let fnrec153 ((smap smap) (form form)) (jolt-invoke (var-deref "clojure.walk" "prewalk") (lambda (x) (let fnrec154 ((x x)) (if (jolt-contains? smap x) (jolt-get smap x) x))) form))))) prewalk-replace))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "keywordize-keys" (letrec ((keywordize-keys (lambda (m) (let fnrec155 ((m m)) (let* ((f (lambda (G__9) (let fnrec156 ((G__9 G__9)) (let* ((G__10 G__9) (k (jolt-nth G__10 0 jolt-nil)) (v (jolt-nth G__10 1 jolt-nil))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "string?") k)) (let* ((_o$157 (jolt-invoke (var-deref "clojure.core" "keyword") k)) (_o$158 v)) (jolt-vector _o$157 _o$158)) (let* ((_o$159 k) (_o$160 v)) (jolt-vector _o$159 _o$160)))))))) (jolt-invoke (var-deref "clojure.walk" "postwalk") (lambda (x) (let fnrec161 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) (let* ((_a$162 (jolt-hash-map)) (_a$163 (jolt-map f x))) (jolt-into _a$162 _a$163)) x))) m)))))) keywordize-keys))) +(guard (e (#t #f)) + (def-var! "clojure.walk" "stringify-keys" (letrec ((stringify-keys (lambda (m) (let fnrec164 ((m m)) (let* ((f (lambda (G__11) (let fnrec165 ((G__11 G__11)) (let* ((G__12 G__11) (k (jolt-nth G__12 0 jolt-nil)) (v (jolt-nth G__12 1 jolt-nil))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "keyword?") k)) (let* ((_o$166 (jolt-invoke (var-deref "clojure.core" "name") k)) (_o$167 v)) (jolt-vector _o$166 _o$167)) (let* ((_o$168 k) (_o$169 v)) (jolt-vector _o$168 _o$169)))))))) (jolt-invoke (var-deref "clojure.walk" "postwalk") (lambda (x) (let fnrec170 ((x x)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) (let* ((_a$171 (jolt-hash-map)) (_a$172 (jolt-map f x))) (jolt-into _a$171 _a$172)) x))) m)))))) stringify-keys))) +(guard (e (#t #f)) + (def-var! "clojure.template" "apply-template" (letrec ((apply-template (lambda (argv expr _values) (let fnrec73 ((argv argv) (expr expr) (_values _values)) (begin (if (jolt-not (jolt-invoke (var-deref "clojure.core" "vector?") argv)) (jolt-throw (jolt-ex-info "Assert failed: (vector? argv)" (jolt-hash-map))) jolt-nil) (if (jolt-not (jolt-invoke (var-deref "clojure.core" "every?") (var-deref "clojure.core" "symbol?") argv)) (jolt-throw (jolt-ex-info "Assert failed: (every? symbol? argv)" (jolt-hash-map))) jolt-nil) (jolt-invoke (var-deref "clojure.walk" "postwalk-replace") (jolt-invoke (var-deref "clojure.core" "zipmap") argv _values) expr)))))) apply-template))) +(guard (e (#t #f)) + (def-var! "clojure.template" "do-template" + (lambda (argv expr . _values) (let fnrec74 ((argv argv) (expr expr) (_values (list->cseq _values))) (let* ((c (jolt-count argv))) (let* ((_a$78 (var-deref "clojure.core" "__sqcat")) (_a$79 (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do"))) (_a$80 (let* ((_a$76 (lambda (a) (let fnrec75 ((a a)) (jolt-invoke (var-deref "clojure.template" "apply-template") argv expr a)))) (_a$77 (jolt-invoke (var-deref "clojure.core" "partition") c _values))) (jolt-map _a$76 _a$77)))) (jolt-invoke _a$78 _a$79 _a$80)))))) + (mark-macro! "clojure.template" "do-template")) +(guard (e (#t #f)) + (def-var! "clojure.edn" "edn->value" (letrec ((edn->value (lambda (opts x) (let fnrec81 ((opts opts) (x x)) (if (jolt= (keyword "jolt" "set") (jolt-get x (keyword "jolt" "type"))) (jolt-invoke (var-deref "clojure.core" "set") (let* ((_a$83 (lambda (v) (let fnrec82 ((v v)) (jolt-invoke edn->value opts v)))) (_a$84 (jolt-get x (keyword #f "value")))) (jolt-map _a$83 _a$84))) (if (jolt= (keyword "jolt" "tagged") (jolt-get x (keyword "jolt" "type"))) (let* ((tag (jolt-get x (keyword #f "tag"))) (v (jolt-invoke edn->value opts (jolt-get x (keyword #f "form")))) (tag-sym (let* ((n (jolt-invoke (var-deref "clojure.core" "name") tag))) (jolt-invoke (var-deref "clojure.core" "symbol") (if (jolt= "#" (jolt-invoke (var-deref "clojure.core" "subs") n 0 1)) (jolt-invoke (var-deref "clojure.core" "subs") n 1) n)))) (custom (jolt-get (jolt-get opts (keyword #f "readers")) tag-sym))) (if (jolt-truthy? custom) (jolt-invoke custom v) (if (jolt-truthy? (jolt-get opts (keyword #f "default"))) (jolt-invoke (jolt-get opts (keyword #f "default")) tag v) (if (jolt-truthy? (keyword #f "else")) (jolt-invoke (var-deref "clojure.core" "__read-tagged") tag v) jolt-nil)))) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "map?") x)) (let* ((_a$88 (jolt-hash-map)) (_a$89 (jolt-map (lambda (e) (let fnrec85 ((e e)) (let* ((_o$86 (jolt-invoke edn->value opts (jolt-invoke (var-deref "clojure.core" "key") e))) (_o$87 (jolt-invoke edn->value opts (jolt-invoke (var-deref "clojure.core" "val") e)))) (jolt-vector _o$86 _o$87)))) x))) (jolt-into _a$88 _a$89)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "vector?") x)) (jolt-invoke (var-deref "clojure.core" "mapv") (lambda (v) (let fnrec90 ((v v)) (jolt-invoke edn->value opts v))) x) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "seq?") x)) (jolt-map (lambda (v) (let fnrec91 ((v v)) (jolt-invoke edn->value opts v))) x) (if (jolt-truthy? (keyword #f "else")) x jolt-nil)))))))))) edn->value))) +(guard (e (#t #f)) + (def-var! "clojure.edn" "read-edn" (letrec ((read-edn (lambda (opts s) (let fnrec92 ((opts opts) (s s)) (if (jolt-truthy? (let* ((or__14__auto (jolt-invoke (var-deref "clojure.core" "nil?") s))) (if (jolt-truthy? or__14__auto) or__14__auto (jolt-invoke (var-deref "clojure.string" "blank?") s)))) (jolt-get opts (keyword #f "eof") jolt-nil) (jolt-invoke (var-deref "clojure.edn" "edn->value") opts (jolt-invoke (var-deref "clojure.core" "read-string") s))))))) read-edn))) +(guard (e (#t #f)) + (def-var! "clojure.edn" "read-string" (letrec ((read-string (case-lambda ((s) (let fnrec93 ((s s)) (jolt-invoke (var-deref "clojure.edn" "read-edn") (jolt-hash-map) s))) ((opts s) (let fnrec94 ((opts opts) (s s)) (jolt-invoke (var-deref "clojure.edn" "read-edn") opts s)))))) read-string))) +(guard (e (#t #f)) + (def-var! "clojure.edn" "drain-reader" (letrec ((drain-reader (lambda (reader) (let fnrec95 ((reader reader)) (if (jolt= (keyword "core" "file") (host-static-call "janet" "type" reader)) (host-static-call "janet.file" "read" reader (keyword #f "all")) (let* ((acc (jolt-invoke (var-deref "clojure.core" "transient") (jolt-vector))) (c (record-method-dispatch reader "read" (jolt-vector)))) (let loop96 ((acc acc) (c c)) (if (jolt-truthy? (jolt-invoke (var-deref "clojure.core" "==") -1 c)) (jolt-apply (var-deref "clojure.core" "str") (jolt-map (var-deref "clojure.core" "char") (jolt-invoke (var-deref "clojure.core" "persistent!") acc))) (let* ((_a$97 (jolt-invoke (var-deref "clojure.core" "conj!") acc c)) (_a$98 (record-method-dispatch reader "read" (jolt-vector)))) (loop96 _a$97 _a$98)))))))))) drain-reader))) +(guard (e (#t #f)) + (def-var! "clojure.edn" "read" (letrec ((read (case-lambda ((reader) (let fnrec99 ((reader reader)) (jolt-invoke read (jolt-hash-map) reader))) ((opts reader) (let fnrec100 ((opts opts) (reader reader)) (jolt-invoke (var-deref "clojure.edn" "read-edn") opts (jolt-invoke (var-deref "clojure.edn" "drain-reader") reader))))))) read))) +(guard (e (#t #f)) + (def-var! "clojure.set" "union" (letrec ((union (case-lambda ((s1) (let fnrec1 ((s1 s1)) s1)) ((s1 s2) (let fnrec2 ((s1 s1) (s2 s2)) (jolt-reduce jolt-conj s2 s1)))))) union))) +(guard (e (#t #f)) + (def-var! "clojure.set" "intersection" (letrec ((intersection (case-lambda ((s1) (let fnrec3 ((s1 s1)) s1)) ((s1 s2) (let fnrec4 ((s1 s1) (s2 s2)) (jolt-reduce (lambda (acc item) (let fnrec5 ((acc acc) (item item)) (if (jolt-contains? s2 item) acc (jolt-invoke (var-deref "clojure.core" "disj") acc item)))) s1 s1)))))) intersection))) +(guard (e (#t #f)) + (def-var! "clojure.set" "difference" (letrec ((difference (case-lambda ((s1) (let fnrec6 ((s1 s1)) s1)) ((s1 s2) (let fnrec7 ((s1 s1) (s2 s2)) (jolt-reduce (var-deref "clojure.core" "disj") s1 s2)))))) difference))) +(guard (e (#t #f)) + (def-var! "clojure.set" "select" (letrec ((select (lambda (pred s) (let fnrec8 ((pred pred) (s s)) (jolt-reduce (lambda (acc item) (let fnrec9 ((acc acc) (item item)) (if (jolt-truthy? (jolt-invoke pred item)) acc (jolt-invoke (var-deref "clojure.core" "disj") acc item)))) s s))))) select))) +(guard (e (#t #f)) + (def-var! "clojure.set" "project" (letrec ((project (lambda (xrel ks) (let fnrec10 ((xrel xrel) (ks ks)) (jolt-invoke (var-deref "clojure.core" "set") (jolt-map (lambda (p__1_) (let fnrec11 ((p__1_ p__1_)) (jolt-invoke (var-deref "clojure.core" "select-keys") p__1_ ks))) xrel)))))) project))) +(guard (e (#t #f)) + (def-var! "clojure.set" "rename-keys" (letrec ((rename-keys (lambda (map kmap) (let fnrec12 ((map map) (kmap kmap)) (let* ((_a$14 (lambda (m G__1) (let fnrec13 ((m m) (G__1 G__1)) (let* ((G__2 G__1) (old (jolt-nth G__2 0 jolt-nil)) (new (jolt-nth G__2 1 jolt-nil))) (if (jolt-contains? map old) (jolt-assoc m new (jolt-get map old)) m))))) (_a$15 (jolt-apply jolt-dissoc map (jolt-keys kmap))) (_a$16 kmap)) (jolt-reduce _a$14 _a$15 _a$16)))))) rename-keys))) +(guard (e (#t #f)) + (def-var! "clojure.set" "map-invert" (letrec ((map-invert (lambda (m) (let fnrec17 ((m m)) (let* ((_a$19 (lambda (acc G__3) (let fnrec18 ((acc acc) (G__3 G__3)) (let* ((G__4 G__3) (k (jolt-nth G__4 0 jolt-nil)) (v (jolt-nth G__4 1 jolt-nil))) (jolt-assoc acc v k))))) (_a$20 (jolt-hash-map)) (_a$21 m)) (jolt-reduce _a$19 _a$20 _a$21)))))) map-invert))) +(guard (e (#t #f)) + (def-var! "clojure.set" "rename" (letrec ((rename (lambda (xrel kmap) (let fnrec22 ((xrel xrel) (kmap kmap)) (jolt-invoke (var-deref "clojure.core" "set") (jolt-map (lambda (m) (let fnrec23 ((m m)) (let* ((_a$25 (lambda (acc G__5) (let fnrec24 ((acc acc) (G__5 G__5)) (let* ((G__6 G__5) (old (jolt-nth G__6 0 jolt-nil)) (new (jolt-nth G__6 1 jolt-nil))) (if (jolt-contains? m old) (jolt-assoc acc new (jolt-get m old)) acc))))) (_a$26 (jolt-apply jolt-dissoc m (jolt-keys kmap))) (_a$27 kmap)) (jolt-reduce _a$25 _a$26 _a$27)))) xrel)))))) rename))) +(guard (e (#t #f)) + (def-var! "clojure.set" "index" (letrec ((index (lambda (xrel ks) (let fnrec28 ((xrel xrel) (ks ks)) (let* ((_a$30 (lambda (m x) (let fnrec29 ((m m) (x x)) (let* ((ik (jolt-invoke (var-deref "clojure.core" "select-keys") x ks))) (jolt-assoc m ik (jolt-conj (jolt-get m ik (jolt-hash-set)) x)))))) (_a$31 (jolt-hash-map)) (_a$32 xrel)) (jolt-reduce _a$30 _a$31 _a$32)))))) index))) +(guard (e (#t #f)) + (def-var! "clojure.set" "join" (letrec ((join (case-lambda ((xrel yrel) (let fnrec33 ((xrel xrel) (yrel yrel)) (if (jolt-truthy? (let* ((and__13__auto (jolt-seq xrel))) (if (jolt-truthy? and__13__auto) (jolt-seq yrel) and__13__auto))) (let* ((ks (let* ((_a$34 (var-deref "clojure.set" "intersection")) (_a$35 (jolt-invoke (var-deref "clojure.core" "set") (jolt-keys (jolt-first xrel)))) (_a$36 (jolt-invoke (var-deref "clojure.core" "set") (jolt-keys (jolt-first yrel))))) (jolt-invoke _a$34 _a$35 _a$36))) (G__7 (if (let* ((_a$37 (jolt-count xrel)) (_a$38 (jolt-count yrel))) (<= _a$37 _a$38)) (let* ((_o$39 xrel) (_o$40 yrel)) (jolt-vector _o$39 _o$40)) (let* ((_o$41 yrel) (_o$42 xrel)) (jolt-vector _o$41 _o$42)))) (r (jolt-nth G__7 0 jolt-nil)) (s (jolt-nth G__7 1 jolt-nil)) (idx (jolt-invoke (var-deref "clojure.set" "index") r ks))) (let* ((_a$45 (lambda (ret x) (let fnrec43 ((ret ret) (x x)) (let* ((found (jolt-invoke idx (jolt-invoke (var-deref "clojure.core" "select-keys") x ks)))) (if (jolt-truthy? found) (jolt-reduce (lambda (acc y) (let fnrec44 ((acc acc) (y y)) (jolt-conj acc (jolt-invoke (var-deref "clojure.core" "merge") y x)))) ret found) ret))))) (_a$46 (jolt-hash-set)) (_a$47 s)) (jolt-reduce _a$45 _a$46 _a$47))) (jolt-hash-set)))) ((xrel yrel km) (let fnrec48 ((xrel xrel) (yrel yrel) (km km)) (let* ((G__8 (if (let* ((_a$49 (jolt-count xrel)) (_a$50 (jolt-count yrel))) (<= _a$49 _a$50)) (let* ((_o$51 xrel) (_o$52 yrel) (_o$53 (jolt-invoke (var-deref "clojure.set" "map-invert") km))) (jolt-vector _o$51 _o$52 _o$53)) (let* ((_o$54 yrel) (_o$55 xrel) (_o$56 km)) (jolt-vector _o$54 _o$55 _o$56)))) (r (jolt-nth G__8 0 jolt-nil)) (s (jolt-nth G__8 1 jolt-nil)) (k (jolt-nth G__8 2 jolt-nil)) (idx (jolt-invoke (var-deref "clojure.set" "index") r (jolt-vals k)))) (let* ((_a$59 (lambda (ret x) (let fnrec57 ((ret ret) (x x)) (let* ((found (jolt-invoke idx (jolt-invoke (var-deref "clojure.set" "rename-keys") (jolt-invoke (var-deref "clojure.core" "select-keys") x (jolt-keys k)) k)))) (if (jolt-truthy? found) (jolt-reduce (lambda (acc y) (let fnrec58 ((acc acc) (y y)) (jolt-conj acc (jolt-invoke (var-deref "clojure.core" "merge") y x)))) ret found) ret))))) (_a$60 (jolt-hash-set)) (_a$61 s)) (jolt-reduce _a$59 _a$60 _a$61)))))))) join))) +(guard (e (#t #f)) + (def-var! "clojure.set" "subset?" (letrec ((subset? (lambda (set1 set2) (let fnrec62 ((set1 set1) (set2 set2)) (let* ((and__13__auto (let* ((_a$63 (jolt-count set1)) (_a$64 (jolt-count set2))) (<= _a$63 _a$64)))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (p__2_) (let fnrec65 ((p__2_ p__2_)) (jolt-contains? set2 p__2_))) set1) and__13__auto)))))) subset?))) +(guard (e (#t #f)) + (def-var! "clojure.set" "superset?" (letrec ((superset? (lambda (set1 set2) (let fnrec66 ((set1 set1) (set2 set2)) (let* ((and__13__auto (let* ((_a$67 (jolt-count set1)) (_a$68 (jolt-count set2))) (>= _a$67 _a$68)))) (if (jolt-truthy? and__13__auto) (jolt-invoke (var-deref "clojure.core" "every?") (lambda (p__3_) (let fnrec69 ((p__3_ p__3_)) (jolt-contains? set1 p__3_))) set2) and__13__auto)))))) superset?))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.pprint" "code-dispatch" (keyword #f "code-dispatch") (jolt-hash-map (keyword #f "doc") "Recognized but not used for layout on jolt."))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.pprint" "simple-dispatch" (keyword #f "simple-dispatch") (jolt-hash-map (keyword #f "doc") "Recognized but not used for layout on jolt."))) +(guard (e (#t #f)) + (def-var-with-meta! "clojure.pprint" "*print-pprint-dispatch*" (var-deref "clojure.pprint" "simple-dispatch") (jolt-hash-map (keyword #f "dynamic") #t))) +(guard (e (#t #f)) + (def-var! "clojure.pprint" "pprint" (letrec ((pprint (case-lambda ((object) (let fnrec70 ((object object)) (jolt-invoke (var-deref "clojure.core" "prn") object))) ((object _writer) (let fnrec71 ((object object) (_writer _writer)) (jolt-invoke (var-deref "clojure.core" "prn") object)))))) pprint))) +(guard (e (#t #f)) + (def-var! "clojure.pprint" "with-pprint-dispatch" + (lambda (_dispatch . body) (let fnrec72 ((_dispatch _dispatch) (body (list->cseq body))) (jolt-invoke (var-deref "clojure.core" "__sqcat") (jolt-invoke (var-deref "clojure.core" "__sq1") (jolt-symbol #f "do")) body)))) + (mark-macro! "clojure.pprint" "with-pprint-dispatch")) \ No newline at end of file diff --git a/host/chez/selfcheck.sh b/host/chez/selfcheck.sh new file mode 100755 index 0000000..509ccdd --- /dev/null +++ b/host/chez/selfcheck.sh @@ -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 diff --git a/host/chez/seq.ss b/host/chez/seq.ss new file mode 100644 index 0000000..722bb03 --- /dev/null +++ b/host/chez/seq.ss @@ -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 +;; 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))))) diff --git a/host/chez/smoke.sh b/host/chez/smoke.sh new file mode 100755 index 0000000..4002b5f --- /dev/null +++ b/host/chez/smoke.sh @@ -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 ] diff --git a/host/chez/sqlite.ss b/host/chez/sqlite.ss new file mode 100644 index 0000000..c508434 --- /dev/null +++ b/host/chez/sqlite.ss @@ -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:" (or "jdbc:sqlite:"). +(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)))) diff --git a/host/chez/syntax-quote.ss b/host/chez/syntax-quote.ss new file mode 100644 index 0000000..ab1d50c --- /dev/null +++ b/host/chez/syntax-quote.ss @@ -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 +;; }), 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) diff --git a/host/chez/transients.ss b/host/chez/transients.ss new file mode 100644 index 0000000..4aff566 --- /dev/null +++ b/host/chez/transients.ss @@ -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= 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 (fxidx i)) (cnt (jolt-transient-n t))) + (cond ((and (fixnum? i) (fx>=? i 0) (fx 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) (fxidx 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) diff --git a/host/chez/values.ss b/host/chez/values.ss new file mode 100644 index 0000000..3f95c0c --- /dev/null +++ b/host/chez/values.ss @@ -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)))) diff --git a/host/chez/vars.ss b/host/chez/vars.ss new file mode 100644 index 0000000..938721b --- /dev/null +++ b/host/chez/vars.ss @@ -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) diff --git a/jolt-core/clojure/core/00-kernel.clj b/jolt-core/clojure/core/00-kernel.clj index 93a16e4..1e6d326 100644 --- a/jolt-core/clojure/core/00-kernel.clj +++ b/jolt-core/clojure/core/00-kernel.clj @@ -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)) diff --git a/jolt-core/clojure/core/00-syntax.clj b/jolt-core/clojure/core/00-syntax.clj index 0e3fc71..f224fc3 100644 --- a/jolt-core/clojure/core/00-syntax.clj +++ b/jolt-core/clojure/core/00-syntax.clj @@ -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)) diff --git a/jolt-core/clojure/core/10-seq.clj b/jolt-core/clojure/core/10-seq.clj index 03c7177..f933562 100644 --- a/jolt-core/clojure/core/10-seq.clj +++ b/jolt-core/clojure/core/10-seq.clj @@ -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 diff --git a/jolt-core/clojure/core/20-coll.clj b/jolt-core/clojure/core/20-coll.clj index 7dc44e6..d192332 100644 --- a/jolt-core/clojure/core/20-coll.clj +++ b/jolt-core/clojure/core/20-coll.clj @@ -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) diff --git a/jolt-core/clojure/core/25-sorted.clj b/jolt-core/clojure/core/25-sorted.clj index 689590f..891993f 100644 --- a/jolt-core/clojure/core/25-sorted.clj +++ b/jolt-core/clojure/core/25-sorted.clj @@ -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)) diff --git a/jolt-core/clojure/core/30-macros.clj b/jolt-core/clojure/core/30-macros.clj index c80411e..75c8e7a 100644 --- a/jolt-core/clojure/core/30-macros.clj +++ b/jolt-core/clojure/core/30-macros.clj @@ -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, diff --git a/jolt-core/clojure/core/40-lazy.clj b/jolt-core/clojure/core/40-lazy.clj index 878b13d..444c13b 100644 --- a/jolt-core/clojure/core/40-lazy.clj +++ b/jolt-core/clojure/core/40-lazy.clj @@ -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] diff --git a/jolt-core/clojure/core/50-io.clj b/jolt-core/clojure/core/50-io.clj index 98d9ff9..72dd7e0 100644 --- a/jolt-core/clojure/core/50-io.clj +++ b/jolt-core/clojure/core/50-io.clj @@ -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))))))) diff --git a/jolt-core/jolt/analyzer.clj b/jolt-core/jolt/analyzer.clj index 81bf2b5..dc0f28e 100644 --- a/jolt-core/jolt/analyzer.clj +++ b/jolt-core/jolt/analyzer.clj @@ -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 ) +;; 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 _) 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")))) diff --git a/jolt-core/jolt/backend_scheme.clj b/jolt-core/jolt/backend_scheme.clj new file mode 100644 index 0000000..400a3f7 --- /dev/null +++ b/jolt-core/jolt/backend_scheme.clj @@ -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; ; 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 ). 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))) {})))) diff --git a/jolt-core/jolt/deps.clj b/jolt-core/jolt/deps.clj new file mode 100644 index 0000000..1474b26 --- /dev/null +++ b/jolt-core/jolt/deps.clj @@ -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"))) diff --git a/jolt-core/jolt/ir.clj b/jolt-core/jolt/ir.clj index 0ba5cb3..63be8c8 100644 --- a/jolt-core/jolt/ir.clj +++ b/jolt-core/jolt/ir.clj @@ -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))) diff --git a/jolt-core/jolt/main.clj b/jolt-core/jolt/main.clj new file mode 100644 index 0000000..fb46c93 --- /dev/null +++ b/jolt-core/jolt/main.clj @@ -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 [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 " 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)))) diff --git a/jolt-core/jolt/passes/types.clj b/jolt-core/jolt/passes/types.clj index 105070a..6bca28c 100644 --- a/jolt-core/jolt/passes/types.clj +++ b/jolt-core/jolt/passes/types.clj @@ -25,7 +25,7 @@ ;; :phm (persistent hash map; NOT raw-get-safe) ;; :any (top), nil (bottom, identity for join). ;; Compound types are small jolt maps, so they compare by value on both the -;; Clojure and the Janet (orchestrator) side. struct/vec/set use distinct keys so +;; Clojure and the host (orchestrator) side. struct/vec/set use distinct keys so ;; a type is recognised by which key it carries. ;; (get t :KEY) is nil for a keyword type and the child for a compound, so a ;; compound is detected by some? — no map?/contains? needed. diff --git a/jolt-core/jolt/reader.clj b/jolt-core/jolt/reader.clj new file mode 100644 index 0000000..bb0504e --- /dev/null +++ b/jolt-core/jolt/reader.clj @@ -0,0 +1,469 @@ +(ns jolt.reader + "Portable Clojure reader: source text -> reader forms (Chez Phase 3, jolt-cf1q.4). + + All the lexing/parsing LOGIC + is portable Clojure; form CONSTRUCTION and string->number parsing delegate to the + jolt.host contract (form-make-symbol/char, form-char-from-name, form-scan-number) + — a Clojure source file cannot write a {:jolt/type :symbol} literal (it parses as + a tagged reader form), and the concrete form representation is the host's to own. + Same split the analyzer uses for the form-* readers. Once cross-compiled this runs + ON Chez to drive compile-from-source. + + Positions are CHARACTER indices; for ASCII + source they coincide with byte indices, and form VALUES are identical either way — the parity gate + compares values, not positions. + + INCREMENT 5a (jolt-50xx): the ATOM layer — whitespace/comments, symbols (+ nil/ + true/false), keywords, strings, numbers (sign/hex/radix/ratio/fractional/ + exponent, trailing N/M), characters. Collections, quote/deref/meta, and dispatch + (#) land in 5b/5c (they throw not-yet-ported so a hit is loud)." + (:require [clojure.string :as str] + [jolt.host :refer [form-make-symbol form-make-char form-char-from-name + form-scan-number form-make-list form-make-vector + form-make-map form-sym-merge-meta form-make-set + form-make-tagged form-gensym-name + form-sym? form-sym-name form-sym-ns form-char? + form-list? form-vec? form-set? form-map? + form-elements form-vec-items form-set-items + form-map-pairs]])) + +;; Source access by CHARACTER codepoint +;; (identical to byte access for ASCII). cp = codepoint at i; len = character count. +(defn- cp [s i] (int (nth s i))) +(defn- len [s] (count s)) + +(defn- whitespace? [c] (or (= c 32) (= c 9) (= c 10) (= c 13) (= c 44))) ; space tab nl cr , +(defn- digit? [c] (and (>= c 48) (<= c 57))) +(defn- hex-digit? [c] + (or (digit? c) (and (>= c 65) (<= c 70)) (and (>= c 97) (<= c 102)))) +(defn- symbol-start? [c] + (or (and (>= c 65) (<= c 90)) (and (>= c 97) (<= c 122)) + (= c 42) (= c 43) (= c 33) (= c 95) (= c 45) (= c 63) (= c 46) + (= c 60) (= c 62) (= c 61) (= c 38) (= c 124) (= c 36) (= c 37) (= c 47))) +(defn- symbol-char? [c] + (or (symbol-start? c) (digit? c) (= c 35) (= c 39) (= c 58))) ; + # ' : + +(defn- skip-whitespace [s pos] + (if (and (< pos (len s)) (whitespace? (cp s pos))) + (recur s (inc pos)) + pos)) + +(defn- read-until-newline [s pos] + (if (or (>= pos (len s)) (= (cp s pos) 10)) pos (recur s (inc pos)))) + +;; --- symbols ----------------------------------------------------------------- +(defn- read-symbol-name [s pos end] + (if (and (< end (len s)) (symbol-char? (cp s end))) (recur s pos (inc end)) end)) + +(defn- read-symbol* [s pos] + (let [end (read-symbol-name s pos pos)] + (when (= end pos) + (throw (ex-info (str "Unrecognized character: " (char (cp s pos))) {}))) + (let [nm (subs s pos end)] + (cond + (= nm "nil") [nil end] + (= nm "true") [true end] + (= nm "false") [false end] + :else [(form-make-symbol nm) end])))) + +;; --- keywords ---------------------------------------------------------------- +(defn- read-keyword-name [s pos end] + (if (and (< end (len s)) (symbol-char? (cp s end))) (recur s pos (inc end)) end)) + +(defn- read-keyword* [s pos] + ;; pos is at the first colon; ::foo is treated as :foo (no auto-resolution). + (let [start (if (and (< (inc pos) (len s)) (= (cp s (inc pos)) 58)) (+ pos 2) (inc pos)) + end (read-keyword-name s start start)] + [(keyword (subs s start end)) end])) + +;; --- strings ----------------------------------------------------------------- +(defn- escape-char [c] + (cond (= c 110) "\n" (= c 116) "\t" (= c 114) "\r" (= c 92) "\\" (= c 34) "\"" + :else (str (char c)))) + +(defn- read-string* [s pos] + ;; pos at opening double-quote + (loop [p (inc pos) acc []] + (when (>= p (len s)) (throw (ex-info "Unterminated string" {}))) + (let [c (cp s p)] + (cond + (= c 92) (let [np (inc p)] + (when (>= np (len s)) (throw (ex-info "Unterminated escape" {}))) + (recur (+ p 2) (conj acc (escape-char (cp s np))))) + (= c 34) [(apply str acc) (inc p)] + :else (recur (inc p) (conj acc (str (char c)))))))) + +;; --- numbers ----------------------------------------------------------------- +(defn- read-digits [s pos end] + (if (and (< end (len s)) (digit? (cp s end))) (recur s pos (inc end)) end)) +(defn- read-hex-digits [s pos end] + (if (and (< end (len s)) (hex-digit? (cp s end))) (recur s pos (inc end)) end)) + +;; Value of an alphanumeric digit for radix parsing (0-9, a-z/A-Z = 10-35). +(defn- radix-digit-val [c] + (cond + (and (>= c 48) (<= c 57)) (- c 48) + (and (>= c 97) (<= c 122)) (+ 10 (- c 97)) + (and (>= c 65) (<= c 90)) (+ 10 (- c 65)) + :else nil)) +(defn- read-alnum [s pos end] + (if (and (< end (len s)) (radix-digit-val (cp s end))) (recur s pos (inc end)) end)) + +(defn- read-exponent [s end] + ;; if s[end] is e/E (optionally signed) followed by digits, return index past it + (if (and (< end (len s)) (let [c (cp s end)] (or (= c 101) (= c 69)))) + (let [p (if (and (< (inc end) (len s)) (let [c (cp s (inc end))] (or (= c 43) (= c 45)))) + (+ end 2) (inc end)) + de (read-digits s p p)] + (if (> de p) de end)) + end)) + +;; Jolt has no bignum/ratio: N (bigint) / M (bigdec) suffixes read as the plain +;; number, a ratio a/b reads as the double quotient, radixed ints by base. +(defn- read-number* [s pos] + (let [length (len s) + ;; optional leading sign: - negates; + is a positive no-op (Clojure reads + ;; +5 as 5). read-form only dispatches +digit/-digit, so the sign is real. + neg (and (< pos length) (= (cp s pos) 45)) + plus (and (< pos length) (= (cp s pos) 43)) + start (if (or neg plus) (inc pos) pos) + hex? (and (< (inc start) length) (= (cp s start) 48) + (let [c1 (cp s (inc start))] (or (= c1 120) (= c1 88))))] ; 0x / 0X + (if hex? + (let [hs (+ start 2) he (read-hex-digits s hs hs)] + (when (= he hs) (throw (ex-info "Expected hex digits" {}))) + (let [he2 (if (and (< he length) (= (cp s he) 78)) (inc he) he) ; trailing N + val (form-scan-number (str "0x" (subs s hs he)))] + [(if neg (- val) val) he2])) + (let [iend (read-digits s start start)] + (when (= iend start) (throw (ex-info "Expected number" {}))) + (cond + ;; radix integer r + (and (< iend length) (let [c (cp s iend)] (or (= c 114) (= c 82)))) + (let [base (form-scan-number (subs s start iend)) + ds (inc iend) de (read-alnum s ds ds)] + (when (= de ds) (throw (ex-info "Expected radix digits" {}))) + (let [acc (reduce (fn [a i] (+ (* a base) (radix-digit-val (cp s i)))) 0 (range ds de))] + [(if neg (- acc) acc) de])) + ;; ratio / (only when a digit follows the slash) + (and (< (inc iend) length) (= (cp s iend) 47) (digit? (cp s (inc iend)))) + (let [ds (inc iend) de (read-digits s ds ds) + numr (form-scan-number (subs s start iend)) + den (form-scan-number (subs s ds de))] + [(if neg (- (/ numr den)) (/ numr den)) de]) + ;; fractional and/or exponent, optional trailing N/M + :else + (let [frac-end (if (and (< iend length) (= (cp s iend) 46)) + (let [fs (inc iend) fe (read-digits s fs fs)] + (when (= fe fs) (throw (ex-info "Expected digit after ." {}))) + fe) + iend) + exp-end (read-exponent s frac-end) + val (form-scan-number (subs s start exp-end)) + fin (if (and (< exp-end length) (let [c (cp s exp-end)] (or (= c 78) (= c 77)))) + (inc exp-end) exp-end)] + [(if neg (- val) val) fin])))))) + +;; --- characters -------------------------------------------------------------- +(defn- read-char-name-end [s pos] + (if (and (< pos (len s)) (symbol-char? (cp s pos))) (recur s (inc pos)) pos)) + +(defn- read-char* [s pos] + (when (>= (inc pos) (len s)) (throw (ex-info "unexpected end of input after \\" {}))) + (let [end (read-char-name-end s (inc pos))] + (if (= end (inc pos)) + ;; a non-symbol char right after \ is a one-character literal of itself + [(form-make-char (cp s (inc pos))) (+ pos 2)] + [(form-char-from-name (subs s (inc pos) end)) end]))) + +;; --- dispatcher -------------------------------------------------------------- +;; read-form returns a CONTROL triple [kind payload pos]: +;; :form payload=the form a real datum +;; :skip payload=nil a comment (;) or #_ discard — produced nothing +;; :splice payload=items-vector #?@ — contributes 0+ items to the enclosing coll +;; Out-of-band control (rather than :jolt/skip / :jolt/splice sentinel +;; FORMS) keeps it collision-free and host-neutral — no tagged-struct to build or +;; recognize. Collection readers dispatch on kind; read-next-form skips :skip. +(declare read-form) + +(defn- number-start? [s pos c] + (or (digit? c) + (and (= c 45) (< (inc pos) (len s)) (digit? (cp s (inc pos)))) + (and (= c 43) (< (inc pos) (len s)) (digit? (cp s (inc pos)))))) + +;; Read items until `close`, dispatching control kinds. Returns [items-vec end]. +(defn- read-delimited [s start-pos close errmsg] + (loop [pos start-pos items []] + (let [pos (skip-whitespace s pos)] + (when (>= pos (len s)) (throw (ex-info errmsg {}))) + (if (= (cp s pos) close) + [items (inc pos)] + (let [[kind payload np] (read-form s pos)] + (case kind + :skip (recur np items) + :splice (recur np (into items payload)) + :form (recur np (conj items payload)))))))) + +(defn- read-list* [s pos] + (let [[items end] (read-delimited s (inc pos) 41 "Unterminated list")] ; ) + [:form (form-make-list items) end])) + +(defn- read-vector* [s pos] + (let [[items end] (read-delimited s (inc pos) 93 "Unterminated vector")] ; ] + [:form (form-make-vector items) end])) + +;; Map: pair up keys and values, skipping comments/#_ in either slot while keeping +;; the pending key (dropping both desyncs the pairing). Splice in a map slot lands +;; in inc 5c; here a key/value is always a single :form (or :skip). +(defn- read-map* [s pos] + (loop [pos (inc pos) kvs []] + (let [pos (skip-whitespace s pos)] + (when (>= pos (len s)) (throw (ex-info "Unterminated map" {}))) + (if (= (cp s pos) 125) ; } + [:form (form-make-map kvs) (inc pos)] + (let [[kk kp knp] (read-form s pos)] + (if (= kk :skip) + (recur knp kvs) + ;; key in hand; read the value slot, skipping trivia but keeping the key + (let [[v vnp] + (loop [vp (skip-whitespace s knp)] + (when (>= vp (len s)) (throw (ex-info "Unterminated map" {}))) + (let [[vk vp2 vnp2] (read-form s vp)] + (if (= vk :skip) (recur (skip-whitespace s vnp2)) [vp2 vnp2])))] + (recur vnp (conj (conj kvs kp) v))))))))) + +;; Read the next REAL form (skip :skip), returning [form pos]. Used wherever a +;; single datum is needed (quote/meta/top level). +(defn- read-next-form [s pos] + (let [[kind payload np] (read-form s pos)] + (case kind + :skip (recur s np) + :form [payload np] + :splice (throw (ex-info "splice (#?@) not inside a collection" {}))))) + +;; syntax-quote of a self-evaluating literal collapses to the literal at read time +;; (so nested backticks over literals are inert). NOT symbols (they qualify) or +;; collections (they template). +(defn- self-evaluating-literal? [form] + (or (nil? form) (true? form) (false? form) (number? form) + (string? form) (keyword? form) (form-char? form))) + +(defn- read-quote* [s newpos token-sym] + (let [[form finalpos] (read-next-form s newpos)] + (if (and (= "syntax-quote" (form-sym-name token-sym)) (self-evaluating-literal? form)) + [:form form finalpos] + [:form (form-make-list [token-sym form]) finalpos]))) + +;; Normalize a metadata reader form: keyword -> {kw true}; symbol/string -> {:tag …} +;; (a symbol tag keeps its ns qualifier); else nil (a map-literal meta). +(defn- meta-form->map [meta-form] + (cond + (keyword? meta-form) {meta-form true} + (form-sym? meta-form) {:tag (if (form-sym-ns meta-form) + (str (form-sym-ns meta-form) "/" (form-sym-name meta-form)) + (form-sym-name meta-form))} + (string? meta-form) {:tag meta-form} + :else nil)) + +(defn- read-meta* [s pos] + ;; pos at ^ + (let [[meta-form np] (read-next-form s (inc pos)) + [form np2] (read-next-form s np) + m (meta-form->map meta-form)] + (if (and m (form-sym? form)) + ;; attach to the symbol itself (^Type x / ^:dynamic) — stays a bare symbol + [:form (form-sym-merge-meta form m) np2] + ;; non-symbol target -> a runtime with-meta form (normalized map, or the + ;; raw map-literal meta when m is nil) + [:form (form-make-list [(form-make-symbol "with-meta") form (if m m meta-form)]) np2]))) + +;; --- dispatch (#) ------------------------------------------------------------ +;; Reader-conditional feature set (spec 02-reader). jolt's portable default; the +;; JOLT_FEATURES env override is a host concern wired later. :default always honored. +(def reader-features (atom #{:jolt :default})) +(defn set-reader-features! [features] (reset! reader-features (conj (set features) :default))) + +(defn- read-set* [s pos] + ;; pos at #, next char { + (let [[items end] (read-delimited s (+ pos 2) 125 "Unterminated set")] ; } + [:form (form-make-set items) end])) + +(defn- read-var-quote* [s pos] + ;; pos at #, next char ' + (let [[form np] (read-next-form s (+ pos 2))] + [:form (form-make-list [(form-make-symbol "var") form]) np])) + +(defn- read-regex* [s pos] + ;; pos at #, next char "; read raw to the unescaped closing " (backslashes kept) + (loop [i (+ pos 2)] + (when (>= i (len s)) (throw (ex-info "Unterminated regex literal" {}))) + (let [c (cp s i)] + (cond + (= c 92) (recur (+ i 2)) ; backslash escapes next char + (= c 34) [:form (form-make-tagged :regex (subs s (+ pos 2) i)) (inc i)] + :else (recur (inc i)))))) + +;; #?(…) / #?@(…): pick the first clause whose feature key is active (clause order, +;; like Clojure). #? -> :skip when the result is nil (e.g. a :cljs branch); #?@ -> +;; :splice the resolved items into the enclosing collection. +(defn- rc-resolve [clauses] + ;; clauses: a jolt vector of [feature-kw form feature-kw form ...] + (loop [i 0] + (if (>= i (count clauses)) + [false nil] + (if (contains? @reader-features (nth clauses i)) + [true (nth clauses (inc i))] + (recur (+ i 2)))))) + +(defn- read-reader-conditional* [s pos] + ;; pos at #, next char ? (optionally ?@) + (let [splice? (and (< (+ pos 2) (len s)) (= (cp s (+ pos 2)) 64)) ; @ + form-start (if splice? (+ pos 3) (+ pos 2)) + [form np] (read-next-form s form-start)] + (if (form-list? form) + (let [clauses (form-elements form) + [matched result] (rc-resolve clauses)] + (if splice? + (let [items (cond (not matched) [] + (form-list? result) (vec (form-elements result)) + (form-vec? result) (vec (form-vec-items result)) + :else [result])] + [:splice items np]) + (if (or (not matched) (nil? result)) [:skip nil np] [:form result np]))) + (throw (ex-info "reader conditional body must be a list" {}))))) + +;; Symbolic values ##Inf ##-Inf ##NaN. +(defn- read-symbolic* [s pos] + (let [end (read-symbol-name s (+ pos 2) (+ pos 2)) + nm (subs s (+ pos 2) end)] + (cond + (= nm "Inf") [:form ##Inf end] + (= nm "-Inf") [:form ##-Inf end] + (= nm "NaN") [:form ##NaN end] + :else (throw (ex-info (str "Invalid symbolic value: ##" nm) {}))))) + +(defn- read-tagged* [s pos] + ;; unknown dispatch -> a tagged literal (#inst, #uuid, #foo). The tag includes + ;; the leading # (read-symbol-name starts at #). + (let [end (read-symbol-name s pos pos) + tag (subs s pos end) + [form np] (read-next-form s end)] + [:form (form-make-tagged (keyword tag) form) np])) + +(declare read-anon-fn*) + +(defn- read-dispatch* [s pos] + ;; pos at # + (when (>= (inc pos) (len s)) (throw (ex-info "Unexpected end after #" {}))) + (let [c (cp s (inc pos))] + (cond + (= c 123) (read-set* s pos) ; #{ + (= c 40) (read-anon-fn* s pos) ; #( + (= c 63) (read-reader-conditional* s pos) ; #? + (= c 95) (let [[_ _ np] (read-form s (+ pos 2))] [:skip nil np]) ; #_ discard + (= c 39) (read-var-quote* s pos) ; #' + (= c 94) (read-meta* s (inc pos)) ; #^ (deprecated, = ^) + (= c 34) (read-regex* s pos) ; #" + (= c 35) (read-symbolic* s pos) ; ## + :else (read-tagged* s pos)))) + +;; #(...) anonymous fn. Positional %-arg index: % and %1 => 1, %N => N, %& => the +;; rest param (:rest); anything else is not positional (nil). Fixed arity = max +;; index used (Clojure: #(do %2 %&) => [p1 p2 & rest], unused lower slots still +;; get a placeholder param). +(defn- pct-index [nm] + (cond + (= nm "%") 1 + (= nm "%&") :rest + (and (> (count nm) 1) (= "%" (subs nm 0 1))) + (let [n (form-scan-number (subs nm 1))] + (if (and n (integer? n) (>= n 1)) n nil)) + :else nil)) + +;; Pass 1: collect every %-index used anywhere in the form tree. +(defn- collect-pcts [form acc] + (cond + (form-sym? form) (let [i (pct-index (form-sym-name form))] (if i (conj acc i) acc)) + (form-list? form) (reduce (fn [a x] (collect-pcts x a)) acc (form-elements form)) + (form-vec? form) (reduce (fn [a x] (collect-pcts x a)) acc (form-vec-items form)) + (form-set? form) (reduce (fn [a x] (collect-pcts x a)) acc (form-set-items form)) + (form-map? form) (reduce (fn [a p] (collect-pcts (nth p 1) (collect-pcts (nth p 0) a))) + acc (form-map-pairs form)) + :else acc)) + +;; Pass 2: replace each %-symbol with its slot's gensym (rebuilding collections). +(defn- replace-pct [form slot-syms rest-sym] + (cond + (form-sym? form) (let [idx (pct-index (form-sym-name form))] + (cond (= idx :rest) rest-sym + idx (get slot-syms idx) + :else form)) + (form-list? form) (form-make-list (mapv #(replace-pct % slot-syms rest-sym) (form-elements form))) + (form-vec? form) (form-make-vector (mapv #(replace-pct % slot-syms rest-sym) (form-vec-items form))) + (form-set? form) (form-make-set (mapv #(replace-pct % slot-syms rest-sym) (form-set-items form))) + (form-map? form) (form-make-map + (vec (mapcat (fn [p] [(replace-pct (nth p 0) slot-syms rest-sym) + (replace-pct (nth p 1) slot-syms rest-sym)]) + (form-map-pairs form)))) + :else form)) + +(defn- gensym-param [] (form-make-symbol (str (form-gensym-name) "#"))) + +(defn- read-anon-fn* [s pos] + ;; pos at #, next char ( + (let [[form np] (read-next-form s (inc pos)) + pcts (collect-pcts form []) + max-n (reduce (fn [m i] (if (and (number? i) (> i m)) i m)) 0 pcts) + has-rest (boolean (some #(= :rest %) pcts)) + slot-syms (into {} (map (fn [i] [i (gensym-param)]) (range 1 (inc max-n)))) + rest-sym (when has-rest (gensym-param)) + replaced (replace-pct form slot-syms rest-sym) + arg-names (let [base (mapv #(get slot-syms %) (range 1 (inc max-n)))] + (if has-rest (conj base (form-make-symbol "&") rest-sym) base))] + [:form (form-make-list [(form-make-symbol "fn*") (form-make-vector arg-names) replaced]) np])) + +(defn read-form [s pos] + (let [pos (skip-whitespace s pos)] + (if (>= pos (len s)) + [:form nil pos] + (let [c (cp s pos)] + (cond + (= c 59) [:skip nil (read-until-newline s pos)] ; ; comment + (= c 34) (let [r (read-string* s pos)] [:form (nth r 0) (nth r 1)]) + (= c 58) (let [r (read-keyword* s pos)] [:form (nth r 0) (nth r 1)]) + (= c 92) (let [r (read-char* s pos)] [:form (nth r 0) (nth r 1)]) + (= c 40) (read-list* s pos) ; ( + (= c 91) (read-vector* s pos) ; [ + (= c 123) (read-map* s pos) ; { + (= c 39) (read-quote* s (inc pos) (form-make-symbol "quote")) ; ' + (= c 96) (read-quote* s (inc pos) (form-make-symbol "syntax-quote")) ; ` + (= c 126) (if (and (< (inc pos) (len s)) (= (cp s (inc pos)) 64)) ; ~ / ~@ + (read-quote* s (+ pos 2) (form-make-symbol "unquote-splicing")) + (read-quote* s (inc pos) (form-make-symbol "unquote"))) + (= c 64) (read-quote* s (inc pos) (form-make-symbol "clojure.core/deref")) ; @ + (= c 94) (read-meta* s pos) ; ^ + (= c 41) (throw (ex-info "Unmatched delimiter: )" {})) + (= c 93) (throw (ex-info "Unmatched delimiter: ]" {})) + (= c 125) (throw (ex-info "Unmatched delimiter: }" {})) + (= c 35) (read-dispatch* s pos) ; # + (number-start? s pos c) (let [r (read-number* s pos)] [:form (nth r 0) (nth r 1)]) + (symbol-start? c) (let [r (read-symbol* s pos)] [:form (nth r 0) (nth r 1)]) + :else (throw (ex-info (str "read-form: unexpected char '" (char c) "' (" c ")") {}))))))) + +(defn read-one + "Read the first form of `s` (skipping leading trivia). Returns the form." + [s] + (first (read-next-form s 0))) + +(defn read-all + "Read every top-level form of `s`, returning them in a vector (trivia skipped)." + [s] + (loop [pos 0 acc []] + (let [p (skip-whitespace s pos)] + (if (>= p (len s)) + acc + (let [[kind payload np] (read-form s p)] + (case kind + :skip (recur np acc) + :splice (recur np (into acc payload)) + :form (recur np (conj acc payload)))))))) diff --git a/project.janet b/project.janet deleted file mode 100644 index f843185..0000000 --- a/project.janet +++ /dev/null @@ -1,17 +0,0 @@ -(declare-project - :name "jolt" - :description "Clojure interpreter on Janet") - -(declare-source - :source @["src"]) - -(declare-executable - :name "jolt" - :entry "src/jolt/main.janet") - -# Deprecated shim kept for back-compat: deps.edn resolution is built into `jolt` -# now (the CLI front-end resolves into JOLT_PATH in-process; the runtime core -# stays deps-agnostic). Forwards to `jolt`; prefer `jolt -M:…` / `jolt path`. -(declare-executable - :name "jolt-deps" - :entry "src/jolt/deps_cli.janet") diff --git a/run-tests.janet b/run-tests.janet deleted file mode 100644 index 1f460cd..0000000 --- a/run-tests.janet +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env janet -# Parallel test runner — the gate, faster. -# -# `jpm test` runs every file under test/ serially; this runs the same set across -# a pool of worker processes (each test file is an independent `janet FILE`). -# Build the executable FIRST (`jpm build`) so the binary-spawning tests don't -# skip: jpm build && janet run-tests.janet -# -# Worker count is the detected CPU count; override with JOLT_TEST_JOBS. Per-file -# stdout+stderr is captured to a temp file and only printed for failures (and, -# with -v / JOLT_TEST_VERBOSE, for everything). Exits non-zero if any file fails -# and prints the literal "All tests passed." on success (CI greps for it). - -(defn- detect-jobs [] - (or (when-let [j (os/getenv "JOLT_TEST_JOBS")] (scan-number j)) - (try - (let [p (os/spawn ["sh" "-c" "nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null"] - :p {:out :pipe}) - out (:read (p :out) :all)] - (os/proc-wait p) - (scan-number (string/trim (or out "")))) - ([_] nil)) - 4)) - -(defn- find-tests [dir acc] - (each name (sorted (os/dir dir)) - (def full (string dir "/" name)) - (case (os/stat full :mode) - # support/ holds shared libraries (harness, shims), not standalone tests — - # jpm doesn't run them and neither do we. - :directory (unless (= name "support") (find-tests full acc)) - :file (when (string/has-suffix? ".janet" name) (array/push acc full)))) - acc) - -(def verbose? (or (has-value? (dyn :args) "-v") (os/getenv "JOLT_TEST_VERBOSE"))) -(def janet-bin (dyn :executable)) -(def tmpdir (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-test-" (os/getpid))) -(os/mkdir tmpdir) - -(def files (find-tests "test" @[])) -(def total (length files)) -(def jobs (max 1 (min 16 (detect-jobs)))) - -(def results @[]) -(var done 0) - -(defn- run-one [file] - (def t0 (os/clock)) - (def of (string tmpdir "/" (string/replace-all "/" "_" file) ".out")) - # let the shell own redirection — avoids pipe-buffer deadlock on chatty tests. - (def cmd (string/format "exec '%s' '%s' > '%s' 2>&1" janet-bin file of)) - (def rc (os/proc-wait (os/spawn ["sh" "-c" cmd] :p))) - (def dt (- (os/clock) t0)) - (array/push results {:file file :rc rc :out of :dt dt}) - (++ done) - (printf "[%d/%d] %s %6.2fs %s%s" done total (if (zero? rc) "ok " "FAIL") - dt file (if (zero? rc) "" (string/format " (rc=%d)" rc))) - (flush)) - -# A :stop sentinel per worker signals end-of-queue — ev/chan-close discards -# buffered items (Janet 1.41), so we can't just close and drain. -(def q (ev/chan (+ total jobs))) -(each f files (ev/give q f)) -(loop [_ :range [0 jobs]] (ev/give q :stop)) - -(defn- worker [&] - (forever - (def f (ev/take q)) - (if (= f :stop) (break) (run-one f)))) - -(printf "running %d test files across %d workers...\n" total jobs) -(flush) -(def wall0 (os/clock)) -(def super (ev/chan)) -(loop [_ :range [0 jobs]] (ev/go worker nil super)) -(loop [_ :range [0 jobs]] (ev/take super)) -(def wall (- (os/clock) wall0)) - -(def failed (filter |(not (zero? ($ :rc))) results)) -(def slow (->> results (sorted-by |(- ($ :dt))) (take 5))) - -(print "\n--- slowest ---") -(each r slow (printf " %6.2fs %s" (r :dt) (r :file))) - -(when verbose? - (each r results - (printf "\n===== %s (rc=%d, %.2fs) =====" (r :file) (r :rc) (r :dt)) - (print (slurp (r :out))))) - -(unless (empty? failed) - (print "\n--- FAILURES ---") - (each r failed - (printf "\n===== %s (rc=%d) =====" (r :file) (r :rc)) - (print (slurp (r :out))))) - -(printf "\n%d files, %d failed, %.1fs wall (%d workers)" - total (length failed) wall jobs) -(if (empty? failed) - (do (print "\nAll tests passed.") (os/exit 0)) - (do (printf "\n%d test files FAILED." (length failed)) (os/exit 1))) diff --git a/spike/chez/collections-experiment.ss b/spike/chez/collections-experiment.ss new file mode 100644 index 0000000..00eb268 --- /dev/null +++ b/spike/chez/collections-experiment.ss @@ -0,0 +1,119 @@ +;; Phase 0c — persistent-collection perf experiment. +;; +;; Decides shim-vs-self-hosted for collections: is a persistent HAMT fast enough +;; on the Chez substrate that we can afford to SELF-HOST it (in Clojure compiled +;; by Chez) rather than keep it in the Scheme shim? This measures the substrate +;; ceiling with a hand-written Scheme HAMT (what the backend would emit) against +;; Chez's native mutable hashtable (the non-persistent lower bound), on the +;; collections-bench map workload (freq-map + sum-vals, n keys mod 4096). +;; chez --script collections-experiment.ss [n=30000] [optlevel=2] +(import (chezscheme)) +(optimize-level + (let ((a (command-line-arguments))) + (if (and (pair? a) (pair? (cdr a))) (string->number (cadr a)) 2))) + +;; ---- persistent bitmap HAMT (assoc/get), 5 bits/level, integer-key hash ------ +(define-record-type hnode (fields bitmap arr) (nongenerative hnode-v1)) +(define empty-map (make-hnode 0 (vector))) + +(define (popcount n) + (let loop ((n n) (c 0)) (if (fx=? n 0) c (loop (fxand n (fx- n 1)) (fx+ c 1))))) +(define (mask h shift) (fxand (fxsra h shift) 31)) +(define (idxof bitmap bit) (popcount (fxand bitmap (fx- bit 1)))) + +(define (vec-insert v i x) + (let* ((n (vector-length v)) (out (make-vector (fx+ n 1)))) + (let loop ((j 0)) + (when (fx? shift 30) + ;; hash exhausted (won't happen for distinct small ints) — chain via assoc-list leaf + (cons 'collision (list e1 (cons k2 v2))) + (let ((i1 (mask k1h shift)) (i2 (mask k2h shift))) + (if (fx=? i1 i2) + (let ((sub (merge-leaves (fx+ shift 5) k1h e1 k2h k2 v2))) + (make-hnode (fxsll 1 i1) (vector sub))) + (let* ((b1 (fxsll 1 i1)) (b2 (fxsll 1 i2))) + (if (fx replace + (make-hnode bm (vec-set arr i (cons key val)))) + (else ; leaf, diff key -> split + (make-hnode bm (vec-set arr i (merge-leaves (fx+ shift 5) + (car child) child h key val))))))))) +(define (assoc-map m key val) (assoc-h m 0 key key val)) ; hash = key (distinct small ints) + +(define (get-h node shift h key default) + (let* ((bit (fxsll 1 (mask h shift))) (bm (hnode-bitmap node))) + (if (fx=? 0 (fxand bm bit)) default + (let ((child (vector-ref (hnode-arr node) (idxof bm bit)))) + (cond ((hnode? child) (get-h child (fx+ shift 5) h key default)) + ((eqv? (car child) key) (cdr child)) + (else default)))))) +(define (get-map m key default) (get-h m 0 key key default)) + +;; ---- workloads (mirror bench/collections.clj freq-map + sum-vals) ------------ +(define buckets 4096) +(define (freq-hamt n) + (let loop ((i 0) (m empty-map)) + (if (fxinexact (/ (apply + acc) 3.0)))))) + +(let* ((a (command-line-arguments)) + (n (if (pair? a) (string->number (car a)) 30000))) + (printf "collections map-churn (n=~a, ~a buckets)\n" n buckets) + (bench "persistent HAMT (self-hostable) " freq-hamt sum-hamt n) + (bench "native hashtable (mutable, ceil)" freq-native sum-native n)) diff --git a/spike/chez/fib.ss b/spike/chez/fib.ss new file mode 100644 index 0000000..0dc5bc9 --- /dev/null +++ b/spike/chez/fib.ss @@ -0,0 +1,25 @@ +;; fib spike — translated from bench/fib.clj. Pure call + integer arith. +;; chez --script fib.ss [n=30] [optlevel=2] +(import (chezscheme)) +(optimize-level + (let ((a (command-line-arguments))) + (if (and (pair? a) (pair? (cdr a))) (string->number (cadr a)) 2))) + +(define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) +(define (run n) (fib n)) + +(define (now-ns) + (let ((t (current-time 'time-monotonic))) + (+ (* (time-second t) 1000000000) (time-nanosecond t)))) + +(let* ((a (command-line-arguments)) + (n (if (pair? a) (string->number (car a)) 30))) + (run (- n 6)) (run (- n 6)) ; warmup + (let loop ((k 0) (acc '())) + (if (< k 3) + (let* ((t0 (now-ns)) (r (run n)) (ms (/ (- (now-ns) t0) 1000000.0))) + (loop (+ k 1) (cons ms acc))) + (begin + (printf "fib n ~a result ~a\n" n (run n)) + (printf "runs: ~a\n" (reverse acc)) + (printf "mean: ~a ms\n" (exact->inexact (/ (apply + acc) 3.0))))))) diff --git a/spike/chez/mandelbrot-fl.ss b/spike/chez/mandelbrot-fl.ss new file mode 100644 index 0000000..8a62b31 --- /dev/null +++ b/spike/chez/mandelbrot-fl.ss @@ -0,0 +1,45 @@ +;; mandelbrot, flonum-specialized — what a type-aware jolt->Chez backend would +;; emit (fl*/fl+/fl< unbox; fx ops for the integer counter). This is the real +;; substrate ceiling vs the generic version (which boxes every flonum). +;; chez --script mandelbrot-fl.ss [n=200] [optlevel=3] +(import (chezscheme)) +(optimize-level + (let ((a (command-line-arguments))) + (if (and (pair? a) (pair? (cdr a))) (string->number (cadr a)) 3))) + +(define (count-point cr ci cap) + (let loop ((i 0) (zr 0.0) (zi 0.0)) + (if (or (fx>= i cap) (fl> (fl+ (fl* zr zr) (fl* zi zi)) 4.0)) + i + (loop (fx+ i 1) + (fl+ (fl- (fl* zr zr) (fl* zi zi)) cr) + (fl+ (fl* 2.0 (fl* zr zi)) ci))))) + +(define (run n) + (let ((cap 200) (nd (fixnum->flonum n))) + (let loopy ((y 0) (acc 0)) + (if (fx< y n) + (let* ((ci (fl- (fl/ (fl* 2.0 (fixnum->flonum y)) nd) 1.0)) + (row (let loopx ((x 0) (a 0)) + (if (fx< x n) + (let ((cr (fl- (fl/ (fl* 2.0 (fixnum->flonum x)) nd) 1.5))) + (loopx (fx+ x 1) (fx+ a (count-point cr ci cap)))) + a)))) + (loopy (fx+ y 1) (fx+ acc row))) + acc)))) + +(define (now-ns) + (let ((t (current-time 'time-monotonic))) + (+ (* (time-second t) 1000000000) (time-nanosecond t)))) + +(let* ((a (command-line-arguments)) + (n (if (pair? a) (string->number (car a)) 200))) + (run n) (run n) + (let loop ((k 0) (acc '())) + (if (< k 3) + (let* ((t0 (now-ns)) (r (run n)) (ms (/ (- (now-ns) t0) 1000000.0))) + (loop (+ k 1) (cons ms acc))) + (begin + (printf "mandelbrot-fl n ~a result ~a\n" n (run n)) + (printf "runs: ~a\n" (reverse acc)) + (printf "mean: ~a ms\n" (exact->inexact (/ (apply + acc) 3.0))))))) diff --git a/spike/chez/mandelbrot.ss b/spike/chez/mandelbrot.ss new file mode 100644 index 0000000..d369215 --- /dev/null +++ b/spike/chez/mandelbrot.ss @@ -0,0 +1,44 @@ +;; mandelbrot spike — translated from bench/mandelbrot.clj. Pure float compute, +;; tight recur loops (here named-let tail loops). cap=200 like the .clj. +;; chez --script mandelbrot.ss [n=200] [optlevel=2] +(import (chezscheme)) +(optimize-level + (let ((a (command-line-arguments))) + (if (and (pair? a) (pair? (cdr a))) (string->number (cadr a)) 2))) + +(define (count-point cr ci cap) + (let loop ((i 0) (zr 0.0) (zi 0.0)) + (if (or (>= i cap) (> (+ (* zr zr) (* zi zi)) 4.0)) + i + (loop (+ i 1) + (+ (- (* zr zr) (* zi zi)) cr) + (+ (* 2.0 (* zr zi)) ci))))) + +(define (run n) + (let ((cap 200) (nd (* 1.0 n))) + (let loopy ((y 0) (acc 0)) + (if (< y n) + (let* ((ci (- (/ (* 2.0 y) nd) 1.0)) + (row (let loopx ((x 0) (a 0)) + (if (< x n) + (let ((cr (- (/ (* 2.0 x) nd) 1.5))) + (loopx (+ x 1) (+ a (count-point cr ci cap)))) + a)))) + (loopy (+ y 1) (+ acc row))) + acc)))) + +(define (now-ns) + (let ((t (current-time 'time-monotonic))) + (+ (* (time-second t) 1000000000) (time-nanosecond t)))) + +(let* ((a (command-line-arguments)) + (n (if (pair? a) (string->number (car a)) 200))) + (run n) (run n) ; warmup + (let loop ((k 0) (acc '())) + (if (< k 3) + (let* ((t0 (now-ns)) (r (run n)) (ms (/ (- (now-ns) t0) 1000000.0))) + (loop (+ k 1) (cons ms acc))) + (begin + (printf "mandelbrot n ~a result ~a\n" n (run n)) + (printf "runs: ~a\n" (reverse acc)) + (printf "mean: ~a ms\n" (exact->inexact (/ (apply + acc) 3.0))))))) diff --git a/spike/native/aot-demo.janet b/spike/native/aot-demo.janet deleted file mode 100644 index 231c449..0000000 --- a/spike/native/aot-demo.janet +++ /dev/null @@ -1,47 +0,0 @@ -# AOT build/deploy demo (jolt-a7ds). Two phases, run as separate processes: -# janet spike/native/aot-demo.janet build # needs cc; compiles + writes manifest -# janet spike/native/aot-demo.janet deploy # run with cc REMOVED from PATH -# Proves the deploy target needs no C toolchain: it only loads the prebuilt .so. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/cgen :as cgen) - -(def cp "(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 "(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))))") -(def manifest (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-aot-demo.jdn")) -(def dir "spike/native/build/aot") - -(defn setup [ctx] - (put (ctx :env) :direct-linking? true) - (api/eval-string ctx "(ns demo)")) - -(def phase (get (dyn :args) 1)) -(cond - (= phase "build") - (do - (def ctx (api/init-cached {:compile? true})) - (put (ctx :env) :cgen-collect? true) - (setup ctx) - (api/eval-string ctx cp) - (api/eval-string ctx run) - (def build (cgen/aot-build (get (ctx :env) :cgen-collected) {:dir dir})) - (cgen/write-manifest manifest build) - (printf "BUILD: cc-available? %p -> %s (%d fn)" (cgen/toolchain-available?) - (build :sopath) (length (build :entries)))) - - (= phase "deploy") - (do - (printf "DEPLOY: cc-available? %p (should be false with cc off PATH)" - (cgen/toolchain-available?)) - (def ctx (api/init-cached {:compile? true})) - (setup ctx) - (put (ctx :env) :cgen-prebuilt (cgen/load-aot manifest)) - (api/eval-string ctx cp) - (api/eval-string ctx run) - (def native? (cfunction? (api/eval-string ctx "count-point"))) - (def t0 (os/clock)) - (def total (api/eval-string ctx "(run 200)")) - (def ms (* 1000 (- (os/clock) t0))) - (printf "DEPLOY: count-point native? %p total %d (%s) %.1f ms" - native? total (if (= total 3288753) "OK" "MISMATCH") ms)) - - (eprint "usage: aot-demo.janet build|deploy")) diff --git a/spike/native/bench-native.janet b/spike/native/bench-native.janet deleted file mode 100644 index 316cbe9..0000000 --- a/spike/native/bench-native.janet +++ /dev/null @@ -1,53 +0,0 @@ -# Benchmark the native-C mandelbrot vs the spike's other legs (jolt-5vsp lever 1). -# janet spike/native/bench-native.janet 200 -(import ./build/mandel :as mandel) - -(defn bench [label f n] - (repeat 2 (f (div n 2))) - (def times @[]) - (var last-r 0) - (repeat 3 - (def t0 (os/clock)) - (set last-r (f n)) - (array/push times (* 1000.0 (- (os/clock) t0)))) - (printf "%-28s n %d result %d mean %.2f ms" - label n last-r (/ (sum times) 3))) - -# Leg A: whole run in native C (pure native-codegen ceiling). -(defn run-pure-c [n] (mandel/run-c n)) - -# Leg B: Janet `while` loop, but count-point is a native C cfunction called n^2 -# times — measures the Janet->C boundary-crossing cost (the incremental hybrid). -(defn run-boundary [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 (mandel/count-point-c cr ci cap))) - (++ x)) - (set acc (+ acc a)) - (++ y)) - acc) - -# Leg C: C run loop calling a Janet bytecode count-point back via janet_call n^2 -# times — the reverse crossing (hot C fn -> cold bytecode helper). -(defn count-point-janet [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-callback [n] (mandel/run-callback n count-point-janet)) - -(defn main [& args] - (def n (if (> (length args) 1) (scan-number (get args 1)) 200)) - (bench "native-C whole run" run-pure-c n) - (bench "Janet loop -> C count-point" run-boundary n) - (bench "C loop -> janet_call back" run-callback n)) diff --git a/spike/native/dump-ir.janet b/spike/native/dump-ir.janet deleted file mode 100644 index d6a751c..0000000 --- a/spike/native/dump-ir.janet +++ /dev/null @@ -1,15 +0,0 @@ -# Dump the analyzed IR (not emitted Janet) for count-point, so the C emitter can -# be written against the real node shapes. jolt-ihdp. -(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 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 ir (backend/analyze-form ctx (reader/parse-string src))) -(printf "%P" ir) diff --git a/spike/native/mandel.c b/spike/native/mandel.c deleted file mode 100644 index f555177..0000000 --- a/spike/native/mandel.c +++ /dev/null @@ -1,91 +0,0 @@ -/* Native-C mandelbrot, exposed as a Janet module — the lever-1 ceiling probe for - * the foundational-runtime epic (jolt-5vsp). Measures: - * (1) mandel/run-c — whole run in C (count_point inlined in C). The pure - * native-codegen ceiling: no Janet in the hot loop. - * (2) mandel/count-point-c — just count_point exposed as a Janet cfunction, so a - * Janet `while` loop can call it n^2 times. Measures the - * Janet->C boundary-crossing cost — the incremental - * hybrid (hot fn in C, caller still bytecode) pays this. - * Build: jpm --local build (project.janet declares the native module). */ -#include - -/* Pure C. cr/ci/cap are doubles; cap compared as int iteration count. */ -static long count_point(double cr, double ci, long cap) { - long i = 0; - double zr = 0.0, zi = 0.0; - while (i < cap && (zr*zr + zi*zi) <= 4.0) { - double nzr = zr*zr - zi*zi + cr; - double nzi = 2.0*zr*zi + ci; - zr = nzr; zi = nzi; - i++; - } - return i; -} - -static long run_c(long n) { - long cap = 200; - double nd = (double)n; - long acc = 0; - for (long y = 0; y < n; y++) { - double ci = (2.0*y)/nd - 1.0; - long a = 0; - for (long x = 0; x < n; x++) { - double cr = (2.0*x)/nd - 1.5; - a += count_point(cr, ci, cap); - } - acc += a; - } - return acc; -} - -static Janet cfun_run_c(int32_t argc, Janet *argv) { - janet_fixarity(argc, 1); - long n = (long)janet_getinteger(argv, 0); - return janet_wrap_number((double)run_c(n)); -} - -/* count_point exposed for the Janet-loop-calls-C boundary test. */ -static Janet cfun_count_point_c(int32_t argc, Janet *argv) { - janet_fixarity(argc, 3); - double cr = janet_getnumber(argv, 0); - double ci = janet_getnumber(argv, 1); - long cap = (long)janet_getinteger(argv, 2); - return janet_wrap_number((double)count_point(cr, ci, cap)); -} - -/* run loop in C, but count_point is a Janet function called back via janet_call - * n^2 times — the reverse crossing: a C-compiled hot fn invoking a cold bytecode - * helper. Measures janet_call overhead (the cost the hybrid pays when native code - * calls back into the bytecode world). */ -static Janet cfun_run_callback(int32_t argc, Janet *argv) { - janet_fixarity(argc, 2); - long n = (long)janet_getinteger(argv, 0); - JanetFunction *cp = janet_getfunction(argv, 1); - long cap = 200; - double nd = (double)n; - long acc = 0; - for (long y = 0; y < n; y++) { - double ci = (2.0*y)/nd - 1.0; - long a = 0; - for (long x = 0; x < n; x++) { - double cr = (2.0*x)/nd - 1.5; - Janet args[3] = { janet_wrap_number(cr), janet_wrap_number(ci), - janet_wrap_number((double)cap) }; - Janet r = janet_call(cp, 3, args); - a += (long)janet_unwrap_number(r); - } - acc += a; - } - return janet_wrap_number((double)acc); -} - -static const JanetReg cfuns[] = { - {"run-c", cfun_run_c, "(mandel/run-c n) whole mandelbrot run in native C."}, - {"count-point-c", cfun_count_point_c, "(mandel/count-point-c cr ci cap) one point, native C."}, - {"run-callback", cfun_run_callback, "(mandel/run-callback n count-point-fn) C loop calling a Janet fn back via janet_call."}, - {NULL, NULL, NULL} -}; - -JANET_MODULE_ENTRY(JanetTable *env) { - janet_cfuns(env, "mandel", cfuns); -} diff --git a/spike/native/project.janet b/spike/native/project.janet deleted file mode 100644 index 327f1b6..0000000 --- a/spike/native/project.janet +++ /dev/null @@ -1,6 +0,0 @@ -(declare-project - :name "mandel-native-spike") - -(declare-native - :name "mandel" - :source ["mandel.c"]) diff --git a/src/jolt/aot.janet b/src/jolt/aot.janet deleted file mode 100644 index 0527534..0000000 --- a/src/jolt/aot.janet +++ /dev/null @@ -1,47 +0,0 @@ -# Ahead-of-time images for compiled namespaces. -# -# Compile-by-default turns each form into Janet bytecode at load time. AOT skips -# that work on subsequent runs by serializing a namespace's compiled vars to a -# bytecode image and loading them back. -# -# The trick is the marshal dictionary. A compiled jolt function closes over core -# fns (core-map, +, …) and var cells; those core fns are Janet cfunctions/closures -# that can't be marshaled by value. But the runtime env that holds them is baked -# into the binary and is byte-for-byte identical at save and load time, so we -# marshal *against* it: core fns are referenced by name, and only the user's -# bytecode plus its var cells are actually serialized. - -(import ./backend :as backend) # backend/jolt-runtime-env -(use ./types) - -# Forward dict (key -> value) for unmarshal; reverse (value -> key) for marshal. -# Built from the runtime env, which chains to the Janet boot env, so both core fns -# and Janet builtins resolve by name. -(defn- fwd-dict [] (env-lookup backend/jolt-runtime-env)) -(defn- rev-dict [] (invert (env-lookup backend/jolt-runtime-env))) - -(defn marshal-ns - "Marshal namespace `ns-name`'s var mappings to a byte buffer. The whole mappings - table is marshaled in one call so var cells shared between defs stay shared." - [ctx ns-name] - (marshal ((ctx-find-ns ctx ns-name) :mappings) (rev-dict))) - -(defn unmarshal-ns! - "Install mappings produced by marshal-ns into `ns-name` in ctx, overwriting - same-named vars. Returns ns-name." - [ctx ns-name bytes] - (let [mappings (unmarshal bytes (fwd-dict)) - ns (ctx-find-ns ctx ns-name)] - (each [sym v] (pairs mappings) (put (ns :mappings) sym v)) - ns-name)) - -(defn save-ns - "Write an AOT image of compiled namespace `ns-name` to `path`." - [ctx ns-name path] - (spit path (marshal-ns ctx ns-name))) - -(defn load-ns-image - "Read an AOT image written by save-ns back into ctx under `ns-name`. Skips - parse/analyze/emit/compile entirely — the bytecode is already built." - [ctx ns-name path] - (unmarshal-ns! ctx ns-name (slurp path))) diff --git a/src/jolt/api.janet b/src/jolt/api.janet deleted file mode 100644 index d5991f9..0000000 --- a/src/jolt/api.janet +++ /dev/null @@ -1,434 +0,0 @@ -# Jolt Public API -# High-level interface for the Clojure-on-Janet interpreter. - -(use ./types) -(use ./pv) -(use ./plist) -(use ./reader) -(use ./evaluator) -(use ./core) -(use ./loader) -(use ./async) -(import ./backend :as backend) -(import ./stdlib_embed :as stdlib-embed) -(import ./host_iface :as host) -(import ./config :as config) -# Host interop: JVM class/method shims + collection interop (.iterator/.nth/...) -# register into the evaluator at module load. See src/jolt/host_interop.janet. -(import ./host_interop) - -# A defmacro expander compiles to a native fn (built as (fn args body...) and run -# through the self-hosted pipeline) so macro expansion is COMPILED code, zero runtime -# cost — instead of an interpreted closure, mirroring Clojure (macros are ordinary -# compiled fns). Wrapped in the `fn` MACRO (not the `fn*` primitive) so a destructured -# macro arglist — `[a & [b]]`, `[& {:keys [x]}]`, nested — desugars before lowering; -# raw fn* punts on a destructuring rest param. Returns nil when the analyzer isn't -# built yet (the early macros, expanded WHILE the analyzer is being bootstrapped) or -# the body isn't compilable; in that case defmacro keeps an interpreted closure, and -# backend/recompile-macros! replaces it with a compiled expander once the analyzer -# comes alive (staged bootstrap — the interpreter is a build-time crutch, gone by -# steady state). -(set macro-compile-hook - (fn [ctx args-form body] - (backend/try-compile-fn ctx - (array/concat @[{:jolt/type :symbol :ns nil :name "fn"} args-form] body)))) - -(defn normalize-pvecs - "Deep-convert any sequential (pvec/tuple/array) to a Janet tuple. Test helper - so Janet-level `=`/deep= can compare jolt collection results against Janet - tuple literals regardless of representation — mirroring Clojure, where vectors - and lists with the same elements are equal." - [x] - (cond - # lazy-seq: realize to a tuple (map/filter/take now return lazy seqs). - (and (table? x) (= (get x :jolt/type) :jolt/lazy-seq)) - (tuple ;(map normalize-pvecs (realize-for-iteration x))) - (pvec? x) (tuple ;(map normalize-pvecs (pv->array x))) - (plist? x) (tuple ;(map normalize-pvecs (pl->array x))) - (tuple? x) (tuple ;(map normalize-pvecs x)) - (array? x) (tuple ;(map normalize-pvecs x)) - x)) - - -# Ordered clojure.core tiers (embedded jolt-core/clojure/core/NN-*.clj). Each tier -# may reference only the Janet seed + earlier tiers. A :kernel tier holds the -# structural fns the self-hosted compiler itself uses (second/peek/subvec/mapv/ -# update); in compile mode it must be bootstrap-compiled into clojure.core BEFORE -# the analyzer is built (the analyzer depends on it), so it bypasses the -# self-hosted pipeline. Non-kernel tiers route through eval-toplevel like any -# source (compiled when :compile?, interpreted otherwise — the analyzer, built -# lazily on the first such form, sees the kernel tier already in place). -(def- core-tiers - [{:ns "clojure.core.00-syntax" :kernel false} - {:ns "clojure.core.00-kernel" :kernel true} - {:ns "clojure.core.10-seq" :kernel false} - {:ns "clojure.core.20-coll" :kernel false} - {:ns "clojure.core.25-sorted" :kernel false} - {:ns "clojure.core.30-macros" :kernel false} - {:ns "clojure.core.40-lazy" :kernel false} - {:ns "clojure.core.50-io" :kernel false}]) - -(defn- eval-overlay-source [ctx src] - (var s src) - (while (> (length (string/trim s)) 0) - (def [form rest] (parse-next s)) - (set s rest) - (when (not (nil? form)) (eval-toplevel ctx form)))) - -(defn- load-core-overlay! - "Load the Clojure portion of clojure.core in dependency-ordered tiers. See - core-tiers and jolt-core/clojure/core/." - [ctx] - (def env (ctx :env)) - (def compile? (get env :compile?)) - # Core compiles with direct-linking on when :aot-core? (so core->core calls - # are direct). The flag is restored to the user-code default afterward, so - # user/REPL code stays indirect and fully redefinable. - (def user-dl (get env :direct-linking?)) - (def core-dl (get env :aot-core?)) - (def saved (ctx-current-ns ctx)) - (ctx-set-current-ns ctx "clojure.core") - # Gate the analyzer build until the kernel tier loads (see ensure-analyzer): - # present-and-false here means pre-kernel compiles fall back to the interpreter. - (put env :kernel-ready? false) - # Pre/at-kernel defns load interpreted in some mode (00-syntax always; the - # kernel tier too in interpret mode); stash their fn sources so the staged - # recompile pass (backend/recompile-defns!) can compile them once the - # analyzer is alive. Cleared after the kernel tier so later tiers and user - # code don't stash. - (put env :stash-defn-src? true) - (each tier core-tiers - (when-let [src (get stdlib-embed/sources (tier :ns))] - (put env :direct-linking? core-dl) - (if (and compile? (tier :kernel)) - (backend/bootstrap-load-source ctx "clojure.core" src) - (eval-overlay-source ctx src)) - # The self-hosted compiler depends on the kernel tier (second/peek/mapv/...). - # Mark it ready once that tier is in place so the analyzer can be built; a - # pre-kernel tier that triggers a compile (e.g. a defn in 00-syntax) instead - # falls back to the interpreter rather than building the analyzer against a - # half-loaded core (which would forward-ref the missing kernel fns to nil). - (when (tier :kernel) - (put env :kernel-ready? true) - (put env :stash-defn-src? false)))) - (put env :direct-linking? user-dl) - (ctx-set-current-ns ctx saved) - # Stage 3 interpreted bootstrap: the analyzer was loaded INTERPRETED (no - # bootstrap compiler); have it compile itself + the kernel tier before the - # macro pass, so steady-state compilation runs compiled. - (when compile? - (backend/self-compile-compiler! ctx)) - # Staged bootstrap: the early macros (00-syntax) were defined while the analyzer - # was still being built, so their expanders are interpreted closures. Now that the - # full overlay + analyzer are in place, recompile those expanders to native code — - # by steady state no macro expansion runs interpreted (no-op in interpreter mode). - (backend/ensure-macros-compiled! ctx) - # print-method's record hook: only wirable once the overlay multimethod - # exists (50-io tier), so it rides the end of overlay load. - (install-print-method-cb! ctx)) - -# clojure.math (Clojure 1.11) backed directly by Janet's math natives -# (jolt-h79). The vars hold plain Janet functions, so compiled calls -# direct-link — unlike Math/sqrt interop forms, which are in the frozen -# interpret-only punt set (~5us/call vs ~30ns here). Installed as a -# populated namespace, so (require '[clojure.math :as m]) is a no-op pass. -(defn- install-clojure-math! [ctx] - (def ns (ctx-find-ns ctx "clojure.math")) - (def fns - {"sqrt" math/sqrt "cbrt" math/cbrt "pow" math/pow - "exp" math/exp "expm1" math/expm1 - "log" math/log "log10" math/log10 "log1p" math/log1p - "sin" math/sin "cos" math/cos "tan" math/tan - "asin" math/asin "acos" math/acos "atan" math/atan "atan2" math/atan2 - "sinh" math/sinh "cosh" math/cosh "tanh" math/tanh - "floor" math/floor "ceil" math/ceil "rint" math/round - "round" (fn cm-round [x] (math/round x)) - "signum" (fn cm-signum [x] (cond (< x 0) -1.0 (> x 0) 1.0 0.0)) - "to-degrees" (fn cm-to-degrees [r] (/ (* r 180.0) math/pi)) - "to-radians" (fn cm-to-radians [d] (/ (* d math/pi) 180.0)) - "hypot" (fn cm-hypot [a b] (math/sqrt (+ (* a a) (* b b)))) - "floor-div" (fn cm-floor-div [a b] (math/floor (/ a b))) - "floor-mod" (fn cm-floor-mod [a b] (mod a b)) - "E" math/e "PI" math/pi}) - (eachp [nm f] fns (ns-intern ns nm f)) - # mark loaded so maybe-require-ns never goes looking for a source file - (def loaded (or (get (ctx :env) :loaded-namespaces) - (let [t @{}] (put (ctx :env) :loaded-namespaces t) t))) - (put loaded "clojure.math" true)) - -(defn init - "Create a new Jolt evaluation context. - opts may contain: - :namespaces — map of {ns-name → {sym → value, ...}, ...} - :mutable? — use Janet mutable data structures instead of persistent - :compile? — compile Clojure forms via the self-hosted pipeline (analyzer -> - IR -> Janet back end), falling back to the interpreter as needed - :paths — extra source roots to search for namespaces (after the stdlib)" - [&opt opts] - (default opts {}) - (let [ctx (make-ctx opts)] - # The .clj stdlib (clojure.string, jolt.http, …) baked into the image at build - # time, so it loads from any directory; the loader falls back to this when a - # namespace isn't found on disk. (See stdlib-embed.) - (put (ctx :env) :embedded-sources stdlib-embed/sources) - # Extra source roots: opts :paths, then JOLT_PATH (colon-separated). These are - # searched after the stdlib so (require ...) finds deps.edn-resolved libs. - (let [roots (get (ctx :env) :source-paths)] - (each p (get opts :paths []) (array/push roots p)) - (when-let [jp (os/getenv "JOLT_PATH")] - (each p (string/split ":" jp) (when (> (length p) 0) (array/push roots p))))) - # App source roots (jolt-87e): the project's own roots (opts :app-paths, then - # JOLT_APP_PATHS from jolt-deps). The whole-program inference fixpoint is - # scoped to namespaces loaded from these — deps load-infer per-ns instead. - # Empty => no app/dep distinction, so whole-program covers every namespace - # (a bare program run with no deps.edn keeps its old behavior). - (let [aps @[]] - (each p (get opts :app-paths []) (array/push aps p)) - (when-let [jap (os/getenv "JOLT_APP_PATHS")] - (each p (string/split ":" jap) (when (> (length p) 0) (array/push aps p)))) - (put (ctx :env) :app-source-paths aps)) - # Collection representation (persistent vs mutable) is selected at BUILD time - # via JOLT_MUTABLE (see config.janet); init-core! registers vec/vector/conj/ - # etc. that produce the mode-appropriate values, so nothing extra to load. - (init-core! ctx) - # clojure.core.async (channels + go blocks on Janet fibers); pre-populated - # so (require '[clojure.core.async ...]) finds it and applies :as/:refer. - (install-async! ctx) - # Host contract (ns jolt.host): the seam the portable jolt-core compiler calls. - (host/install! ctx) - (install-clojure-math! ctx) - # require/maybe-require-ns route loaded namespaces through the loader's - # compile-or-interpret eval-toplevel (the evaluator can't import the loader - # — that would be circular — so it reads this hook). Without it, required - # namespaces ran interpreted-only. - (put (ctx :env) :toplevel-eval eval-toplevel) - # Inter-procedural type-inference hook (jolt-767): the evaluator calls this - # after a unit finishes loading (optimization mode only). Installed here to - # avoid an evaluator->backend circular import. - (put (ctx :env) :infer-unit! backend/infer-unit!) - (put (ctx :env) :infer-program! backend/infer-program!) # jolt-t34 whole-program - # Stateful primitives as ctx-capturing clojure.core fns (protocol-dispatch, - # register-method, …) — so the protocol macros compile to plain invokes. Must - # precede the overlay (its defprotocol/extend-type expansions call these). - (install-stateful-fns! ctx) - # Clojure portion of clojure.core (jolt-core/clojure/core.clj): fns expressed - # in plain Clojure on top of the Janet primitives interned above. Loaded into - # clojure.core and compiled by the self-hosted pipeline (or interpreted when - # :compile? is off). Phase 4 kernel-shrink seam — see that file. - (load-core-overlay! ctx) - # load-string and eval as VALUES need the loader's compile-or-interpret - # routing, which lives above the evaluator — intern them here. (The eval - # special form still handles direct calls; this covers value position, - # e.g. (map eval forms).) - (let [core (ctx-find-ns ctx "clojure.core")] - (ns-intern core "load-string" - (fn [s] - (var cur s) - (var result nil) - (while (> (length (string/trim cur)) 0) - (def [form rest-src] (parse-next cur)) - (set cur rest-src) - (when (not (nil? form)) (set result (eval-toplevel ctx form)))) - result)) - (ns-intern core "eval" (fn [form] (eval-toplevel ctx form)))) - # Init is done: core + the self-hosted compiler are loaded with :inline? off - # (so they compiled exactly as before). Flip inlining on for subsequent - # user-code compilation iff user direct-linking is on (JOLT_DIRECT_LINK=1) — - # the inline pass only inlines targets that won't be redefined, the same - # safety the direct-linking flag asserts (jolt-87f). - (put (ctx :env) :inline? (if (get (ctx :env) :direct-linking?) true false)) - # jolt-t34. Two shape gates: - # :shapes? — shape-recs are active. Records use declared-shape layout + - # bare-index reads here. ON wherever the inference that proves - # reads runs = direct-linking. JOLT_NO_SHAPE force-disables. - # :map-shapes? — also shape generic const-key MAP literals. Opt-in (JOLT_SHAPE) - # because shaping maps net-loses on unproven reads; records win. - (put (ctx :env) :shapes? - (and (get (ctx :env) :direct-linking?) (not (os/getenv "JOLT_NO_SHAPE")))) - (put (ctx :env) :map-shapes? - (and (os/getenv "JOLT_SHAPE") (not (os/getenv "JOLT_NO_SHAPE")))) - # Whole-program (Stalin) mode (jolt-t34): opt-in, closed-world. Defers the - # per-ns inference and runs one fixpoint over all units at the end (main, or a - # harness calling infer-program!). Needs direct-linking (the closed-world - # assumption); slow/memory-heavy builds are the documented trade-off. - (put (ctx :env) :whole-program? - (and (os/getenv "JOLT_WHOLE_PROGRAM") (get (ctx :env) :direct-linking?))) - ctx)) - -# --- Context snapshot/fork + disk image (AOT context image) ------------------ -# -# init is expensive (~50 ms interpreted, ~900 ms compiled: tier loading, analyzer -# build, macro recompilation). For workloads that need MANY isolated contexts — -# the test harnesses build a fresh ctx per case — snapshot a fully-built ctx once -# and fork cheap deep copies (~2 ms) from it via Janet marshal/unmarshal. A fork -# shares nothing mutable with the original: defs, protocol extensions, hierarchy -# changes, atom states in one fork are invisible to the others. -# -# load-ctx-image/save-ctx-image add the disk layer (fork->validate->rewire load, -# atomic save) shared by init-cached and main's deps-image cache (jolt-q5ql) — -# the callers differ only in the validity predicate. They live here (not a -# separate module) because Janet's `use` doesn't transitively re-export, and the -# snapshot/fork they build on are already api's and consumed via (use ./api). -# -# The reverse-lookup dicts must be built from root-env (cfunctions and abstract -# values from the Janet runtime marshal by reference through them) BEFORE any ctx -# values exist in scope — module load time here, so user code can't leak into it. -(def- image-load-dict (env-lookup root-env)) -(def- image-make-dict (invert image-load-dict)) - -(defn snapshot - "Marshal a fully-built context into a buffer that fork can cheaply clone. - Build the ctx (init), customize it if needed, then snapshot once." - [ctx] - (marshal ctx image-make-dict)) - -(defn fork - "A fresh, fully-isolated deep copy of a snapshotted context (~2 ms, vs - re-running init). (fork (snapshot ctx)) behaves exactly like ctx did at - snapshot time; mutations to a fork never affect the original or other forks." - [snap] - (unmarshal snap image-load-dict)) - -(defn load-ctx-image - "Load a marshaled ctx image from `path`: fork it, verify it really is a ctx (a - corrupt image can unmarshal to a non-ctx value), run the optional `valid?` - predicate (e.g. a source-mtime check), and replay the per-PROCESS module-state - wiring an image restore skips by calling `(rewire! ctx)` (the print-method hook - lives in module state, not the marshaled ctx). Returns the ctx, or nil if the - file is absent, unreadable, not a ctx, or fails `valid?`." - [path rewire! &opt valid?] - (when (os/stat path) - (def r (protect (fork (slurp path)))) - (when (and (r 0) (ctx? (r 1)) (or (nil? valid?) (valid? (r 1)))) - (def c (r 1)) - (when rewire! (rewire! c)) - c))) - -(defn save-ctx-image - "Atomically write ctx's marshaled image to `path` (write a pid-tagged tmp file - then rename) so concurrent cold starts never observe a torn image. Best-effort: - a failed write/rename is swallowed (the next run just rebuilds)." - [ctx path] - (def tmp (string path "." (os/getpid) ".tmp")) - (when (protect (spit tmp (snapshot ctx))) - (protect (os/rename tmp path)))) - -# init in compile mode is ~2.4 s (tier loading, analyzer self-compile, macro -# recompilation) — paid by every PROCESS that builds a ctx from source, e.g. -# each `jpm test` file. init-cached pays it once: the built ctx is snapshotted -# to an image file and later processes unmarshal it (~tens of ms). Marshaling -# is against root-env (same dicts as snapshot/fork), so core cfunctions ride by -# name and everything jolt-level rides by value — a loaded image needs nothing -# from the baking process. The cache key fingerprints everything a fresh build -# would read: the embedded .clj stdlib (which includes jolt-core — the -# analyzer, IR, and core tiers), the .janet seed sources next to this module, -# the janet version, and the init opts. Any change rebuilds; a corrupt or -# unreadable image silently rebuilds. JOLT_NO_IMAGE_CACHE=1 disables. - -# Captured at module load: in source mode this is .../src/jolt/api.janet, so -# the seed sources can be fingerprinted; nil or stale in a built binary, where -# the baked-at-build-time ctx makes init-cached pointless anyway. -(def- api-module-file (dyn :current-file)) - -(defn- src-dir [] - (when api-module-file - (let [idxs (string/find-all "/" api-module-file)] - (when (not (empty? idxs)) - (string/slice api-module-file 0 (last idxs)))))) - -# Every .janet seed file under `dir`, RECURSIVELY (src/jolt/ has subdirs now — -# interop/), keyed by repo-relative path so files in different dirs don't alias. -# Sorted for a stable fingerprint. Non-recursive (os/dir) would silently miss a -# subdir edit and serve a stale image — the map-nil-style footgun, for the cache. -(defn- janet-sources-under [dir] - (def acc @[]) - (defn- walk [d prefix] - (each name (sorted (os/dir d)) - (def full (string d "/" name)) - (def rel (string prefix name)) - (case (os/stat full :mode) - :directory (walk full (string rel "/")) - :file (when (string/has-suffix? ".janet" name) (array/push acc [rel full]))))) - (walk dir "") - acc) - -(defn- source-fingerprint - "Hash + total length of every source a fresh init depends on. Two numbers, so - a 32-bit hash collision alone can't alias two different source trees." - [] - (def buf @"") - (each k (sorted (keys stdlib-embed/sources)) - (buffer/push buf k "\x00" (get stdlib-embed/sources k) "\x00")) - (def dir (src-dir)) - (when dir - (each [rel full] (janet-sources-under dir) - (buffer/push buf rel "\x00" (slurp full) "\x00"))) - [(hash (string buf)) (length buf)]) - -(defn- image-cache-path [opts] - (def dir (or (os/getenv "JOLT_IMAGE_CACHE_DIR") - (os/getenv "TMPDIR") - "/tmp")) - (def [h len] (source-fingerprint)) - # Opts land in the key via their printed form; an opt that prints unstably - # (e.g. a closure in :namespaces) just degrades to a cache miss, never to a - # wrong hit. Every ctx-shaping env var rides along via config/ctx-cache-key — - # one canonical list shared with the deps-image key (jolt-q5ql), so a new knob - # can't be added to one key and forgotten in the other. - (def key (config/ctx-cache-key [:janet (string janet/version "-" janet/build) :opts opts])) - (string dir "/jolt-ctx-" (band h 0x7FFFFFFF) "-" len "-" (band (hash key) 0x7FFFFFFF) ".jimg")) - -(defn init-cached - "init, but disk-cached: the first call builds the context and writes a - bytecode image; later calls (any process, same sources) load the image - instead of rebuilding. Same opts as init. JOLT_NO_IMAGE_CACHE=1 disables; - JOLT_IMAGE_CACHE_DIR overrides the cache directory (default TMPDIR)." - [&opt opts] - (default opts {}) - (if (or (= "1" (os/getenv "JOLT_NO_IMAGE_CACHE")) (nil? (src-dir))) - (init opts) - (let [path (image-cache-path opts)] - # The source-fingerprint is already in the path, so any cached image at - # this path is valid — no extra predicate, just the per-process rewiring. - (or (load-ctx-image path install-print-method-cb!) - (let [ctx (init opts)] - (save-ctx-image ctx path) - ctx))))) - -(defn eval-one - "Evaluate a single already-parsed form. Routing (compile when :compile? is set, - stateful forms interpret, interpreter fallback for forms the compiler can't - handle) lives in loader/eval-toplevel so load-ns and eval-one stay in sync." - [ctx form] - (eval-toplevel ctx form)) - -(defn eval-string - "Evaluate a Clojure source string in a Jolt context. - When :compile? is enabled, compiles to Janet and evaluates. - Macros are expanded at compile time. - Context-modifying forms (ns, defmacro, deftype, require, in-ns, defmulti, defmethod) - always use the interpreter." - [ctx s] - (eval-one ctx (parse-string s))) - -(defn eval-string* - "Evaluate a Clojure source string with explicit bindings." - [ctx s bindings] - (let [form (parse-string s)] - (eval-form ctx bindings form))) - -(defn load-string - "Evaluate all forms from a Clojure source string. - Uses parse-next to load every top-level form in sequence. - Returns the result of the last form evaluated." - [ctx s &opt file] - (default file "") - # record form positions so the checker can report file:line:col (jolt-fqy). - # The checker is on when JOLT_TYPE_CHECK selects it, OR by default in - # direct-link builds (where it piggybacks on inference for free). - (when (or (checker-enabled?) (get (ctx :env) :inline?)) - (track-positions! true) - (put (ctx :env) :tc-source s) - (put (ctx :env) :tc-file file)) - (eval-forms-positioned ctx (parse-all-positioned s file) file)) - diff --git a/src/jolt/async.janet b/src/jolt/async.janet deleted file mode 100644 index 8f9c385..0000000 --- a/src/jolt/async.janet +++ /dev/null @@ -1,208 +0,0 @@ -# clojure.core.async on Janet fibers. -# -# Janet fibers are stackful coroutines, so a `go` block is just "run the body in -# a fiber" — the body parks on a channel op by yielding to the event loop, and -# the whole interpreter call stack rides along on the fiber's stack. No CPS/state -# machine transform (unlike Clojure's `go` macro), so ! work anywhere -# (inside try, nested fns, loops, …). -# -# A channel is a pair of Janet ev/chans wrapped in a tagged table: a `:ch` that -# carries values and a `:done` that is closed to signal channel close. A take is -# `(ev/select :ch :done)` — ev/select checks in order, so buffered values drain -# before the close signal is seen, giving Clojure's drain-then-nil semantics. We -# use a separate `:done` channel because Janet's ev/chan-close *discards* a -# channel's buffered values. close! just closes :done (idempotent, no fiber), so -# nothing leaks. -# -# Single OS thread: go blocks run cooperatively on the event loop, so buf 0)) {:kind :fixed :n buf} - nil)) - (def vc (if spec (ev/chan (spec :n)) (ev/chan))) - (def w (wrap vc (ev/chan))) - (when spec (put w :bufkind (spec :kind))) - (when (and xform (not (nil? xform))) - (put w :xrf (xform (make-add-rf w)))) - w) - -(defn async-close! [ch] - (when (not (in (ch :closed) 0)) - (put (ch :closed) 0 true) - # flush any buffered state of a stateful transducer (completion arity) - (when (ch :xrf) (protect ((ch :xrf) (ch :ch)))) - (protect (ev/chan-close (ch :done)))) - nil) - -# ! / >!! — put, parking the fiber. Returns true if delivered, false if the -# channel is closed. nil may not be put on a channel (it is the closed value). -# With a transducer, the value is run through it (so one put may yield zero or -# more values on the channel); a `reduced` result (e.g. from `take`) closes it. -(defn async-give [ch v] - (when (nil? v) (error "Can't put nil on a channel")) - (cond - (in (ch :closed) 0) false - (ch :xrf) - (let [r ((ch :xrf) (ch :ch) v)] - (when (reduced? r) (async-close! ch)) - true) - (buf-give ch v))) - -# Run thunk (a jolt 0-arg closure, directly callable) in a fiber; return a -# buffered(1) channel that conveys its value once, then closes. A nil result -# just closes. Buffered(1) so a fire-and-forget go leaves no parked fiber. -# -# The dynamic-var bindings in effect at spawn time are conveyed into the fiber -# (Clojure binding conveyance): we snapshot them here (on the spawning fiber) -# and install a private copy inside the new fiber before running the body. -(defn async-go-spawn [thunk] - (def snap (snapshot-bindings)) - (def w (async-chan 1)) - (ev/go (fn [] - (install-bindings snap) - (def res (protect (thunk))) - (when (and (in res 0) (not (nil? (in res 1)))) - (async-give w (in res 1))) - (async-close! w))) - w) - -# (alts! [ch ...]) — take from whichever channel is ready first; returns -# [value channel] (value is nil if that channel closed). Take-only for v1. -(defn async-alts [chans] - (def cs (cond (pvec? chans) (pv->array chans) - (tuple? chans) chans - (array? chans) chans - (error "alts! expects a vector of channels"))) - (def raws @[]) - (def lookup @{}) # raw ev/chan -> [jolt-chan done?] - (each c cs - (array/push raws (c :ch)) (put lookup (c :ch) [c false]) - (array/push raws (c :done)) (put lookup (c :done) [c true])) - (def r (ev/select ;raws)) - (def info (get lookup (in r 1))) - (def jc (in info 0)) - (def val (if (or (in info 1) (not= :take (in r 0))) nil (in r 2))) - (pv-from-indexed @[val jc])) - -# (timeout ms) — a channel that closes after ms milliseconds. -(defn async-timeout [ms] - (def w (async-chan)) - (ev/go (fn [] (ev/sleep (/ ms 1000)) (async-close! w))) - w) - -# (put! ch v [cb]) — async put; (take! ch cb) — async take. Fire a fiber and -# call the optional callback with the result. -(defn async-put! [ch v &opt cb] - (ev/go (fn [] - (def ok (async-give ch v)) - (when (and cb (not (nil? cb))) (cb ok)))) - nil) -(defn async-take! [ch cb] - (ev/go (fn [] - (def val (async-take ch)) - (when (and cb (not (nil? cb))) (cb val)))) - nil) - -# --- macros (Janet macro-fns that return forms) --- - -(defn- sym [name &opt ns] {:jolt/type :symbol :ns ns :name name}) - -# (go body...) -> (go-spawn (fn* [] body...)) -(defn async-go [& body] - @[(sym "go-spawn" "clojure.core.async") (array (sym "fn*") [] ;body)]) - -# (go-loop bindings body...) -> (go (loop bindings body...)) -(defn async-go-loop [bindings & body] - @[(sym "go" "clojure.core.async") (array (sym "loop") bindings ;body)]) - -# (thread body...) — runs cooperatively in a fiber here (no OS thread); same -# shape as go (returns a result channel). -(defn async-thread [& body] - @[(sym "go-spawn" "clojure.core.async") (array (sym "fn*") [] ;body)]) - -(def- async-bindings - @{"chan" async-chan - "chan?" jolt-chan? - "close!" async-close! - "!" async-give ">!!" async-give - "alts!" async-alts "alts!!" async-alts - "timeout" async-timeout - "buffer" async-buffer - "dropping-buffer" async-dropping-buffer - "sliding-buffer" async-sliding-buffer - "put!" async-put! - "take!" async-take! - "go-spawn" async-go-spawn - "go" async-go - "go-loop" async-go-loop - "thread" async-thread}) - -(def- async-macros @{"go" true "go-loop" true "thread" true}) - -(defn install-async! - "Create/populate the clojure.core.async namespace in ctx." - [ctx] - (let [ns (ctx-find-ns ctx "clojure.core.async")] - (loop [[name f] :pairs async-bindings] - (def v (ns-intern ns name f)) - (when (get async-macros name) (put v :macro true))) - ns)) diff --git a/src/jolt/backend.janet b/src/jolt/backend.janet deleted file mode 100644 index 5ed8c52..0000000 --- a/src/jolt/backend.janet +++ /dev/null @@ -1,1300 +0,0 @@ -# Janet back end: host-neutral IR (from jolt.analyzer) -> Janet form -> bytecode. -# -# Host-specific by definition (it targets Janet). It resolves name-based :var -# nodes to Janet var cells and reuses runtime helpers (jolt-call, make-vec, -# build-map-literal). The portable front end (jolt.analyzer) never sees any of -# this; a different runtime provides its own back end against the same IR. -# -# In src/jolt/ (not host/janet/) for the same module-resolution reason as -# host_iface — see that file's header. - -(use ./types) -(use ./core) -(use ./evaluator) -(import ./reader :as r) -(import ./cgen :as cgen) -(import ./phm :as phm) -(import ./phs :as phs) -(import ./pv :as pv) - -# The IR is portable data; reading its representation is a host-layer concern. -# Most nodes are Janet structs (raw-readable), but a node carrying a nil-valued -# field — an anonymous fn's :name, a nil const's :val, a def with no :meta, an -# arity with no :rest — is a phm, whose fields live under :buckets, not as direct -# keys. Densify such a node to a struct: phm-to-struct drops exactly those -# nil-valued fields, which is what the back end wants (it already treats an absent -# field as nil). Structs (the common case) pass through untouched. Applied at the -# few points where a node first reaches the emitter, so the rest of the back end -# keeps using plain (node :key) access and the portable front end never sees this. -# --- Runtime kernel (absorbed from the retired bootstrap compiler) ---------- - -# The Janet env compiled code evaluates in. Captured at module load: backend's -# env chains types/core/evaluator/reader/phm, so emitted symbols (let/fn/in/ -# var-get/tuple-slice/...) and jolt runtime helpers resolve by name. -(def jolt-runtime-env (curenv)) - -# Janet's `in` accessor as an embedded VALUE (jolt-fjb1). The back end uses `in` -# to index cells/shape-recs/arg tuples in code it EMITS. Emitting the bare symbol -# `in` is unhygienic: a user local named `in` (malli's explainer binds `[value in -# acc]`) shadows it in the surrounding scope, so the generated `(in cell :root)` -# would call the user's value as a function — " called with 2 arguments". -# Embedding the function value (as with jolt-call/core-get) can't be shadowed. -(def- jin in) - -(defn ctx-janet-env - "Lazily create/cache a per-context Janet environment for compiled code: a child - of the runtime env (so core fns resolve) that holds this context's user defs. - For a nil context (one-off compile/eval) returns a fresh child env." - [ctx] - (if (and ctx (table? (get ctx :env))) - (or (get (ctx :env) :janet-rt) - (let [e (make-env jolt-runtime-env)] - (put (ctx :env) :janet-rt e) - e)) - (make-env jolt-runtime-env))) - -(defn build-map-literal - "Build a map value from evaluated k v k v ... args. A phm (not a Janet struct) - when a key is a collection (value hashing) or a key/value is nil (structs drop - nil; phm preserves it, matching Clojure)." - [& kvs] - (var need-phm false) - (var ki 0) - (while (< ki (length kvs)) - (let [kk (in kvs ki) vv (in kvs (+ ki 1))] - (when (or (table? kk) (array? kk) (nil? kk) (nil? vv)) (set need-phm true))) - (+= ki 2)) - (if need-phm - (do (var m (phm/make-phm)) (var j 0) - (while (< j (length kvs)) (set m (phm/phm-assoc m (in kvs j) (in kvs (+ j 1)))) (+= j 2)) - m) - (struct ;kvs))) - -(defn- norm-node [n] - (if (phm/phm? n) (phm/phm-to-struct n) n)) - -# Inline registry (jolt-87f). When a defn of a SINGLE FIXED-ARITY fn compiles -# under :inline?, stash its body IR on the var cell so the inline pass -# (jolt.passes) can splice it into callers. Eligibility beyond single-fixed-arity -# (body grammar, size budget) is decided by the pass, which walks the body to -# alpha-rename it anyway. Skip ^:redef / ^:dynamic (those vars stay redefinable, -# so a call to them must not be inlined). The stash is {:params [..] :body }. -(defn- inline-stash! [ctx cell node] - (when (get (ctx :env) :inline?) - (def init (norm-node (node :init))) - (def meta (node :meta)) - (def redefable (and meta (or (get meta :redef) (get meta :dynamic)))) - (cond - redefable nil - (= :fn (init :op)) - (let [arities (vview (init :arities))] - (when (= 1 (length arities)) - (def ar (norm-node (in arities 0))) - (unless (ar :rest) - (put cell :inline-ir {:params (ar :params) :body (ar :body)}) - # jolt-767: stash the whole (post-pass) :def IR so the inter-procedural - # pass can re-infer its body with discovered param types and re-emit it. - (put cell :infer-ir node)))) - # a non-fn def: stash so the pass can infer its VALUE type (jolt-d6u), e.g. - # a color table used via rand-nth — its element type flows to lookups. - true (put cell :infer-ir node)))) - -# Var late-binding: reads go through `(var-get cell)` with the cell embedded as a -# constant, so compiled code sees redefinition (Janet early-binds plain symbols) -# — var-get reads the cell's root live. Writes go through a memoized setter. -(defn- var-setter [cell] - (or (get cell :jolt/setter) - (let [s (fn [v] (bind-root cell v) cell)] (put cell :jolt/setter s) s))) - -# Setter that also applies def metadata to the var (so ^:dynamic / ^:redef / -# ^:private survive compilation, matching the interpreter's def). Not memoized: -# the meta is specific to this def site. -(defn- var-setter-meta [cell meta] - (fn [v] - (bind-root cell v) - (put cell :meta (merge (or (cell :meta) {}) meta)) - (when (get meta :dynamic) (put cell :dynamic true)) - cell)) - -(defn- cell-for [ctx ns-name nm] - (ns-intern (ctx-find-ns ctx ns-name) nm)) - -# Direct-linking decision (call-site/unit property, Clojure-style). A var -# reference compiles to its embedded value (direct) iff: -# - the compiling unit has direct-linking on (env :direct-linking?), -# - the target opts in (NOT ^:redef / ^:dynamic — those force indirect), -# - the target is already defined AND its root is a Janet function. -# The function? guard is essential: embedding a non-function value (a jolt -# collection/symbol) into the emitted form would make Janet evaluate it AS code. -# So we direct-link exactly the call-optimization case; everything else stays -# indirect (live var deref → redefinable). Default user/REPL units: flag off, -# so all user calls are indirect and redefinable with no annotation. -# A var DEF'd earlier as a sibling in the current compilation unit can't be -# direct-linked/const-linked: its embedded root is the value from BEFORE this -# unit runs, but the unit's own (def …) rebinds it first — so a later reference -# in the same unit (e.g. deftype's `(def ->R R)` alias after `(def R …)`) would -# capture the stale pre-redef root (jolt-wf4). Self-reference inside a def's own -# init is unaffected: the cell is registered only AFTER its init is emitted, so a -# fn body's recursive call still direct-links (and runs after the def completes). -(defn- unit-redefined? [ctx cell] - (let [ud (get (ctx :env) :unit-defs)] (and ud (get ud cell) true))) - -(defn- direct-var? [ctx cell] - (and (get (ctx :env) :direct-linking?) - (not (cell :dynamic)) - (not (let [m (cell :meta)] (and m (get m :redef)))) - (not (unit-redefined? ctx cell)) - (let [r (cell :root)] (or (function? r) (cfunction? r))))) - -# Whole-program constant-linking (closed world): under JOLT_WHOLE_PROGRAM every -# non-dynamic var has a stable root we can embed as a CONSTANT, eliminating the -# per-reference cell deref the indirect path pays. This covers what direct-var? -# can't: ^:redef vars (no reloading under the flag, so redef is moot), data vars -# (def of a number/vector/etc.), and record-type / non-fn callable roots. The -# value is quoted at the emit site unless it's callable (a function/cfunction is -# valid in head AND value position as-is). Dynamic vars stay indirect — thread -# binding is a runtime mechanism, not redefinition. A nil root (a not-yet-run -# forward def) stays indirect so the live deref picks the value up; the -# whole-program re-emit (infer-program!, callee-first after full load) then -# const-links it once its root is in place. -(defn- const-link? [ctx cell] - (and (get (ctx :env) :whole-program?) - (get (ctx :env) :direct-linking?) - (not (cell :dynamic)) - (not (unit-redefined? ctx cell)) - (not (nil? (cell :root))))) - -# Fresh Janet symbol for back-end-introduced bindings (arity dispatch). NOT -# Janet's `gensym` — `(use ./core)` shadows it with Jolt's, which returns a jolt -# symbol struct (invalid in a Janet param position). -(var- gsym-counter 0) -(defn- gsym [] (def s (symbol "_be$" gsym-counter)) (++ gsym-counter) s) - -(var emit nil) - -(defn- emit-seq [ctx node] - (def out @['do]) - (each s (vview (node :statements)) (array/push out (emit ctx s))) - (array/push out (emit ctx (node :ret))) - (tuple/slice out)) - -(defn- emit-let [ctx node] - (def binds @[]) - (each pair (vview (node :bindings)) - (def p (vview pair)) - (array/push binds (symbol (in p 0))) - (array/push binds (emit ctx (in p 1)))) - ['let (tuple/slice binds) (emit ctx (node :body))]) - -# An arity compiles to a named Janet fn whose name is its recur target, so recur -# is a self-call (Janet tail-calls it). The rest param is an ORDINARY positional -# param holding a seq (not Janet `&`), so `(recur fixed... rest-seq)` re-enters -# the way Clojure recur into a variadic arity does (rebinds the rest seq directly, -# no re-collection). The dispatch wrapper (emit-fn-body) collects the call's args. -(defn- emit-arity-fn [ctx ar] - (def ps @[]) - (each pn (vview (ar :params)) (array/push ps (symbol pn))) - (when (ar :rest) (array/push ps (symbol (ar :rest)))) - ['fn (symbol (ar :recur-name)) (tuple/slice ps) (emit ctx (ar :body))]) - -# Invoke an arity's fn with args pulled from the dispatch tuple: fixed params by -# index, rest as a slice from n-fixed on. -(defn- emit-arity-invoke [ctx ar jargs] - (def nfixed (length (vview (ar :params)))) - (def call @[(emit-arity-fn ctx ar)]) - (for i 0 nfixed (array/push call [jin jargs i])) - # empty rest binds to NIL, not () — (f) with [& r] gives r = nil in Clojure - (when (ar :rest) - (array/push call ['if ['> ['length jargs] nfixed] ['tuple/slice jargs nfixed]])) - (tuple/slice call)) - -# A tail loop lowers to a Janet `while` + state vars (jolt-v28u), NOT a -# self-recursive closure called once per iteration — that paid a fn frame + arg -# bind every iteration, which the jolt-5vsp spike localized as the ENTIRE ~1.43x -# jolt-over-hand-Janet gap on compute loops. Shape: -# (let [b0 init0] (let [b1 init1] ... ; sequential inits (later sees earlier) -# (do (var $b0 b0) (var $b1 b1) ... ; state carried across iterations -# (var flag true) (var result nil) -# (while flag -# (set flag false) -# (let [b0 $b0 b1 $b1 ...] ; FRESH immutable per-iteration binding -# (set result ))) ; a tail recur sets the $vars + flag -# result))) -# The per-iteration `let` is load-bearing, not cosmetic: a closure built in the -# body must capture THIS iteration's value (Clojure semantics), and Janet closures -# capture vars BY REFERENCE — close over a shared mutable var and every closure -# sees the final value ([3 3 3]). Rebinding into an immutable `let` each iteration -# restores per-iteration capture ([0 1 2]). recur reads the immutable bi and writes -# $bi, so the read/write sets are disjoint and cross-referencing args (swap, fib) -# need no temps. -(defn- emit-loop [ctx node] - (def recur-name (node :recur-name)) - (def syms @[]) # loop binding names (source symbols), read by the body - (def state @[]) # fresh vars carrying each binding across iterations - (def inits @[]) - (each pair (vview (node :bindings)) - (def p (vview pair)) - (array/push syms (symbol (in p 0))) - (array/push state (gsym)) - (array/push inits (emit ctx (in p 1)))) - (def flag (gsym)) - (def result (gsym)) - # Register this loop so its recurs lower to state-var sets (emit-recur looks it - # up by recur-name); restore any prior binding after the body (nil removes it). - (def frames (or (get (ctx :env) :loop-frames) - (let [t @{}] (put (ctx :env) :loop-frames t) t))) - (def prev (get frames recur-name)) - (put frames recur-name {:state state :flag flag}) - (def body (emit ctx (node :body))) - (put frames recur-name prev) - (def per-iter @[]) - (for i 0 (length syms) (array/push per-iter (syms i) (state i))) - (def block @['do]) - (for i 0 (length syms) (array/push block ['var (state i) (syms i)])) - (array/push block ['var flag true] ['var result nil]) - (array/push block ['while flag - ['set flag false] - ['let (tuple/slice per-iter) ['set result body]]]) - (array/push block result) - (var form (tuple/slice block)) - (for ri 0 (length syms) - (def i (- (length syms) 1 ri)) - (set form ['let [(syms i) (inits i)] form])) - form) - -(defn- emit-recur [ctx node] - (def recur-name (node :recur-name)) - (def frame (get (get (ctx :env) :loop-frames @{}) recur-name)) - (if frame - # while-lowered loop: write each state var from its recur arg (args read the - # immutable iteration bindings — disjoint from the $vars, so no clobber), then - # raise the continue flag. The `do` yields the flag value, discarded in tail. - (let [args (map |(emit ctx $) (vview (node :args))) - block @['do]] - (for i 0 (length (frame :state)) - (array/push block ['set ((frame :state) i) (args i)])) - (array/push block ['set (frame :flag) true]) - (tuple/slice block)) - # fn-arity recur: a self-call the Janet runtime tail-calls (unchanged path). - (tuple/slice (array/concat @[(symbol recur-name)] - (map |(emit ctx $) (vview (node :args))))))) - -# Var-cell read of a clojure.core fn, as ((in 'cell :root) args...) — the same -# live-root call the :var emit uses, for the ns get/set helpers below. -(defn- core-fn-call [ctx nm & args] - (def cell (cell-for ctx "clojure.core" nm)) - (tuple (tuple jin (tuple 'quote cell) :root) ;args)) - -(defn- emit-try [ctx node] - (def core - (if (node :catch-sym) - # Restore current-ns in the catch: a caught throw from an INTERPRETED fn - # leaves ctx-current-ns set to that fn's defining ns (it can't restore on - # unwind), which then breaks alias resolution in the catching ns. Snapshot - # the ns at try entry, reset it on catch (mirrors the interpreter's try). - (let [saved (gsym) raw (gsym)] - ['let [saved (core-fn-call ctx "__current-ns")] - ['try (emit ctx (node :body)) - [[raw] - ['do (core-fn-call ctx "__set-current-ns!" saved) - # bind the catch symbol to the UNWRAPPED value (mirrors the - # interpreter), so an interpreted throw's envelope doesn't leak here. - ['let [(symbol (node :catch-sym)) (core-fn-call ctx "__unwrap-ex" raw)] - (emit ctx (node :catch-body))]]]]]) - (emit ctx (node :body)))) - (if (node :finally) - ['defer (emit ctx (node :finally)) core] - core)) - -(defn- emit-fn-body [ctx node] - (def arities (map norm-node (vview (node :arities)))) - (def multi (> (length arities) 1)) - (cond - # Single fixed arity (the hot case): emit the arity fn directly — its name is - # the recur target, no dispatch overhead. - (and (not multi) (not ((first arities) :rest))) - (emit-arity-fn ctx (first arities)) - # Single variadic arity: a thin wrapper collects the call's args so the rest - # seq can be built, then hands off to the arity fn. Fewer args than the - # fixed params is an arity error (jolt-6xn) — without the guard the fixed - # binds fell off the end of the args tuple with a raw index error. - (not multi) - (let [jargs (gsym) - ar (first arities) - nfixed (length (vview (ar :params)))] - ['fn ['& jargs] - ['if ['< ['length jargs] nfixed] - ['error ['string "Wrong number of args (" ['length jargs] ") passed to: " - (or (node :name) "fn")]] - (emit-arity-invoke ctx ar jargs)]]) - # Multi-arity: dispatch on arg count. Fixed arities match exactly; the (one) - # variadic arity matches >= its fixed count. - (let [jargs (gsym) - nsym (gsym) - cf @['cond]] - (each ar arities - (def nfixed (length (vview (ar :params)))) - (array/push cf (if (ar :rest) [>= nsym nfixed] [= nsym nfixed])) - (array/push cf (emit-arity-invoke ctx ar jargs))) - (array/push cf ['error ['string "Wrong number of args (" nsym ") passed to: " - (or (node :name) "fn")]]) - ['fn ['& jargs] - ['do ['def nsym ['length jargs]] (tuple/slice cf)]]))) - -# A named fn (fn self [..] .. (self ..)) references itself by name. The analyzer -# binds that name as a local; bind it here to the fn value via a var (set before -# any call, so the captured closure sees it — same scheme as emit-loop). recur -# stays a separate self-call to the arity fn; this only covers by-name self-refs. -(defn- emit-fn [ctx node] - (def body (emit-fn-body ctx node)) - (if (node :name) - (let [s (symbol (node :name))] - ['do ['var s nil] ['set s body] s]) - body)) - -# A direct Janet call (f args) is only correct when the callee is definitely a -# function: Janet calling a pvec/keyword/etc. does get (or the wrong thing), not -# IFn dispatch. So only emit a direct call for :fn / :host (always functions) and -# a :var whose CURRENT root is a function (the common user/core-fn case). A :var -# holding an IFn COLLECTION (vector/keyword/set used as a fn) or a :local of -# unknown value falls through to jolt-call, which dispatches IFn correctly -# (function fast-path first). Trade-off, like direct-linking: a fn-var redefined -# to a collection after this call was compiled would still emit a direct call. -(defn- direct-call? [ctx fnode] - (case (fnode :op) - :fn true - :host true - :var (let [r (get (cell-for ctx (fnode :ns) (fnode :name)) :root)] - (or (function? r) (cfunction? r))) - false)) - -# Hot primitives emitted as native Janet ops (host-specific optimization): a -# call to clojure.core/+ etc. becomes (+ …) rather than a var deref + variadic -# core fn. Matches numeric semantics; relaxes the non-number checks (a documented -# perf-mode divergence, same as the bootstrap's core-renames). -(def- native-ops - {"+" '+ "-" '- "*" '* "/" '/ "<" '< ">" '> "<=" '<= ">=" '>= - "inc" '++ "dec" '-- - # verified semantic parity with the jolt fns (incl. negative operands): - # mod is floored, rem (janet %) truncates, / is variadic with (/ x) -> 1/x. - # quot is deliberately ABSENT: janet div floors where Clojure truncates. - "mod" 'mod "rem" '% - # jolt's bit fns are 2-arg (unlike Clojure's variadic), so these emit native - # only at exactly the arity the interpreted fn accepts; bit-not is unary. - "bit-and" 'band "bit-or" 'bor "bit-xor" 'bxor - "bit-shift-left" 'blshift "bit-shift-right" 'brshift "bit-not" 'bnot - # janet min/max are variadic with Clojure's numeric semantics; nil?/some? - # lower to janet's fastfun = / not= against nil (pure opcodes), and `not` - # to janet not — all hot in predicate-heavy loops (jolt-4vr). Same - # documented numbers-only relaxation as the arithmetic ops above. - "min" 'min "max" 'max - "nil?" 'jolt-nil? "some?" 'jolt-some? "not" 'not}) - -(def- unary-ops {'++ true '-- true 'bnot true - 'jolt-nil? true 'jolt-some? true 'not true}) -(def- binary-ops {'mod true '% true 'band true 'bor true 'bxor true - 'blshift true 'brshift true}) - -(defn- native-op - "If fnode is a clojure.core ref (or host ref) to a native-op primitive, return - the Janet op symbol, else nil — only at an arity where the janet op and the - jolt fn agree." - [fnode nargs] - (def nm (case (fnode :op) - :var (when (= "clojure.core" (fnode :ns)) (fnode :name)) - :host (fnode :name) - nil)) - (def op (and nm (get native-ops nm))) - (cond - (nil? op) nil - (and (get unary-ops op) (not= nargs 1)) nil - (and (get binary-ops op) (not= nargs 2)) nil - (and (or (= op 'min) (= op 'max)) (= nargs 0)) nil - op)) - -# Janet-level gensym for the inline fast paths: (use ./core) shadows janet's -# gensym with jolt's (which returns a jolt symbol STRUCT — useless as a janet -# binding target). _fp$ mirrors the reserved _r$ compiler prefix. -(var- fp-counter 0) -(defn- jsym [] (symbol "_fp$" (++ fp-counter))) - -# Is fnode a reference to clojure.core/get (or a host `get`)? Used to give -# (get m :kw [d]) the same inlined keyword-lookup treatment as (:kw m [d]). -(defn- get-head? [fnode] - (case (fnode :op) - :var (and (= "clojure.core" (fnode :ns)) (= "get" (fnode :name))) - :host (= "get" (fnode :name)) - false)) - -# Is fnode a reference to clojure.core/ (or host )? -(defn- core-head? [fnode name] - (case (fnode :op) - :var (and (= "clojure.core" (fnode :ns)) (= name (fnode :name))) - :host (= name (fnode :name)) - false)) - -# Is this IR node a :local the inference proved to be a vector ({:vec ...})? -(defn- vec-hinted? [n] (and (= :local (n :op)) (= :vector (n :hint)))) - -# Shared emit for a constant-keyword map lookup — both (:kw m [d]) and -# (get m :kw [d]). subj-node is the subject's IR node (carries the type hint), -# m-expr its emitted form, k the keyword, d-expr the emitted default or nil. -# - unhinted: GUARDED — (if (get m :jolt/type) (core-get …) (bare get)). The -# guard (one opcode) routes tagged reps (phm/sorted/transient/lazy-seq) to -# core-get; a plain struct/record (no :jolt/type) takes the bare get, which -# matches core-get for keyword keys. -# - ^:struct / ^Record hinted subject: skip the guard, bare get (~20 vs ~36ns). -# - hinted + JOLT_CHECK_HINTS: keep the guard but THROW on the tagged arm, so a -# lying hint surfaces a clear error (dev aid; off by default, no perf cost). -(defn- emit-kw-lookup [ctx subj-node m-expr k d-expr] - # the subject is a struct (raw-get-safe) when hinted so — by an explicit - # ^:struct/^Record hint on a local, OR by inference tagging ANY subject - # expression it proved to be a struct (jolt-d6u/RFC 0005), which is what lets - # nested access like (:r (:direction ray)) drop its guard. - (def hinted (and subj-node (= :struct (subj-node :hint)))) - (def checked (and hinted (os/getenv "JOLT_CHECK_HINTS"))) - (def m (if (symbol? m-expr) m-expr (jsym))) - (def wrap (fn [body] (if (symbol? m-expr) body ['let [m m-expr] body]))) - (def err (when checked - ['error (string "type hint violated on `" (subj-node :name) "`: (" - k " " (subj-node :name) ") — value carries :jolt/type " - "(a phm/sorted/transient/lazy-seq), not the plain " - "struct/record the ^:struct/^Record hint asserts")])) - # Subject carries a complete :shape (jolt-t34) => it is provably a shape-rec; - # the field reads by bare index. The :shape vector is ALREADY in layout order — - # declared order for records (record-shape-for), str-sorted for map literals - # (the inference's shape-order, matching emit-map) — so the field's position in - # :shape IS its slot. (:shapes? = shapes active = direct-link.) - (def sidx - (when (and (get (ctx :env) :shapes?) subj-node (subj-node :shape)) - (def raw (let [s (subj-node :shape)] (if (pv/pvec? s) (pv/pv->array s) s))) - (var pos nil) (var i 0) - (each kk raw (when (= kk k) (set pos i)) (++ i)) - (when pos (+ pos 1)))) - # sidx => proven complete shape: bare index (fastest). Otherwise a raw-get-safe - # value may still be a shape-rec (its :shape dropped by a join, or an unproven - # param). Read it INLINE from its own descriptor — a shape-rec is a tuple whose - # head is a descriptor struct; index the present field directly. A missing key - # (incl. the virtual :jolt/deftype) falls to core-get, which is nil-safe and - # shape-aware; a struct/other takes the bare get. The inline read matters: a - # core-get fn call per field read is ~2.5x slower on map-through-fn code. - # NOT gated on compile-time shapes — core is baked without the flag but still - # receives user shape-recs, so this must hold in baked core too. (jolt-t34) - (defn get-or-shape [getexpr] - (if sidx [jin m sidx] - (let [pos (jsym)] - ['if ['and ['tuple? m] ['struct? ['get m 0]]] - ['let [pos ['get [['get m 0] :idx] k]] - ['if ['nil? pos] (tuple core-get m k nil) [jin m ['+ 1 pos]]]] - getexpr]))) - (if (nil? d-expr) - (let [fast (get-or-shape ['get m k])] - (wrap (cond - checked ['if ['get m :jolt/type] err fast] - hinted fast - ['if ['get m :jolt/type] (tuple core-get m k) fast]))) - (let [d (if (symbol? d-expr) d-expr (jsym)) - v (jsym) - fast ['let [v (get-or-shape ['get m k])] ['if ['nil? v] d v]] - body (cond - checked ['if ['get m :jolt/type] err fast] - hinted fast - ['if ['get m :jolt/type] (tuple core-get m k d) fast]) - body (if (symbol? d-expr) body ['let [d d-expr] body])] - (wrap body)))) - -(defn- emit-invoke [ctx node] - (def fnode (norm-node (node :fn))) - (def args (map |(emit ctx $) (vview (node :args)))) - (def nop (native-op fnode (length args))) - (def argnodes (vview (node :args))) - # devirtualization (jolt-41m): the inference proved this is a protocol call on a - # known record type. Resolve the method impl at COMPILE time and emit a direct - # call to it, skipping the runtime protocol-dispatch registry walk. The impl is - # embedded as a constant fn value in the call head. - (def dvt (node :devirt-type)) - (def devirt-impl - (when dvt (find-protocol-method ctx dvt (node :devirt-proto) (node :devirt-method)))) - (cond - devirt-impl (tuple devirt-impl ;args) - - nop (case nop - '++ ['+ (in args 0) 1] - '-- ['- (in args 0) 1] - 'jolt-nil? ['= nil (in args 0)] - 'jolt-some? ['not= nil (in args 0)] - (tuple nop ;args)) - # (:kw m) / (:kw m default) — inline the lookup (jank-style, jolt-4vr). - # The guard is (get m :jolt/type): janet compiles `get` to an opcode - # (~17ns) where a struct?-style cfunction predicate costs ~85ns/lookup. - # :jolt/type is a reserved key — user map literals can't contain it (the - # reader treats such maps as tagged forms) — and every table-backed rep - # that must NOT be raw-indexed carries it (phm — tagged for this guard — - # sorted, transient, pvec, atoms, lazy-seqs), so a non-nil tag routes to - # core-get's full semantics. Everything else (structs = literal maps, - # records with direct field keys, nil, janet arrays, scalars) gets janet - # `get` semantics, which match core-get for keyword keys. Structs never - # store nil values (nil values force the phm rep), so present-but-nil - # can't be confused with missing on the fast arm. A ^:struct/^Record hint on - # the subject skips the guard entirely (jolt-94n; see emit-kw-lookup). - (and (= :const (fnode :op)) (keyword? (fnode :val)) - (>= 2 (length args) 1)) - (emit-kw-lookup ctx (norm-node (in argnodes 0)) (in args 0) (fnode :val) - (when (= 2 (length args)) (in args 1))) - # (get m :kw) / (get m :kw default) — same inlined keyword lookup as (:kw m), - # so an explicit get with a constant keyword gets the guard fast path and the - # ^:struct/^Record hint (jolt-94n). Only when the key is a constant keyword; - # a variable/number/string key falls through to core-get below. - (and (get-head? fnode) (>= (length args) 2) (<= (length args) 3) - (let [a1 (norm-node (in argnodes 1))] (and (= :const (a1 :op)) (keyword? (a1 :val))))) - (emit-kw-lookup ctx (norm-node (in argnodes 0)) (in args 0) - ((norm-node (in argnodes 1)) :val) - (when (= 3 (length args)) (in args 2))) - # (count v) on an inferred vector -> pv-count, skipping core-count's dispatch - # chain (jolt-d6u, Phase 2). Sound: a {:vec ...}-typed value is a pvec. - (and (core-head? fnode "count") (= 1 (length args)) (vec-hinted? (norm-node (in argnodes 0)))) - (tuple pv/pv-count (in args 0)) - # (nth v i default) on an inferred vector -> pv-nth. Only the 3-ARG form: the - # 2-arg nth ERRORS on out-of-bounds where pv-nth returns nil, so specializing - # it would change semantics; the 3-arg default matches pv-nth exactly. - (and (core-head? fnode "nth") (= 3 (length args)) (vec-hinted? (norm-node (in argnodes 0)))) - (tuple pv/pv-nth (in args 0) (in args 1) (in args 2)) - (direct-call? ctx fnode) (tuple (emit ctx fnode) ;args) - # Local callee (closure param, let-bound fn, defn self-name): inline the - # function check so the overwhelmingly-common function case is a direct - # janet call with no variadic arg-tuple packing — jolt-call only handles - # the IFn-collection leftovers (jank's dynamic_call removal, jolt-507). - # The callee is rebound to a reserved _fp$ symbol first: a raw jolt local - # name in janet CALL-HEAD position resolves against janet's macro table - # before the lexical upvalue, so a local named like a janet core macro - # (clojure.core/repeat's self-name vs janet's repeat macro) would expand - # as that macro. Argument positions (the old jolt-call shape, the rebind - # here) never consult the macro table, so the rebind is safe. - (= :local (fnode :op)) - (let [fsym (jsym)] - ['let [fsym (emit ctx fnode)] - ['if ['function? fsym] - (tuple fsym ;args) - (tuple jolt-call fsym ;args)]]) - (tuple jolt-call (emit ctx fnode) ;args))) - -(defn- emit-vector [ctx node] - (def items (map |(emit ctx $) (vview (node :items)))) - (tuple make-vec (tuple/slice (array/concat @['tuple] items)))) - -(defn- emit-map [ctx node] - (def pairs (vview (node :pairs))) - # Fast path (jolt-4vr): when every key is a scalar const (keyword/string/ - # number/bool — never a collection, so value-hashing can't be needed from - # the keys), construct the Janet struct inline with one nil-check per - # value instead of calling variadic build-map-literal and re-scanning the - # kvs at runtime. A nil value still falls back to the phm rep (Clojure - # keeps nil entries; structs drop them). - (var fast (> (length pairs) 0)) - (each pair pairs - (def k (norm-node (in (vview pair) 0))) - (def kv (get k :val)) - (unless (and (= :const (k :op)) - (or (keyword? kv) (string? kv) (number? kv) (boolean? kv))) - (set fast false))) - # Shape-record representation (jolt-t34, JOLT_SHAPE): EVERY constant-key map - # literal becomes a shape tuple (≈2x cheaper than a struct), CONSISTENTLY — - # not gated on the inference, so a value's representation always matches what - # the type system claims about it. The layout is the runtime's canonical - # shape-sort of the keys (the single source of truth all sites share). Values - # are emitted in that order; element 0 is the compile-time shape descriptor. - # gated on :inline? — shapes apply to USER code only, never to core or the - # compiler's own IR-node map literals (which the back end reads with raw - # keyword access and would break if turned into tuples) - (def shape-keys - (when (and fast (get (ctx :env) :map-shapes?) (get (ctx :env) :inline?)) - (def ks @[]) - (each pair pairs (array/push ks ((norm-node (in (vview pair) 0)) :val))) - (shape-sort ks))) - (if shape-keys - (do - (def desc (shape-for shape-keys)) - (def by-key @{}) - (each pair pairs - (def p (vview pair)) - (put by-key ((norm-node (in p 0)) :val) (emit ctx (in p 1)))) - # quote the descriptor: it is a struct constant, and its keys are a parens - # tuple — unquoted in code position Janet would try to CALL it ((:b :g)) - (def out @['tuple ['quote desc]]) - (each k shape-keys (array/push out (get by-key k))) - (tuple/slice out)) - (if fast - (do - (def binds @[]) - (def skvs @['struct]) - (def phm-args @[build-map-literal]) - (def truthy @['and]) - (each pair pairs - (def p (vview pair)) - (def kk ((norm-node (in p 0)) :val)) - (def vs (jsym)) - (array/push binds vs) - (array/push binds (emit ctx (in p 1))) - (array/push truthy vs) - (array/push skvs kk) (array/push skvs vs) - (array/push phm-args kk) (array/push phm-args vs)) - # `and` is pure branch opcodes, so the all-truthy common case pays no - # predicate calls at all. nil OR false values (rare) drop to - # build-map-literal, which re-checks nil properly (false values come - # back out on the struct arm there; nil values get the phm rep). - ['let (tuple/slice binds) - ['if (tuple/slice truthy) - (tuple/slice skvs) - (tuple/slice phm-args)]]) - (do - (def args @[build-map-literal]) - (each pair pairs - (def p (vview pair)) - (array/push args (emit ctx (in p 0))) - (array/push args (emit ctx (in p 1)))) - (tuple/slice args))))) - -# A set literal: build (make-phs e1 e2 …) so each element is evaluated at runtime -# then the persistent set is constructed — mirrors compiler.janet's emit-set-expr. -(defn- emit-set [ctx node] - (def items (map |(emit ctx $) (vview (node :items)))) - (tuple/slice (array/concat @[phs/make-phs] items))) - -# Native codegen hook (jolt-ihdp). Under :cgen?, a plain defn of a numeric-leaf -# fn is compiled to C and the resulting cfunction installed as the var root, so -# direct-linked callers embed native code. Returns the cfunction or nil (not a -# candidate / redefable / toolchain absent / cc failed -> normal bytecode path). -# Skip ^:redef / ^:dynamic: those must stay redefinable bytecode. -(defn- cgen-root [ctx node] - (def env (ctx :env)) - (def meta (node :meta)) - (def redefable (and meta (or (get meta :redef) (get meta :dynamic)))) - (when (not redefable) - (def prebuilt (get env :cgen-prebuilt)) - (def qn (string (node :ns) "/" (node :name))) - (cond - # AOT deploy: install the build-time-compiled cfunction as the root (no cc). - # Same timing as the JIT path, so callers compiled later direct-link to it. - (and prebuilt (get prebuilt qn)) (get prebuilt qn) - # JIT: compile to C now (runs cc). - (and (get env :cgen?) (cgen/numeric-leaf? (node :init))) - (let [r (protect (cgen/compile-fn (node :init) {:name (string (node :ns) "_" (node :name))}))] - (and (r 0) (r 1)))))) - -# Build-time collection (jolt-a7ds): under :cgen-collect?, record each numeric- -# leaf defn's full fn IR (with its ns/name) so an AOT driver can compile them all -# into one native module. Does NOT swap the root — the app still loads as bytecode -# during collection; the native version is wired at the later deploy run. -(defn- cgen-collect! [ctx node] - (def env (ctx :env)) - (when (get env :cgen-collect?) - (def meta (node :meta)) - (def redefable (and meta (or (get meta :redef) (get meta :dynamic)))) - (when (and (not redefable) (cgen/numeric-leaf? (node :init))) - (def coll (or (get env :cgen-collected) - (let [a @[]] (put env :cgen-collected a) a))) - (array/push coll {:ns (node :ns) :name (node :name) :ir (node :init)})))) - -(set emit - (fn emit [ctx raw] - (def node (norm-node raw)) - (case (node :op) - :const (node :val) - :local (symbol (node :name)) - :host (symbol (node :name)) - :var (let [cell (cell-for ctx (node :ns) (node :name))] - (if (direct-var? ctx cell) - (cell :root) # direct link: embed the fn value - (if (const-link? ctx cell) - # whole-program closed world: embed the stable root as a constant. - # Callable roots go in bare (valid in head/value position); any - # other value is quoted so Janet returns it rather than evaluating - # it as code (a bare tuple/struct in code position would be called). - (let [r (cell :root)] - (if (or (function? r) (cfunction? r)) r (tuple 'quote r))) - # Indirect: live deref, with the var-get FN CALL inlined away - # (jolt-8sq): a non-dynamic var's value is always its root, so - # the common case is two native table ops + a branch instead of - # a function call. Dynamic vars take the full var-get (thread- - # binding walk). The cell is quoted so it's embedded by - # reference (a bare table in arg position would be re-evaluated - # as a constructor — deep-copying it, and any atom in :root, - # each call). Redefinition stays live: :root is read per call. - # The :dynamic check must be PER CALL, not at emit: a - # (def ^:dynamic x) in the same compiled unit marks the cell - # dynamic only when the def RUNS, after this site was emitted — - # the same reason JVM Clojure's Var.deref() checks the - # thread-bound bit on every call. Non-dynamic vars (the vast - # majority) pay two native table ops + a branch instead of a - # function call. - (let [qcell (tuple 'quote cell)] - ['if [jin qcell :dynamic] - (tuple var-get qcell) - [jin qcell :root]])))) - # (var x): the var object itself (not its value) — the embedded cell, by - # reference. binding keys its thread-binding frame on this exact cell. - :the-var (tuple 'quote (cell-for ctx (node :ns) (node :name))) - :if ['if (emit ctx (node :test)) (emit ctx (node :then)) (emit ctx (node :else))] - :do (emit-seq ctx node) - :loop (emit-loop ctx node) - :recur (emit-recur ctx node) - :try (emit-try ctx node) - :throw ['error (emit ctx (node :expr))] - :def (let [cell (cell-for ctx (node :ns) (node :name)) - meta (node :meta) - setter (if (and meta (not (empty? meta))) (var-setter-meta cell meta) (var-setter cell)) - _ (cgen-collect! ctx node) - cfn (cgen-root ctx node)] - # cgen path: install the native cfunction as the root and DON'T - # inline-stash — callers must call the C fn, not inline the bytecode - # body (which would bypass the native version). Otherwise the normal - # bytecode path: stash for inlining, emit the init. - (if cfn - (do (when-let [ud (get (ctx :env) :unit-defs)] (put ud cell true)) - (tuple setter cfn)) - (do (inline-stash! ctx cell node) - # Emit the init BEFORE marking the cell unit-defined, so a - # recursive self-reference in the init still direct-links; a - # LATER sibling reference in this unit then sees it as - # redefined (jolt-wf4). - (let [init-form (emit ctx (node :init))] - (when-let [ud (get (ctx :env) :unit-defs)] (put ud cell true)) - (tuple setter init-form))))) - :let (emit-let ctx node) - :fn (emit-fn ctx node) - :invoke (emit-invoke ctx node) - :vector (emit-vector ctx node) - :map (emit-map ctx node) - :set (emit-set ctx node) - :quote ['quote (node :form)] - (error (string "backend: unhandled op " (node :op)))))) - -(defn emit-ir - "IR node -> Janet form (public entry for the back end)." - [ctx node] - # Fresh per-unit set of vars (re)defined in THIS top-level form, so a sibling - # reference to one can't direct-link to its pre-redef root (jolt-wf4). Scoped - # to one emit pass; each compile-and-eval / re-emit call is its own unit. - (when (table? (get ctx :env)) (put (ctx :env) :unit-defs @{})) - (emit ctx node)) - -# --- pipeline wiring (the self-hosted compile path) --- - -# Bootstrap-compile a source string into target-ns: each form is compiled via the -# bootstrap (native Janet) compiler and its defs interned in target-ns. This is -# the stage-1 builder — it runs BEFORE the self-hosted analyzer exists, so it's -# how both the compiler namespaces (jolt.ir/jolt.analyzer) and the clojure.core -# kernel tier (the structural fns the analyzer itself calls) get built. The -# analyzer uses unqualified referred names (jolt.host form-* + IR ctors), so the -# bootstrap's plain :var path compiles it; stateful forms fall back to interp. -(defn bootstrap-load-source - "Stage-1 builder: load a source string into target-ns INTERPRETED. Runs before - the self-hosted analyzer exists (it builds jolt.ir/jolt.analyzer and the kernel - tier); self-compile-compiler! then re-runs those sources through the live - analyzer so the steady-state compiler is compiled by itself — the retired - bootstrap compiler's job, done by the interpreter + one fixpoint turn." - [ctx target-ns src] - (def saved (ctx-current-ns ctx)) - (ctx-set-current-ns ctx target-ns) - (var s src) - (while (> (length (string/trim s)) 0) - (def parsed (r/parse-next s)) - (set s (in parsed 1)) - (def f (in parsed 0)) - (when (not (nil? f)) - (eval-form ctx @{} f))) - (ctx-set-current-ns ctx saved)) - -# Compile-load an embedded jolt-core namespace by name (source from the stdlib map). -(defn- compile-load [ctx ns-name] - (def src (get (get (ctx :env) :embedded-sources @{}) ns-name)) - (when src (bootstrap-load-source ctx ns-name src))) - -# Build the self-hosted compiler (IR ctors + analyzer) via the bootstrap. The -# analyzer's references to clojure.core fns it uses (second/peek/subvec/mapv/ -# update) resolve to whatever is interned in clojure.core at this point — so the -# kernel tier must already be loaded (see api/load-core-overlay!). -(defn- build-compiler! [ctx] - (compile-load ctx "jolt.ir") - (compile-load ctx "jolt.analyzer") - # jolt.passes is split into three weakly-coupled namespaces; load them in - # dependency order (fold is the base) before the façade requires them. - (compile-load ctx "jolt.passes.fold") - (compile-load ctx "jolt.passes.inline") - (compile-load ctx "jolt.passes.types") - (compile-load ctx "jolt.passes")) - -(defn- ensure-analyzer [ctx] - # Don't build until the kernel tier is loaded (see api/load-core-overlay! and - # build-compiler!). Before then a compile request — e.g. a defn in a pre-kernel - # tier — must fall back to the interpreter, not build the analyzer against a - # core missing the fns it references (which would intern them as nil cells that - # then shadow the real definitions on the self-rebuild). The flag is absent in - # bare/test contexts that never load core; treat that as ready so those keep - # building the analyzer lazily as before. - (def env (ctx :env)) - (def gated (and (has-key? env :kernel-ready?) (not (get env :kernel-ready?)))) - (when (and (not gated) - (= 0 (length ((ctx-find-ns ctx "jolt.analyzer") :mappings)))) - (build-compiler! ctx))) - -(defn rebuild-compiler! - "Recompile the self-hosted compiler (jolt.ir + jolt.analyzer) against the - CURRENT clojure.core. The fractal turn: once a core tier supplies Clojure - definitions the compiler itself uses, rebuilding makes the compiler run on - them. Idempotent; re-interns the compiler namespaces over the existing cells." - [ctx] - (build-compiler! ctx)) - -(defn- report-diags! - "Render and emit success-type diagnostics (RFC 0006) at the given strictness: - `warn` prints to stderr, `error` throws (failing this form's compilation). - file:line:col when the diagnostic carries an offset and the source is on the - env (jolt-fqy); else the ns." - [ctx diags strictness ns] - (def src (get (ctx :env) :tc-source)) - (def file (or (get (ctx :env) :tc-file) (and ns (string ns)))) - (each d diags - (def off (get d :pos)) - (def loc - (if (and off src) - (let [lc (r/line-col src off)] - (string (or file "?") ":" (in lc 0) ":" (in lc 1))) - (string "in " (if ns (string ns) "?")))) - (def msg (string "type error " loc ": " (get d :msg))) - (if (= strictness "error") - (error msg) - (eprint " " msg)))) - -(defn type-check! - "Decoupled success-type check (RFC 0006): run jolt.passes/check-form as its OWN - inference pass over `ir` and report. Used in NON-direct-link builds, where the - optimization inference doesn't run — so checking costs a separate pass. (In - direct-link builds checking piggybacks on run-passes' inference instead, near - free; see analyze-form.) Protected so a checker bug never breaks compilation. - - JOLT_TYPE_CHECK_USER (an orthogonal opt-in knob, jolt-zo1) additionally - reports calls to user functions whose concrete argument types provably make - the body throw — sound only under the closed-world assumption, hence opt-in." - [ctx ir strictness ns] - (def cf (ns-find (ctx-find-ns ctx "jolt.passes") "check-form")) - (when cf - (def uenv (os/getenv "JOLT_TYPE_CHECK_USER")) - (def strict? (and uenv (not= uenv "0") (not= uenv "off"))) - (def r (protect ((var-get cf) ir strict?))) - (when (r 0) - (def diags (if (pv/pvec? (r 1)) (pv/pv->array (r 1)) (r 1))) - (when (and diags (> (length diags) 0)) - (report-diags! ctx diags strictness ns))))) - -(defn analyze-form - "Run the portable Clojure analyzer (jolt.analyzer/analyze) on a reader form, - returning host-neutral IR." - [ctx form] - (ensure-analyzer ctx) - # Capture the real compile ns: the analyzer runs interpreted (defined in - # jolt.analyzer), and the interpreter rebinds current-ns to a fn's defining ns - # while it runs — so h/current-ns must read this instead of ctx-current-ns. - (put (ctx :env) :compile-ns (ctx-current-ns ctx)) - (def saved-ns (ctx-current-ns ctx)) - (def av (ns-find (ctx-find-ns ctx "jolt.analyzer") "analyze")) - # Pre-kernel bootstrap: ensure-analyzer is gated until the kernel tier loads - # (see api/load-core-overlay!), so a compile request from an earlier tier (e.g. - # 00-syntax's destructure defn) finds no analyzer. That fallback is DESIGNED — - # route it through the sanctioned punt channel rather than crashing on a nil var. - (unless av - (put (ctx :env) :compile-ns nil) - (error "jolt/uncompilable: analyzer not built (pre-kernel bootstrap)")) - # The analyzer runs INTERPRETED; the interpreter rebinds current-ns to a fn's - # defining ns (jolt.analyzer) while it runs and only restores on normal return. - # A punt THROWS out of those frames, leaking jolt.analyzer as current-ns (and - # :compile-ns stayed set) — the fallback interpretation then resolves user vars - # against the wrong ns. Restore both on every exit. - (def r (protect ((var-get av) ctx form))) - (put (ctx :env) :compile-ns nil) - (ctx-set-current-ns ctx saved-ns) - (unless (r 0) (error (r 1))) - # IR passes (jolt.passes/run-passes — nanopass-lite, jolt-2om): pure IR->IR - # rewrites (constant folding, ...) between the analyzer and the back end. - # Resolved lazily; absent during the pre-passes bootstrap window. - (def pv (unless (= "1" (os/getenv "JOLT_NO_IR_PASSES")) - (ns-find (ctx-find-ns ctx "jolt.passes") "run-passes"))) - # Success-type checking level (RFC 0006). JOLT_TYPE_CHECK wins when set; - # otherwise it defaults to `warn` in a direct-link build, where the inference - # already runs so checking piggybacks for nearly free — EXCEPT when direct- - # linking was auto-enabled by a casual program run (:direct-link-auto?), which - # shouldn't spam type warnings. Stays OFF for plain REPL/dev builds too; opt in - # anywhere with JOLT_TYPE_CHECK. (jolt audit) - (def tc (os/getenv "JOLT_TYPE_CHECK")) - (def tc-off (or (= tc "off") (= tc "0"))) - (def direct-link? (if (get (ctx :env) :inline?) true false)) - (def auto-dl? (if (get (ctx :env) :direct-link-auto?) true false)) - (def level (cond tc-off nil tc tc (and direct-link? (not auto-dl?)) "warn" true nil)) - (def uenv (os/getenv "JOLT_TYPE_CHECK_USER")) - (def strict? (and uenv (not= uenv "0") (not= uenv "off") true)) - # piggyback: check DURING run-passes' inference (direct-link, the cheap path) - (def piggyback? (and level direct-link? pv true)) - (def scm (and piggyback? (ns-find (ctx-find-ns ctx "jolt.passes") "set-check-mode!"))) - (when scm ((var-get scm) true strict?)) - (def result - (if pv - (let [pr (protect ((var-get pv) (r 1) ctx))] - # the pass runs interpreted; a throw inside it unwinds past the - # interpreter's ns restores — put the compile ns back either way, or - # the REST of this compilation resolves in jolt.passes - (ctx-set-current-ns ctx saved-ns) - (if (pr 0) (pr 1) (r 1))) - (r 1))) - (when scm ((var-get scm) false false)) - (cond - # direct-link: collect the diagnostics infer-top emitted and report them - piggyback? - (let [td (ns-find (ctx-find-ns ctx "jolt.passes") "take-diags!")] - (when td - (def raw ((var-get td))) - (def diags (if (pv/pvec? raw) (pv/pv->array raw) raw)) - (when (and diags (> (length diags) 0)) - (report-diags! ctx diags level saved-ns)))) - # plain build with checking explicitly requested: a separate inference pass - (and level (not direct-link?)) - (type-check! ctx (r 1) level saved-ns)) - result) - -# The analyzer's deliberate punt signal — (uncompilable why) throws the string -# "jolt/uncompilable: ". Anything else escaping the compile step is an -# unexpected compiler error, not a punt. -(defn- uncompilable-error? [err] - # The punt may arrive as a plain string (compiled analyzer) or wrapped in the - # interpreter's exception struct {:jolt/type :jolt/exception :value s} - # (interpreted analyzer — the stage-3 bootstrap path). - (def msg (if (and (struct? err) (= :jolt/exception (get err :jolt/type))) - (get err :value) - err)) - (and (or (string? msg) (buffer? msg)) - (string/has-prefix? "jolt/uncompilable" (string msg)))) - -(defn compile-and-eval - "Self-hosted compile path: analyze (portable Clojure) -> IR -> Janet -> eval. - The interpreter fallback is DELIBERATE-ONLY (Stage 2): only an analyzer punt - (jolt/uncompilable — the curated stateful/letrec set) falls back; any other - compile-step error is a compiler bug and propagates rather than being silently - hidden by interpretation. Runtime errors in compiled code propagate as before - (no double-eval, no hidden errors)." - [ctx form] - (def compiled (protect (emit-ir ctx (analyze-form ctx form)))) - (if (compiled 0) - (eval (compiled 1) (ctx-janet-env ctx)) - (if (uncompilable-error? (compiled 1)) - (eval-form ctx @{} form) - (error (compiled 1))))) - -(defn self-compile-compiler! - "Stage 3 (interpreted bootstrap): once the overlay + interpreted analyzer are - alive, run the kernel tier, jolt.ir, and jolt.analyzer back through the - SELF-HOSTED pipeline — the analyzer compiles itself (and the kernel fns it - uses), so by steady state the compiler runs compiled with no bootstrap - compiler involved. Forms a punt can't compile stay interpreted (the - deliberate channel)." - [ctx] - (def saved (ctx-current-ns ctx)) - (each [ns-name target] [["clojure.core.00-kernel" "clojure.core"] - ["jolt.ir" "jolt.ir"] - ["jolt.analyzer" "jolt.analyzer"]] - (def src (get (get (ctx :env) :embedded-sources @{}) ns-name)) - (when src - (ctx-set-current-ns ctx target) - (var s src) - (while (> (length (string/trim s)) 0) - (def parsed (r/parse-next s)) - (set s (in parsed 1)) - (def f (in parsed 0)) - (when (not (nil? f)) - (def r (protect (compile-and-eval ctx f))) - (unless (r 0) (eval-form ctx @{} f)))))) - (ctx-set-current-ns ctx saved)) - -(defn analyzer-built? [ctx] - (> (length ((ctx-find-ns ctx "jolt.analyzer") :mappings)) 0)) - -(defn try-compile-fn - "Compile a fn* form to a native Janet fn via the self-hosted pipeline, or nil if - it can't be compiled (analyzer not yet built, or the body isn't compilable). - Used to compile macro expanders for native-speed expansion." - [ctx fn-form] - (when (analyzer-built? ctx) - (def compiled (protect (emit-ir ctx (analyze-form ctx fn-form)))) - (when (compiled 0) - (def r (protect (eval (compiled 1) (ctx-janet-env ctx)))) - (when (r 0) (r 1))))) - -# Wrap expanders in the `fn` MACRO, not the `fn*` primitive: `fn` desugars a -# destructured macro arglist (`[a & [b]]`, `[& {:keys [x]}]`) before lowering, -# whereas raw fn* punts on a destructuring rest param. -(def- fn-sym {:jolt/type :symbol :ns nil :name "fn"}) - -(defn recompile-macros! - "Staged-bootstrap second pass: once the self-hosted analyzer is alive, replace - every interpreted macro expander with a COMPILED one. The early macros (00-syntax - etc.) are defined WHILE the analyzer is still being bootstrapped, so their - expanders can't compile yet (the analyzer they'd compile through doesn't exist) — - defmacro gives them an interpreted closure as a build-time crutch and stashes the - source on the var (:macro-src). This pass compiles that source through the now-live - analyzer and rebinds the var, so by steady state no macro expansion is interpreted - — mirroring how a self-hosting compiler recompiles its seed once it can. - - Idempotent: a var compiled once is marked :macro-compiled and skipped (so the - refer of a core macro into another ns, or a later rebuild, costs nothing). A macro - whose body uses &env/&form keeps its interpreted closure (the compiled fn* has no - such params). Returns the number of expanders compiled this pass." - [ctx] - (var n 0) - (each ns (all-ns ctx) - (each v (ns :mappings) - (when (and (var? v) (var-macro? v) - (v :macro-src) (not (v :macro-compiled)) - (not (v :macro-uses-env))) - (def [args-form body] (v :macro-src)) - (def compiled - (try-compile-fn ctx (array/concat @[fn-sym args-form] body))) - (when compiled - (bind-root v compiled) - (put v :macro-compiled true) - (++ n))))) - n) - -(defn recompile-defns! - "Staged-bootstrap pass for early DEFNS (jolt-4j3) — the defn analog of - recompile-macros!. Pre/at-kernel overlay defns (00-syntax's destructure, - empty?/keys/vals, and the kernel tier in interpret mode) load as interpreted - closures; the evaluator stashes their fn source on the var (:defn-src). - Once the analyzer is alive, compile that source and swap the var's ROOT — - callers go through the var, so they pick up the compiled fn. Skips vars - already done; a body the analyzer can't compile stays interpreted." - [ctx] - (def mappings ((ctx-find-ns ctx "clojure.core") :mappings)) - (var n 0) - (each nm (keys mappings) - (def v (get mappings nm)) - (when (and (table? v) (get v :defn-src) (not (get v :defn-compiled))) - (def compiled (try-compile-fn ctx (get v :defn-src))) - (when compiled - (put v :root compiled) - (put v :defn-compiled true) - (++ n)))) - n) - -# Inter-procedural collection-type inference + recompile (jolt-767, Phase 1), -# closed-world / optimization mode. After a unit loads, every single-fixed-arity -# fn stashed a post-pass :def IR (:infer-ir). We: -# 1. run a whole-unit fixpoint: a fn's param types = lub of its in-unit -# call-site arg types (computed by jolt.passes/infer-body); a fn whose var -# escapes as a VALUE keeps :any params (its callers aren't all visible). -# 2. re-infer + re-emit each fn body with its param types seeded, so -# param-dependent lookups specialize (drop the :jolt/type guard). -# Recompiled bodies are semantically identical to the guarded ones, so this is -# correct regardless of recompile order; order only affects how far a direct- -# linked call propagates the faster callee. -(defn- itype-join [a b] - (cond - (nil? a) b - (nil? b) a - (= a b) a - # compound vector types {:vec ELEM} join element-wise (jolt-d6u) - (and (struct? a) (struct? b) (in a :vec) (in b :vec)) - (struct :vec (itype-join (in a :vec) (in b :vec))) - :any)) - -(defn infer-unit! - # ns-names-arg is one ns-name (per-namespace pass, the default) or a LIST of - # ns-names (whole-program pass, jolt-t34): gathering all units into ONE fixpoint - # propagates param types across namespace boundaries, which the per-ns pass - # can't (a fn's callers in another ns aren't visible when its own ns is typed). - [ctx ns-names-arg] - (def ns-names (if (indexed? ns-names-arg) ns-names-arg [ns-names-arg])) - (def pns (ctx-find-ns ctx "jolt.passes")) - (def f-set-rtenv (and pns (ns-find pns "set-rtenv!"))) - (def f-set-vtypes (and pns (ns-find pns "set-vtypes!"))) - (def f-join (and pns (ns-find pns "join-types"))) - (def f-infer-body (and pns (ns-find pns "infer-body"))) - (def f-reinfer (and pns (ns-find pns "reinfer-def"))) - (def f-reset-esc (and pns (ns-find pns "reset-escapes!"))) - (def f-set-rshapes (and pns (ns-find pns "set-record-shapes!"))) # jolt-t34 - (def f-set-mshapes (and pns (ns-find pns "set-map-shapes!"))) # jolt-t34 - (def f-set-pmethods (and pns (ns-find pns "set-protocol-methods!"))) # jolt-41m - (def f-phint-seed (and pns (ns-find pns "phint-seed"))) # jolt-3ko - (def f-get-esc (and pns (ns-find pns "collected-escapes"))) - (def report @{}) - (when (and f-set-rtenv f-set-vtypes f-join f-infer-body f-reinfer f-reset-esc f-get-esc) - # gather single-fixed-arity fns AND non-fn defs that stashed a :def IR, across - # every ns in ns-names (one ns for the per-unit pass, all for whole-program) - (def fns @[]) - (def defs @[]) - (def by-key @{}) - (def vtypes @{}) # var VALUE types: fns -> :truthy (non-nil), defs -> inferred - (each ns-name ns-names - (def ns (ctx-find-ns ctx ns-name)) - (when ns - (each nm (keys (ns :mappings)) - (def v (get (ns :mappings) nm)) - (when (and (table? v) (get v :infer-ir)) - (def d (norm-node (get v :infer-ir))) - (def init (norm-node (d :init))) - (def key (string ns-name "/" nm)) - (if (= :fn (init :op)) - (let [ars (vview (init :arities))] - (when (= 1 (length ars)) - (def ar (norm-node (in ars 0))) - (unless (ar :rest) - (def pv (vview (ar :params))) - (def rec @{:key key :cell v :def d :params (ar :params) :body (ar :body) - :phints (ar :phints) :np (length pv) - :pt (array/new-filled (length pv)) :ret nil}) - (array/push fns rec) - (put by-key key rec) - # a fn value is non-nil -> :truthy (sealed root in opt mode) - (put vtypes key :truthy)))) - # non-fn def: its value type is inferred from its init (jolt-d6u) - (array/push defs @{:key key :init (d :init) :vt nil})))))) - (when (or (> (length fns) 0) (> (length defs) 0)) - ((var-get f-reset-esc)) - # jolt-t34: feed record-ctor shapes + the map-shaping flag to the inference - (when f-set-rshapes ((var-get f-set-rshapes) (or (get (ctx :env) :record-shapes) @{}))) - (when f-set-mshapes ((var-get f-set-mshapes) (get (ctx :env) :map-shapes?))) - # jolt-3ko: resolve each fn's declared ^Record param hints to positional - # type seeds (needs the registry above). Seeded as a param-type FLOOR in the - # fixpoint so a hinted param propagates its (field-read) types to callees - # during inference, not only at the final re-emit. - (when f-phint-seed - (each f fns - (put f :phint-types (vview ((var-get f-phint-seed) (f :params) (or (f :phints) [])))))) - # jolt-41m: feed the protocol-method registry for devirtualization - (when f-set-pmethods ((var-get f-set-pmethods) (or (get (ctx :env) :protocol-methods) @{}))) - # --- param/return/value-type fixpoint (chaotic iteration to LEAST fixpoint) --- - # Param types are RECOMPUTED FRESH each iteration, not accumulated: :any is - # the lattice top, so a join with an early-iteration :any (a caller whose own - # params weren't typed yet) would poison the result permanently. Recomputing - # from the current state lets a param refine as its callers' types improve. - (var prev-rt @{}) - (var changed true) (var iter 0) - (while (and changed (< iter 16)) - ((var-get f-set-rtenv) prev-rt) - ((var-get f-set-vtypes) vtypes) - # type every fn body once under current param types; stash ret + calls - (each f fns - (def tenv @{}) - (def pv (vview (f :params))) - (for i 0 (f :np) (when (in (f :pt) i) (put tenv (in pv i) (in (f :pt) i)))) - (def res (vview ((var-get f-infer-body) (f :body) tenv))) - (put f :tret (in res 0)) - (put f :tcalls (in res 2))) - # infer each def's VALUE type from its init - (each dv defs - (put dv :tvt (in (vview ((var-get f-infer-body) (dv :init) @{})) 0))) - # recompute param types FRESH (start at bottom) from this round's calls. - # Bottom is nil, EXCEPT a declared ^Record hint seeds its slot as a floor - # (jolt-3ko) — a fixed declared type can't poison the fixpoint the way an - # early-iteration :any would, and it lets a hinted param propagate to its - # callees even when it has no callers of its own. - (def newpt @{}) - (each f fns - (def npa (array/new-filled (f :np))) - (def phts (f :phint-types)) - (when phts (for i 0 (f :np) (when (in phts i) (put npa i (in phts i))))) - (put newpt (f :key) npa)) - (each f fns - (each c (vview (f :tcalls)) - (def cv (vview c)) - (def npa (get newpt (in cv 0))) - (when npa - (def callee (get by-key (in cv 0))) - (def ats (vview (in cv 1))) - (def lim (min (length ats) (callee :np))) - (for i 0 lim (put npa i ((var-get f-join) (in npa i) (in ats i))))))) - # commit + detect change - (set changed false) - (def nrt @{}) - (each f fns - (def np (get newpt (f :key))) - (for i 0 (f :np) (when (not= (in np i) (in (f :pt) i)) (set changed true))) - (when (not= (f :tret) (f :ret)) (set changed true)) - (put f :pt np) - (put f :ret (f :tret)) - (when (f :tret) (put nrt (f :key) (f :tret)))) - (each dv defs - (when (not= (dv :tvt) (dv :vt)) (set changed true)) - (put dv :vt (dv :tvt)) - (when (dv :tvt) (put vtypes (dv :key) (dv :tvt)))) - (set prev-rt nrt) - (++ iter)) - # --- escaped fns: var used as a value -> params untrustworthy -> skip --- - (def esc @{}) - (each k (vview ((var-get f-get-esc))) (put esc k true)) - # install the FINAL return + value types so reinfer-def sees them - (def final-rt @{}) - (each f fns (when (f :ret) (put final-rt (f :key) (f :ret)))) - ((var-get f-set-rtenv) final-rt) - ((var-get f-set-vtypes) vtypes) - # --- re-emit the WHOLE unit, callees first (jolt-d6u) ------------------- - # Re-inference alone only rebinds a fn's own var, but the hot path runs - # through callee bodies INLINED / direct-linked into callers at first - # compile. Re-emitting in callee-first (reverse-topological) order makes - # each caller re-embed its now-recompiled callees, and re-infers its body - # (typing locals via return inference) — so the specialization propagates, - # and a call site compiled AFTER this pass (the -e entry) links the whole - # recompiled chain. Every fn is re-emitted, not just those with concrete - # params, so the embedding refreshes even where a fn gained no param type. - (def order @[]) - (def seen @{}) - (defn visit [k] - (unless (get seen k) - (put seen k true) - (def f (get by-key k)) - (when f - (each c (vview (f :tcalls)) (visit (in (vview c) 0))) - (array/push order f)))) - (each f fns (visit (f :key))) - (each f order - (put report (f :key) (f :pt)) - (def ptmap @{}) - # escaped fn: its param types are untrustworthy (callers not all visible), - # so re-emit it WITHOUT seeding params (still re-embeds recompiled callees). - (unless (get esc (f :key)) - (def pv (vview (f :params))) - (for i 0 (f :np) - (def t (in (f :pt) i)) - (when (and t (not= t :any)) (put ptmap (in pv i) t)))) - (def def2 ((var-get f-reinfer) (f :def) ptmap)) - (protect (eval (emit-ir ctx def2) (ctx-janet-env ctx)))))) - report) - -(defn infer-program! - "Whole-program closed-world pass (jolt-t34, opt-in JOLT_WHOLE_PROGRAM): run ONE - inference fixpoint over every user namespace at once, so param types propagate - across namespace boundaries (the per-ns pass can't see a fn's callers in other - units). Sound only under the closed-world assumption — direct-linking, no later - eval/redefinition — which the flag asserts. The recorded ns list is in load - (topological) order; the fixpoint is order-independent but re-emit is callee- - first regardless." - [ctx] - (def nses (get (ctx :env) :inferred-nses)) - (when (and nses (> (length nses) 0)) - (infer-unit! ctx nses))) - -(defn ensure-macros-compiled! - "Called once the overlay is fully loaded (api/load-core-overlay!): ensure the - analyzer is built, then run the staged macro-recompile pass so the early - (interpreted-during-bootstrap) macro expanders become compiled. Runs in EVERY - mode — macro expansion is compiled code even when evaluation is interpreted - (in interpret mode the tiers load fast interpreted, then this one pass builds - the analyzer and compiles all stashed expanders; the analyzer itself stays - interpreted there). :compile-macros? false (JOLT_INTERPRET_MACROS=1) skips it, - keeping the fully-interpreted oracle. Cheap to call again (recompile-macros! - skips already-compiled vars)." - [ctx] - (when (get (ctx :env) :compile-macros?) - (ensure-analyzer ctx) - (when (analyzer-built? ctx) - # defns first: the expanders call them, and a recompiled expander that - # ran before the defn pass still resolves through the var either way. - (recompile-defns! ctx) - (recompile-macros! ctx)))) diff --git a/src/jolt/cgen.janet b/src/jolt/cgen.janet deleted file mode 100644 index 4cac298..0000000 --- a/src/jolt/cgen.janet +++ /dev/null @@ -1,353 +0,0 @@ -# Native code generation: jolt IR -> C, for hot numeric-leaf fns (jolt-ihdp, the -# lever-1 native-codegen tier of epic jolt-5vsp). The spike -# (docs/foundational-runtime-lever1-native-codegen.md) showed native-C compute -# beats the Janet-VM floor (~18-22x faster than bytecode, edges out JVM Clojure), -# and that compiling a hot LEAF fn to C — called from a bytecode loop — captures -# the win because the forward (bytecode -> C) crossing is nearly free. -# -# This module is the IR -> C translator + a cc/load driver. It is a standalone -# library: nothing wires it into the default compile path yet (that — detecting -# hot fns and installing the C version onto the var cell — is the next step). A -# fn is a candidate only if its whole body is numeric (params/locals/return are -# numbers, all calls are native-op arithmetic): then everything stays in C -# `double`s, unboxed at entry and reboxed at return, with no Janet in the hot loop. -(import ./core_types :as ct) -(import ./phm :as phm) - -(defn- norm-node [n] (if (phm/phm? n) (phm/phm-to-struct n) n)) - -# jolt core fn name -> {:c "" :kind :infix|:incdec}. The subset of -# backend/native-ops that maps to a C double operator with matching semantics. -# (mod/rem/bit-ops/min/max deliberately omitted for now — they need helper calls -# or differ from C operators; add them as the candidate grammar grows.) -(def- c-ops - {"+" {:c "+" :kind :infix} "-" {:c "-" :kind :infix} - "*" {:c "*" :kind :infix} "/" {:c "/" :kind :infix} - "<" {:c "<" :kind :infix} ">" {:c ">" :kind :infix} - "<=" {:c "<=" :kind :infix} ">=" {:c ">=" :kind :infix} - "=" {:c "==" :kind :infix} - "inc" {:c "+" :kind :incdec} "dec" {:c "-" :kind :incdec}}) - -(defn- args-of [node] (ct/vview (node :args))) - -# A native-op invoke -> its c-ops entry, else nil (the head must be a clojure.core -# ref to a supported primitive at the right arity). -(defn- op-for [node] - (def n (norm-node node)) - (def f (and (= :invoke (n :op)) (norm-node (n :fn)))) - (and f (= :var (f :op)) (= "clojure.core" (f :ns)) - (let [op (get c-ops (f :name)) - nargs (length (args-of n))] - (and op - (if (= (op :kind) :incdec) (= 1 nargs) (= 2 nargs)) - op)))) - -# --- candidate check: every node in the body is C-translatable --- -(var- numeric-ok? nil) -(defn- bindings-ok? [node] - (all (fn [pair] (numeric-ok? (in (ct/vview pair) 1))) (ct/vview (node :bindings)))) -(set numeric-ok? - (fn numeric-ok? [raw] - (def node (norm-node raw)) - (case (node :op) - :const (number? (node :val)) - :local true - :if (and (numeric-ok? (node :test)) (numeric-ok? (node :then)) (numeric-ok? (node :else))) - :do (and (all numeric-ok? (ct/vview (node :statements))) (numeric-ok? (node :ret))) - :let (and (bindings-ok? node) (numeric-ok? (node :body))) - :loop (and (bindings-ok? node) (numeric-ok? (node :body))) - :recur (all numeric-ok? (args-of node)) - :invoke (and (op-for node) (all numeric-ok? (args-of node))) - false))) - -(defn fn-ir-of - "Unwrap a :def-of-fn or a bare :fn IR node to the :fn node, or nil." - [ir] - (def n (norm-node ir)) - (def init (norm-node (get n :init n))) - (and (= :fn (init :op)) init)) - -(defn numeric-leaf? - "True when ir is a single-fixed-arity fn whose entire body is C-translatable - (numeric in, numeric out, only native-op arithmetic)." - [ir] - (def fnode (fn-ir-of ir)) - (and fnode - (let [ars (ct/vview (fnode :arities))] - (and (= 1 (length ars)) - (not ((first ars) :rest)) - (numeric-ok? ((first ars) :body)))))) - -# --- C generation --- -# scope: jolt-local-name (string) -> C var name. Fresh C names sidestep charset -# and keyword collisions. rctx (recur target): {:vars [c-names] :flag flag-name}. - -(defn- new-namer [] - (def counter @[0]) - (fn [] (def n (in counter 0)) (put counter 0 (+ n 1)) (string "v" n))) - -(defn- fmtnum [x] - (def s (string/format "%.17g" (* 1.0 x))) - (if (or (string/find "." s) (string/find "e" s) (string/find "n" s)) s (string s ".0"))) - -(var- c-expr nil) -(set c-expr - (fn c-expr [raw scope] - (def node (norm-node raw)) - (case (node :op) - :const (fmtnum (node :val)) - :local (or (get scope (node :name)) (error (string "cgen: unbound local " (node :name)))) - :invoke (let [op (op-for node) as (args-of node)] - (if (= (op :kind) :incdec) - (string "(" (c-expr (in as 0) scope) " " (op :c) " 1)") - (string "(" (c-expr (in as 0) scope) " " (op :c) " " (c-expr (in as 1) scope) ")"))) - (error (string "cgen: non-pure op in expr position: " (node :op)))))) - -(defn- pure? [node] - (case (node :op) :const true :local true :invoke (truthy? (op-for node)) false)) - -# emit-to: append C statements that compute node's (double) value into dest. -# Control-flow forms (if/do/let/loop/recur) lower to statements; pure nodes to a -# single assignment. A comparison yields C int 0/1, which is a fine double here. -(var- emit-to nil) -(set emit-to - (fn emit-to [raw dest scope rctx out namer] - (def node (norm-node raw)) - (case (node :op) - :if (let [t (namer)] - (buffer/push out "double " t ";\n") - (emit-to (node :test) t scope rctx out namer) - (buffer/push out "if (" t " != 0.0) {\n") - (emit-to (node :then) dest scope rctx out namer) - (buffer/push out "} else {\n") - (emit-to (node :else) dest scope rctx out namer) - (buffer/push out "}\n")) - :do (do (each s (ct/vview (node :statements)) - (def junk (namer)) (buffer/push out "double " junk ";\n") - (emit-to s junk scope rctx out namer)) - (emit-to (node :ret) dest scope rctx out namer)) - :let (let [scope2 (table/clone scope)] - (each pair (ct/vview (node :bindings)) - (def p (ct/vview pair)) - (def cv (namer)) - (buffer/push out "double " cv ";\n") - (emit-to (in p 1) cv scope2 rctx out namer) - (put scope2 (string (in p 0)) cv)) - (emit-to (node :body) dest scope2 rctx out namer)) - :loop (let [scope2 (table/clone scope) cvars @[] flag (namer)] - (each pair (ct/vview (node :bindings)) - (def p (ct/vview pair)) - (def cv (namer)) - (buffer/push out "double " cv ";\n") - (emit-to (in p 1) cv scope2 rctx out namer) - (put scope2 (string (in p 0)) cv) - (array/push cvars cv)) - (buffer/push out "int " flag " = 1;\n") - (buffer/push out "while (" flag ") {\n" flag " = 0;\n") - (emit-to (node :body) dest scope2 {:vars cvars :flag flag} out namer) - (buffer/push out "}\n")) - # recur: compute new values into temps first (avoid clobbering loop vars - # mid-update), then assign and set the continue flag. Produces no value — - # the enclosing while re-runs. - :recur (let [as (args-of node) tmps @[]] - (each a as - (def tv (namer)) - (buffer/push out "double " tv ";\n") - (emit-to a tv scope rctx out namer) - (array/push tmps tv)) - (for i 0 (length tmps) - (buffer/push out (in (rctx :vars) i) " = " (in tmps i) ";\n")) - (buffer/push out (rctx :flag) " = 1;\n")) - (if (pure? node) - (buffer/push out dest " = " (c-expr node scope) ";\n") - (error (string "cgen: unsupported op " (node :op))))))) - -(defn- sanitize [name] - (def b @"") - (each c name - (buffer/push b (if (or (and (>= c 97) (<= c 122)) (and (>= c 65) (<= c 90)) - (and (>= c 48) (<= c 57)) (= c 95)) c 95))) - (string b)) - -# Emit just the `static Janet cfun_(...) { ... }` definition for one fn -# into buf. Shared by the single-fn and multi-fn (AOT module) generators. -(defn- emit-cfun [buf ir c-name] - (def fnode (fn-ir-of ir)) - (def ar (first (ct/vview (fnode :arities)))) - (def params (map string (ct/vview (ar :params)))) - (def namer (new-namer)) - (def scope @{}) - (buffer/push buf "static Janet cfun_" c-name "(int32_t argc, Janet *argv) {\n") - (buffer/push buf "janet_fixarity(argc, " (string (length params)) ");\n") - (eachp [i pn] params - (def cv (namer)) - (buffer/push buf "double " cv " = janet_getnumber(argv, " (string i) ");\n") - (put scope pn cv)) - (def ret (namer)) - (buffer/push buf "double " ret ";\n") - (emit-to (ar :body) ret scope nil buf namer) - (buffer/push buf "return janet_wrap_number(" ret ");\n}\n")) - -(defn gen-c-module - "entries: [{:sym :ir } ...] -> C source for - ONE Janet native module exporting every entry's :sym as a cfunction. This is - the AOT/build-time shape (jolt-a7ds): all of an app's hot fns in a single .so, - compiled once at build time. Assumes each :ir is a numeric leaf." - [entries] - (def buf @"") - (buffer/push buf "#include \n") - (each e entries (emit-cfun buf (e :ir) (e :sym))) - (buffer/push buf "static const JanetReg cfuns[] = {\n") - (each e entries - (buffer/push buf " {\"" (e :sym) "\", cfun_" (e :sym) ", NULL},\n")) - (buffer/push buf " {NULL, NULL, NULL}};\n") - (buffer/push buf "JANET_MODULE_ENTRY(JanetTable *env) { janet_cfuns(env, \"cg\", cfuns); }\n") - (string buf)) - -(defn gen-c-fn - "ir (a numeric-leaf :def-of-fn or :fn node), c-name -> C source for a Janet - native module exporting `c-name` as a cfunction. Assumes (numeric-leaf? ir)." - [ir c-name] - (gen-c-module [{:sym c-name :ir ir}])) - -# --- toolchain --- -(defn header-dir - "Directory containing janet.h, probed from syspath + common prefixes, or nil." - [] - (def sp (dyn :syspath)) - (def cands @[(string sp "/../../include") "/opt/homebrew/include" - "/usr/local/include" "/usr/include"]) - (var found nil) - (each c cands (when (and (not found) (os/stat (string c "/janet.h"))) (set found c))) - found) - -(defn toolchain-available? - "True when a C compiler and janet.h are present (so compile-fn can work). Never - throws: a missing cc (not on PATH) makes os/execute raise, so guard it — a - toolchain-less deploy target must get false, not a crash." - [] - (and (header-dir) - (let [r (protect (os/execute ["cc" "--version"] :p - {:out (file/open "/dev/null" :w) - :err (file/open "/dev/null" :w)}))] - (and (r 0) (= 0 (r 1)))))) - -(defn- mkdirs [path] - (def parts (filter |(not (empty? $)) (string/split "/" path))) - (var acc (if (string/has-prefix? "/" path) "" ".")) - (each p parts (set acc (string acc "/" p)) (os/mkdir acc))) - -(defn- cache-dir [] - # Persistent across runs (like the ctx image cache, which also defaults to - # TMPDIR). Override with JOLT_CGEN_CACHE_DIR. - (string (or (os/getenv "JOLT_CGEN_CACHE_DIR") (os/getenv "TMPDIR") "/tmp") "/jolt-cgen")) - -(defn- cc-compile [cpath sopath] - # macOS needs -undefined dynamic_lookup so the module's janet_* refs resolve - # against the host at load time; ELF (Linux/BSD) resolves them then anyway. - (def cmd @["cc" "-shared" "-fPIC" "-O2" (string "-I" (header-dir))]) - (when (= :macos (os/which)) (array/push cmd "-undefined") (array/push cmd "dynamic_lookup")) - (array/push cmd cpath "-o" sopath) - (def r (os/execute cmd :p)) - (unless (= 0 r) (error (string "cgen: cc failed (" r ") for " cpath)))) - -(defn- abspath [p] (if (string/has-prefix? "/" p) p (string (os/cwd) "/" p))) - -# Build a .so from C source, content-addressed and cached. The C + Janet ABI + -# platform fully determine the .so, so a matching cache entry is always valid. -# Returns the absolute .so path. JOLT_CGEN_NO_CACHE=1 forces a rebuild. -(defn- build-so [src dir] - (def stamp (string src "|" janet/version "-" janet/build "|" (os/which))) - (def key (string (band (hash stamp) 0x7FFFFFFF) "-" (length src))) - (mkdirs dir) - (def base (string dir "/cg-" key)) - (def sopath (string base ".so")) - (def abs (abspath sopath)) - (unless (and (not (os/getenv "JOLT_CGEN_NO_CACHE")) (os/stat abs)) - (def cpath (string base ".c")) - (spit cpath src) - (cc-compile cpath sopath)) - abs) - -(defn load-module - "Load a prebuilt cgen .so (NO cc — works on a target with no toolchain) and - return a table of symbol-string -> cfunction for every cfunction it exports. - This is the runtime side of the build-time/AOT path (jolt-a7ds)." - [sopath] - (def env @{}) - (native (abspath sopath) env) - (def out @{}) - (eachp [k v] env - (when (and (symbol? k) (table? v) (or (cfunction? (v :value)) (function? (v :value)))) - (put out (string k) (v :value)))) - out) - -(defn compile-module - "AOT path: compile MANY numeric-leaf fns into ONE native module, once, at build - time. entries: [{:sym :ir } ...]. Returns - {:sopath :fns {sym -> cfunction}}, or nil if the toolchain is absent - or any entry isn't a numeric leaf. opts: :dir (cache dir)." - [entries &opt opts] - (default opts {}) - (when (and (header-dir) (all |(numeric-leaf? ($ :ir)) entries)) - (def src (gen-c-module entries)) - (def sopath (build-so src (get opts :dir (cache-dir)))) - {:sopath sopath :fns (load-module sopath)})) - -(defn compile-fn - "Compile a single numeric-leaf fn IR to a native Janet cfunction. Returns the - cfunction, or nil if ir isn't a candidate or the toolchain is unavailable. - opts: :dir (cache dir, default a persistent jolt-cgen under TMPDIR), :name (C - identifier base). Content-addressed/cached like compile-module." - [ir &opt opts] - (default opts {}) - (when (and (numeric-leaf? ir) (header-dir)) - (def c-name (sanitize (get opts :name "jolt_cfn"))) - (def src (gen-c-fn ir c-name)) - (def sopath (build-so src (get opts :dir (cache-dir)))) - (def env @{}) - (native sopath env) - ((get env (symbol c-name)) :value))) - -# --- AOT build/deploy (jolt-a7ds) --------------------------------------------- -# Build phase (needs cc): collect an app's numeric-leaf fns (the backend's -# :cgen-collect? mode fills (ctx :env) :cgen-collected with [{:ns :name :ir}]), -# compile them all into ONE native module, and write a manifest. Deploy phase -# (NO cc, target needs no toolchain): load the prebuilt module + manifest into a -# qname->cfunction map that the backend installs as var roots (:cgen-prebuilt). - -(defn aot-build - "collected: [{:ns :name :ir} ...] (numeric-leaf fns). Compile them into one - native module and return {:sopath :entries [{:ns :name :sym}]}, or - nil (toolchain absent / a non-leaf / empty). opts: :dir (cache dir). - Syms are positional (f0, f1, ...) so they're collision-free." - [collected &opt opts] - (default opts {}) - (when (and (header-dir) (not (empty? collected))) - (def entries @[]) - (def manifest @[]) - (eachp [i e] collected - (def sym (string "f" i)) - (array/push entries {:sym sym :ir (e :ir)}) - (array/push manifest {:ns (e :ns) :name (e :name) :sym sym})) - (def m (compile-module entries opts)) - (and m {:sopath (m :sopath) :entries manifest}))) - -(defn write-manifest - "Persist an aot-build result to path as jdn (the deploy side reads it)." - [path build] - (spit path (string/format "%j" build))) - -(defn load-aot - "Deploy side (NO cc): read a manifest written by write-manifest, load its - prebuilt .so, and return a qname (\"ns/name\") -> cfunction map suitable for - (ctx :env) :cgen-prebuilt. nil if the manifest/.so is missing." - [manifest-path] - (when (os/stat manifest-path) - (def build (parse (slurp manifest-path))) - (def fns (load-module (build :sopath))) - (def out @{}) - (each e (build :entries) - (when-let [f (get fns (e :sym))] - (put out (string (e :ns) "/" (e :name)) f))) - out)) diff --git a/src/jolt/cgen_build.janet b/src/jolt/cgen_build.janet deleted file mode 100644 index 76a49f0..0000000 --- a/src/jolt/cgen_build.janet +++ /dev/null @@ -1,211 +0,0 @@ -# Single-binary native build (jolt-a7ds, epic jolt-5vsp). The AOT path -# (cgen.janet) compiles an app's numeric-leaf fns into one prebuilt .so + a -# manifest, loaded at deploy with no cc. This module fuses that native code into -# the jpm-built executable so an app ships as ONE static file: no sidecar .so, no -# toolchain on the target. -# -# Shape (validated by the spike, docs/foundational-runtime-lever1-native-codegen.md): -# a staging dir with `src`/`jolt-core` symlinks into the jolt source tree, the -# generated cg.c (native module of the app's hot fns), an uberscript-style bundle -# of the app source, and an entry that bakes the jolt runtime, installs the native -# fns as var roots (:cgen-prebuilt), and runs -main. `jpm build` static-links cg.a -# (declare-native builds it) into the final exe. Build needs cc; the result does -# not. See build-app for the driver and `jolt cgen-build` (main.janet) for the CLI. -(import ./api :as api) -(import ./types :as t) -(import ./cgen :as cgen) - -# --- jolt source location ---------------------------------------------------- -# Baking the runtime into the app binary needs the jolt source tree (src/jolt + -# jolt-core). The shipped binary doesn't carry its own source, so locate a -# checkout: JOLT_HOME wins, else walk up from cwd for the marker files. -(defn- jolt-home? [d] - (and (os/stat (string d "/src/jolt/api.janet")) - (os/stat (string d "/jolt-core")))) - -(defn find-jolt-home - "Directory of a jolt source checkout (has src/jolt + jolt-core), or nil. - JOLT_HOME overrides; otherwise walk up from `start` (default cwd)." - [&opt start] - (def env-home (os/getenv "JOLT_HOME")) - (cond - (and env-home (jolt-home? env-home)) env-home - (do - (var d (or start (os/cwd))) - (var found nil) - (while (and (not found) (> (length d) 1)) - (if (jolt-home? d) - (set found d) - (set d (string/slice d 0 (max 0 (last (string/find-all "/" d))))))) - found))) - -# --- generation -------------------------------------------------------------- -(defn gen-c-and-manifest - "collected: [{:ns :name :ir} ...] (numeric-leaf fns from a :cgen-collect? load). - Emit the C source for ONE native module exporting them all, plus a positional - manifest [{:ns :name :sym} ...] mapping each app fn to its C symbol. Mirrors - cgen/aot-build but yields C source (compiled at build) rather than a .so." - [collected] - (def entries @[]) - (def manifest @[]) - (eachp [i e] collected - (def sym (string "f" i)) - (array/push entries {:sym sym :ir (e :ir)}) - (array/push manifest {:ns (e :ns) :name (e :name) :sym sym})) - {:c-src (cgen/gen-c-module entries) :manifest manifest}) - -(defn bundle-source - "Concatenate the app's loaded source files (load order: deps before dependents) - into one closed-world bundle the baked entry can eval. Verbatim — DCE is the - uberscript path's concern, not needed here for correctness." - [files] - (def buf @"") - (each f files - (buffer/push-string buf "; --- " f " ---\n" (slurp f) "\n")) - (string buf)) - -(defn collect-app - "Load main-ns through the full pipeline with :cgen-collect? on (records the - numeric-leaf fns' IR without swapping roots), returning the collected fns and - the source files loaded (for the bundle). source-roots seed :source-paths so - the app + its deps resolve. Throws on a load error." - [main-ns source-roots] - (def ctx (api/init-cached {:compile? true})) # discarded; cached for speed - (each r source-roots - (when (> (length r) 0) (array/push (get (ctx :env) :source-paths) r))) - (put (ctx :env) :direct-linking? true) - (put (ctx :env) :cgen-collect? true) - (put (ctx :env) :loaded-files @[]) - (api/load-string ctx (string "(require '[" main-ns "])") "") - (def seen @{}) - (def files @[]) - (each f (get (ctx :env) :loaded-files) - (unless (get seen f) (put seen f true) (array/push files f))) - {:collected (or (get (ctx :env) :cgen-collected) @[]) :files files}) - -(defn run-main! - "Runtime helper baked into a generated app binary: bind *command-line-args* to - args (a tuple/array of strings) and invoke main-ns/-main." - [ctx main-ns args] - (def core (t/ctx-find-ns ctx "clojure.core")) - (t/ns-intern core "*command-line-args*" (tuple/slice (tuple ;args))) - (api/eval-string ctx (string "(apply " main-ns "/-main *command-line-args*)"))) - -(defn gen-entry-source - "The generated main.janet: imports the jolt runtime + the static cg module, - builds qname->cfunction from the manifest, bakes the ctx with the app compiled - and the native fns installed as roots, and runs -main at startup. Strings are - emitted with %j so embedded source/manifest can't break the quoting." - [main-ns app-source manifest] - (string - "# Generated by `jolt cgen-build` — do not edit.\n" - "(import \"./src/jolt/api\" :as api)\n" - "(import \"./src/jolt/cgen_build\" :as cb)\n" - "(import \"./cg\" :as cg)\n\n" - "(def manifest " (string/format "%j" manifest) ")\n" - "(def app-source " (string/format "%j" app-source) ")\n" - "(def main-ns " (string/format "%j" main-ns) ")\n\n" - "(def cg-env (require \"./cg\"))\n" - "(def prebuilt\n" - " (let [tb @{}]\n" - " (each e manifest\n" - " (when-let [cell (get cg-env (symbol (e :sym)))]\n" - " (put tb (string (e :ns) \"/\" (e :name)) (get cell :value))))\n" - " tb))\n\n" - "(def ctx (api/init {:compile? true}))\n" - "(put (ctx :env) :direct-linking? true)\n" - "(put (ctx :env) :cgen-prebuilt prebuilt)\n" - "(api/load-string ctx app-source \"app.clj\")\n\n" - "(defn main [&]\n" - " (def args (or (dyn :args) @[]))\n" - " (cb/run-main! ctx main-ns (slice args 1)))\n")) - -(defn gen-project-source - "The generated project.janet. The executable's entry imports cg at build - (dofile) and static-links cg.a, so both must build first — jpm infers neither, - and cg.a isn't pulled into a non-release `build` task, so wire deps explicitly." - [exe-name] - (string - "(declare-project :name \"jolt-cgen-app\")\n\n" - "(declare-native :name \"cg\" :source @[\"cg.c\"])\n\n" - "(declare-executable :name " (string/format "%j" exe-name) " :entry \"main.janet\")\n\n" - "(add-dep \"./" exe-name "\" \"./cg.so\")\n" - "(add-dep \"./" exe-name "\" \"./cg.a\")\n")) - -# --- driver ------------------------------------------------------------------ -(defn- mkdir-p [path] - (def parts (filter |(not (empty? $)) (string/split "/" path))) - (var acc (if (string/has-prefix? "/" path) "" ".")) - (each p parts (set acc (string acc "/" p)) (os/mkdir acc))) - -(defn- rm-rf [path] - # lstat, never stat: the staging dir holds symlinks INTO the jolt tree - # (src, jolt-core); following them would delete real source. A symlink — even - # one pointing at a directory — is removed with os/rm, not recursed into. - (when-let [st (os/lstat path)] - (if (= :directory (st :mode)) - (do (each e (os/dir path) (rm-rf (string path "/" e))) (os/rmdir path)) - (os/rm path)))) - -(defn build-app - "Build main-ns into a single static executable at :out. Needs cc + jpm at build - time; the result needs neither. opts: - :main app namespace (string, required) - :out output binary path (required) - :jolt-home jolt source checkout (default: find-jolt-home) - :source-roots extra source roots for the app + deps (default from JOLT_PATH) - :stage staging dir (default: a fresh temp dir; removed unless :keep) - :keep keep the staging dir for inspection - Returns {:out :native-count :stage }." - [opts] - (def main-ns (assert (opts :main) "cgen-build: :main namespace required")) - (def out (assert (opts :out) "cgen-build: :out path required")) - (def home (or (opts :jolt-home) (find-jolt-home))) - (assert home "cgen-build: could not locate jolt source (set JOLT_HOME)") - (def source-roots - (or (opts :source-roots) - (let [jp (os/getenv "JOLT_PATH")] - (if jp (filter |(> (length $) 0) (string/split ":" jp)) @[])))) - (def exe-name "app") - - # 1. Collect the app's numeric-leaf fns + its full source bundle. - (def {:collected collected :files files} (collect-app main-ns source-roots)) - (def {:c-src c-src :manifest manifest} (gen-c-and-manifest collected)) - (def app-source (bundle-source files)) - - # 2. Stage: symlinks into the jolt tree + the generated build inputs. - (def stage - (or (opts :stage) - (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-cgen-build-" - (string/format "%x" (band (hash (string main-ns out)) 0x7fffffff))))) - (rm-rf stage) - (mkdir-p stage) - (os/symlink (string home "/src") (string stage "/src")) - (os/symlink (string home "/jolt-core") (string stage "/jolt-core")) - (spit (string stage "/cg.c") c-src) - (spit (string stage "/main.janet") (gen-entry-source main-ns app-source manifest)) - (spit (string stage "/project.janet") (gen-project-source exe-name)) - - # 3. jpm build in the staging dir (cwd + JANET_BUILDPATH=. so artifacts land - # beside the entry, where ./cg and cg.a resolve). - (def prev-cwd (os/cwd)) - (def prev-bp (os/getenv "JANET_BUILDPATH")) - (defer (do (os/cd prev-cwd) (os/setenv "JANET_BUILDPATH" prev-bp)) - (os/cd stage) - (os/setenv "JANET_BUILDPATH" ".") - # --workers=1: the build shells out to cc; one worker keeps it from saturating - # every core (it runs inside the parallel test gate, where that starves - # siblings into timeouts). Only a few small C files, so the cost is marginal. - (def code (os/execute ["jpm" "--workers=1" "build"] :p)) - (os/cd prev-cwd) - (unless (= 0 code) (error (string "cgen-build: jpm build failed (" code ")")))) - - # 4. Install the binary, then clean up staging. - (def built (string stage "/" exe-name)) - (assert (os/stat built) (string "cgen-build: expected binary at " built)) - (let [od (string/slice out 0 (max 0 (last (or (string/find-all "/" out) [0]))))] - (when (> (length od) 0) (mkdir-p od))) - (spit out (slurp built)) - (os/chmod out 8r755) - (unless (opts :keep) (rm-rf stage)) - {:out out :native-count (length manifest) :stage stage}) diff --git a/src/jolt/clojure/java/io.clj b/src/jolt/clojure/java/io.clj deleted file mode 100644 index 1f29f23..0000000 --- a/src/jolt/clojure/java/io.clj +++ /dev/null @@ -1,95 +0,0 @@ -; Jolt Standard Library: clojure.java.io -; -; A Janet-backed shim: file I/O via Janet's file/ and os/ through the janet.* -; interop bridge. It deals in plain path strings and Janet file handles, not -; java.io objects — so JVM-specific interop on the results (.toURL, .lastModified, -; …) won't work, but file/reader/writer/resource/copy/slurp do. - -(defn file - "A java.io.File. With a parent and child, joins them with '/'. Returns a - :jolt/file value (instance? File true) with the File method surface; str/slurp - and io/reader coerce it back to its path." - ([path] (__make-file path)) - ([parent child] (__make-file parent child))) - -(defn as-file [x] (if (__file? x) x (__make-file x))) - -(defn as-url - "Coerce `x` to a java.net.URL value (a :jolt/url). Strings are parsed." - [x] - (if (= :jolt/url (get x :jolt/type)) x (java.net.URL. (str x)))) - -(defn reader [x] - (cond - ;; already a reader (java.io shim or janet file handle) — pass through, - ;; like the JVM's io/reader on a Reader - (= :jolt/jio-string-reader (get x :jolt/type)) x - (= :jolt/url (get x :jolt/type)) (java.io.StringReader. (janet/slurp (.getPath x))) - (= :core/file (janet/type x)) x - (sequential? x) (java.io.StringReader. (apply str x)) ; char[] → in-memory reader - ;; a path: an in-memory reader over the file's content — gives the - ;; java.io.Reader surface (.read/.mark/.reset) plus line-seq's - ;; :read-line-fn, which a raw janet file handle has neither of - :else (java.io.StringReader. (janet/slurp (str x))))) -(defn writer [x] - (cond - ;; already a Writer/StringWriter shim — pass through, like the JVM's - ;; io/writer on a Writer (markdown-clj's md-to-html writes into a StringWriter) - (= :jolt/writer (get x :jolt/type)) x - (= :core/file (janet/type x)) x ; already a janet file handle - :else (janet.file/open (str x) :w))) ; a path -(defn input-stream [x] (reader x)) -(defn output-stream [x] (writer x)) - -(defn resource - "Returns a slurp-able path for `path` if it exists, else nil. (Clojure - returns a classpath URL; here the loader's source roots play the classpath - role — the bare path is tried first, then path under each root.)" - [path] - (let [p (str path)] - (if (janet.os/stat p) - p - (loop [roots (seq (__source-roots))] - (when roots - (let [cand (str (first roots) "/" p)] - (if (janet.os/stat cand) - cand - (recur (next roots))))))))) - -(defn delete-file - ([f] (delete-file f false)) - ([f silently] - (try (do (janet.os/rm (str f)) true) - (catch Throwable e (if silently false (throw e)))))) - -(defn make-parents - "Create the parent directories of `f`." - [f] - (let [path (str f) - i (clojure.string/last-index-of path "/")] - (when (and i (pos? i)) - (let [parent (subs path 0 i)] - (make-parents parent) - (when-not (janet.os/stat parent) (janet.os/mkdir parent)))))) - -(defn copy - "Copy from `in` to `out`. A value carrying a truthy `:jolt/output-stream` - marker is treated as a java.io OutputStream (write via its .write); a - `:jolt/input-stream` source is pumped through its .read. This lets host-shim - libraries (e.g. jolt-lang/http-client's byte streams) participate without core - knowing their concrete types. Falls back to the original path/handle copy." - [in out & opts] - (cond - (get out :jolt/output-stream) - (if (get in :jolt/input-stream) - (let [buf (byte-array 8192)] - (loop [] - (let [n (.read in buf 0 8192)] - (when (not= -1 n) - (.write out buf 0 n) - (recur))))) - ;; in is a byte-array / string - (.write out in)) - :else - (let [content (if (string? in) (slurp in) (janet.file/read in :all))] - (if (string? out) (spit out content) (janet.file/write out content))))) diff --git a/src/jolt/clojure/pprint.clj b/src/jolt/clojure/pprint.clj index 20f4d49..4b8bbee 100644 --- a/src/jolt/clojure/pprint.clj +++ b/src/jolt/clojure/pprint.clj @@ -16,10 +16,15 @@ (def ^:dynamic *print-pprint-dispatch* simple-dispatch) (defn pprint - "Print object readably followed by a newline. Writes to *out* (or the given - writer). Not a pretty-printer on jolt — no column-aware layout." + "Print object readably followed by a newline. Not a pretty-printer on jolt — + no column-aware layout. jolt routes all printing through the host output seam + (with-out-str captures it), and *out* is not a bindable var, so an explicit + writer arg is accepted for API compatibility but not honored — output goes to + the current output. (The old `(binding [*out* writer] ...)` never redirected + anything either, and made the defn fall back to the interpreter; dropping it + lets pprint compile cleanly, which the no-fallback Chez back end requires.)" ([object] (prn object)) - ([object writer] (binding [*out* writer] (prn object)))) + ([object _writer] (prn object))) (defmacro with-pprint-dispatch "Evaluate body with the given pprint dispatch selected. On jolt the dispatch is diff --git a/src/jolt/config.janet b/src/jolt/config.janet deleted file mode 100644 index ceef368..0000000 --- a/src/jolt/config.janet +++ /dev/null @@ -1,76 +0,0 @@ -# Build-time collection mode. -# -# Jolt can be built with either immutable (persistent) collections — proper -# Clojure value semantics — or fast Janet-native mutable collections. -# -# jpm build # immutable (default) -# JOLT_MUTABLE=1 jpm build # mutable -# -# This reads the environment at module-load time, so for a jpm-compiled -# executable the value is fixed when the binary is built (a true compile flag). -# `mutable?` is a constant, so the type-mode branches throughout core fold away. -(def mutable? (= "1" (os/getenv "JOLT_MUTABLE"))) - -# Convenience: immutable? is the default. -(def immutable? (not mutable?)) - -# --------------------------------------------------------------------------- -# Run-mode + cache-key policy (jolt-q5ql). Lifted out of main so it is unit- -# testable without the CLI and so the disk-cache keys share ONE canonical list -# of ctx-shaping env vars (a positional %q key silently misaligned if a knob was -# added in only one place — the footgun this fixes). -# --------------------------------------------------------------------------- - -# Every env var that shapes the built/optimized ctx. Both image caches key on -# this exact list, so adding a knob here updates every cache key at once. -(def ctx-shaping-env-vars - ["JOLT_PATH" "JOLT_APP_PATHS" "JOLT_MUTABLE" "JOLT_AOT_CORE" "JOLT_FEATURES" - "JOLT_INTERPRET" "JOLT_INTERPRET_MACROS" "JOLT_DIRECT_LINK" - "JOLT_NO_DIRECT_LINK" "JOLT_OPTIMIZE" "JOLT_WHOLE_PROGRAM" - "JOLT_NO_WHOLE_PROGRAM" "JOLT_SHAPE" "JOLT_NO_SHAPE" - "JOLT_NO_IR_PASSES" "JOLT_CHECK_HINTS" "JOLT_CGEN"]) - -(defn ctx-cache-key - "Build a disk-cache key from labeled prefix pairs plus the value of every - ctx-shaping env var. Each component is tagged by name (`label=value`), so a - new knob can't positionally alias two different builds. `prefix` is a flat - array of label,value,label,value,... (e.g. version + entry ns + opts)." - [prefix] - (def parts @[]) - (var i 0) - (while (< i (length prefix)) - (array/push parts (string/format "%s=%q" (in prefix i) (in prefix (+ i 1)))) - (+= i 2)) - (each ev ctx-shaping-env-vars - (array/push parts (string/format "%s=%q" ev (os/getenv ev)))) - (string/join parts "|")) - -(defn resolve-run-mode - "Resolve the compile/optimization knobs from argv-derived flags + env. - `open-mode?` = an interactive/non-program invocation (repl/-e/help/uberscript); - `main-entry?` = a -m/-M program entry. Returns the ctx env knob map that main - installs. Explicit env always wins (JOLT_NO_DIRECT_LINK / JOLT_DIRECT_LINK)." - [open-mode? main-entry?] - (def dl-forced - (cond (os/getenv "JOLT_NO_DIRECT_LINK") :off - (= "1" (os/getenv "JOLT_DIRECT_LINK")) :on - :none)) - (def dl (case dl-forced :off false :on true (not open-mode?))) - # Inference/specialization is the expensive part — default OFF, opt in with - # JOLT_OPTIMIZE (or an explicit JOLT_DIRECT_LINK, which signals a full build). - (def optimize? - (and dl (or (not (nil? (os/getenv "JOLT_OPTIMIZE"))) - (= "1" (os/getenv "JOLT_DIRECT_LINK"))))) - {:direct-linking? dl - :inline? optimize? - # auto-enabled (vs explicitly requested) — suppresses the checker default-on. - :direct-link-auto? (and dl (= dl-forced :none)) - :shapes? (and dl (not (os/getenv "JOLT_NO_SHAPE"))) - :map-shapes? (and (os/getenv "JOLT_SHAPE") (not (os/getenv "JOLT_NO_SHAPE"))) - :whole-program? (and optimize? - (not (os/getenv "JOLT_NO_WHOLE_PROGRAM")) - (or main-entry? (os/getenv "JOLT_WHOLE_PROGRAM"))) - # Native codegen (jolt-ihdp): compile numeric-leaf fns to C at def time and - # install the cfunction as the var root, so callers direct-link to native - # code. Opt-in (cc latency per fn); needs direct-linking so callers embed it. - :cgen? (and dl (= "1" (os/getenv "JOLT_CGEN")))}) diff --git a/src/jolt/core.janet b/src/jolt/core.janet deleted file mode 100644 index 3c1e0e2..0000000 --- a/src/jolt/core.janet +++ /dev/null @@ -1,336 +0,0 @@ -# Jolt Core Library -# Clojure-compatible core functions for the Jolt interpreter. -# -# This file is the AGGREGATOR (jolt-nma8, phase 2b): the implementation now lives -# in cohesive cluster modules, loaded here in dependency order and re-exported -# (:export true) so every consumer keeps a single `(use ./core)`. The bottom of -# this file owns the registration table (core-bindings) and init-core!, which -# reference fns from every cluster. - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./regex) -(use ./config) -(use ./pv) -(use ./plist) - -# Cluster modules, in load order (each uses the ones before it). :export true -# re-exports each module's OWN defs through core, so `(use ./core)` sees them all. -(import ./core_types :prefix "" :export true) -(import ./core_coll :prefix "" :export true) -(import ./core_print :prefix "" :export true) -(import ./core_io :prefix "" :export true) -(import ./core_refs :prefix "" :export true) -(import ./core_extra :prefix "" :export true) - -(def- core-bindings - "Map of symbol name → function for all core functions." - @{"nil?" core-nil? - "string?" core-string? - "number?" core-number? - "fn?" core-fn? - "keyword?" core-keyword? - "symbol?" core-symbol? - "vector?" core-vector? - "map?" core-map? - "seq?" core-seq? - "coll?" core-coll? - "identical?" core-identical? - "integer?" core-integer? - "list?" core-list? - "+" core-+ - "-" core-sub - "*" core-* - "/" core-/ - "inc" core-inc - "dec" core-dec - "even?" core-even? - "odd?" core-odd? - "mod" core-mod - "rem" core-rem - "quot" core-quot - "rand" core-rand - "=" core-= - "<" core-< - ">" core-> - "<=" core-<= - ">=" core->= - "conj" core-conj - "assoc" core-assoc - "dissoc" core-dissoc - "get" core-get - "contains?" core-contains? - "count" core-count - "format" core-format - "first" core-first - "rest" core-rest - "next" core-next - "cons" core-cons - "seq" core-seq - "vec" core-vec - "__sq1" core-sq1 - "__sqcat" core-sqcat - "__sqvec" core-sqvec - "__sqmap" core-sqmap - "__sqset" core-sqset - "into" core-into - "with-meta" core-with-meta - "map" core-map - "filter" core-filter - "remove" core-remove - "reduce" core-reduce - "apply" core-apply - "map-entry?" core-map-entry? - "future-call" core-future-call - "future?" core-future? - "future-cancel" core-future-cancel - "tagged-literal" core-tagged-literal - "re-groups" core-re-groups - "transient" core-transient - "transient?" core-transient? - "persistent!" core-persistent! - "conj!" core-conj! - "assoc!" core-assoc! - "dissoc!" core-dissoc! - "pop!" core-pop! - "hash-combine" core-hash-combine - "hash-ordered-coll" core-hash-ordered-coll - "hash-unordered-coll" core-hash-unordered-coll - "gensym" gensym - "__write" core-write - "__eprint" core-eprint - "__eprintf" core-eprintf - "__jdbc-wrap-conn" core-jdbc-wrap-conn - "__jdbc-conn-raw" core-jdbc-conn-raw - "__jdbc-make-stmt" core-jdbc-make-stmt - "__make-file" core-make-file - "__file?" core-file? - "__pr-str1" core-pr-str1 - "__make-uuid" make-uuid - "compare" core-compare - "type" core-type - "slurp" core-slurp - "spit" core-spit - "flush" core-flush - "get-thread-bindings" core-get-thread-bindings - "__thread-bound?" core-thread-bound?* - "__dir?" core-dir? - "__list-dir" core-list-dir - "parse-long" core-parse-long - "parse-double" core-parse-double - "current-time-ms" core-current-time-ms - "mapcat" core-mapcat - "sequence" core-sequence - "keyword" core-keyword - "symbol" core-symbol - "namespace" core-namespace - "reduced" core-reduced - "reduced?" core-reduced? - "rseq" core-rseq - "ex-info" core-ex-info - "__with-out-str" core-with-out-str - "delay?" core-delay? - "make-delay" core-make-delay - "take" core-take - "drop" core-drop - "take-while" core-take-while - "drop-while" core-drop-while - "concat" core-concat - "nth" core-nth - "sort" core-sort - "partition" core-partition - "range" core-range - "vector" core-vector - "hash-map" core-hash-map - "array-map" core-array-map - "hash-set" core-hash-set - "set" core-set - "list" core-list - "set?" core-set? - "disj" core-disj - "coll->cells" coll->cells - "make-lazy-seq" make-lazy-seq - "lazy-cons" lazy-cons - "lazy-from" lazy-from - "str" core-str - "name" core-name - "subs" core-subs - "str-trim" string/trim - "str-upper" string/ascii-upper - "str-lower" string/ascii-lower - "str-find" string/find - "str-replace" core-str-replace-first - "str-replace-all" core-str-replace-all - "str-reverse-b" string/reverse - "str-join" core-str-join - "str-split" core-str-split - "re-pattern" re-pattern - "re-find" re-find - "re-matches" re-matches - "re-seq" re-seq - "regex?" regex? - "str-triml" string/triml - "str-trimr" string/trimr - # Java-style arrays (buffers for bytes, arrays otherwise) - "aclone" core-aclone - "object-array" core-object-array - "int-array" core-int-array - "long-array" core-long-array - "short-array" core-short-array - "double-array" core-double-array - "float-array" core-float-array - "char-array" core-char-array - "boolean-array" core-boolean-array - "byte-array" core-byte-array - "aset-byte" core-aset-byte - "aset-int" core-aset-int - "aset-long" core-aset-long - "aset-short" core-aset-short - "aset-double" core-aset-double - "aset-float" core-aset-float - "aset-char" core-aset-char - "aset-boolean" core-aset-boolean - "make-array" core-make-array - "into-array" core-into-array - "to-array" core-to-array - "bytes" core-bytes - "booleans" core-booleans - "ints" core-ints - "longs" core-longs - "shorts" core-shorts - "doubles" core-doubles - "floats" core-floats - "chars" core-chars - "byte" core-byte - "short" core-short - "bigint" core-bigint - "biginteger" core-biginteger - "chunk-buffer" core-chunk-buffer - "chunk-append" core-chunk-append - "chunk" core-chunk - "chunk-first" core-chunk-first - "chunk-rest" core-chunk-rest - "chunk-next" core-chunk-next - "chunk-cons" core-chunk-cons - "boolean" core-boolean - "cat" core-cat - "disj!" core-disj! - "reader-conditional" core-reader-conditional - "class" core-class - "re-matcher" core-re-matcher - # Bit operations - "__bit-and" core-bit-and - "__bit-or" core-bit-or - "__bit-xor" core-bit-xor - "bit-not" core-bit-not - "bit-shift-left" core-bit-shift-left - "bit-shift-right" core-bit-shift-right - "bit-clear" core-bit-clear - "bit-set" core-bit-set - "bit-flip" core-bit-flip - "bit-test" core-bit-test - "__bit-and-not" core-bit-and-not - "unsigned-bit-shift-right" core-unsigned-bit-shift-right - # Integer coercion / unchecked math - "int" core-int - "long" core-long - "double" core-double - "float" core-float - "char" core-char - # Hash - "hash" core-hash - "atom" core-atom - "deref" core-deref - "reset!" core-reset! - "swap!" core-swap! - "not" core-not - "Object" core-Object - "make-protocol" core-make-protocol - # satisfies?/resolve are interned by install-stateful-fns! (ctx-capturing); - # type->str was an inert SCI stub with no callers. - "implements?" core-implements? - "volatile!" core-volatile! - "Thread" core-Thread - "ThreadLocal" core-ThreadLocal - "IllegalStateException" core-IllegalStateException - "copy-core-var" core-copy-core-var - "copy-var" core-copy-var - "macrofy" core-macrofy - "new-var" core-new-var - "__local-var" core-local-var - "__close" core-close-resource - "avoid-method-too-large" core-avoid-method-too-large - "bytes?" core-bytes? - "meta" core-meta - "var-get" core-var-get - "var-set" core-var-set - "var?" core-var? - "var-dynamic?" core-var-dynamic? - "alter-var-root" core-alter-var-root - "alter-meta!" core-alter-meta! - "reset-meta!" core-reset-meta! - "push-thread-bindings" core-push-thread-bindings - "pop-thread-bindings" core-pop-thread-bindings - # Dynamic vars — stubs for SCI bootstrap - "*unchecked-math*" false - "*clojure-version*" @{:major 1 :minor 11 :incremental 0 :qualifier nil} - "*1" :jolt/nil-sentinel - "*2" :jolt/nil-sentinel - "*3" :jolt/nil-sentinel - "*e" :jolt/nil-sentinel - "*assert" true}) - -(defn core-macro-names - "Set of core binding names that are macros. Empty now that every core macro - lives in the Clojure overlay (clojure.core.*-syntax / *-macros tiers)." - [] - @{}) - -# Wire the print-method callback once the overlay (and its print-method -# multimethod) exists: the renderer's record fallthrough consults the methods -# table on the var; only a USER-registered method fires — the multimethod's -# :default would bounce straight back into the renderer. -(defn install-print-method-cb! [ctx] - (def core-ns (ctx-find-ns ctx "clojure.core")) - (def pm-var (ns-find core-ns "print-method")) - (when pm-var - (set-print-method-cb! - (fn [v emit] - (def methods (get pm-var :jolt/methods)) - (when methods - (def mt (core-meta v)) - (def t (and mt (core-get mt :type))) - (def dval (if (keyword? t) t (core-type v))) - (def m (get methods dval)) - (when m - (m v @{:jolt/type :jolt/writer :sink emit}) - true))))) - # A record/deftype's own Object/toString (jolt-rt6n): str routes records here - # so a deftype with (toString [_] ...) renders via it instead of the data repr. - (set-record-tostring-cb! - (fn [v] - (def tag (record-tag v)) - (when tag - (def m (find-method-any-protocol ctx tag "toString")) - (when m (m v)))))) - -(def init-core! - (fn [& args] - (case (length args) - 1 (let [ctx (args 0) - ns (ctx-find-ns ctx "clojure.core")] - (loop [[name fn] :pairs core-bindings] - (def v (ns-intern ns name (if (= fn :jolt/nil-sentinel) nil fn))) - (when (get (core-macro-names) name) - (put v :macro true))) - ns) - 2 (let [ctx (args 0) ns-name (args 1) - ns (ctx-find-ns ctx ns-name)] - (loop [[name fn] :pairs core-bindings] - (def v (ns-intern ns name (if (= fn :jolt/nil-sentinel) nil fn))) - (when (get (core-macro-names) name) - (put v :macro true))) - ns) - (error "Wrong number of args passed to: init-core!")))) diff --git a/src/jolt/core_coll.janet b/src/jolt/core_coll.janet deleted file mode 100644 index 53fac0f..0000000 --- a/src/jolt/core_coll.janet +++ /dev/null @@ -1,1198 +0,0 @@ -# Jolt Core — collections, transducers, seqs, HOFs, constructors -# Extracted from core.janet (jolt-nma8, phase 2b split). -# -# REP vs API: this file holds the Clojure-facing collection ops and dispatches -# on `:jolt/type` over the internal persistent structures, whose representations -# live elsewhere: persistent vector → pv.janet, list → plist.janet, hash map → -# phm.janet, set → phs.janet, lazy seq → lazyseq.janet. Grep a structure's file -# header for the primitive (pv-*/pl-*/phm-*/phs-*/ls-*) it exposes. - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./regex) -(use ./config) -(use ./pv) -(use ./plist) -(use ./core_types) -# Collections -# ============================================================ - -# Small maps are Janet structs (native, O(1) get) but assoc copies them whole -# (O(n)); past this many entries a map promotes to the phm HAMT (O(log n) assoc) -# so incremental building isn't O(n^2). Mirrors cljs PersistentArrayMap's -# HASHMAP-THRESHOLD (jolt-684u). -(def- map-array-threshold 8) - -# Is x a map value (for conj/merge semantics: conj-ing a map merges its entries)? -(defn- map-value? [x] - (or (phm? x) (and (struct? x) (nil? (get x :jolt/type))))) - -# --- Sorted collections (sorted-map / sorted-set) ------------------------------- -# Pure Clojure now (stage 3, jolt-0lj — jolt-core/clojure/core/25-sorted.clj). -# A sorted coll is a tagged table {:jolt/type .. :entries SORTED-VECTOR :cmp -# :ops {kw fn}} whose ops travel WITH the value, so the seed's dispatch -# branches below are each a one-line call through (coll :ops) — no module-level -# hooks, correct across contexts/forks/AOT images. The tag predicates and the -# entries view live near the top of this module (canon-key/empty?/equality -# need them); only this dispatch accessor is left here. -(defn sorted-op - "The overlay-attached implementation of `op` for sorted coll `coll`." - [coll op] - (get (coll :ops) op)) - -# Merge conj items onto a map receiver. assoc1 is phm-assoc for a phm receiver, -# map-assoc1 for a struct/host-table receiver — the only thing that differs -# between the two map-conj paths. -(defn- conj-into-map [coll xs assoc1] - (var result coll) - (each x xs - (cond - # conj nil onto a map is a no-op (Clojure) - (nil? x) nil - # conj a map -> merge its entries - (map-value? x) - (each e (map-entries-of x) (set result (assoc1 result (in e 0) (in e 1)))) - # a [k v] entry: exactly a 2-element vector (Clojure throws otherwise — and - # merge inherits this strictness through conj) - (and (or (pvec? x) (tuple? x) (array? x)) (= 2 (vcount x))) - (set result (assoc1 result (vnth x 0) (vnth x 1))) - (error "Vector arg to map conj must be a pair"))) - result) - -# Dispatch is on :jolt/type via one case (the type is fetched once and the arm -# calls the concrete op directly) rather than a chain of (and (table? x) (= ..)) -# predicates — same hot-path cost as the predicate chain for the common types, -# one place per op. Host values (tuple/array/nil) and tuple-based shape-recs -# carry no :jolt/type and stay in the per-op fallback. -(defn core-conj [& args] - (if (= 0 (length args)) (make-vec @[]) # (conj) -> [] - (let [coll (first args) xs (tuple/slice args 1)] - (if (table? coll) - (case (get coll :jolt/type) - :jolt/pvec (do (var r coll) (each x xs (set r (pv-conj r x))) r) - :jolt/phm (conj-into-map coll xs phm-assoc) - # list: prepend, O(1) per element via structural sharing - :jolt/plist (do (var r coll) (each x xs (set r (pl-cons x r))) r) - # conj onto a seq prepends (Clojure: a Cons cell) - :jolt/lazy-seq (do (var r coll) (each x xs (set r (pl-cons x (realize-for-iteration r)))) r) - :jolt/set (apply phs-conj coll xs) - :jolt/sorted-map ((sorted-op coll :conj) coll xs) - :jolt/sorted-set ((sorted-op coll :conj) coll xs) - # other tables (raw host table / deftype instance) conj like a map - (conj-into-map coll xs map-assoc1)) - (cond - # conj onto nil builds a list (prepends): (conj nil 1 2) -> (2 1) - (nil? coll) (do (var r nil) (each x xs (set r (pl-cons x r))) r) - (tuple? coll) (tuple/slice (tuple ;(array/concat (array/slice coll) xs))) - (array? coll) - (if mutable? - # mutable mode: arrays are vectors — append in place - (do (each x xs (array/push coll x)) coll) - # immutable mode: arrays are lists — prepend onto a persistent cons - # node, sharing the original array as the tail (O(1) per element) - (do (var r coll) (each x xs (set r (pl-cons x r))) r)) - # struct map literal: merge entries - (conj-into-map coll xs map-assoc1)))))) - -(defn core-assoc [m & kvs] - (when (odd? (length kvs)) - (error "assoc expects an even number of key/value arguments")) - # assoc is defined on maps, vectors and nil; reject other shapes - (when (or (number? m) (string? m) (buffer? m) (keyword? m) (boolean? m) - (plist? m) (set? m) (core-transient? m) (core-sorted-set? m) - (and (struct? m) (get m :jolt/type))) - (error (string "assoc requires a map or vector, got " (type m)))) - (cond - (shape-rec? m) - (do (var result m) (var i 0) - (while (< i (length kvs)) (set result (shape-assoc result (kvs i) (kvs (+ i 1)))) (+= i 2)) - result) - (core-sorted-map? m) ((sorted-op m :assoc) m kvs) - (phm? m) - (do (var result m) (var i 0) (while (< i (length kvs)) (set result (phm-assoc result (kvs i) (kvs (+ i 1)))) (+= i 2)) result) - (pvec? m) - (do (var result m) (var i 0) - (while (< i (length kvs)) - (let [idx (kvs i)] - (when (not (and (number? idx) (= idx (math/floor idx)) (>= idx 0) (<= idx (pv-count result)))) - (error (string "Index " idx " out of bounds for assoc on a vector of length " (pv-count result)))) - (set result (pv-assoc result idx (kvs (+ i 1))))) - (+= i 2)) result) - # vector: assoc by integer index (appending at count is allowed); stays a vector - (or (tuple? m) (array? m)) - (do (var result (array/slice m)) (var i 0) - (while (< i (length kvs)) - (let [idx (kvs i) v (kvs (+ i 1))] - (when (not (and (number? idx) (= idx (math/floor idx)) (>= idx 0) (<= idx (length result)))) - (error (string "Index " idx " out of bounds for assoc on a vector of length " (length result)))) - (if (= idx (length result)) (array/push result v) (put result idx v))) - (+= i 2)) - (if (tuple? m) (tuple/slice (tuple ;result)) result)) - # map (struct/table). Promote to a phm when (a) any new key is a collection - # (a Janet struct/table would key it by identity) or any new key/value is nil - # (a struct drops nil; phm preserves it), or (b) the result would exceed the - # small-map threshold — a Janet struct copies wholesale on assoc (O(n)), so a - # growing map must ride the phm HAMT (O(log n)) past ~8 entries. Mirrors cljs - # PersistentArrayMap -> PersistentHashMap (jolt-684u). m is a struct here - # (phm handled above), so only the current size + new kvs matter. - (let [coll-key (do (var c false) (var i 0) - (while (< i (length kvs)) - (let [k (in kvs i) v (in kvs (+ i 1))] - (when (or (table? k) (array? k) (nil? k) (nil? v)) (set c true))) - (+= i 2)) c) - promote (or coll-key - (> (+ (if m (length m) 0) (/ (length kvs) 2)) map-array-threshold))] - (if promote - (do (var result (make-phm)) - (when m (each k (keys m) (set result (phm-assoc result k (get m k))))) - (var i 0) (while (< i (length kvs)) (set result (phm-assoc result (in kvs i) (in kvs (+ i 1)))) (+= i 2)) - result) - (do (var result @{}) (when m (each k (keys m) (put result k (get m k)))) - (var i 0) (while (< i (length kvs)) (let [k (kvs i) v (kvs (+ i 1))] (put result k v) (+= i 2))) - # nil assocs to a fresh immutable map ((assoc nil :a 1) => {:a 1}); a - # raw table here would not count?/seq like a Clojure map (assoc-in into - # an absent key recurses through nil — migratus's migration maps). - (if (or (struct? m) (nil? m)) (table/to-struct result) result)))))) - -(defn core-dissoc [m & ks] - (cond - (nil? m) nil - # dissoc loses a key -> the shape changes; bridge through a struct (cold op) - (shape-rec? m) (core-dissoc (shape->struct m) ;ks) - (core-sorted-map? m) ((sorted-op m :dissoc) m ks) - (phm? m) (do (var result m) (each k ks (set result (phm-dissoc result k))) result) - # reject clearly non-map values (scalars, sequences, sets, symbol/char structs) - (or (number? m) (string? m) (buffer? m) (keyword? m) (boolean? m) - (pvec? m) (plist? m) (tuple? m) (array? m) (set? m) (core-transient? m) - (and (struct? m) (get m :jolt/type))) - (error (string "dissoc requires a map, got " (type m))) - # struct map / sorted-map / record / meta-wrapped map - (do (var result @{}) (each k (keys m) (var in-ks false) (each k2 ks (if (deep= k k2) (do (set in-ks true) (break)))) (if (not in-ks) (put result k (m k)))) - (if (struct? m) (table/to-struct result) result)))) - -(defn core-get [m k &opt default] - (default default nil) - (if (nil? m) default - # inline the shape check (no fn call) so non-shape gets pay only a tuple? test - (if (and (tuple? m) (> (length m) 0) (struct? (in m 0)) (not (nil? (in (in m 0) :jolt/shape)))) - (shape-get m k default) - (if (core-sorted? m) ((sorted-op m :get) m k default) - (if (core-transient? m) - (case (m :kind) - :vector (if (and (number? k) (>= k 0) (< k (length (m :arr)))) (in (m :arr) k) default) - :map (let [p (get (m :tbl) (tbl-key k))] (if p (in p 1) default)) - :set (if (nil? (get (m :tbl) (tbl-key k))) default k)) - (if (set? m) (phs-get m k default) - (if (phm? m) (phm-get m k default) - (if (pvec? m) - (if (and (number? k) (>= k 0) (< k (pv-count m))) (pv-nth m k) default) - (if (or (struct? m) (table? m)) - (let [v (m k)] - (if (nil? v) default v)) - (if (and (or (tuple? m) (array? m)) (number? k) (>= k 0) (< k (length m))) - (in m k) - # Clojure's get indexes strings too (returns the char) — reitit's path - # parser relies on (get path i). nth already did; get did not, so - # (get "a:b" 1) was nil. - (if (and (or (string? m) (buffer? m)) (number? k) (>= k 0) (< k (length m))) - (make-char (in m k)) - default))))))))))) - -# Runtime invoke dispatch for COMPILED code (interpreter uses evaluator's -# jolt-invoke). Handles real functions plus Clojure IFn collections. -(defn jolt-call [f & args] - (cond - (or (function? f) (cfunction? f)) (apply f args) - # a var is callable as its current value (Clojure vars implement IFn) - (var? f) (apply jolt-call (var-get f) args) - (shape-rec? f) (core-get f (get args 0) (get args 1)) - (keyword? f) (core-get (get args 0) f (get args 1)) - (and (struct? f) (= :symbol (f :jolt/type))) (core-get (get args 0) f (get args 1)) - (core-sorted? f) ((sorted-op f :get) f (get args 0) (get args 1)) - (phm? f) (phm-get f (get args 0) (get args 1)) - (set? f) (if (phs-contains? f (get args 0)) (get args 0) (get args 1)) - (pvec? f) - (let [k (get args 0)] - (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (pv-count f))) - (pv-nth f k) - (error (string "Index " k " out of bounds for vector of length " (pv-count f))))) - (or (tuple? f) (array? f)) - (let [k (get args 0)] - (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (length f))) - (in f k) - (error (string "Index " k " out of bounds for vector of length " (length f))))) - # Map literal (struct with no :jolt/type marker) or a record: callable as a - # key lookup. A TAGGED struct (char/etc.) is NOT a fn — symbols are handled - # above; everything else with a :jolt/type falls through to the error. - (or (and (struct? f) (nil? (get f :jolt/type))) (and (table? f) (get f :jolt/deftype))) - (let [v (get f (get args 0) :jolt/not-found)] - (if (= v :jolt/not-found) (get args 1) v)) - (error (string "Cannot call " (type f) " as a function")))) - -(defn core-apply - "(apply f a b ... coll) — call f with the leading args plus the elements of - the final collection spliced in. Materializes pvec/lazy-seq/set tails." - [f & args] - (let [n (length args)] - (if (= n 0) - (jolt-call f) - (let [fixed (array/slice args 0 (- n 1)) - t (in args (- n 1)) - tail (cond (nil? t) [] # (apply f x nil) == (f x), as in Clojure - (set? t) (phs-seq t) (phm? t) (tuple ;(phm-entries t)) - (realize-for-iteration t))] - (jolt-call f ;fixed ;tail))))) - -# get-in now lives in the Clojure collection tier (core/20-coll.clj). - -(defn core-contains? [coll key] - (if (shape-rec? coll) (shape-contains? coll key) - (if (core-sorted? coll) (if ((sorted-op coll :contains) coll key) true false) - (if (core-transient? coll) - (case (coll :kind) - :vector (and (number? key) (>= key 0) (< key (length (coll :arr)))) - (not (nil? (get (coll :tbl) (tbl-key key))))) - (if (set? coll) (phs-contains? coll key) - (if (phm? coll) (phm-contains? coll key) - (if (pvec? coll) (and (number? key) (>= key 0) (< key (pv-count coll))) - (if (struct? coll) (not (nil? (coll key))) - (if (table? coll) (not (nil? (coll key))) - (if (or (tuple? coll) (array? coll)) - (and (number? key) (>= key 0) (< key (length coll))) - false)))))))))) - -# Coerce a Clojure IFn value to a Janet-callable fn for higher-order fns -# (map/filter/sort-by/group-by/...). Janet functions pass through; a keyword or -# symbol becomes a key lookup, a map a key lookup, a set a membership test — so -# (map :k coll), (sort-by :k coll), (filter a-set coll) work. -(defn- as-fn [f] - (cond - (or (function? f) (cfunction? f)) f - (keyword? f) (fn [x &opt d] (core-get x f d)) - (core-symbol? f) (fn [x &opt d] (core-get x f d)) - (phm? f) (fn [k &opt d] (core-get f k d)) - (set? f) (fn [x &opt d] (if (core-contains? f x) x d)) - true f)) - -# Sorted collections — minimal: backed by a struct (map) / sorted array (set), -# ordered by key/element on read. Defined early so seq/count/get can dispatch. -# sorted-map/sorted-set predicates, constructors and ops live ABOVE core-conj so -# the collection fns (conj/assoc/get/contains?/…) can branch on them. - -(defn core-count [coll] - (if (table? coll) - (case (get coll :jolt/type) - :jolt/pvec (pv-count coll) - :jolt/phm (coll :cnt) - :jolt/plist (pl-count coll) - :jolt/set (coll :cnt) - :jolt/lazy-seq (ls-count coll) - :jolt/sorted-map ((sorted-op coll :count) coll) - :jolt/sorted-set ((sorted-op coll :count) coll) - :jolt/transient (length (if (= :vector (coll :kind)) (coll :arr) (coll :tbl))) - # other tables: a deftype record instance counts its fields; a raw host - # table is unsupported (matches the original — seq handles it, count never did) - (if (get coll :jolt/deftype) (- (length (keys coll)) 1) - (error (string "count not supported on " (type coll))))) - (cond - (nil? coll) 0 - (shape-rec? coll) (shape-count coll) # shape-recs are tuples, not tables - (or (string? coll) (buffer? coll) (struct? coll) (tuple? coll) (array? coll)) (length coll) - # count is undefined on scalars (numbers/keywords/symbols/booleans/chars) - (error (string "count not supported on " (type coll)))))) - -(defn core-first [coll] - (cond - (shape-rec? coll) (core-first (shape->struct coll)) - (core-sorted? coll) ((sorted-op coll :first) coll) - (lazy-seq? coll) (ls-first coll) - (pvec? coll) (if (= 0 (pv-count coll)) nil (pv-nth coll 0)) - (plist? coll) (if (pl-empty? coll) nil (pl-first coll)) - # maps and sets: first of their seq (an entry / element) - (phm? coll) (let [e (phm-entries coll)] (if (= 0 (length e)) nil (in e 0))) - (set? coll) (let [s (phs-seq coll)] (if (= 0 (length s)) nil (in s 0))) - (and (struct? coll) (nil? (get coll :jolt/type))) - (let [ks (keys coll)] (if (= 0 (length ks)) nil (tuple (in ks 0) (get coll (in ks 0))))) - (nil? coll) nil - (string? coll) (if (= 0 (length coll)) nil (make-char (in coll 0))) - # scalars aren't seqable - (or (number? coll) (boolean? coll) (keyword? coll) (and (struct? coll) (get coll :jolt/type))) - (error (string "first not supported on " (type coll))) - (= 0 (length coll)) nil - (in coll 0))) - -(defn- seq-done? - "True when cursor c (a lazy-seq or a concrete collection) is exhausted. - Uses cell realization for lazy-seqs so nil elements don't end the seq early." - [c] - (if (lazy-seq? c) - (let [cell (realize-ls c)] - (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell)))) - (or (nil? c) (= 0 (length c))))) - -(defn core-rest [coll] - (cond - # rest never returns nil — Clojure's rest yields () on an exhausted seq. - (lazy-seq? coll) (let [r (ls-rest coll)] (if (nil? r) @[] r)) - (plist? coll) (pl-rest coll) - # Indexed collections: an O(1) lazy view from index 1 (Clojure: rest of a - # vector is a seq, not a vector). Slicing per step made first/rest loops - # over concrete collections O(n^2) — a 20k rest-loop took two seconds. - # These stay ABOVE the set/map branches: rest-of-vector is every seq loop's - # hot path and must not pay the wrapper-tag checks. - (pvec? coll) (let [a (pv->array coll)] - (if (<= (length a) 1) @[] - (make-lazy-seq (fn [] (indexed-cells a 1))))) - (or (nil? coll) (= 0 (length coll))) @[] - (string? coll) (tuple ;(map make-char (string/bytes (string/slice coll 1)))) - (tuple? coll) (if (<= (length coll) 1) @[] - (make-lazy-seq (fn [] (indexed-cells coll 1)))) - # Sets, maps and sorted colls rest via their seq. Without these branches - # they fell into the indexed fall-through, which walked the wrapper table's - # INTERNAL fields — (next #{1 2}) was (nil nil) until the canonical every? - # started seq-walking sets (seed-shrink round 4). - (set? coll) (if (= 0 (coll :cnt)) @[] (core-rest (phs-seq coll))) - (phm? coll) (if (= 0 (coll :cnt)) @[] (core-rest (tuple ;(phm-entries coll)))) - (core-sorted? coll) (core-rest ((sorted-op coll :seq) coll)) - # plain struct maps (untagged literals) rest via entries too - (and (struct? coll) (nil? (get coll :jolt/type))) - (core-rest (tuple ;(map-entries-of coll))) - (if (<= (length coll) 1) @[] - (make-lazy-seq (fn [] (indexed-cells coll 1)))))) - -(defn core-next [coll] - # next is rest, but nil when the rest is empty. seq-done? realizes one lazy - # cell so a lazy rest that turns out empty (length on the table won't tell us) - # collapses to nil, matching Clojure. - (let [r (core-rest coll)] - (if (seq-done? r) nil r))) - -(defn core-cons [x coll] - "Prepend x onto coll. For concrete collections this is an O(1) persistent cons - node; for lazy-seqs it stays a lazy cell so laziness is preserved." - (cond - # Lazy tail: return a LazySeq (NOT a bare cell), so a cons-of-a-cons stays a - # proper lazy-seq and the rest-thunk never leaks as a plain array element. - (lazy-seq? coll) (make-lazy-seq (fn [] @[x (fn [] coll)])) - (or (nil? coll) (plist? coll) (array? coll) (tuple? coll)) (pl-cons x coll) - # second arg must be seqable (a collection or string); reject scalars - (not (or (core-coll? coll) (string? coll))) - (error (string "Don't know how to create ISeq from: " (type coll))) - (pl-cons x (realize-for-iteration coll)))) - -(defn core-seq [coll] - (if (table? coll) - (case (get coll :jolt/type) - :jolt/pvec (if (= 0 (pv-count coll)) nil (tuple ;(pv->array coll))) - # empty maps/sets seq to nil, as in Clojure ((seq {}) is nil, not ()) - :jolt/phm (if (= 0 (coll :cnt)) nil (tuple ;(phm-entries coll))) - :jolt/plist (if (pl-empty? coll) nil (tuple ;(pl->array coll))) - # Cell-based emptiness, NOT (nil? (ls-first)): a lazy-seq whose first - # element is legitimately nil is non-empty, so (seq (cons nil ...)) is not nil. - :jolt/lazy-seq (let [cell (realize-ls coll)] - (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) nil coll)) - :jolt/set (if (= 0 (coll :cnt)) nil (phs-seq coll)) - :jolt/sorted-map ((sorted-op coll :seq) coll) - :jolt/sorted-set ((sorted-op coll :seq) coll) - # deftype instance seqs as itself; raw host table (System/getenv) as kv map - (if (get coll :jolt/deftype) coll - (if (= 0 (length coll)) nil - (tuple ;(map (fn [k] (tuple k (get coll k))) (keys coll)))))) - (cond - # shape-recs are tuples — must precede the tuple? branch - (shape-rec? coll) (tuple ;(map (fn [k] (tuple k (shape-get coll k nil))) (shape-keys coll))) - (nil? coll) nil - (buffer? coll) (if (= 0 (length coll)) nil (let [a @[]] (each x coll (array/push a x)) (tuple ;a))) - (tuple? coll) (if (= 0 (length coll)) nil (tuple/slice coll)) - (string? coll) (if (= 0 (length coll)) nil (tuple ;(map make-char (string/bytes coll)))) - (struct? coll) (if (= 0 (length coll)) nil (tuple ;(map (fn [k] (tuple k (get coll k))) (keys coll)))) - (array? coll) (if (= 0 (length coll)) nil (tuple ;coll)) - # scalars/functions aren't seqable - (error (string "seq not supported on " (type coll)))))) - -(defn core-vec [coll] - (when (not (or (nil? coll) (core-coll? coll) (string? coll))) - (error (string "Don't know how to create a vector from " (type coll)))) - (let [coll (realize-for-iteration coll)] - (cond - (array? coll) (make-vec coll) - (tuple? coll) (make-vec coll) - (struct? coll) (make-vec (map |(in (kvs coll) (+ (* $ 2) 1)) (range (/ (length (kvs coll)) 2)))) - (string? coll) (make-vec (map make-char (string/bytes coll))) - (make-vec @[])))) - -# Bulk-build a map value from a native array of [k v] pairs, mirroring -# core-assoc's struct-vs-phm choice: stay a small Janet struct (the -# PersistentArrayMap analog) when every key is a scalar, there is no nil key or -# value, and the distinct count is within the threshold; otherwise bulk-build -# the HAMT once (phm-from-pairs). Used by into-a-struct-map (jolt-5vsp). -(defn- bulk-map-from-pairs [pairs] - (var promote false) - (def t @{}) - (each p pairs - (def k (vnth p 0)) (def v (vnth p 1)) - (if (or (table? k) (array? k) (nil? k) (nil? v)) - (set promote true) - (put t k v))) # scalar keys: last-wins - (if (or promote (> (length t) map-array-threshold)) - (phm-from-pairs pairs) - (table/to-struct t))) - -(defn- into-conj [to items] - (cond - # into onto an existing phm stays a phm: accumulate its entries + the new - # [k v] items and bulk-build the HAMT ONCE (phm-from-pairs, last-value-wins), - # instead of a phm-assoc per element. jolt-5vsp collections. - (phm? to) - (let [acc (array)] - (each e (phm-entries to) (array/push acc e)) - (each item items (array/push acc [(vnth item 0) (vnth item 1)])) - (phm-from-pairs acc)) - # into onto a plain map struct (e.g. the {} literal): same one-pass build, - # but keep the small-scalar-map-stays-a-struct rule (bulk-map-from-pairs) so - # the representation matches the incremental assoc-onto-a-struct path. - (and (struct? to) (nil? (get to :jolt/type))) - (let [acc (array)] - (each e (pairs to) (array/push acc e)) - # each item is either a [k v] pair OR a map whose entries are merged - # (Clojure: (into {} [{:a 1} {:b 2}]) => {:a 1 :b 2}) - (each item items - (if (map-value? item) - (each e (map-entries-of item) (array/push acc e)) - (array/push acc [(vnth item 0) (vnth item 1)]))) - (bulk-map-from-pairs acc)) - # Other map-likes (sorted maps, deftype records): fold core-conj (handles - # both [k v] pairs and map items). - (or (struct? to) (and (table? to) (get to :jolt/deftype))) - (do (var result to) - (each item items (set result (core-conj result item))) - result) - # Accumulate into a native array and bulk-build the pvec ONCE (pv-from-indexed), - # instead of an immutable pv-conj per element (each allocating a wrapper + - # copying the tail). This is the transient-style fast path for into-a-vector. - (pvec? to) (let [arr (array/slice (pv->array to))] - (each x items (array/push arr x)) - (make-vec arr)) - (array? to) (if mutable? - (do (each x items (array/push to x)) to) # vector: append - (do (var result (array/slice to)) (each x items (array/insert result 0 x)) result)) # list: prepend - (tuple? to) (tuple/slice (tuple ;(array/concat (array/slice to) (array/slice items)))) - # hash-set target: accumulate existing members + new items and bulk-build the - # backing HAMT ONCE (phs-from-seq), instead of a phs-conj per element. - (set? to) (let [acc (array)] - (each x (phs-seq to) (array/push acc x)) - (each x items (array/push acc x)) - (phs-from-seq acc)) - # everything else conj-able (sorted colls): fold conj — previously - # this fell through to `to` unchanged, silently dropping all elements - # ((into #{} [:a :b]) was #{}, jolt-h86) - (do (var result to) (each x items (set result (core-conj result x))) result))) - -# merge now lives in the Clojure collection tier (core/20-coll.clj). - -# merge-with now lives in the Clojure collection tier (core/20-coll.clj). - -# keys / vals now live in the syntax tier (core/00-syntax.clj) — canonical -# projections of (seq m), so sorted maps come back in comparator order. - - - -# select-keys now lives in the Clojure collection tier (core/20-coll.clj). - -# zipmap now lives in the Clojure collection tier (core/20-coll.clj). - -# ============================================================ -# Transducers -# ============================================================ -# A transducer is (fn [rf] rf') where rf' is a reducing fn with arities -# []=init, [acc]=complete, [acc x]=step. map/filter/take/... return a -# transducer when called with no collection. - -(defn core-reduced [x] @{:jolt/type :jolt/reduced :val x}) -(defn core-reduced? [x] (and (table? x) (= :jolt/reduced (x :jolt/type)))) -# unreduced lives in the syntax tier (core/00-syntax.clj) over reduced?/deref. -(defn- ensure-reduced [x] (if (core-reduced? x) x (core-reduced x))) - -(defn td-map [f] - (fn [rf] (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) (rf (a 0) (f (a 1))))))) -(defn td-filter [pred] - (fn [rf] (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) - (if (truthy? (pred (a 1))) (rf (a 0) (a 1)) (a 0)))))) -(defn td-remove [pred] (td-filter (fn [x] (not (pred x))))) -# td-keep removed: keep (incl its transducer arity) lives in core/40-lazy.clj. -(defn td-take [n] - (fn [rf] - (var left n) - (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) - (if (<= left 0) (core-reduced (a 0)) - (let [r (rf (a 0) (a 1))] (set left (dec left)) - (if (<= left 0) (ensure-reduced r) r))))))) -(defn td-drop [n] - (fn [rf] - (var left n) - (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) - (if (> left 0) (do (set left (dec left)) (a 0)) (rf (a 0) (a 1))))))) -(defn td-take-while [pred] - (fn [rf] - (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) - (if (truthy? (pred (a 1))) (rf (a 0) (a 1)) (core-reduced (a 0))))))) -(defn td-drop-while [pred] - (fn [rf] - (var dropping true) - (fn [& a] (case (length a) 0 (rf) 1 (rf (a 0)) - (do (when (and dropping (not (truthy? (pred (a 1))))) (set dropping false)) - (if dropping (a 0) (rf (a 0) (a 1)))))))) -# td-map-indexed removed: map-indexed (incl transducer arity) lives in core/40-lazy.clj. - -# Stateful windowing transducers. The 1-arg (completion) arity flushes a partial -# trailing window before delegating to rf's completion; matches Clojure. -# td-partition-all removed: partition-all (incl transducer arity) lives in core/40-lazy.clj. - -# partition-by's transducer arity lives with its (lazy) collection arity in the -# overlay (10-seq tier), written in Clojure with volatiles. - -(defn- reduce-with-reduced - "Reduce coll with reducing fn rf and seed init, honoring `reduced`. Steps lazy - seqs one cell at a time so a reducing fn that returns `reduced` (e.g. the - `take`/`take-while` transducers) can short-circuit over an INFINITE seq instead - of realizing it eagerly. Returns the final (unwrapped) accumulator." - [rf init coll] - (var acc init) - (if (lazy-seq? coll) - (do - (var cur coll) (var go true) - (while go - (let [cell (realize-ls cur)] - (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) - (set go false) - (do - (set acc (rf acc (in cell 0))) - (if (core-reduced? acc) - (do (set acc (acc :val)) (set go false)) - (let [rt (in cell 1)] - (if (nil? rt) (set go false) (set cur (ls-rest-cached cur rt)))))))))) - (do - (var stop false) - (cond - # Indexed colls iterate in place — realize-for-iteration would copy a - # pvec into a fresh array (alloc + pv-nth per element) on EVERY - # reduce call, which dominates tight reduce-over-vector loops - # (jolt-4vr). Also breaks at `reduced` instead of scanning the tail. - (pvec? coll) - (do (def n (pv-count coll)) (var i 0) - (while (and (< i n) (not stop)) - (set acc (rf acc (pv-nth coll i))) - (when (core-reduced? acc) (set acc (acc :val)) (set stop true)) - (++ i))) - (or (tuple? coll) (array? coll)) - (do (def n (length coll)) (var i 0) - (while (and (< i n) (not stop)) - (set acc (rf acc (in coll i))) - (when (core-reduced? acc) (set acc (acc :val)) (set stop true)) - (++ i))) - (each x (if (set? coll) (phs-seq coll) (realize-for-iteration coll)) - (when (not stop) - (set acc (rf acc x)) - (when (core-reduced? acc) (set acc (acc :val)) (set stop true))))))) - acc) - -(defn- transduce-reduce - "Reduce coll with reducing fn rf and seed init, honoring `reduced`." - [rf init coll] - (reduce-with-reduced rf init coll)) - -# SEED-TWIN: transduce is overlay-public (jolt-core/clojure/core/20-coll.clj); -# this seed copy is NOT registered in core-bindings. It survives only as the -# helper core-into calls below — user `transduce` resolves to the overlay. The -# asymmetry with `into` (seed-public) is intentional; docs/seed-overlay-registry.md. -(defn core-transduce - "(transduce xform f coll) or (transduce xform f init coll)." - [xform f & rest] - (let [has-init (= 2 (length rest)) - init (if has-init (in rest 0) (f)) - coll (if has-init (in rest 1) (in rest 0)) - rf (xform f)] - (rf (transduce-reduce rf init coll)))) - -(defn core-into - "(into to from) or (into to xform from)." - [to & rest] - (if (= 2 (length rest)) - (let [xform (in rest 0) from (in rest 1)] - (core-transduce xform (fn [& a] (case (length a) 0 to 1 (a 0) (core-conj (a 0) (a 1)))) to from)) - (into-conj to (realize-for-iteration (in rest 0))))) - -(defn core-sequence - "(sequence coll) -> a seq of coll. (sequence xform coll) -> a LAZY seq of coll - transformed by xform: elements are pulled and pushed through the transducer one - at a time, with outputs buffered and emitted lazily — so it works over infinite - input (matching Clojure). Honors `reduced` (early stop) and runs the completion - arity to flush stateful transducers (e.g. partition-all)." - [a & rest] - (if (= 0 (length rest)) - (core-seq a) - (let [xform a - coll (in rest 0) - buf @[] - state @{:stopped false :completed false} - rf (fn [& args] - (case (length args) - 0 buf - 1 (in args 0) - (do (array/push (in args 0) (in args 1)) (in args 0)))) - xf (xform rf)] - # Pull/complete until buf holds an output or the source is fully drained. - (defn ensure-buf [src] - (var s src) - (while (and (= 0 (length buf)) (not (state :stopped)) (not (seq-done? s))) - (let [r (xf buf (core-first s))] - (set s (core-rest s)) - (when (core-reduced? r) (put state :stopped true)))) - (when (and (= 0 (length buf)) (not (state :completed)) - (or (state :stopped) (seq-done? s))) - (put state :completed true) - (xf buf)) # completion arity — flushes any buffered state - s) - (defn gen [src] - (fn [] - (let [s (ensure-buf src)] - (if (= 0 (length buf)) nil - (let [val (in buf 0)] - (array/remove buf 0 1) - @[val (gen s)]))))) - # core-seq normalizes to a tuple / lazy-seq / nil — all walkable by - # core-first/rest/seq-done?. (Walking a raw pvec/set would misfire: - # seq-done? uses length, which counts a pvec table's KEYS, not elements.) - (make-lazy-seq (gen (core-seq coll)))))) - - -(defn coll->cells [c] - "Convert a seqable to a lazy-seq cell chain: nil or [first, rest-thunk]. - A cons cell is a MUTABLE array `@[val rest-thunk]` (produced by `cons`/the lazy - transformers); user collections (tuples, pvecs, lists) are immutable. We rely - on that distinction: only a mutable 2-array whose tail is a function is treated - as an already-built cell — a user vector like `[first last]` (tail is the fn - `last`) is data and must NOT be misread as a cell. User data is recursed through - immutable tuples so its tails never reach the cell-detection branch." - (if (nil? c) nil - (if (pvec? c) (coll->cells (tuple ;(pv->array c))) - (if (plist? c) (coll->cells (tuple ;(pl->array c))) - (if (function? c) - (let [r (c)] - (if (and (array? r) (= 2 (length r)) (function? (in r 1))) - r - (coll->cells r))) - (if (lazy-seq? c) - (let [cell (realize-ls c)] - (if (= :jolt/pending cell) nil cell)) - (if (tuple? c) - # user sequential data: every element is a value, no cell-detection. - # indexed-cells walks by INDEX — the old (tuple/slice c 1) per cell - # made any walk over a concrete collection O(n^2). - (if (= 0 (length c)) nil (indexed-cells c 0)) - (if (array? c) - # mutable array: a genuine cons cell, or an eager seq result. - (if (= 0 (length c)) nil - (if (and (= 2 (length c)) (function? (in c 1))) - c # already a cell [val, rest-thunk] - (indexed-cells c 0))) - # Other concrete seqables (set/map/sorted coll/string/buffer): coerce - # to a tuple seq via core-seq, then recurse. (lazy/indexed above.) - (if (or (set? c) (phm? c) (buffer? c) (string? c) (core-sorted? c) - (and (struct? c) (nil? (get c :jolt/type))) - # raw host table (System/getenv) — a map: kv entries - (and (table? c) (nil? (get c :jolt/type)) - (nil? (get c :jolt/deftype)))) - (coll->cells (core-seq c)) - nil))))))))) - -(defn lazy-from - "Coerce any seqable to a uniform lazy view without forcing. - Returns nil if coll is nil or empty, the LazySeq unchanged if already lazy, - or a new LazySeq that walks element by element." - [coll] - (if (nil? coll) nil - (if (lazy-seq? coll) coll - (do - # Reject non-seqable scalars (number/boolean/keyword, and tagged structs - # like char/symbol) so a lazy transformer over bad input throws when - # realized — matching Clojure — instead of silently yielding empty. - (when (or (number? coll) (boolean? coll) (keyword? coll) - (and (struct? coll) (not (nil? (get coll :jolt/type))))) - (error (string "Don't know how to create ISeq from: " (type coll)))) - (let [cell (coll->cells coll)] - (if (nil? cell) nil - (make-lazy-seq (fn [] cell)))))))) - -(defn core-map [f & colls] - (def f (as-fn f)) - (if (= 0 (length colls)) - (td-map f) # transducer arity - (if (= 1 (length colls)) - (let [coll (colls 0)] - # Option A: always lazy, even over concrete collections (matches Clojure — - # map returns a seq, not a vector). - (do - (defn mstep [c] - (fn [] - (if (seq-done? c) nil - @[(f (core-first c)) (mstep (core-rest c))]))) - (make-lazy-seq (mstep (lazy-from coll))))) - # Multi-collection: lazy-seq with per-element independent state - (let [init-cs (array/new-filled (length colls) nil) - init-idxs (array/new-filled (length colls) 0) - init-reals (array/new-filled (length colls) nil) - _ (do - (var i 0) - (while (< i (length colls)) - (let [c (in colls i)] - (if (lazy-seq? c) - (put init-cs i c) - (do (put init-cs i nil) - (put init-reals i (if (set? c) (phs-seq c) (realize-for-iteration c)))))) - (++ i)) - nil)] - (defn step [cs idxs reals] - "cs: current lazy-seq cursors, idxs: indices, reals: realized colls" - (fn [] - (var args @[]) - (var next-cs (array/new-filled (length cs) nil)) - (var next-idxs (array/new-filled (length idxs) 0)) - (var next-reals (array/new-filled (length reals) nil)) - (var ok true) - (var i 0) - (while (< i (length cs)) - (let [cur (in cs i) ridx (in idxs i) real (in reals i)] - (if (not (nil? cur)) - # Detect exhaustion with seq-done?, NOT (nil? (ls-first)): a - # lazy-seq can legitimately contain nil elements, and treating the - # first nil as end-of-seq truncates (e.g. mapping over a previous - # map result that holds nils). - (if (seq-done? cur) (do (set ok false) (break)) - (do (array/push args (ls-first cur)) - (put next-cs i (ls-rest cur)) - (put next-idxs i (+ ridx 1)) - (put next-reals i nil))) - (let [c (if (nil? real) - (let [rc (realize-for-iteration (in colls i))] - (put next-reals i rc) rc) - real)] - (if (>= ridx (length c)) (do (set ok false) (break)) - (do (array/push args (in c ridx)) - (put next-cs i nil) - (put next-idxs i (+ ridx 1)) - (put next-reals i c)))))) - (++ i)) - (if (and ok (= (length args) (length cs))) - @[(apply f args) (step next-cs next-idxs next-reals)] - nil))) - (make-lazy-seq (step init-cs init-idxs init-reals)))))) - -(defn core-filter [pred & rest] - (def pred (as-fn pred)) - (if (= 0 (length rest)) (td-filter pred) - (let [coll (in rest 0)] - # Option A: always lazy (matches Clojure — filter returns a seq). - (do - (defn fstep [c] - (fn [] - (var cur c) (var hit nil) (var found false) - (while (and (not found) (not (seq-done? cur))) - (let [x (core-first cur)] - (if (pred x) (do (set hit @[x (core-rest cur)]) (set found true)) - (set cur (core-rest cur))))) - (if found @[(in hit 0) (fstep (in hit 1))] nil))) - (make-lazy-seq (fstep (lazy-from coll))))))) - -(defn core-remove [pred & rest] - (def pred (as-fn pred)) - (if (= 0 (length rest)) (td-remove pred) - (core-filter (fn [x] (not (pred x))) (in rest 0)))) - -(def core-reduce - (fn [& args] - (case (length args) - # 2-arg: seed is the first element; reduce over the rest. Lazy seqs are - # stepped incrementally (via reduce-with-reduced) so `reduced` can - # short-circuit an infinite seq rather than realizing it. - 2 (let [f (args 0) coll (args 1)] - (if (lazy-seq? coll) - (let [cell (realize-ls coll)] - (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) - (f) - (let [rt (in cell 1)] - (if (nil? rt) (in cell 0) - (reduce-with-reduced f (in cell 0) (ls-rest-cached coll rt)))))) - (let [c (if (set? coll) (phs-seq coll) (realize-for-iteration coll))] - (if (= 0 (length c)) (f) - (reduce-with-reduced f (in c 0) (array/slice c 1)))))) - 3 (let [f (args 0) val (args 1) coll (args 2)] - # reify clojure.lang.IReduceInit: the reified value carries its own - # reduce — call it (ring.util.codec's tokenizer reduces this way) - (if-let [m (and (table? coll) - (get coll :jolt/protocol-methods) - (get (get coll :jolt/protocol-methods) :reduce))] - (m coll f val) - (reduce-with-reduced f val coll))) - (error "Wrong number of args passed to: reduce")))) - -(defn core-take [n & rest] - # n is a count — reject non-numbers (e.g. a char/string) like Clojure, rather - # than letting Janet's >= silently compare mixed types. - (unless (number? n) (error (string "take: n must be a number, got " (type n)))) - (if (= 0 (length rest)) (td-take n) - (let [coll (in rest 0)] - # Option A: lazy take (returns a seq, not a vector, even over a vector). - (defn tstep [c i] - (fn [] - (if (or (>= i n) (seq-done? c)) nil - @[(core-first c) (tstep (core-rest c) (+ i 1))]))) - (make-lazy-seq (tstep (lazy-from coll) 0))))) - -(defn core-drop [n & rest] - (if (= 0 (length rest)) (td-drop n) - (let [coll (in rest 0)] - # Option A: lazy drop — skip n (forcing only those), return the lazy tail. - (make-lazy-seq - (fn [] - (var cur (lazy-from coll)) - (var i 0) - (while (and (< i n) (not (seq-done? cur))) - (set cur (core-rest cur)) - (++ i)) - (coll->cells cur)))))) - -# ffirst/nfirst/fnext/nnext/last/butlast (seq tier) and second/peek/subvec/mapv/ -# update (kernel tier) now live in the Clojure clojure.core tiers under -# jolt-core/clojure/core/. The kernel tier is bootstrap-compiled before the -# self-hosted analyzer is built, so the structural fns the analyzer uses come -# from Clojure, not Janet — see api/load-core-overlay! and core/00-kernel.clj. - -(defn core-take-while [pred & rest] - (def pred (as-fn pred)) - (if (= 0 (length rest)) (td-take-while pred) - (let [coll (in rest 0)] - # Option A: lazy take-while. - (defn twstep [c] - (fn [] - (if (seq-done? c) nil - (let [x (core-first c)] - (if (pred x) @[x (twstep (core-rest c))] nil))))) - (make-lazy-seq (twstep (lazy-from coll)))))) - -(defn core-drop-while [pred & rest] - (def pred (as-fn pred)) - (if (= 0 (length rest)) (td-drop-while pred) - (let [coll (in rest 0)] - (if (lazy-seq? coll) - (do - (defn dwstep [c] - (fn [] - (var cur c) - (while (and (not (seq-done? cur)) (pred (ls-first cur))) - (set cur (ls-rest cur))) - (if (seq-done? cur) nil (realize-ls cur)))) - (make-lazy-seq (dwstep coll))) - # A string iterates as a seq of chars in Clojure; realize-for-iteration - # passes strings through, so char-seq it here (as take-while/remove do) — - # otherwise pred sees raw bytes and array/slice rejects the string. - (let [c0 (realize-for-iteration coll) - c (if (string? c0) (map make-char (string/bytes c0)) c0)] - (var start 0) - (while (and (< start (length c)) (pred (c start))) - (++ start)) - (if (tuple? c) - (tuple/slice c start) - (array/slice c start))))))) - -(defn core-concat [& colls] - "Truly lazy concatenation. `step` returns a 0-arg thunk that is only forced - when the consumer asks for the next cell, so nothing in `colls` is realized at - construction time. This is essential for self-referential lazy seqs (e.g. - (def fib (lazy-cat [0 1] (map + (rest fib) fib)))): the later colls must not be - forced until after the surrounding `def` has bound the var." - (if (= 0 (length colls)) @[] - (let [colls (if (tuple? colls) (array/slice colls) colls)] - (defn step [cs] - (fn [] - (if (= 0 (length cs)) - nil - (let [c (in cs 0) - remaining (array/slice cs 1) - cell (coll->cells c)] - (if (nil? cell) - # current coll is empty: advance to the next one - ((step remaining)) - (let [val (in cell 0) - rest-fn (in cell 1)] - @[val (step (if (nil? rest-fn) - remaining - (array/insert remaining 0 rest-fn)))])))))) - (make-lazy-seq (step colls))))) - - -(defn core-mapcat - "(mapcat f & colls) — map then concat. (mapcat f) returns a transducer." - [f & colls] - (if (= 0 (length colls)) - # transducer: map f over each input, then splice (cat) the result - (fn [rf] - (fn [& a] - (case (length a) - 0 (rf) - 1 (rf (a 0)) - (do (var acc (a 0)) - (each x (realize-for-iteration (f (a 1))) - (set acc (rf acc x))) - acc)))) - # collection arity: direct lazy implementation. Pull one element - # from each input coll, apply f, then yield elements from f's result. - # No apply-forcing — walk input colls lazily element-by-element. - (do - (var n (length colls)) - (var init-cs @[]) - (var i 0) - (while (< i n) - (array/push init-cs (lazy-from (in colls i))) - (++ i)) - (defn step [cs res] - (fn [] - (var cursors cs) (var cur-res res) (var hit nil) (var ok false) - (while (not ok) - (if (nil? cur-res) - (do - (var args @[]) (var next-cs @[]) (var exhausted false) (var j 0) - (while (and (< j n) (not exhausted)) - (let [c (in cursors j)] - (if (seq-done? c) (set exhausted true) - (do - (array/push args (ls-first c)) - (array/push next-cs (ls-rest c))))) - (++ j)) - (if exhausted (break)) - (let [r (apply f args)] - (set cursors next-cs) - (set cur-res (if (or (nil? r) (tuple? r) (array? r) - (lazy-seq? r) (pvec? r) (set? r) (plist? r)) - (lazy-from r) - (lazy-from (tuple r)))))) - (if (seq-done? cur-res) - (set cur-res nil) - (let [val (ls-first cur-res) rest (ls-rest cur-res)] - (set hit @[val (step cursors rest)]) - (set ok true))))) - (if ok hit nil))) - (make-lazy-seq (step init-cs nil))))) - -# reverse now lives in the Clojure collection tier ((reduce conj () coll)). - -(defn core-nth - "Return the nth element of a sequential collection. With a not-found arg, return - it when idx is out of bounds (even if it's nil); without one, throw — matching - Clojure, where (nth coll i nil) returns nil rather than throwing." - [coll idx & rest] - (def has-default (> (length rest) 0)) - (def default (if has-default (in rest 0) nil)) - (defn oob [n] (if has-default default (error (string "Index " idx " out of bounds, length: " n)))) - (if (nil? coll) default # (nth nil i) -> nil / default, never throws - (if (core-transient? coll) - (let [a (coll :arr)] (if (and (>= idx 0) (< idx (length a))) (in a idx) (oob (length a)))) - (if (plist? coll) - (let [a (pl->array coll)] - (if (and (>= idx 0) (< idx (length a))) (in a idx) (oob (length a)))) - (if (pvec? coll) - (if (and (>= idx 0) (< idx (pv-count coll))) - (pv-nth coll idx) - (oob (pv-count coll))) - (if (lazy-seq? coll) - # Walk with seq-done?, NOT (ls-first cur): a lazy element may legitimately be - # false or nil, which truthiness would mistake for end-of-seq. - (if (< idx 0) (oob 0) - (do - (var cur coll) - (var i 0) - (while (and (< i idx) (not (seq-done? cur))) - (set cur (core-rest cur)) - (++ i)) - (if (seq-done? cur) (oob i) (core-first cur)))) - (do - (var c (realize-for-iteration coll)) - (if (and (>= idx 0) (< idx (length c))) - (if (string? c) (make-char (in c idx)) (in c idx)) - (oob (length c)))))))))) - -(defn core-sort - "(sort coll) or (sort comparator coll). Comparator may return a boolean or a - Clojure-style negative/zero/positive number." - [a & rest] - (let [has-cmp (> (length rest) 0) - cmp (if has-cmp a nil) - coll (if has-cmp (first rest) a)] - (if (nil? coll) @[] - (let [arr (array/slice (realize-for-iteration coll))] - (if has-cmp - (sort arr (fn [x y] (let [r (cmp x y)] (if (number? r) (< r 0) (truthy? r))))) - (sort arr)) - (tuple/slice (tuple ;arr)))))) - -# (sort-by keyfn coll) or (sort-by keyfn comparator coll). The comparator (when -# given) compares the KEYS and may return a boolean or a Clojure-style number. -# sort-by now lives in the Clojure collection tier — canonical: compare- -# defaulted (nil sorts first), comparator over KEYS, via the host sort seam. - -# distinct now lives in the Clojure lazy tier (core/40-lazy.clj). -# group-by / frequencies now live in the Clojure collection tier -# (core/20-coll.clj). - -(defn core-partition - "(partition n coll), (partition n step coll), or (partition n step pad coll). - Only complete partitions of size n are kept; with pad, the final partial - partition is padded from pad (possibly to fewer than n if pad runs out)." - [n & rest] - (let [argc (length rest) - step (if (>= argc 2) (first rest) n) - pad (if (>= argc 3) (in rest 1) nil) - has-pad (>= argc 3) - coll (case argc 1 (first rest) 2 (in rest 1) 3 (in rest 2))] - # Option A: always lazy. - (defn pstep [c] - (fn [] - (if (seq-done? c) nil - (do - (var part @[]) (var cur c) (var i 0) - (while (and (< i n) (not (seq-done? cur))) - (array/push part (core-first cur)) - (set cur (core-rest cur)) - (++ i)) - (cond - (= i n) - (let [next-cur (if (= step n) cur (lazy-from (core-drop (- step n) cur)))] - @[(tuple/slice (tuple ;part)) (pstep next-cur)]) - # partial final partition: pad it (last partition, then stop) - (and has-pad (> i 0)) - (do - (each x (realize-for-iteration pad) - (when (< (length part) n) (array/push part x))) - @[(tuple/slice (tuple ;part)) (fn [] nil)]) - nil))))) - (make-lazy-seq (pstep (lazy-from coll))))) - -# partition-by now lives in the Clojure seq tier (core/10-seq.clj). - -# partition-all now lives in the Clojure lazy tier (core/40-lazy.clj). - - -# keep-indexed / map-indexed / cycle now live in the Clojure lazy tier -# (core/40-lazy.clj). - -# reduce-kv now lives in the Clojure collection tier (core/20-coll.clj). - -# pop is defined only on stacks (vectors -> last end, lists -> front); Clojure -# throws on sets/maps/seqs/strings/scalars. (peek lives in the Clojure kernel -# tier — core/00-kernel.clj.) -# subvec lives in the Clojure kernel tier — core/00-kernel.clj. - -# trampoline now lives in the Clojure collection tier (core/20-coll.clj). - -(def core-format (fn [fmt & args] (string/format fmt ;args))) - -# ============================================================ -# Sequence generators -# ============================================================ - -(def core-range - (fn [& args] - (if (= 0 (length args)) - # (range) — infinite lazy sequence 0, 1, 2, ... - (do - (defn rstep [i] (fn [] @[i (rstep (+ i 1))])) - (make-lazy-seq (rstep 0))) - (let [start (if (> (length args) 1) (args 0) 0) - end (if (> (length args) 1) (args 1) (args 0)) - step (if (> (length args) 2) (args 2) 1)] - (var result @[]) - (var i start) - (while (if (pos? step) (< i end) (> i end)) - (array/push result i) - (+= i step)) - (tuple/slice (tuple ;result)))))) - -# repeat / iterate now live in the Clojure lazy tier (core/40-lazy.clj). - -# repeatedly now lives in the Clojure lazy tier (core/40-lazy.clj). - -# ============================================================ -# Higher-order functions -# ============================================================ - -# identity / constantly live in the Clojure collection tier (core/20-coll.clj). - -# complement now lives in the Clojure collection tier (core/20-coll.clj). - -# inst?/inst-ms live in the Clojure collection tier (core/20-coll.clj). -# Jolt has no uri host type, so uri? is always false. -# uri? lives in the Clojure collection tier (no uri host type: always false). -# uuid? now lives in the Clojure collection tier (tagged-value predicate). -(defn core-bytes? [x] (buffer? x)) -# tagged-literal? now lives in the Clojure collection tier (tagged-value predicate). - -(defn core-meta [x] - "Returns the metadata of x, or nil." - (cond - (var? x) (var-meta x) - # symbols carry reader metadata (type hints etc.) in a :meta field - (and (struct? x) (= :symbol (get x :jolt/type))) (get x :meta) - (table? x) (or (get x :jolt/meta) (get x :meta)) - nil)) - -# every-pred now lives in the Clojure collection tier (core/20-coll.clj). - -# Public comp lives in the overlay now (20-coll) — its stages can be any jolt -# IFn (keyword/map/set/vector), which raw Janet calls mishandle ((comp seq -# :content) returned nil: janet keyword-apply is not jolt invoke). This -# private composer remains ONLY for the transducer machinery below, where the -# stages are always real fns. -# (td-comp is gone: eduction — its last caller — lives in the overlay now.) - -# partial now lives in the Clojure collection tier (canonical arities). - -# juxt now lives in the Clojure collection tier (core/20-coll.clj). - -# memoize now lives in the Clojure collection tier — find-based, so it -# caches nil results too (this kernel fn re-computed them). - -# ============================================================ -# Collection constructors -# ============================================================ - -(defn core-vector [& xs] (make-vec xs)) -(defn core-hash-map [& kvs] (make-phm kvs)) - -(defn core-array-map [& kvs] - (var result @{}) - (var i 0) - (while (< i (length kvs)) - (put result (kvs i) (kvs (+ i 1))) - (+= i 2)) - (table/to-struct result)) - -(defn core-hash-set [& xs] - (apply make-phs xs)) - -# sorted sets are tagged tables the host set? predicate misses (jolt-dpn) -(defn core-set? [x] (or (set? x) (core-sorted-set? x))) -(defn core-disj [s & ks] - (cond - (core-sorted-set? s) ((sorted-op s :disj) s ks) - (set? s) (apply phs-disj s ks) - (error "disj expects a set"))) - -(defn core-set [coll] - (apply core-hash-set (realize-for-iteration coll))) - -(defn core-list [& xs] - (array ;xs)) - -# ============================================================ diff --git a/src/jolt/core_extra.janet b/src/jolt/core_extra.janet deleted file mode 100644 index a6c0ab5..0000000 --- a/src/jolt/core_extra.janet +++ /dev/null @@ -1,467 +0,0 @@ -# Jolt Core — additional clojure.core fns, transients, hashing -# Extracted from core.janet (jolt-nma8, phase 2b split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./regex) -(use ./config) -(use ./pv) -(use ./plist) -(use ./core_types) -(use ./core_coll) -(use ./core_print) -(use ./core_io) -(use ./core_refs) -# Threading macros (as regular functions? No, as macros in Clojure) -# These need to be defined as macros in the Jolt namespace system. -# For now, skip — they need proper macro definition via the evaluator. -# ============================================================ - -# ============================================================ -# Initialization — intern everything into a context's namespace -# ============================================================ - -(def gensym_counter @{:val 0}) - -(defn gensym - "Returns a new symbol with a unique name." - [&opt prefix-string] - (default prefix-string "G__") - (def n (get gensym_counter :val)) - (put gensym_counter :val (+ n 1)) - {:jolt/type :symbol :ns nil :name (string prefix-string n)}) - - -# if-let/when-let/if-some/when-some now live in the Clojure overlay -# (core/30-macros.clj) as defmacros. - -(defn core-push-thread-bindings [b] (push-thread-bindings b)) -(defn core-pop-thread-bindings [] (pop-thread-bindings)) - -(defn core-var-get [v] (var-get v)) -(defn core-var-set [v val] (var-set v val)) -(defn core-var? [x] (var? x)) -(defn core-alter-var-root [v f & args] (apply alter-var-root v f args)) -(defn core-alter-meta! [v f & args] (apply alter-meta! v f args)) -(defn core-reset-meta! [v meta] (reset-meta! v meta)) - -# intern is a ctx-capturing clojure.core fn now (install-stateful-fns!). - -# get-method/methods/remove-method/remove-all-methods/prefer-method are -# overlay macros (core/30-macros.clj) over the evaluator's *-setup fns. - -(defn core-with-meta [obj meta] - # Functions and scalars can't carry metadata in Jolt's model — return as-is - # rather than crashing (Clojure attaches meta only to IObj values). - (cond - (or (function? obj) (cfunction? obj) (number? obj) (boolean? obj) - (nil? obj) (string? obj) (keyword? obj) (buffer? obj)) - obj - # Symbols carry metadata IN-PLACE in their struct's :meta field (this is how - # the reader attaches ^hint and keeps symbol? true — see reader/read-meta). - # The table-proto path below would make (symbol? (with-meta sym ..)) false and - # break destructuring/hint reading, so keep a symbol a symbol. - (and (struct? obj) (= :symbol (obj :jolt/type))) - (struct ;(kvs obj) :meta meta) - true - (do - (var new-obj @{}) - (each k (keys obj) - (put new-obj k (get obj k))) - # table/setproto requires a table, convert struct meta to table. meta may - # be nil (Clojure allows (with-meta obj nil) to clear metadata). - (var meta-tab @{}) - (when meta (each k (keys meta) (put meta-tab k (get meta k)))) - (table/setproto new-obj meta-tab) - (put new-obj :jolt/meta meta) - new-obj))) - -(defn core-var-dynamic? [v] - (var-dynamic? v)) - -# Java interop stubs -(def core-Object (fn [] (struct ;[:jolt/type :jolt/java-object]))) - -# Volatiles — typed box so deref/volatile? can recognize them. -(defn core-volatile! [v] @{:jolt/type :jolt/volatile :val v}) -# volatile? / vreset! / vswap! now live in the Clojure collection tier — vreset! -# over jolt.host/ref-put!, vswap! over vreset! + get. The constructor stays native. - -# Delays — created lazily by the `delay` macro; forced once via force/deref. -(defn core-make-delay [thunk] @{:jolt/type :jolt/delay :fn thunk :realized false :val nil}) -(defn core-delay? [x] (and (table? x) (= :jolt/delay (x :jolt/type)))) -# Proxy stub — returns nil form (macro, args not evaluated) -# Thread stubs -(def core-Thread (fn [& args] (struct ;[:jolt/type :jolt/thread]))) -(def core-ThreadLocal (fn [& args] (struct ;[:jolt/type :jolt/thread-local]))) -(def core-IllegalStateException (fn [& args] (struct ;[:jolt/type :jolt/exception]))) - - - -# letfn — mutually-recursive local fns. Expands to let* of fn* bindings; jolt -# closures capture the (shared, mutable) bindings table, so forward references -# between the fns resolve at call time. - -# doseq — like `for` but eager and returns nil. Reuse `for`, force realization -# with `count`, discard the result. -# assert — (assert x) / (assert x message). Throws when x is falsy. - -# ns-name now lives in the Clojure collection tier (pure over get + symbol). - -# update lives in the Clojure kernel tier — core/00-kernel.clj. update-in stays -# (it's recursive and has internal callers). -(defn- ks-rest [ks] - (if (tuple? ks) (tuple/slice ks 1) (array/slice ks 1))) - -# assoc-in / update-in now live in the Clojure collection tier (canonical -# recursive ports). - - - -# fnil now lives in the Clojure collection tier (core/20-coll.clj), with -# Clojure's canonical 2/3/4-arity (patch the first 1-3 args only). - -# copy-var stubs for sci.impl.copy-vars (used by sci.impl.namespaces) -(defn core-copy-core-var [sym] nil) -(defn core-copy-var [sym & args] nil) -(defn core-macrofy [sym fn & more] fn) -(defn core-new-var [sym & args] nil) -# A free-standing var cell (not interned anywhere): with-local-vars binds -# these as locals; var-get/var-set work on any cell. -(defn core-local-var [&opt val] - @{:jolt/type :jolt/var :name "local" :ns nil :root val :gen 0}) -# with-open's close seam: a map-like value closes via its :close fn, a host -# file via file/close. No .close interop on the Janet host. -(defn core-close-resource [x] - (cond - (and (or (table? x) (struct? x)) (function? (get x :close))) ((get x :close)) - (= :core/file (type x)) (file/close x) - (error (string "with-open: don't know how to close " (type x))))) -# sci stub: pass the registry map through (it was @{} — a raw host table that -# strict map-conj rightly rejects; identity also keeps sci's registry intact). -(defn core-avoid-method-too-large [& args] (if (> (length args) 0) (in args 0) {})) - -# declare macro — accepts symbols, does nothing (forward declaration) - -# Build a protocol value (a self-evaluating tagged table). Exposed so the overlay -# `defprotocol` can construct one via a fn call rather than embedding a tagged -# struct literal (which the interpreter would try to re-evaluate). `methods` is a -# {kw {:name str}} map; only :name is consulted (by satisfies?). -(defn core-make-protocol [name-str methods] - @{:jolt/type :jolt/protocol - :name {:jolt/type :symbol :ns nil :name name-str} - :methods methods}) - -# extends? is a real overlay fn now (30-macros, over extenders). -(def core-implements? (fn [& args] false)) - -# ============================================================ -# Additional clojure.core functions (conformance batch) -# ============================================================ - -(defn core-keyword - "(keyword name) or (keyword ns name). Namespaced keywords are `:ns/name`. - (keyword nil) is nil; the 2-arg form requires string args (nil ns allowed)." - [& args] - (case (length args) - 1 (let [a (in args 0)] - (cond - (nil? a) nil - (keyword? a) a - (or (string? a) (core-symbol? a)) (keyword (core-name a)) - (error (string "keyword requires a string, symbol or keyword, got " (type a))))) - 2 (let [ns (in args 0) nm (in args 1)] - (when (not (and (or (nil? ns) (string? ns)) (string? nm))) - (error "keyword ns and name must be strings")) - (keyword (if ns (string ns "/" nm) nm))) - (keyword ;args))) - -(defn core-symbol - "(symbol name) or (symbol ns name) -> a jolt symbol struct. name/ns must be - strings (a single symbol arg is returned as-is)." - [& args] - (case (length args) - 1 (let [a (in args 0)] - (cond - (core-symbol? a) a - (or (string? a) (keyword? a)) {:jolt/type :symbol :ns nil :name (core-name a)} - (error (string "symbol requires a string or symbol, got " (type a))))) - 2 (let [ns (in args 0) nm (in args 1)] - (when (not (and (or (nil? ns) (string? ns)) (string? nm))) - (error "symbol ns and name must be strings")) - {:jolt/type :symbol :ns ns :name nm}) - (error "symbol expects 1 or 2 args"))) - -# (take-nth's transducer arity lives in the overlay now.) - - -# filterv now lives in the Clojure collection tier (core/20-coll.clj). - -# mapv lives in the Clojure kernel tier — core/00-kernel.clj. - -# (interpose's transducer arity lives in the overlay now.) -# interpose / take-nth now live in the Clojure lazy tier (core/40-lazy.clj), -# with the canonical transducer arities. - -# keep now lives in the Clojure lazy tier (core/40-lazy.clj). - -# empty now lives in the Clojure collection tier (core/20-coll.clj); a lazy -# seq empties to () there (this fn returned a host table for it). - -# not-empty now lives in the Clojure collection tier (core/20-coll.clj). - -# rseq is defined only on vectors and sorted collections (Reversible). -(defn core-rseq [coll] - (cond - (pvec? coll) (tuple/slice (tuple ;(reverse (pv->array coll)))) - (core-sorted? coll) ((sorted-op coll :rseq) coll) - (error (string "rseq requires a vector or sorted collection, got " (type coll))))) - - - -# some-fn now lives in the Clojure collection tier (core/20-coll.clj). - -# Associative = maps and (real) vectors only. pvec is a literal/built vector; -# tuples and lists are seq results, not associative. -# ifn? now lives in the Clojure collection tier — canonical IFn set (fns, -# keywords, symbols, maps, sets, vectors, vars); lists are NOT IFn. -# With a single item, Clojure returns it WITHOUT calling f. On ties, the last -# extremal item wins (>=/<= update), matching Clojure. -# Clojure's min-key/max-key: the 2-arg base compares with strict < / > (so the -# second wins on ties/NaN), and each further item switches on <= / >=. This -# asymmetry reproduces the JVM's NaN-ordering behavior. Janet's < / > are used -# directly (NaN comparisons are false, never throwing). -# keys must be numbers (NaN allowed) — like Clojure, which compares them with . -# min-key / max-key now live in the Clojure collection tier (core/20-coll.clj). - -# vary-meta / namespace-munge now live in the Clojure collection tier -# (core/20-coll.clj) — pure compositions of meta/with-meta and str/map. - -# Exceptions (ex-info / ex-data / ex-message) -(defn core-ex-info [msg data & more] - @{:jolt/type :jolt/ex-info :message msg :data data - :cause (if (> (length more) 0) (in more 0) nil)}) -# ex-data / ex-message / ex-cause now live in the Clojure collection tier -# (core/20-coll.clj) — pure over get on the tagged value the constructor builds. - -# String split/replace that accept either a literal string or a regex value. -(defn core-str-split [pat s &opt limit] - (if (regex? pat) - (re-split pat s limit) - (let [parts (string/split pat s)] - # literal separator: a positive limit caps the part count; rejoin the tail - # with the (constant) separator to recover the unsplit remainder. - (if (and limit (> limit 0) (> (length parts) limit)) - (array/push (array/slice parts 0 (- limit 1)) - (string/join (array/slice parts (- limit 1)) pat)) - parts)))) -(defn core-str-replace-all [pat repl s] - (if (regex? pat) - (re-replace-all pat s repl) - (string/replace-all pat repl s))) -(defn core-str-replace-first [pat repl s] - (if (regex? pat) - (re-replace-first pat s repl) - (string/replace pat repl s))) - -# Iterator/enumeration seqs — Jolt has no Java iterators, so adapt to plain seq. -# enumeration-seq / iterator-seq live in the Clojure collection tier. -# xml-seq now lives in the Clojure collection tier (core/20-coll.clj). -# line-seq now lives in the Clojure IO tier (core/50-io.clj), over the reader -# protocol of the *in* family. -(defn core-re-matcher [re s] @{:jolt/type :jolt/matcher :re re :s s :pos 0}) - -# bean / print-method / print-dup / the proxy surface live in the Clojure -# collection tier (JVM-shape stubs; print hooks inert until jolt-g1r). -# == lives in the Clojure collection tier (core/20-coll.clj); memfn is an -# overlay macro (core/30-macros.clj) over the .method call sugar. -# eduction / ->Eduction live in the Clojure collection tier (core/20-coll.clj). - -(def- char-escapes - {10 "\\n" 9 "\\t" 13 "\\r" 12 "\\f" 8 "\\b" 34 "\\\"" 92 "\\\\"}) -(def- char-names - {10 "newline" 9 "tab" 13 "return" 12 "formfeed" 8 "backspace" 32 "space"}) -# char-escape-string / char-name-string now live in the Clojure collection -# tier as char-keyed maps. The CODE-keyed tables below stay: pr-render uses them. - - -# subseq / rsubseq over sorted collections -# subseq / rsubseq now live in the Clojure sorted tier (core/25-sorted.clj), -# along with the constructors and all sorted-coll semantics. - -# ============================================================ -# Additional clojure.core functions -# ============================================================ - -# Integer-valued: a finite number equal to its floor. Infinity floors to itself -# but is NOT integer-valued (so float?/double? are true for ##Inf, and int?/ -# pos-int?/… are false), and NaN is excluded by the equality check. -(defn- intval? [x] (and (number? x) (< (math/abs x) math/inf) (= x (math/floor x)))) - -# Forcing lazy seqs -# Map entries (represented as 2-element vectors) -# key/val require a map entry (a 2-element vector/tuple in Jolt); Clojure throws -# otherwise. (Jolt can't distinguish a 2-vector from a real MapEntry.) -# A map entry is a 2-element tuple — Jolt produces tuples only from map -# iteration (first/seq/map over a map), while vector literals are pvecs and -# lists are arrays. So key/val/map-entry? accept a 2-tuple and reject a plain -# vector, matching Clojure (where a MapEntry is distinct from a vector). -(defn- entry-like? [x] (and (tuple? x) (= 2 (length x)))) -# key / val now live in the Clojure collection tier (core/20-coll.clj), -# along with find (previously missing from jolt entirely). -(defn core-map-entry? [x] (entry-like? x)) - -# Reversible (supports rseq) = vectors and sorted collections. -# Numeric predicates (Jolt has no ratios/bigdec). nat-int?/pos-int?/neg-int?/ -# ratio?/decimal?/rational? live in the Clojure collection tier (core/20-coll.clj). -# Jolt has no ratio type, so numerator/denominator have no valid input (Clojure -# requires a Ratio and throws otherwise). -# numerator / denominator now live in the Clojure collection tier (Jolt has -# no ratios; they throw, as on a non-ratio in Clojure). - -# special-symbol? lives in the Clojure collection tier (a quoted symbol set). - -# record? now lives in the Clojure collection tier (tagged-value predicate). - -# Promise: single-threaded box backed by an atom (deref returns nil until set). -# promise / deliver live in the Clojure collection tier (an atom; deref of an -# undelivered promise is nil — single-threaded host, no blocking). - -(defn core-tagged-literal [tag form] @{:jolt/type :jolt/tagged-literal :tag tag :form form}) -# ensure-reduced / halt-when live in the Clojure collection tier -# (core/20-coll.clj) — halt-when is the canonical ::halt-map version there. -(defn core-re-groups [m] (error "re-groups: stateful matchers are not supported in Jolt")) - -# Transients — real mutable scratch collections backed by Janet's native arrays -# and tables (host interop): O(1) conj!/assoc!/dissoc!/disj!/pop!, frozen back to -# a persistent value by persistent!. A transient is a tagged table holding either -# a Janet array (vectors) or a Janet table keyed by canonical key (maps/sets, so -# collection keys still compare by value). The mutating ops return the transient. -(defn core-transient [coll] - (cond - (pvec? coll) - @{:jolt/type :jolt/transient :kind :vector :arr (pv->array coll)} - (set? coll) - (let [t @{}] (each e (phs-seq coll) (put t (tbl-key e) (tbl-box e))) - @{:jolt/type :jolt/transient :kind :set :tbl t}) - (or (phm? coll) (and (struct? coll) (nil? (get coll :jolt/type)))) - (let [t @{}] - (each pair (realize-for-iteration coll) - (put t (tbl-key (in pair 0)) @[(in pair 0) (in pair 1)])) - @{:jolt/type :jolt/transient :kind :map :tbl t}) - # mutable-build arrays (vectors/lists) — copy into a transient vector - (array? coll) @{:jolt/type :jolt/transient :kind :vector :arr (array/slice coll)} - # tuples (reader vectors / map entries) are vectors too - (tuple? coll) @{:jolt/type :jolt/transient :kind :vector :arr (array ;coll)} - (error (string "Don't know how to create a transient from " (type coll))))) - -# A transient is invalidated by persistent!; using it afterwards is a bug. -(defn- tr-check-active! [t] - (when (get t :jolt/persistent) - (error "Transient used after persistent! call"))) - -(defn- tr-conj! [t x] - (tr-check-active! t) - (case (t :kind) - :vector (array/push (t :arr) x) - :set (put (t :tbl) (tbl-key x) (tbl-box x)) - :map (cond - # a [k v] pair (map-entry / 2-vector) - (and (or (pvec? x) (tuple? x) (array? x)) - (= 2 (if (pvec? x) (pv-count x) (length x)))) - (put (t :tbl) (tbl-key (vnth x 0)) @[(vnth x 0) (vnth x 1)]) - # a map: merge all its entries - (or (phm? x) (and (struct? x) (nil? (get x :jolt/type)))) - (each e (map-entries-of x) - (put (t :tbl) (tbl-key (in e 0)) @[(in e 0) (in e 1)])) - (error "conj! on a transient map requires a [key value] pair or a map"))) - t) - -(defn- tr-assoc! [t k v] - (tr-check-active! t) - (case (t :kind) - :vector (let [a (t :arr)] - (when (not (and (number? k) (= k (math/floor k)) (>= k 0) (<= k (length a)))) - (error (string "Index " k " out of bounds for assoc! on a transient vector of length " (length a)))) - (if (= k (length a)) (array/push a v) (put a k v))) - :map (put (t :tbl) (tbl-key k) @[k v]) - (error "assoc! expects a transient vector or map")) - t) - -# The bang ops require a transient (Clojure throws otherwise); no lenient -# fallback to the persistent op. -(defn core-conj! [& args] - (cond - (= 0 (length args)) (core-transient (make-vec @[])) # (conj!) -> (transient []) - (= 1 (length args)) (first args) # (conj! coll) -> coll, as-is - (let [t (first args) xs (tuple/slice args 1)] - (if (core-transient? t) - (do (each x xs (tr-conj! t x)) t) - (error "conj! requires a transient"))))) - -(defn core-assoc! [t & kvs] - # Unlike assoc, assoc! accepts an ODD number of args — a missing final value - # is taken as nil (so (get kvs (+ i 1)) rather than (in ...), which would - # error on the dangling key). - (if (core-transient? t) - (do (var i 0) (while (< i (length kvs)) (tr-assoc! t (in kvs i) (get kvs (+ i 1))) (+= i 2)) t) - (error "assoc! requires a transient"))) - -(defn core-dissoc! [t & ks] - (if (and (core-transient? t) (= :map (t :kind))) - (do (tr-check-active! t) (each k ks (put (t :tbl) (tbl-key k) nil)) t) - (error "dissoc! requires a transient map"))) - -(defn core-disj! [t & xs] - (if (and (core-transient? t) (= :set (t :kind))) - (do (tr-check-active! t) (each x xs (put (t :tbl) (tbl-key x) nil)) t) - (error "disj! requires a transient set"))) - -(defn core-pop! [t] - (if (and (core-transient? t) (= :vector (t :kind))) - (do (tr-check-active! t) - (when (= 0 (length (t :arr))) (error "Can't pop empty vector")) - (array/pop (t :arr)) t) - (error "pop! requires a transient vector"))) - -(defn core-persistent! [t] - (if (core-transient? t) - (do - (tr-check-active! t) - (def result - (case (t :kind) - :vector (make-vec (t :arr)) - # The transient already deduped into a native table; bulk-build the - # persistent value ONCE (bottom-up HAMT) instead of folding a phm-assoc - # per entry. This is the lever behind every transient-based builder - # (frequencies/group-by/set/into) — jolt-5vsp collections. - :set (phs-from-seq (map tbl-unbox (values (t :tbl)))) - :map (phm-from-pairs (values (t :tbl))))) - # Invalidate: any further bang op (or a second persistent!) now throws. - (put t :jolt/persistent true) - result) - (error "persistent! requires a transient"))) - -# Unchecked arithmetic — Jolt numbers don't overflow, so these are plain ops. -# unchecked-* arithmetic lives in the Clojure collection tier -# (core/20-coll.clj); only the masking byte/short/char coercions remain above. - -# Hashing helpers -# Hashes are masked to 24 bits at each step so intermediate products stay within -# Janet's integer range (a float here would make band error). -(defn- h24 [x] (band (hash x) 0xffffff)) -(defn core-hash-combine [a b] (band (bxor (h24 a) (+ (h24 b) 0x9e3779)) 0xffffff)) -(defn core-hash-ordered-coll [coll] - (var h 1) (each x (realize-for-iteration coll) (set h (band (+ (* 31 h) (h24 x)) 0xffffff))) h) -(defn core-hash-unordered-coll [coll] - (var h 0) (each x (realize-for-iteration coll) (set h (band (+ h (h24 x)) 0xffffff))) h) - -# prefers is a macro over prefers-setup now (the store lives on the VAR). - - - -# parse-uuid lives in the Clojure collection tier (core/20-coll.clj) over -# re-matches + the __make-uuid host constructor (types.janet). - diff --git a/src/jolt/core_io.janet b/src/jolt/core_io.janet deleted file mode 100644 index 4e824ec..0000000 --- a/src/jolt/core_io.janet +++ /dev/null @@ -1,235 +0,0 @@ -# Jolt Core — I/O, files, JDBC, compare, type -# Extracted from core.janet (jolt-nma8, phase 2b split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./regex) -(use ./config) -(use ./pv) -(use ./plist) -(use ./core_types) -(use ./core_coll) -(use ./core_print) -# I/O — minimal wrappers -# ============================================================ - -# print/println use str semantics (bare strings); pr/prn use readable (quoted). -# All space-separate their args, like Clojure. -# print/println live in the Clojure collection tier (core/20-coll.clj) over -# the __write / __pr-str1 host seams; str-render-one stays for core-str. -(defn core-write [s] (prin s) nil) - -(defn core-eprint [s] (eprint s) nil) -(defn core-eprintf [fmt & args] (eprintf fmt ;args) nil) - -# next.jdbc host shims (the db library's next.jdbc compat layer builds on these). -# A connection is a tagged table wrapping a jdbc.core conn (:raw) plus clj -# callbacks: :exec runs one SQL string in the transaction (so the janet-side -# Statement.executeBatch can run SQL without a janet->clj call), :close closes -# the underlying conn, :product is the JDBC database product name. instance? -# Connection (evaluator) and the :jolt/jdbc-conn tagged methods (host_interop) key -# off this shape. -(defn core-jdbc-wrap-conn [raw exec closef product] - @{:jolt/type :jolt/jdbc-conn :raw raw :exec exec :close closef - :product product :closed @[false]}) -# Robust unwrap: a wrapped conn -> its :raw; anything else passes through (so the -# next.jdbc fns accept either a wrapped conn or a bare jdbc.core conn/spec). -(defn core-jdbc-conn-raw [x] - (if (and (table? x) (= :jolt/jdbc-conn (get x :jolt/type))) (get x :raw) x)) -(defn core-jdbc-make-stmt [w] - # :close lets with-open close the statement (core-close-resource calls :close); - # nothing to release — executeBatch already ran the commands. - @{:jolt/type :jolt/jdbc-stmt :exec (get w :exec) :cmds @[] :close (fn [] nil)}) - -# java.io.File model (jolt-hjw). io/file and (File. …) build a tagged :jolt/file -# value so (instance? File x) works and migratus's File-vs-jar branching takes -# the filesystem path. The File method surface + nio glob live in host_interop; here -# are the constructor/predicate builtins and the path coercion str/slurp use. -(defn core-file-path - "The path string of a :jolt/file, or (string x) for anything else." - [x] - (if (and (table? x) (= :jolt/file (get x :jolt/type))) (get x :path) (string x))) -(defn core-make-file [path &opt child] - (def base (core-file-path path)) - @{:jolt/type :jolt/file :path (if child (string base "/" (core-file-path child)) base)}) -(defn core-file? [x] (and (table? x) (= :jolt/file (get x :jolt/type)))) - -# newline lives in the Clojure collection tier (core/20-coll.clj). - -# Clojure 1.11 string->scalar parsers: nil on malformed input, throw on a -# non-string. Validation is strict (scan-number alone accepts 0x10 etc.). -(defn- parse-arg-str [s who] - (if (or (string? s) (buffer? s)) (string s) - (error (string who " requires a string, got " (type s))))) - -(defn core-parse-long [s] - (def str* (parse-arg-str s "parse-long")) - (def n (length str*)) - (def start (if (and (> n 0) (or (= 43 (in str* 0)) (= 45 (in str* 0)))) 1 0)) - (if (and (> n start) - (do (var ok true) - (for i start n (when (or (< (in str* i) 48) (> (in str* i) 57)) (set ok false))) - ok)) - (scan-number str*) - nil)) - -(defn core-parse-double [s] - (def str* (parse-arg-str s "parse-double")) - # strict float shape: [+-] digits [. digits] [eE [+-] digits] — at least one - # digit overall; "Infinity"/"-Infinity"/"NaN" accepted like the reference. - (cond - (= str* "Infinity") math/inf - (= str* "-Infinity") (- math/inf) - (= str* "NaN") math/nan - (do - (def pat (peg/compile ~(sequence (opt (set "+-")) (choice (sequence (some :d) (opt (sequence "." (any :d)))) (sequence "." (some :d))) (opt (sequence (set "eE") (opt (set "+-")) (some :d))) -1))) - (if (peg/match pat str*) (scan-number str*) nil)))) - -# parse-boolean lives in the Clojure collection tier (core/20-coll.clj). - -# Host time source for the `time` macro (monotonic, milliseconds). -(defn core-current-time-ms [] (* 1000 (os/clock :monotonic))) - -# Host IO (host-classified in the spec): path-based slurp/spit, *out* flush. -# Opts (:encoding ...) are accepted and ignored — everything is UTF-8 here. -# Reader shims (java.io.StringReader / PushbackReader / anything carrying -# :s + :pos) DRAIN instead of opening a file: Ring middleware slurps request -# bodies, and the jolt Ring adapter hands those over as StringReaders. -(defn core-slurp [src & opts] - (cond - (core-file? src) (string (slurp (core-file-path src))) - (and (table? src) (string? (get src :s)) (number? (get src :pos))) - (let [s (src :s) p (src :pos)] - (put src :pos (length s)) - (string/slice s p)) - # a byte-array / buffer body: bytes already in hand, just stringify - (buffer? src) (string src) - (string (slurp src)))) - -(defn core-spit [path content & opts] - (def append? (do (var a false) (var i 0) - (while (< i (length opts)) - (when (and (= :append (in opts i)) (in opts (+ i 1))) (set a true)) - (+= i 2)) - a)) - (def f (file/open (core-file-path path) (if append? :a :w))) - (file/write f (str-render-one content)) - (file/close f) - nil) - -(defn core-flush [] - (def out (dyn :out)) - (when out (file/flush out)) - nil) - -# Thread-binding introspection over the frame stack (types/cur-binding-stack). -(defn core-get-thread-bindings [] - # Innermost frame wins: merge frames oldest-first. The result is a Janet - # STRUCT keyed by the var tables themselves — the exact frame representation - # var-get reads (identity-keyed get) — so the map can be re-pushed by - # with-bindings*/bound-fn* and remains lookup-able with (get m the-var). - (def acc @{}) - (each frame (snapshot-bindings) - (each entry (realize-for-iteration frame) - (put acc (in entry 0) (in entry 1)))) - (table/to-struct acc)) - -(defn core-thread-bound?* [v] - (var found false) - (each frame (snapshot-bindings) - (each entry (realize-for-iteration frame) - (when (= (in entry 0) v) (set found true)))) - found) - -# Directory primitives for file-seq (paths, not File objects — host-classified). -(defn core-dir? [path] - (def st (os/stat path)) - (and st (= :directory (st :mode)))) - -(defn core-list-dir [path] - (def entries (os/dir path)) - (map (fn [e] (string path "/" e)) (sort entries))) - -# Clojure compare: a total order over comparable values. nil sorts first; -# numbers numerically; strings/keywords lexically; symbols by ns then name; -# booleans false x y) 1 0)) - (cond - (and (nil? a) (nil? b)) 0 - (nil? a) -1 - (nil? b) 1 - (and (number? a) (number? b)) (cmp3 a b) - (and (or (string? a) (buffer? a)) (or (string? b) (buffer? b))) - (cmp3 (string a) (string b)) - (and (keyword? a) (keyword? b)) (cmp3 (string a) (string b)) - (and (core-symbol? a) (core-symbol? b)) - (let [r (cmp3 (string (or (a :ns) "")) (string (or (b :ns) "")))] - (if (= 0 r) (cmp3 (a :name) (b :name)) r)) - (and (boolean? a) (boolean? b)) - (cond (= a b) 0 (= a false) -1 1) - (and (core-char? a) (core-char? b)) (cmp3 (a :ch) (b :ch)) - (and (struct? a) (= :jolt/uuid (get a :jolt/type)) - (struct? b) (= :jolt/uuid (get b :jolt/type))) - (cmp3 (a :str) (b :str)) - (and (struct? a) (= :jolt/inst (get a :jolt/type)) - (struct? b) (= :jolt/inst (get b :jolt/type))) - (cmp3 (a :ms) (b :ms)) - (and (jvec? a) (jvec? b)) - (let [la (vcount a) lb (vcount b)] - (if (not= la lb) - (cmp3 la lb) - (do - (var r 0) (var i 0) - (while (and (= r 0) (< i la)) - (set r (ccompare (vnth a i) (vnth b i))) - (++ i)) - r))) - (error (string "Cannot compare " (type a) " with " (type b)))))) - -# Clojure type: the :type metadata when present, else the value's type. With no -# class objects on this host, the "class" is a symbol: a deftype/record value -# yields its type tag symbol; everything else a taxonomy keyword -# (host-classified — see spec coverage). -(defn core-type [x] - (def m (core-meta x)) - (def override (and m (core-get m :type))) - (if (not (nil? override)) - override - (cond - (and (table? x) (get x :jolt/deftype)) - {:jolt/type :symbol :ns nil :name (get x :jolt/deftype)} - (nil? x) nil - (boolean? x) :boolean - (number? x) :number - (or (string? x) (buffer? x)) :string - (keyword? x) :keyword - (core-symbol? x) :symbol - (core-char? x) :char - (and (struct? x) (get x :jolt/type)) (get x :jolt/type) - (jvec? x) :vector - (core-map? x) :map - (set? x) :set - (core-seq? x) :seq - (or (function? x) (cfunction? x)) :fn - (table? x) (or (get x :jolt/type) :table) - :else (keyword (type x))))) - -# Capture *out*: run thunk with Janet's :out dynamic bound to a buffer, so all -# print/println/pr/prn output (which go through `prin` -> (dyn :out)) is collected -# and returned as a string. The with-out-str macro (overlay) wraps a body thunk. -(defn core-with-out-str [thunk] - (def buf @"") - (with-dyns [:out buf] (thunk)) - (string buf)) - -# pr/prn/pr-str live in the Clojure collection tier (core/20-coll.clj); the -# renderer itself stays host (representation-coupled, shared with hot str). -(defn core-pr-str1 [x] (let [b @""] (pr-render b x) (string b))) - -# ============================================================ diff --git a/src/jolt/core_print.janet b/src/jolt/core_print.janet deleted file mode 100644 index 388c28c..0000000 --- a/src/jolt/core_print.janet +++ /dev/null @@ -1,250 +0,0 @@ -# Jolt Core — string + print rendering (pr-str/str) -# Extracted from core.janet (jolt-nma8, phase 2b split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./regex) -(use ./config) -(use ./pv) -(use ./plist) -(use ./core_types) -(use ./core_coll) -# String functions -# ============================================================ - -# Readable rendering of a value (Clojure pr semantics): strings quoted, -# keywords with leading ':', symbols by name, collections with their reader -# syntax. Used by both pr-str (readable) and str (collection elements). -# A namespace's :name may be a string or a symbol struct depending on the -# creation path — normalize for display. -(defn- ns-display-name [ns] - (def n (ns :name)) - (if (and (struct? n) (= :symbol (get n :jolt/type))) (n :name) (string n))) - -# print-method callback (jolt-g1r): set by api/init AFTER the overlay loads, -# to a (fn [v emit] handled?) that looks for a USER-registered print-method -# multimethod entry for v's dispatch value and renders through it (emit takes -# string pieces). The renderer consults it only on the record/tagged -# fallthrough, so built-in rendering pays nothing. -(var print-method-cb nil) -(defn set-print-method-cb! [f] (set print-method-cb f)) - -# Late-bound hook to a record's custom Object/toString (jolt-rt6n). Returns the -# string a deftype's (toString [_] ...) produces, or nil when the type defines -# none. core can't reach the ctx type-registry directly, so install-print-method-cb! -# wires this per-ctx. str routes records through it; the data repr is the fallback. -(var record-tostring-cb nil) -(defn set-record-tostring-cb! [f] (set record-tostring-cb f)) - -(def- pr-char-escapes - {34 "\\\"" 92 "\\\\" 10 "\\n" 9 "\\t" 13 "\\r" 12 "\\f" 8 "\\b"}) -(var pr-render nil) - -# Format a number the way Clojure prints it: infinity and NaN have named forms -# (Janet renders them "inf"/"-inf"/"nan"). -(defn- fmt-number [v] - (cond - (not (number? v)) (string v) - (= v math/inf) "Infinity" - (= v (- math/inf)) "-Infinity" - (not= v v) "NaN" - (string v))) - -(defn- pr-render-seq [buf items open close] - (buffer/push-string buf open) - (var first true) - (each x items - (if first (set first false) (buffer/push-string buf " ")) - (pr-render buf x)) - (buffer/push-string buf close)) - -(defn- pr-render-pairs [buf pairs] - (buffer/push-string buf "{") - (var first true) - (each pair pairs - (if first (set first false) (buffer/push-string buf ", ")) - (pr-render buf (in pair 0)) - (buffer/push-string buf " ") - (pr-render buf (in pair 1))) - (buffer/push-string buf "}")) - -(defn- name-of - "Extract a plain name string from a string, symbol struct, or a namespace/var - table (reading its :name) — never recurses into the cyclic ns structure." - [x] - (cond - (nil? x) nil - (string? x) x - (and (struct? x) (= :symbol (get x :jolt/type))) (x :name) - (or (struct? x) (table? x)) (name-of (get x :name)) - (string x))) - -(defn- var-display - "Render a Jolt var as #'ns/name. A var's :meta/:ns refs are cyclic, so this - reads only its :name and :ns name — printing the var's pairs would loop." - [v] - (let [nm (name-of (v :name)) - ns (name-of (v :ns))] - (if ns (string "#'" ns "/" nm) (string "#'" nm)))) - -(defn- pr-push-escaped - "Readable string body: escape per char-escapes (quote, backslash, \\n & co), - so pr-str round-trips through the reader (this was unescaped, jolt pre-r6)." - [buf s] - (each c (string/bytes s) - (if-let [esc (get pr-char-escapes c)] - (buffer/push-string buf esc) - (buffer/push-byte buf c)))) - -(set pr-render - (fn [buf v] - (cond - (nil? v) (buffer/push-string buf "nil") - (= true v) (buffer/push-string buf "true") - (= false v) (buffer/push-string buf "false") - (string? v) (do (buffer/push-string buf "\"") (pr-push-escaped buf v) (buffer/push-string buf "\"")) - (buffer? v) (do (buffer/push-string buf "\"") (pr-push-escaped buf (string v)) (buffer/push-string buf "\"")) - (keyword? v) (do (buffer/push-string buf ":") (buffer/push-string buf (string v))) - (core-char? v) (do (buffer/push-string buf "\\") - (buffer/push-string buf - (case (v :ch) - 10 "newline" 32 "space" 9 "tab" 13 "return" - 12 "formfeed" 8 "backspace" 0 "nul" - (char->string v)))) - (number? v) (buffer/push-string buf (fmt-number v)) - (and (struct? v) (= :symbol (v :jolt/type))) - (buffer/push-string buf (if (v :ns) (string (v :ns) "/" (v :name)) (v :name))) - (and (struct? v) (= :jolt/inst (v :jolt/type))) - (do (buffer/push-string buf "#inst \"") (buffer/push-string buf (inst->rfc3339 v)) - (buffer/push-string buf "\"")) - (= :jolt/namespace (get v :jolt/type)) - (do (buffer/push-string buf "#namespace[") - (buffer/push-string buf (ns-display-name v)) - (buffer/push-string buf "]")) - (and (table? v) (= :jolt/var (get v :jolt/type))) (buffer/push-string buf (var-display v)) - (shape-rec? v) - (let [rtag (record-tag v) - pairs (map (fn [k] [k (shape-get v k nil)]) (shape-keys v))] - (cond - # a record shape-rec prints Clojure-style: #ns.Type{:k v, ...} - (and rtag print-method-cb (print-method-cb v (fn [piece] (buffer/push-string buf piece)))) nil - rtag (do (buffer/push-string buf (string "#" rtag)) - (pr-render-pairs buf pairs)) - (pr-render-pairs buf pairs))) - (core-sorted-map? v) (pr-render-pairs buf - (map (fn [e] [(vnth e 0) (vnth e 1)]) (sorted-entries-arr v))) - (core-sorted-set? v) (pr-render-seq buf (sorted-entries-arr v) "#{" "}") - (lazy-seq? v) (pr-render-seq buf (realize-for-iteration v) "(" ")") - (set? v) (pr-render-seq buf (phs-seq v) "#{" "}") - (phm? v) (pr-render-pairs buf (phm-entries v)) - (pvec? v) (pr-render-seq buf (pv->array v) "[" "]") - (plist? v) (pr-render-seq buf (pl->array v) "(" ")") - (and (table? v) (get v :jolt/deftype)) - (if (and print-method-cb (print-method-cb v (fn [piece] (buffer/push-string buf piece)))) - nil - # Clojure's record syntax: #ns.Type{:k v, ...} (fields only, the - # deftype tag elided). This used to print the raw janet table. - (do - (buffer/push-string buf (string "#" (get v :jolt/deftype))) - (pr-render-pairs buf - (filter (fn [pair] (not= :jolt/deftype (in pair 0))) (pairs v))))) - (tuple? v) (pr-render-seq buf v "[" "]") - # mutable mode: arrays are vectors -> print with [] (else lists -> ()) - (array? v) (if mutable? (pr-render-seq buf v "[" "]") (pr-render-seq buf v "(" ")")) - # Any remaining TAGGED value dispatches through print-method when the - # hook is wired: the io tier owns the cold renderings (uuid, regex, - # transient, channel — branches that used to live here), and user - # defmethods on any :jolt/* tag fire from inside nested values. Before - # the overlay loads (init-time error messages) these fall through to - # the raw pairs view below. - (and print-method-cb (get v :jolt/type) - (print-method-cb v (fn [piece] (buffer/push-string buf piece)))) - nil - (struct? v) (pr-render-pairs buf (pairs v)) - (table? v) (pr-render-pairs buf (pairs v)) - true (buffer/push-string buf (string v))))) - -(defn str-render-one - "Render one value with Clojure's `str`/.toString semantics (bare strings, - nil -> empty, keywords/symbols by name, collections via pr-render)." - [v] - (cond - (nil? v) "" - (string? v) v - (buffer? v) (string v) - (core-char? v) (char->string v) - (keyword? v) (string ":" (string v)) - (and (struct? v) (= :symbol (v :jolt/type))) - (if (v :ns) (string (v :ns) "/" (v :name)) (v :name)) - (and (struct? v) (= :jolt/uuid (v :jolt/type))) (v :str) - (and (struct? v) (= :jolt/inst (v :jolt/type))) (inst->rfc3339 v) - # a java.io.File renders as its path (Clojure's File.toString) - (and (table? v) (= :jolt/file (get v :jolt/type))) (get v :path) - # (str pattern) -> raw regex source (no #"" delimiters), so libraries that - # compose patterns via (re-pattern (str p1 ...)) work (Pattern.toString). - (and (table? v) (= :jolt/regex (get v :jolt/type))) (get v :source) - (= :jolt/namespace (get v :jolt/type)) (ns-display-name v) - (and (table? v) (= :jolt/var (get v :jolt/type))) (var-display v) - (number? v) (fmt-number v) - (= true v) "true" - (= false v) "false" - # a record/deftype with a custom Object/toString renders via it (Clojure's - # str/.toString semantics); plain records fall through to the data repr. - (if-let [s (and record-tostring-cb (record-tag v) (record-tostring-cb v))] - s - (let [buf @""] (pr-render buf v) (string buf))))) - -(defn core-str [& xs] - (if (= 0 (length xs)) "" - (do - (var result @[]) - (each x xs (array/push result (str-render-one x))) - (string/join result "")))) - -(defn core-str-join - "clojure.string/join: stringify each element (Clojure semantics), then join." - [coll &opt sep] - (default sep "") - (let [items (realize-for-iteration coll) - parts @[]] - (each x items (array/push parts (str-render-one x))) - (string/join parts (str-render-one sep)))) - -(defn core-name - "Returns the name string of a keyword, symbol, or string (without namespace)." - [x] - (cond - (keyword? x) (let [s (string x) i (string/find "/" s)] (if i (string/slice s (+ i 1)) s)) - (and (struct? x) (= :symbol (x :jolt/type))) (x :name) - (string? x) x - "")) - -(defn core-namespace - "Returns the namespace string of a keyword/symbol, or nil if none." - [x] - (cond - (keyword? x) (let [s (string x) i (string/find "/" s)] (if i (string/slice s 0 i) nil)) - (and (struct? x) (= :symbol (x :jolt/type))) - (if (x :ns) (if (struct? (x :ns)) ((x :ns) :name) (string (x :ns))) nil) - nil)) - -(def core-subs - (fn [& args] - (when (not (or (= 2 (length args)) (= 3 (length args)))) - (error "Wrong number of args passed to: subs")) - (let [s (args 0) - start (get args 1)] - (when (not (string? s)) (error (string "subs requires a string, got " (type s)))) - (let [len (length s) - end (if (= 3 (length args)) (args 2) len)] - # Clojure validates bounds (no negative/from-end/clamping like Janet): - # 0 <= start <= end <= (count s). - (when (not (and (number? start) (number? end) - (= start (math/floor start)) (= end (math/floor end)) - (>= start 0) (<= start end) (<= end len))) - (error "String index out of range")) - (string/slice s start end))))) - -# ============================================================ diff --git a/src/jolt/core_refs.janet b/src/jolt/core_refs.janet deleted file mode 100644 index 9c218d7..0000000 --- a/src/jolt/core_refs.janet +++ /dev/null @@ -1,313 +0,0 @@ -# Jolt Core — arrays, bit ops, coercions, hash, atoms/refs -# Extracted from core.janet (jolt-nma8, phase 2b split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./regex) -(use ./config) -(use ./pv) -(use ./plist) -(use ./core_types) -(use ./core_coll) -(use ./core_print) -(use ./core_io) -# Java-style arrays — backed by Janet's C primitives. Byte arrays use Janet -# buffers (contiguous, O(1) indexed get/put — genuinely fast); object and -# numeric arrays use Janet arrays. aget/aset/alength/aclone work over both. -# ============================================================ - -# alength / aget / aset now live in the Clojure collection tier — count/nth reads -# and an aset write through jolt.host/ref-put!. The typed/object array constructors -# below stay native (they build the mutable backing). - -(defn core-aclone [arr] - (cond - (buffer? arr) (buffer/slice arr) - (pvec? arr) (array ;(pv->array arr)) - (array/slice arr))) - -# Numeric / object arrays: (T-array size) | (T-array size init) | (T-array seq) -(defn- make-num-array [a rest init] - (if (number? a) - (array/new-filled a (if (> (length rest) 0) (in rest 0) init)) - (array ;(realize-for-iteration a)))) -(defn core-object-array [a & rest] (make-num-array a rest nil)) -(defn core-int-array [a & rest] (make-num-array a rest 0)) -(defn core-long-array [a & rest] (make-num-array a rest 0)) -(defn core-short-array [a & rest] (make-num-array a rest 0)) -(defn core-double-array [a & rest] (make-num-array a rest 0)) -(defn core-float-array [a & rest] (make-num-array a rest 0)) -(defn core-char-array [a & rest] - # JVM char-array also accepts a STRING/char-seq (char[] of its characters) — - # selmer's parse-str does (char-array template). - (cond - (string? a) (map make-char (string/bytes a)) - (buffer? a) (map make-char (string/bytes (string a))) - (make-num-array a rest (make-char 0)))) -(defn core-boolean-array [a & rest] (make-num-array a rest false)) - -# Byte arrays — Janet buffers (each element a 0..255 byte). -(defn core-byte-array [a & rest] - (if (number? a) - (buffer/new-filled a (band (if (> (length rest) 0) (in rest 0) 0) 0xff)) - (let [b (buffer/new 0)] - (each x (realize-for-iteration a) (buffer/push-byte b (band x 0xff))) - b))) - -(defn core-aset-byte [arr i v] (put arr i (band v 0xff)) v) -(defn core-aset-int [arr i v] (put arr i v) v) -(defn core-aset-long [arr i v] (put arr i v) v) -(defn core-aset-short [arr i v] (put arr i v) v) -(defn core-aset-double [arr i v] (put arr i v) v) -(defn core-aset-float [arr i v] (put arr i v) v) -(defn core-aset-char [arr i v] (put arr i v) v) -(defn core-aset-boolean [arr i v] (put arr i v) v) - -(defn core-make-array [a & rest] - # (make-array len) or (make-array type len ...); ignore the type tag - (let [len (if (number? a) a (in rest 0))] (array/new-filled len nil))) - -(defn core-into-array [a & rest] - (let [s (if (> (length rest) 0) (in rest 0) a)] - (array ;(realize-for-iteration s)))) - -(defn core-to-array [coll] - (def arr @[]) (each x (realize-for-iteration coll) (array/push arr x)) arr) -# to-array-2d lives in the Clojure collection tier (core/20-coll.clj). - -# Array-element casts — identity on arrays; `bytes` coerces to a byte buffer. -(defn core-bytes [x] (if (buffer? x) x (core-byte-array x))) -(defn core-booleans [x] x) -(defn core-ints [x] x) -(defn core-longs [x] x) -(defn core-shorts [x] x) -(defn core-doubles [x] x) -(defn core-floats [x] x) -(defn core-chars [x] x) - -# Scalar numeric coercions -(defn core-byte [x] (let [b (band (math/trunc x) 0xff)] (if (>= b 128) (- b 256) b))) -(defn core-short [x] (let [s (band (math/trunc x) 0xffff)] (if (>= s 0x8000) (- s 0x10000) s))) -# The masking unchecked-byte/short/char and float/double coercions live in -# the Clojure collection tier (core/20-coll.clj). - -# 64-bit integers (Janet int/s64 — C-backed) -(defn core-bigint [x] (int/s64 x)) -(defn core-biginteger [x] (int/s64 x)) -# bigdec now lives in the Clojure collection tier (no BigDecimal: a double). - -# Chunked seqs — Jolt does not chunk, so these are simple eager equivalents. -(defn core-chunk-buffer [capacity] @[]) -(defn core-chunk-append [b x] (array/push b x) b) -(defn core-chunk [b] b) -# chunked-seq? now lives in the Clojure collection tier (always false on Jolt). -(defn core-chunk-first [s] (core-first s)) -(defn core-chunk-rest [s] (core-rest s)) -(defn core-chunk-next [s] (core-next s)) -(defn core-chunk-cons [chunk rest] (core-concat (realize-for-iteration chunk) rest)) - -# More clojure.core: real implementations backed by existing Jolt machinery. -(defn core-boolean [x] (if x true false)) -(defn core-cat [rf] - (fn [& a] - (case (length a) - 0 (rf) 1 (rf (a 0)) - (do (var acc (a 0)) (each x (realize-for-iteration (a 1)) (set acc (rf acc x))) acc)))) -(defn core-reader-conditional [form splicing?] - @{:jolt/type :jolt/reader-conditional :form form :splicing? splicing?}) -# reader-conditional? now lives in the Clojure collection tier (tagged-value predicate). -# sorted-map-by / sorted-set-by (and all other sorted-coll constructors and -# semantics) now live in the Clojure sorted tier (core/25-sorted.clj). -# array-seq / seque live in the Clojure collection tier (core/20-coll.clj). -# supers now lives in the Clojure collection tier (no class hierarchy: #{}). -(defn core-class [x] - (cond - # typed throwables carry their JVM class name (host_net's HTTP/SSL shims): - # (class e) -> "java.net.SocketTimeoutException" so (= ClassSym (class e)) holds - (and (table? x) (get x :class)) (get x :class) - (nil? x) nil (number? x) "java.lang.Number" (string? x) "java.lang.String" - (boolean? x) "java.lang.Boolean" (keyword? x) "clojure.lang.Keyword" - (function? x) "clojure.lang.IFn" (buffer? x) "[B" - (string (type x)))) -# clojure-version / munge / test now live in the Clojure collection tier -# (core/20-coll.clj). - - -# ============================================================ -# Bit operations (needed for persistent data structures) -# ============================================================ - -(def core-bit-and (fn [a b] (band a b))) -(def core-bit-or (fn [a b] (bor a b))) -(def core-bit-xor (fn [a b] (bxor a b))) -(def core-bit-not (fn [a] (bnot a))) -(def core-bit-shift-left (fn [x n] (blshift x n))) -(def core-bit-shift-right (fn [x n] (brshift x n))) -(def core-bit-clear (fn [x n] (band x (bnot (blshift 1 n))))) -(def core-bit-set (fn [x n] (bor x (blshift 1 n)))) -(def core-bit-flip (fn [x n] (bxor x (blshift 1 n)))) -(def core-bit-test (fn [x n] (not= 0 (band x (blshift 1 n))))) -(def core-bit-and-not (fn [a b] (band a (bnot b)))) -(def core-unsigned-bit-shift-right (fn [x n] (brushift x n))) - -# ============================================================ -# Integer coercion -# ============================================================ - -(def core-int (fn [x] (if (core-char? x) (x :ch) (math/trunc x)))) -(def core-long (fn [x] (if (core-char? x) (x :ch) (math/trunc x)))) -(def core-double (fn [x] (* 1.0 (if (core-char? x) (x :ch) x)))) -(def core-float core-double) -# num and the unchecked-*/promoting-' arithmetic live in the Clojure -# collection tier (core/20-coll.clj) — jolt numbers don't overflow. -(defn core-char [x] - "(char code-or-char) -> a character value." - (cond - (core-char? x) x - (number? x) (make-char (math/trunc x)) - (string? x) (make-char (in x 0)) - (error "char expects a number or character"))) - -# ============================================================ -# Hash -# ============================================================ - -(def core-hash (fn [x] (hash x))) - - -# ============================================================ -# Atom -# ============================================================ - -(defn core-atom - "Create an atom. Accepts optional :validator fn and :meta map." - [val & opts] - (var atm @{:jolt/type :jolt/atom :value val :watches @{} :validator nil}) - (var i 0) - (while (< i (length opts)) - (case (opts i) - :validator (put atm :validator (opts (+ i 1))) - :meta (let [m (opts (+ i 1))] - (var meta-tab @{}) - (each k (keys m) (put meta-tab k (get m k))) - (table/setproto atm meta-tab) - (put atm :jolt/meta m))) - (+= i 2)) - atm) - -# atom? now lives in the Clojure collection tier (tagged-value predicate). - -# Futures — run the body on a real OS thread (ev/thread) for true parallelism. -# Janet threads have separate heaps, so the thunk and the state it closes over are -# MARSHALLED (copied) to the worker thread and the result is marshalled back. A -# future therefore sees a *snapshot* of captured state and communicates only via -# its return value — mutating a captured atom does not propagate to the parent. -# Coordination uses two channels: a thread-chan carries the single [:ok v] / -# [:error e] result back, and a parent-local chan acts as a broadcast latch that -# is closed when the result lands so any number of deref-ers can unpark. -(defn core-future? [x] (and (table? x) (= :jolt/future (x :jolt/type)))) - -(defn core-future-call [thunk] - (def tc (ev/thread-chan 1)) # worker thread -> collector (shared, thread-safe) - (def latch (ev/chan)) # parent-local: closed when the result is in - (def fut @{:jolt/type :jolt/future :latch latch :cached false :res nil :cancelled false}) - # Worker: compute on a fresh OS thread, send back a marshalled result. The give - # is guarded so a non-marshallable value can't strand deref-ers forever. - (ev/spawn-thread - (def res (try [:ok (thunk)] ([e] [:error e]))) - (try (ev/give tc res) - ([_] (ev/give tc [:error "future result is not marshallable across threads"])))) - # Collector: a parent-side fiber bridges the single result into the box and - # closes the latch to wake every waiter. If the future was already cancelled, - # the box is finalized — drop the late result and don't re-close the latch. - (ev/spawn - (def res (ev/take tc)) - (when (not (fut :cancelled)) - (put fut :res res) - (put fut :cached true) - (try (ev/chan-close latch) ([_] nil)))) - fut) - -(defn- future-result [fut] - (def res (fut :res)) - (if (= :error (in res 0)) (error (in res 1)) (in res 1))) - -# future-done? / future-cancelled? now live in the Clojure collection tier (pure -# reads of :cached/:cancelled). core-future? stays — deref/future-cancel call it. -# Janet OS threads can't be interrupted, so the worker still runs to completion -# in the background; we can only mark the *future* cancelled (done) so deref -# raises and realized?/future-done?/future-cancelled? reflect it. Returns false -# if the future has already completed (matching Clojure). -(defn core-future-cancel [x] - (if (and (core-future? x) (not (x :cached)) (not (x :cancelled))) - (do - (put x :cancelled true) - (put x :res [:error "future cancelled"]) - (put x :cached true) - (try (ev/chan-close (x :latch)) ([_] nil)) - true) - false)) - -# future macro: (future body...) -> (future-call (fn* [] body...)) -(defn core-deref [ref & opts] - (cond - (and (table? ref) (= :jolt/reduced (ref :jolt/type))) - (ref :val) - (and (table? ref) (= :jolt/atom (ref :jolt/type))) - (ref :value) - (and (table? ref) (= :jolt/volatile (ref :jolt/type))) - (ref :val) - (and (table? ref) (= :jolt/delay (ref :jolt/type))) - (if (ref :realized) (ref :val) - (let [v ((ref :fn))] (put ref :val v) (put ref :realized true) v)) - (and (table? ref) (= :jolt/future (ref :jolt/type))) - (if (empty? opts) - (do (when (not (ref :cached)) (ev/take (ref :latch))) (future-result ref)) - # (deref future timeout-ms timeout-val): wait at most timeout-ms. The - # deadline cancels the parked take; if the result still hasn't landed we - # return the supplied timeout value (the future keeps running). - (let [timeout-val (in opts 1)] - (when (not (ref :cached)) - (try (ev/with-deadline (/ (in opts 0) 1000) (ev/take (ref :latch))) ([_] nil))) - (if (ref :cached) (future-result ref) timeout-val))) - (and (table? ref) (= :jolt/var (ref :jolt/type))) - (ref :root) - ref)) - -(defn- atom-validate - "Call validator on atm. Returns the value if valid, errors otherwise." - [atm val] - (let [v (atm :validator)] - (if v - (if (v val) val - (error "Validator rejected value")) - val))) - -(defn- atom-notify-watches - [atm old-val new-val] - (loop [[k w] :pairs (atm :watches)] - (w k atm old-val new-val))) - -(defn core-reset! [atm val] - (let [old-val (atm :value)] - (atom-validate atm val) - (put atm :value val) - (atom-notify-watches atm old-val val) - val)) - -(defn core-swap! [atm f & args] - (var old-val (atm :value)) - (var new-val (apply f old-val args)) - (atom-validate atm new-val) - (put atm :value new-val) - (atom-notify-watches atm old-val new-val) - new-val) - -# Atom peripheral ops (swap-vals!/reset-vals!/compare-and-set!/get-validator/ -# add-watch/remove-watch/set-validator!) now live in the Clojure collection tier — -# composed over the native atom ops + jolt.host/ref-put!. atom/swap!/reset!/deref -# and the atom-validate/atom-notify-watches helpers stay native (compiler-critical). - -# ============================================================ diff --git a/src/jolt/core_types.janet b/src/jolt/core_types.janet deleted file mode 100644 index ca35f03..0000000 --- a/src/jolt/core_types.janet +++ /dev/null @@ -1,470 +0,0 @@ -# Jolt Core — vector helpers, predicates, math, comparison, equality -# Extracted from core.janet (jolt-nma8, phase 2b split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./regex) -(use ./config) -(use ./pv) -(use ./plist) - -# ------------------------------------------------------------ -# Vector representation helpers -# -# In immutable mode a vector value is a structural-sharing persistent vector -# (pvec); in mutable mode it is a plain Janet array. Janet tuples may also still -# appear (e.g. literals that have not been routed through make-vec), so the read -# helpers below accept tuple, pvec and (mutable mode) array uniformly. -# ------------------------------------------------------------ - -(defn jvec? - "True when x is a vector VALUE. In immutable mode that is a persistent vector - or tuple; in mutable mode vectors are plain arrays (so vectors and lists share - one fast representation — `vector?` is true for both)." - [x] - (if mutable? - (or (array? x) (tuple? x)) - (or (tuple? x) (pvec? x)))) - -(defn vcount [x] (if (pvec? x) (pv-count x) (length x))) -(defn vnth [x i] (if (pvec? x) (pv-nth x i) (in x i))) - -(defn vview - "An indexed (tuple/array) view of a vector value, for iteration/slicing." - [x] - (if (pvec? x) (pv->array x) x)) - -(defn make-vec - "Build a vector value from a Janet array/tuple of elements, honoring the - build-time collection mode." - [xs] - (if mutable? (array ;xs) (pv-from-indexed xs))) - -(defn core-transient? - "True when x is a transient (a mutable scratch collection). See `transient`." - [x] - (and (table? x) (= :jolt/transient (get x :jolt/type)))) - -# Sorted-coll tag checks + entries view, defined this early because canon-key, -# empty?, and jolt-equal? (all below) need them. The sorted-coll SEMANTICS are -# pure Clojure (core/25-sorted.clj); see the dispatch section further down. -# SEED-TWIN: sorted-map?/sorted-set?/sorted? also live in the overlay -# (jolt-core/clojure/core/25-sorted.clj); the overlay copies are the public ones -# (NOT in core-bindings). These seed copies exist only for earlier-tier seed -# dispatch. Change both copies together — docs/seed-overlay-registry.md. -(defn core-sorted-map? [x] (and (table? x) (= :jolt/sorted-map (x :jolt/type)))) -(defn core-sorted-set? [x] (and (table? x) (= :jolt/sorted-set (x :jolt/type)))) -(defn core-sorted? [x] (or (core-sorted-map? x) (core-sorted-set? x))) -# The comparator-ordered entries as a Janet array (entries are jolt vectors: -# pvecs in immutable mode, arrays in mutable mode) — for the seed's printers/ -# equality. Materialized from the red-black tree via the coll's own :entries op -# (jolt-0hbr); the old sorted-VECTOR rep is read directly as a fallback. -(defn sorted-entries-arr [coll] - (def ef (let [ops (coll :ops)] (and ops (ops :entries)))) - (def e (if ef (ef coll) (coll :entries))) - (if (pvec? e) (pv->array e) e)) - -# Lazy cell chain over an indexed (tuple/array) collection, walking by INDEX — -# O(1) per step. Slicing the remainder per step (the old shape) made every -# full walk over a concrete collection O(n^2). -(defn indexed-cells [t i] - (if (>= i (length t)) nil - @[(in t i) (fn [] (indexed-cells t (+ i 1)))])) - -# A nil element/key/value nested in a collection used AS a map key would be -# dropped when canon-key re-keys a native Janet table (a Janet struct can't hold a -# nil key or value), so #{nil 1} would canonicalize like #{1} and collide as a key -# (jolt-zcm9). Box a nested nil to a marker. It must be VALUE-hashable: the -# canonical struct becomes a long-lived phm key whose hash has to survive the -# marshal/snapshot/fork that init-cached uses, so an identity-hashed mutable table -# (like the transient sentinel below) won't do — its hash isn't preserved across -# unmarshal. An interned keyword hashes by content. Collision risk is only a real -# element equal to this exact keyword — the same negligible class as canon-key's -# existing set/map struct aliasing. -(def canon-nil (keyword "jolt.lang/canonical-nil")) -(defn- canon-box [c] (if (nil? c) canon-nil c)) - -# Canonicalize a collection key/element to a value-hashable Janet struct/tuple so -# the PHM/PHS treat value-equal maps/vectors as the same key (Janet hashes tables -# by identity otherwise). Installed into phm via set-canonicalize-key!. -(var canon-key nil) -(set canon-key - (fn [k] - (cond - (pvec? k) (tuple ;(map canon-key (pv->array k))) - (plist? k) (tuple ;(map canon-key (pl->array k))) - (set? k) (do (def t @{}) (each e (phs-seq k) (put t (canon-box (canon-key e)) true)) (table/to-struct t)) - (phm? k) (do (def t @{}) (each pair (phm-entries k) (put t (canon-box (canon-key (in pair 0))) (canon-box (canon-key (in pair 1))))) (table/to-struct t)) - # sorted colls canonicalize like their unsorted counterparts, so - # (get {(sorted-map :a 1) :hit} {:a 1}) finds the key - (core-sorted-map? k) (do (def t @{}) (each e (sorted-entries-arr k) (put t (canon-box (canon-key (vnth e 0))) (canon-box (canon-key (vnth e 1))))) (table/to-struct t)) - (core-sorted-set? k) (do (def t @{}) (each x (sorted-entries-arr k) (put t (canon-box (canon-key x)) true)) (table/to-struct t)) - (and (table? k) (get k :jolt/deftype)) - (do (def t @{}) (each kk (keys k) (when (not= kk :jolt/deftype) (put t kk (canon-box (canon-key (get k kk)))))) (table/to-struct t)) - (struct? k) (do (def t @{}) (each kk (keys k) (put t (canon-box (canon-key kk)) (canon-box (canon-key (get k kk))))) (table/to-struct t)) - (array? k) (tuple ;(map canon-key k)) - (tuple? k) (tuple ;(map canon-key k)) - k))) -(set-canonicalize-key! canon-key) - -# Janet tables silently drop a nil key (put/get with nil is a no-op), but Clojure -# maps allow a nil key. The transient map/set keys its native table by canon-key, -# which returns nil only for nil input — so route nil to a unique sentinel. This -# one is a fresh mutable table (canon-key never produces one, so no collision); it -# is fine here because a transient's native table is built and consumed within one -# operation and never crosses a marshal boundary, so identity hashing is stable. -(def tbl-nil-key @{}) -(defn tbl-key [k] (if (nil? k) tbl-nil-key (canon-key k))) - -# A transient SET stores `(tbl-key x) -> x`, i.e. the member IS the table value. A -# nil member can't be a Janet table value either (put with a nil value drops the -# entry), so box nil as the same sentinel and unbox on read-back. -(defn tbl-box [x] (if (nil? x) tbl-nil-key x)) -(defn tbl-unbox [v] (if (= v tbl-nil-key) nil v)) - -# All [k v] entries of a map (struct or phm), nil-valued keys included. Use this -# instead of (keys (phm-to-struct m)) — phm-to-struct drops keys whose value is -# nil, which is exactly what Clojure maps must keep. -(defn map-entries-of [m] - (if (phm? m) (phm-entries m) (map (fn [k] [k (in m k)]) (keys m)))) - -# assoc one entry onto a map value (struct or phm), preserving a nil key/value and -# value-comparing collection keys (promotes a struct to a phm when needed). A -# single-entry core-assoc usable by fns defined before core-assoc itself. -(defn map-assoc1 [m k v] - (cond - (phm? m) (phm-assoc m k v) - (or (nil? k) (nil? v) (table? k) (array? k)) - (do (var p (make-phm)) (each ek (keys m) (set p (phm-assoc p ek (in m ek)))) (phm-assoc p k v)) - (do (def t (merge @{} m)) (put t k v) (table/to-struct t)))) - -# Build a map from a flat [k v k v ...] array: a phm when any key/value is nil or -# a key is a collection (value hashing); a struct otherwise. One O(n) pass. -(defn- kvs->map [kvs] - (var need-phm false) (var i 0) - (while (< i (length kvs)) - (let [k (in kvs i) v (in kvs (+ i 1))] - (when (or (nil? k) (nil? v) (table? k) (array? k)) (set need-phm true))) - (+= i 2)) - (if need-phm - (do (var m (make-phm)) (var j 0) - (while (< j (length kvs)) (set m (phm-assoc m (in kvs j) (in kvs (+ j 1)))) (+= j 2)) m) - (struct ;kvs))) - -(defn realize-for-iteration [c] - "Normalize a seqable to a Janet array/tuple for iteration: pvec -> array, - set -> seq, lazy-seq -> realized array; others pass through. Warning: will - loop on infinite lazy-seqs. Terminates on the empty cell, not on nil." - (cond - # nil is an empty seq in Clojure — iterating it yields nothing. - (nil? c) @[] - (shape-rec? c) (map (fn [k] (tuple k (shape-get c k nil))) (shape-keys c)) - (pvec? c) (pv->array c) - (plist? c) (pl->array c) - (set? c) (phs-seq c) - (phm? c) (phm-entries c) - # sorted colls iterate their comparator-ordered entries/elements - (core-sorted? c) (sorted-entries-arr c) - # a string is a seqable of CHARS in Clojure (not bytes/1-char strings) — mirror - # core-seq so vec/set/into over a string agree with seq (jolt-dl4s) - (string? c) (tuple ;(map make-char (string/bytes c))) - # byte array (Janet buffer) -> array of byte values - (buffer? c) (let [a @[]] (each x c (array/push a x)) a) - # struct map literal (no :jolt/type marker — not a symbol/char) -> entries - (and (struct? c) (nil? (get c :jolt/type))) (map (fn [k] (tuple k (get c k))) (keys c)) - # raw host table (System/getenv, os/environ) — also a map: entries - (and (table? c) (nil? (get c :jolt/type)) (nil? (get c :jolt/deftype))) - (map (fn [k] (tuple k (get c k))) (keys c)) - (lazy-seq? c) - (do - (var items @[]) - (var cur c) - (var go true) - (while go - (let [cell (realize-ls cur)] - (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) - (set go false) - (do - (array/push items (in cell 0)) - (let [rt (in cell 1)] - (if (nil? rt) (set go false) (set cur (ls-rest-cached cur rt)))))))) - items) - c)) - -# Syntax-quote form builders. The syntax-quote lowering (evaluator) emits calls to -# these so a `(...)/`[...] body is plain compilable code instead of an interpreted -# special form. A list FORM is a Janet array, a vector FORM a tuple (the reader's -# representation), so these build those types. Each concat part is either a 1-elem -# wrap (__sq1, a non-spliced item) or a spliced seq (~@), flattened in order. -(defn core-sq1 [x] @[x]) - -(defn core-sqcat [& parts] - (def r @[]) - (each p parts (each x (realize-for-iteration p) (array/push r x))) - r) - -(defn core-sqvec [& parts] - (def r @[]) - (each p parts (each x (realize-for-iteration p) (array/push r x))) - (tuple/slice r)) - -# Map builder: parts are alternating k v (no splicing in map syntax-quote). -(defn core-sqmap [& parts] - # A syntax-quoted map template is Clojure's array-map case: construction - # order is source order and must survive into the built map, which usually - # becomes a FORM whose entries the evaluator walks (jolt-p3c). Same - # carriers as the reader: struct prototype / phm field. - (def kvs (array ;parts)) - (def m (kvs->map kvs)) - (cond - (struct? m) (struct/with-proto (struct :jolt/kv-order (tuple/slice kvs)) ;kvs) - (table? m) (do (put m :jolt/kv-order (tuple/slice kvs)) m) - m)) - -# Set builder: like core-sqvec but yields a set, so `#{~@a} splices into a set. -(defn core-sqset [& parts] - (def r @[]) - (each p parts (each x (realize-for-iteration p) (array/push r x))) - (apply make-phs r)) - -# ============================================================ -# Predicates -# ============================================================ - -# SEED-TWIN: char? is also defined in the overlay (jolt-core/clojure/core/ -# 20-coll.clj) and the overlay copy is the public one (NOT in core-bindings). -# This seed copy is internal type dispatch only. docs/seed-overlay-registry.md. -(defn core-char? [x] (and (struct? x) (= :jolt/char (x :jolt/type)))) -(defn char-code [c] (c :ch)) -(defn char->string [c] (string/from-bytes (c :ch))) - -(defn core-nil? [x] (nil? x)) -(defn core-not [x] (if x false true)) -# some? / true? / false? now live in the Clojure collection tier. -(defn core-string? [x] (string? x)) -(defn core-number? [x] (number? x)) -(defn core-fn? [x] (or (function? x) (cfunction? x))) -(defn core-keyword? [x] (keyword? x)) -(defn core-symbol? [x] (and (struct? x) (= :symbol (x :jolt/type)))) -# A record shape-rec is a Janet tuple (jvec? true), but a record is NOT a vector -# in Clojure — `(vector? record)` is false, and so is `(sequential? record)`. -# Excluding it here keeps map-destructuring of a record off the `& {:keys}` kwargs -# coerce path (which does `(apply hash-map x)` for a sequential x). jvec? itself -# stays as-is for internal representation dispatch. -(defn core-vector? [x] (and (jvec? x) (not (shape-rec? x)))) -# map? is STRICT: a plain struct map literal, a phm, a sorted map, or a record. -# Tagged structs (symbols/chars/uuids — anything with :jolt/type) are VALUES, -# not maps. (sorted-map? is defined later, so the table check is inlined.) -(defn core-map? [x] - (or (shape-rec? x) - (phm? x) - (and (struct? x) (nil? (get x :jolt/type))) - (and (table? x) - (or (not (nil? (get x :jolt/deftype))) - (= :jolt/sorted-map (get x :jolt/type)))))) -# seq? is true only for actual sequences (lists, lazy-seqs) — NOT vectors, which -# are not ISeq in Clojure. (A Janet array represents a Clojure list/seq result.) -(defn core-seq? [x] (or (array? x) (plist? x) (lazy-seq? x))) -# coll? mirrors map?'s strictness for structs/tables, and includes the sorted -# collections and records (IPersistentCollection in Clojure). -(defn core-coll? [x] - (or (array? x) (tuple? x) (pvec? x) (plist? x) (phm? x) (set? x) (lazy-seq? x) - (and (struct? x) (nil? (get x :jolt/type))) - (and (table? x) - (or (not (nil? (get x :jolt/deftype))) - (= :jolt/sorted-map (get x :jolt/type)) - (= :jolt/sorted-set (get x :jolt/type)))))) - - - -(defn core-identical? [a b] (= a b)) - -# Strictness helpers: like Clojure, numeric ops reject non-numbers, and the -# integer ops (odd?/even?) reject non-integers (incl. infinities, NaN, fractions). -(defn- finite-num? [x] (and (number? x) (= x x) (< (if (< x 0) (- x) x) math/inf))) -(defn- need-num [x op] - (if (number? x) x (error (string op " requires a number, got " (type x))))) -(defn- need-int [x op] - (if (and (number? x) (= x x) (< (if (< x 0) (- x) x) math/inf) (= x (math/floor x))) x - (error (string op " requires an integer")))) - -# zero? / pos? live in the syntax tier (core/00-syntax.clj) — empty? and the -# analyzer use them; neg? lives in the collection tier (20-coll.clj). -# even?/odd? are PERF-WALL residents: (filter even? ...) is idiomatic and the -# overlay versions cost an extra call layer per element (seq-pipe bench 4x). -(defn core-even? [n] (= 0 (% (need-int n "even?") 2))) -(defn core-odd? [n] (not= 0 (% (need-int n "odd?") 2))) - -# Finite integral number: NaN and the infinities are NOT integers (floor of -# inf is inf, so the naive floor check wrongly accepted them). -(defn core-integer? [x] - (and (number? x) (= x x) - (< x math/inf) (> x (- math/inf)) - (= x (math/floor x)))) -(defn core-list? [x] (or (plist? x) (and (array? x) (not (get x :jolt/type))))) - -# empty? now lives in the syntax tier (core/00-syntax.clj): the expanders -# call it, so it must exist before the kernel tier compiles. - -# every? lives in the syntax tier (core/00-syntax.clj) — the analyzer uses it; -# the canonical seq/first/next walk short-circuits lazy seqs the same way. - -# ============================================================ -# Math — Clojure semantics (variadic, / with one arg = reciprocal) -# ============================================================ - -(def core-+ (fn [& args] (if (= 0 (length args)) 0 (+ ;args)))) - -(def core-sub - (fn [& args] - (if (= 0 (length args)) - (error "Wrong number of args (0) passed to: -") - (apply - args)))) - -(def core-* (fn [& args] (if (= 0 (length args)) 1 (* ;args)))) - -(def core-/ - (fn [& args] - (case (length args) - 0 (error "Wrong number of args (0) passed to: /") - 1 (/ 1 (args 0)) - (apply / args)))) - -(def core-inc inc) -(def core-dec dec) -# Clojure integer division: quot truncates toward zero; rem matches the sign of -# the dividend; mod matches the sign of the divisor (floored). -(def core-quot (fn [n d] - (when (or (not (finite-num? n)) (not (finite-num? d))) (error "quot requires finite numbers")) - (when (= d 0) (error "Divide by zero")) - (let [q (/ n d)] (if (< q 0) (math/ceil q) (math/floor q))))) -(def core-rem (fn [n d] (- n (* (core-quot n d) d)))) -(def core-mod (fn [n d] - (let [m (core-rem n d)] - (if (or (= m 0) (= (> n 0) (> d 0))) m (+ m d))))) - -# max / min now live in the Clojure collection tier (canonical pairwise -# >/<, so non-numbers throw and NaN behaves as on the JVM). - - -(defn core-rand [& n] (let [r (math/random)] (if (empty? n) r (* r (in n 0))))) -# rand-int / shuffle / random-uuid now live in the Clojure collection tier -# over the rand host seam (canonical: rand-int truncates toward zero). - -# ============================================================ -# Comparison -# ============================================================ - -(defn- eq-seqable - "If x is a Clojure sequential (vector/list/lazy-seq), return its elements as - an array; otherwise nil. Lets = compare across tuple/array/lazy-seq." - [x] - (cond - # a shape-rec is a MAP, not a sequence, even though it is a tuple - (shape-rec? x) nil - (lazy-seq? x) (realize-for-iteration x) - (pvec? x) (pv->array x) - (plist? x) (pl->array x) - (tuple? x) x - (array? x) x - nil)) - -(defn- eq-map-pairs - "Return [k v] pairs for a map-like value (phm/sorted-map/struct/table), else nil." - [x] - (cond - # a record shape-rec returns nil so equality falls to deep=, which is - # type-aware (the descriptor is interned per type): a record equals only a - # same-type record, never a plain map — mirroring the :jolt/deftype table - # form below. A plain-map shape-rec compares by pairs. - (shape-rec? x) (if (record-tag x) nil (map (fn [k] @[k (shape-get x k nil)]) (shape-keys x))) - (phm? x) (phm-entries x) - # sorted-map equals any map with the same pairs (representation-agnostic, as - # in Clojure); sorted-set is handled by the set branch of jolt-equal? - (core-sorted-map? x) (map (fn [e] @[(vnth e 0) (vnth e 1)]) (sorted-entries-arr x)) - (core-sorted-set? x) nil - (and (table? x) (get x :jolt/deftype)) nil - (struct? x) (pairs x) - (table? x) (pairs x) - nil)) - -# Elements of a set-like value (phs or sorted-set) as an array, else nil. -(defn- eq-set-elems [x] - (cond - (set? x) (phs-seq x) - (core-sorted-set? x) (sorted-entries-arr x) - nil)) - -(var jolt-equal? nil) -(set jolt-equal? - (fn [a b] - (let [sa (eq-seqable a) sb (eq-seqable b)] - (cond - # both sequential: compare element-wise (vectors/lists/lazy-seqs equal) - (and sa sb) - (if (= (length sa) (length sb)) - (do (var ok true) (var i 0) - (while (and ok (< i (length sa))) - (unless (jolt-equal? (in sa i) (in sb i)) (set ok false)) - (++ i)) - ok) - false) - (or sa sb) false - # sets (phs or sorted-set, in any combination) - (or (set? a) (set? b) (core-sorted-set? a) (core-sorted-set? b)) - # value-based: same size and every element of a is value-equal to some - # element of b (so #{ {:a 1} } equals #{ (hash-map :a 1) } regardless of - # the elements' underlying representations) - (let [ea (eq-set-elems a) eb (eq-set-elems b)] - (if (and ea eb (= (length ea) (length eb))) - (do - (var ok true) - (each x ea - (unless (some (fn [y] (jolt-equal? x y)) eb) (set ok false))) - ok) - false)) - # maps: compare key/value pairs recursively, order-independent - true - (let [pa (eq-map-pairs a) pb (eq-map-pairs b)] - (if (or pa pb) - (if (and pa pb (= (length pa) (length pb))) - (do (var ok true) - (each pair pa - (let [k (in pair 0) v (in pair 1) - found (do (var fv :jolt/none) - (each p2 pb (when (jolt-equal? k (in p2 0)) (set fv (in p2 1)))) - fv)] - (unless (and (not= found :jolt/none) (jolt-equal? v found)) (set ok false)))) - ok) - false) - (deep= a b))))))) - -(defn core-= [& args] - (if (< (length args) 2) true - (do - (var ok true) - (var i 0) - (while (and ok (< i (dec (length args)))) - (unless (jolt-equal? (args i) (args (+ i 1))) (set ok false)) - (++ i)) - ok))) - -# not= lives in the syntax tier (core/00-syntax.clj) — the kernel uses it. - -# Comparisons are variadic: (< a b c) means a < b < c. -(defn- chain-cmp [op opname xs] - # 1-arity (e.g. (< x)) is true regardless of x and does no type check. - (when (>= (length xs) 2) (each x xs (need-num x opname))) - (var ok true) (var i 0) - (while (and ok (< i (dec (length xs)))) - (unless (op (in xs i) (in xs (+ i 1))) (set ok false)) - (++ i)) - ok) -(defn core-< [& xs] (chain-cmp < "<" xs)) -(defn core-> [& xs] (chain-cmp > ">" xs)) -(defn core-<= [& xs] (chain-cmp <= "<=" xs)) -(defn core->= [& xs] (chain-cmp >= ">=" xs)) - -# ============================================================ diff --git a/src/jolt/deps.janet b/src/jolt/deps.janet deleted file mode 100644 index c84a1b9..0000000 --- a/src/jolt/deps.janet +++ /dev/null @@ -1,300 +0,0 @@ -# deps.edn resolution for Jolt. -# -# Resolve git and :local/root dependencies from a deps.edn into a list of source -# directories, which the loader then searches (see evaluator/find-ns-file). We -# reuse jpm's git fetch + cache (jpm/pm) rather than shipping a package manager. -# Maven (:mvn/version) deps are ignored — git only, pure clj/cljc only. -# -# jpm is loaded lazily (require, not import) so it's needed only at resolve time -# (dev/build), never embedded in the shipped binary. - -(import ./reader :as reader) - -# Read deps.edn with Jolt's reader (not Janet's parse) so EDN `;` line comments -# are handled. It returns plain Janet data — structs with keyword keys, tuples — -# which we walk directly. (#{} sets and tagged literals aren't expected in the -# :deps/:paths we read.) -(defn read-edn [path] - (when (os/stat path) - (try (reader/parse-string (slurp path)) ([_] nil)))) - -(defn- jpm-fn [mod sym] - (get-in (require mod) [sym :value])) - -(defn- ensure-jpm-config [tree] - ((jpm-fn "jpm/config" 'load-default)) - (setdyn :modpath tree) - (setdyn :gitpath (dyn :gitpath "git"))) - -(defn- clone-git [spec] - # spec is a deps.edn dep value: {:git/url ... :git/sha/:git/tag ...} - (def resolve-bundle (jpm-fn "jpm/pm" 'resolve-bundle)) - (def download-bundle (jpm-fn "jpm/pm" 'download-bundle)) - # Run git silenced (jpm's shell honors :silent): its checkout chatter - # ("HEAD is now at …") otherwise lands on STDOUT and corrupts the - # documented `JOLT_PATH=$(jolt-deps path)` capture. Progress goes to stderr. - (eprintf "jolt-deps: fetching %s @ %s" - (get spec :git/url) (or (get spec :git/sha) (get spec :git/tag) "HEAD")) - (with-dyns [:silent true] - (def b (resolve-bundle {:url (get spec :git/url) - :sha (get spec :git/sha) - :tag (get spec :git/tag) - :shallow false})) - (download-bundle (b :url) (b :type) (b :tag) (b :shallow)))) - -(defn- src-roots - "Source dirs of a project/dep at `dir`: its deps.edn :paths joined to dir - (default [\"src\"])." - [dir edn] - (map |(string dir "/" $) (or (and edn (get edn :paths)) ["src"]))) - -# --- user config + aliases (tools.deps-shaped, scoped to git/:local) ----------- - -(defn config-dir - "User-level config dir: $JOLT_CONFIG, else $XDG_CONFIG_HOME/jolt, else - ~/.jolt — the same fallback chain the Clojure CLI uses for ~/.clojure." - [] - (or (os/getenv "JOLT_CONFIG") - (when-let [x (os/getenv "XDG_CONFIG_HOME")] - (when (> (length x) 0) (string x "/jolt"))) - (string (os/getenv "HOME") "/.jolt"))) - -(defn- merge-per-key [a b] # dictionary union, b's entries win - (def out @{}) - (each m [a b] (when (dictionary? m) (eachp [k v] m (put out k v)))) - out) - -# Reader symbols carry position metadata, so any map keyed by SYMBOLS (deps -# libs, task names) must be re-keyed by name before merging or deduping. -(defn- sym-name [x] - (if (and (dictionary? x) (get x :name)) - (if-let [ns (get x :ns)] - (string ns "/" (get x :name)) - (get x :name)) - (string x))) - - -(defn- ensure-jpm-dep - "A :jpm/module dep declares a janet module installed through jpm (e.g. - spork/http). jolt-deps doesn't manage janet packages — jpm does — so this - just verifies the module is importable, optionally running `jpm install - <:jpm/install>` once when it isn't, and fails with the install hint - otherwise. Contributes no source roots; the janet.* bridge autoloads the - module at first use." - [lib spec] - (def mod (get spec :jpm/module)) - (defn importable? [] ((protect (require mod)) 0)) - (unless (importable?) - (when-let [pkg (get spec :jpm/install)] - (eprintf "jolt-deps: %s: jpm module %s missing — running `jpm install %s`" - (sym-name lib) mod pkg) - (os/execute ["jpm" "install" pkg] :p)) - (unless (importable?) - (errorf "%s: janet module %s is not importable. Install it with `jpm install %s` (jolt-deps leaves janet packages to jpm)." - (sym-name lib) mod (or (get spec :jpm/install) mod))))) - -(defn- merge-by-name [a b] # union of symbol-keyed dictionaries, b wins - (def out @{}) - (each m [a b] (when (dictionary? m) (eachp [k v] m (put out (sym-name k) v)))) - out) - -(defn- mkdirs [p] - (def abs (string/has-prefix? "/" p)) - (var acc nil) - (each seg (filter |(not= "" $) (string/split "/" p)) - (set acc (cond (nil? acc) (if abs (string "/" seg) seg) (string acc "/" seg))) - (unless (os/stat acc) (os/mkdir acc)))) - -(defn- default-tree - "Where git clones land when no tree is given: $JOLT_GITLIBS, else - (config-dir)/gitlibs — a global, sha-immutable cache shared across projects - (the tools.gitlibs ~/.gitlibs model), not a per-project ./jpm_tree." - [] - (def g (os/getenv "JOLT_GITLIBS")) - (if (and g (> (length g) 0)) g (string (config-dir) "/gitlibs"))) - -(defn load-config - "The project deps.edn merged over the user-level one (config-dir)/deps.edn. - tools.deps merge semantics: scalar keys and :paths replace (project wins), - :deps and :aliases merge per key with the project winning. Relative - :local/root in the USER file is resolved against the cwd — prefer absolute - paths there." - [deps-edn-path] - (def proj (read-edn deps-edn-path)) - (def user (read-edn (string (config-dir) "/deps.edn"))) - (if (and (nil? user) (nil? proj)) - nil - # normalize even when only one file exists: :deps/:tasks come back keyed - # by NAME (reader symbols carry position metadata and never compare equal) - (let [u (when (dictionary? user) user) - p (when (dictionary? proj) proj) - out (merge-per-key u p)] - (put out :deps (merge-by-name (and u (get u :deps)) (and p (get p :deps)))) - (put out :aliases (merge-per-key (and u (get u :aliases)) (and p (get p :aliases)))) - (put out :tasks (merge-by-name (and u (get u :tasks)) (and p (get p :tasks)))) - out))) - -(defn combine-aliases - "Combine the selected alias keywords against `edn`'s :aliases: - :extra-paths and :extra-deps accumulate in order, :main-opts is last-wins - (the tools.deps CLI rules). Unknown alias -> error." - [edn aliases] - (def als (or (and (dictionary? edn) (get edn :aliases)) {})) - (def extra-paths @[]) - (def extra-deps @{}) - (var main-opts nil) - (each a (or aliases []) - (def spec (get als a)) - (when (nil? spec) (error (string "unknown alias: " a))) - (each p (or (get spec :extra-paths) []) (array/push extra-paths p)) - (when (dictionary? (get spec :extra-deps)) - (eachp [lib coord] (get spec :extra-deps) (put extra-deps lib coord))) - (when-let [mo (get spec :main-opts)] - (set main-opts (tuple ;(map string mo))))) - {:extra-paths extra-paths :extra-deps extra-deps :main-opts main-opts}) - -(defn alias-main-opts - "The :main-opts the selected aliases produce (last alias with the key wins), - or nil. Reads the merged user+project config." - [deps-edn-path aliases] - (get (combine-aliases (load-config deps-edn-path) aliases) :main-opts)) - -(defn resolve-deps - "Resolve the git/:local deps of `deps-edn-path` into an ordered, de-duplicated - array of source dirs (the project's own :paths first, then each dependency's, - transitively). `tree` is where jpm's clone cache lives (default ./jpm_tree). - `aliases` (keywords) pull :extra-paths/:extra-deps from the merged config's - :aliases. The user-level deps.edn (see load-config) merges under the project." - [deps-edn-path &opt tree aliases] - (default tree (default-tree)) - (mkdirs tree) - (ensure-jpm-config tree) - (def edn (load-config deps-edn-path)) - (def extra (combine-aliases edn aliases)) - (def roots @[]) - (def seen @{}) # lib name -> chosen coordinate (for conflict reporting) - (defn add-root [r] (unless (index-of r roots) (array/push roots r))) - (defn coord-str [spec] - (cond - (and (dictionary? spec) (get spec :local/root)) - (string ":local/root " (get spec :local/root)) - (and (dictionary? spec) (get spec :git/url)) - (string (get spec :git/url) " @ " (or (get spec :git/sha) (get spec :git/tag))) - (string/format "%j" spec))) - (defn coord= [a b] - (and (deep= (get a :local/root) (get b :local/root)) - (deep= (get a :git/url) (get b :git/url)) - (deep= (get a :git/sha) (get b :git/sha)) - (deep= (get a :git/tag) (get b :git/tag)) - (deep= (get a :jpm/module) (get b :jpm/module)))) - (def queue @[]) - (defn discover [lib spec base-dir] - (def k (sym-name lib)) - (if-let [prev (get seen k)] - (unless (coord= prev spec) - (eprintf "WARNING: %s: conflicting coordinates — using %s, ignoring %s" - k (coord-str prev) (coord-str spec))) - (do - (put seen k spec) - (when (and (dictionary? spec) (get spec :jpm/module)) - (ensure-jpm-dep lib spec)) - (def dir - (cond - (and (dictionary? spec) (get spec :git/url)) - # :deps/root (tools.deps): the project lives in a subdirectory - # of the repo — monorepos like ring-clojure/ring. - (let [cloned (clone-git spec) - root (get spec :deps/root)] - (if root (string cloned "/" root) cloned)) - (and (dictionary? spec) (get spec :local/root)) - (let [lr (get spec :local/root)] - (if (string/has-prefix? "/" lr) lr (string base-dir "/" lr))) - nil)) # :mvn/* and anything else: skip - (when dir - (def dep-edn (read-edn (string dir "/deps.edn"))) - (each r (src-roots dir dep-edn) (add-root r)) - (array/push queue [dep-edn dir]))))) - # the project's own paths (+ alias extra paths) lead the roots - (each r (src-roots (os/cwd) edn) (add-root r)) - (each pp (extra :extra-paths) (add-root (string (os/cwd) "/" pp))) - # breadth-first: every top-level dep registers before any transitive dep — - # so a top-level coordinate always wins, matching tools.deps. Alias - # :extra-deps go first: a selected alias's pin beats the project's. - (eachp [lib spec] (extra :extra-deps) - (discover lib spec (os/cwd))) - (eachp [lib spec] (or (and (dictionary? edn) (get edn :deps)) {}) - (discover lib spec (os/cwd))) - (while (> (length queue) 0) - (def [dep-edn dir] (get queue 0)) - (array/remove queue 0) - (when (dictionary? dep-edn) - (eachp [lib spec] (or (get dep-edn :deps) {}) - (discover lib spec dir)))) - roots) - -(defn resolve-deps-cached - "Like resolve-deps, but caches the resolved roots in the tree keyed on a hash - of the project deps.edn + the user deps.edn + the selected aliases, so an - unchanged config resolves without re-fetching." - [deps-edn-path &opt tree aliases] - (default tree (default-tree)) - (when (os/stat deps-edn-path) - # the roots depend on the PROJECT (config + aliases), so their cache is - # project-local like tools.deps' .cpcache; the clone tree stays global - (os/mkdir ".cpcache") - (def cache-file ".cpcache/jolt-deps.jdn") - (def user-path (string (config-dir) "/deps.edn")) - # The raw key material, not (hash …): janet's hash is seeded per process, - # so a hashed key never matches across invocations and the cache never hit. - (def key [(slurp deps-edn-path) - (or (when (os/stat user-path) (slurp user-path)) "") - (string/format "%j" (map string (or aliases [])))]) - (def cached (when (os/stat cache-file) (try (parse (slurp cache-file)) ([_] nil)))) - (if (and cached (deep= key (get cached :key))) - (get cached :roots) - (let [roots (resolve-deps deps-edn-path tree aliases)] - (spit cache-file (string/format "%j" {:key key :roots roots})) - roots)))) - -(defn project-source-roots - "The project's OWN source roots — its deps.edn :paths plus any alias - :extra-paths, joined to cwd — as opposed to dependency roots. These are the - 'app' namespaces: the runtime scopes the whole-program inference fixpoint to - them (JOLT_APP_PATHS) so a dep-heavy app's startup doesn't re-infer every - transitive dependency namespace (jolt-87e)." - [deps-edn-path &opt aliases] - (def out @[]) - (when (os/stat deps-edn-path) - (def edn (load-config deps-edn-path)) - (def extra (combine-aliases edn aliases)) - (each r (src-roots (os/cwd) edn) (array/push out r)) - (each pp (extra :extra-paths) (array/push out (string (os/cwd) "/" pp)))) - out) - -# --- :tasks (the honest subset of babashka's) ---------------------------------- -# A STRING task is a shell command. A MAP task carries :main-opts (jolt args — -# `-e "(...)"` covers expression tasks) and an optional :doc. Babashka-style -# bare-expression tasks aren't supported: the reader hands us parsed data, and -# round-tripping it back to source isn't worth the fragility. - -(defn tasks - "Sorted [name doc] pairs from the merged user+project :tasks." - [deps-edn-path] - (def m (get (load-config deps-edn-path) :tasks)) - (def names (sort (keys (or m @{})))) - (map (fn [n] - (def v (get m n)) - [n (when (dictionary? v) (get v :doc))]) - names)) - -(defn task-spec - "What running task `name` means: {:type :shell :cmd s} or - {:type :jolt :argv [...]}; nil when undefined." - [deps-edn-path name] - (def v (get (or (get (load-config deps-edn-path) :tasks) @{}) name)) - (cond - (nil? v) nil - (or (string? v) (buffer? v)) {:type :shell :cmd (string v)} - (and (dictionary? v) (get v :main-opts)) - {:type :jolt :argv (tuple ;(map string (get v :main-opts)))} - (error (string "task " name ": use a shell string or {:main-opts [...]}")))) diff --git a/src/jolt/deps_cli.janet b/src/jolt/deps_cli.janet deleted file mode 100644 index 3d0de25..0000000 --- a/src/jolt/deps_cli.janet +++ /dev/null @@ -1,27 +0,0 @@ -# jolt-deps — deprecated shim. Dependency resolution is now built into `jolt` -# itself (the runtime stays deps-agnostic; the CLI front-end resolves deps.edn -# into JOLT_PATH in-process). This binary forwards everything to `jolt` so -# existing scripts keep working — prefer calling `jolt` directly: -# -# jolt-deps -M:nrepl -> jolt -M:nrepl -# jolt-deps path -> jolt path -# jolt-deps run FILE -> jolt run FILE -# -# The jolt binary is found via $JOLT_BIN, else the `jolt` sitting next to this -# shim (built as a pair), else `jolt` on PATH. - -(defn- jolt-bin [] - (or (os/getenv "JOLT_BIN") - (let [self (or (first (dyn :args)) (dyn :executable)) - slashes (when self (string/find-all "/" self)) - dir (when (and slashes (> (length slashes) 0)) - (string/slice self 0 (last slashes))) - sibling (when dir (string dir "/jolt"))] - (when (and sibling (os/stat sibling)) sibling)) - "jolt")) - -(defn main [&] - (def argv (tuple/slice (or (dyn :args) @[]) 1)) - (eprint "jolt-deps is deprecated — dependency resolution is built into `jolt` now " - "(e.g. `jolt -M:nrepl`, `jolt path`, `jolt run FILE`).") - (os/exit (os/execute [(jolt-bin) ;argv] :p))) diff --git a/src/jolt/eval_base.janet b/src/jolt/eval_base.janet deleted file mode 100644 index 8587a3b..0000000 --- a/src/jolt/eval_base.janet +++ /dev/null @@ -1,609 +0,0 @@ -# Jolt Evaluator — base: forward vars, syntax-quote, ns-loading, registries -# Extracted from evaluator.janet (jolt-oudv, phase 2a split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./pv) -(use ./plist) -(use ./config) -(use ./reader) -(use ./regex) - -# Host PNG encoder, exposed to the overlay as `janet.png/encode` / `janet.png/write` -# (resolved through module-load-env below). Pure Janet, no jolt deps. -(import ./png :prefix "png/") - - -# The env this module was loaded under — proto-chains to the Janet root env; -# the janet/* interop bridge falls back to it inside env-less fibers. -(def module-load-env (fiber/getenv (fiber/current))) - -# jpm-module autoload: a janet./ reference whose module isn't -# in the env is satisfied by requiring it from the jpm module path on first -# use — (janet.spork.http/server ...) just works when spork is installed, -# and the same goes for any jpm module. Loaded bindings are cached here -# (and failures negatively cached, so a missing module errors fast). -(def janet-bridge-extras @{}) -(def janet-bridge-failed @{}) -(defn bridge-autoload - "jname is spork.http/server-shaped: require spork/http, cache its public - bindings under the dotted prefix, return the one asked for (nil when the - module is missing or has no such binding)." - [jname] - (def slash (string/find "/" jname)) - (when slash - (def mod-ns (string/slice jname 0 slash)) - (unless (get janet-bridge-failed mod-ns) - (def mod-path (string/replace-all "." "/" mod-ns)) - (def r (protect (require mod-path))) - (if (r 0) - (eachp [sym entry] (r 1) - (when (and (symbol? sym) (table? entry) (not (get entry :private))) - (put janet-bridge-extras (string mod-ns "/" sym) (get entry :value)))) - (put janet-bridge-failed mod-ns true)))) - (in janet-bridge-extras jname)) - -(defn sym-name? - [sym-s name-str] - (and (struct? sym-s) (= :symbol (sym-s :jolt/type)) (= name-str (sym-s :name)))) - -(defn- special-symbol? - [name] - (or (= name "quote") (= name "syntax-quote") (= name "unquote") - (= name "unquote-splicing") (= name "do") (= name "if") - (= name "def") (= name "defmacro") (= name "fn*") (= name "let*") (= name "loop*") - (= name "recur") (= name "throw") (= name "try") - (= name "set!") (= name "var") - (= name "eval") - (= name "new") (= name ".") - # var-get/var-set/var?/alter-var-root/alter-meta!/reset-meta! are plain - # clojure.core fns (core-bindings); find-var/intern are ctx-capturing fns - # (install-stateful-fns!) — no longer special forms (Stage 2 tier 6). - # locking/instance?/satisfies?/defonce/read-string/macroexpand-1 and the - # multimethod table ops are overlay macros / clojure.core fns now - # (Stage 2 tier 6c) — not special forms. - )) - -(var eval-form nil) - -# Macro expansion cache (interpreter): a macro CALL form expands ONCE and the -# result is reused — macroexpansion is a compile-time step with zero runtime cost, -# the proper Lisp model. Keyed by the call form's identity (a fn body re-evaluates -# the same form arrays each call). Also gives compile-once gensym semantics (a -# foo# auto-gensym is fixed across calls, unlike per-call re-expansion). Cleared -# when a macro is (re)defined so stale expansions don't linger. -(def macro-cache @{}) - -# Compile hook for macro expanders: set by the api to (fn [ctx args-form body] -> -# compiled-janet-fn | nil). When set and the body is compilable (no &env/&form, -# analyzer available), defmacro uses the compiled expander instead of the -# interpreted closure — macro expansion at native speed, zero runtime cost. -(var macro-compile-hook nil) - -(defn form-uses-sym? [form nm] - (cond - (and (struct? form) (= :symbol (form :jolt/type))) (= nm (form :name)) - (or (array? form) (tuple? form)) - (do (var found false) (each x form (when (form-uses-sym? x nm) (set found true) (break))) found) - (and (struct? form) (nil? (form :jolt/type))) - (do (var found false) (each k (keys form) - (when (or (form-uses-sym? k nm) (form-uses-sym? (get form k) nm)) (set found true) (break))) found) - false)) - -# A transient is a tagged mutable table @{:jolt/type :jolt/transient :kind ...}. -(defn- jolt-transient? [x] - (and (table? x) (= :jolt/transient (get x :jolt/type)))) - -# Read-only lookup over a transient (vector index / map key / set membership), -# mirroring core-get. Map/set backing tables are keyed by the same canon used -# by phm, so canonicalize collection keys here too. -(defn- transient-lookup [t k default] - (case (t :kind) - :vector (let [a (t :arr)] - (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (length a))) - (in a k) default)) - :map (let [e (get (t :tbl) (canon k))] (if (nil? e) default (in e 1))) - :set (if (nil? (get (t :tbl) (canon k))) default k) - default)) - -(defn coll-lookup - "Clojure `get` semantics over a jolt collection, used for collection-as-IFn." - [coll k default] - (cond - (jolt-transient? coll) (transient-lookup coll k default) - (shape-rec? coll) (shape-get coll k default) - # sorted colls are tables — without this arm they fell into the raw - # table-get branch and (:k (sorted-map ...)) was always nil (jolt-4vr spec) - (and (table? coll) (or (= :jolt/sorted-map (coll :jolt/type)) - (= :jolt/sorted-set (coll :jolt/type)))) - ((get (coll :ops) :get) coll k default) - (phm? coll) (phm-get coll k default) - (set? coll) (if (phs-contains? coll k) k default) - (pvec? coll) - (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (pv-count coll))) - (pv-nth coll k) default) - (or (tuple? coll) (array? coll)) - (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (length coll))) - (in coll k) default) - (or (struct? coll) (table? coll)) - (let [v (get coll k :jolt/not-found)] - (if (= v :jolt/not-found) default v)) - (nil? coll) default - default)) - -(defn jolt-invoke - "Apply f to already-evaluated args. Handles real functions and Clojure's - IFn collections: vectors (index lookup), maps/sets/keywords/symbols (get), - and deftype/record values implementing IFn. `args` is an array." - [ctx f args] - (cond - (or (function? f) (cfunction? f)) (apply f args) - # a var is callable as its current value (Clojure vars implement IFn) — - # e.g. (wrap-request #'core/request) threads the var as the base client - (var? f) (jolt-invoke ctx (var-get f) args) - (jolt-transient? f) (transient-lookup f (get args 0) (get args 1)) - # a record shape-rec is callable: IFn impl if it has one, else map-like - # field access. A plain (non-record) shape-rec is just field access. - (shape-rec? f) - (let [tag (record-tag f) - ifn (when tag (find-protocol-method ctx tag "IFn" "-invoke"))] - (if ifn (apply ifn f args) (shape-get f (get args 0) (get args 1)))) - (keyword? f) (coll-lookup (get args 0) f (get args 1)) - (and (struct? f) (= :symbol (f :jolt/type))) - (coll-lookup (get args 0) f (get args 1)) - (and (table? f) (or (= :jolt/sorted-map (f :jolt/type)) - (= :jolt/sorted-set (f :jolt/type)))) - # the overlay-attached :get op (comparator-based lookup, like Clojure) - ((get (f :ops) :get) f (get args 0) (get args 1)) - (phm? f) (phm-get f (get args 0) (get args 1)) - (set? f) (if (phs-contains? f (get args 0)) (get args 0) (get args 1)) - (pvec? f) - (let [k (get args 0)] - (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (pv-count f))) - (pv-nth f k) - (error (string "Index " k " out of bounds for vector of length " (pv-count f))))) - (or (tuple? f) (array? f)) - (let [k (get args 0)] - (if (and (number? k) (= k (math/floor k)) (>= k 0) (< k (length f))) - (in f k) - (error (string "Index " k " out of bounds for vector of length " (length f))))) - # Map literal only (struct with no :jolt/type). A tagged struct (char/etc.) - # is not callable — symbols are handled above; chars fall through to the error. - (and (struct? f) (nil? (get f :jolt/type))) - (let [v (get f (get args 0) :jolt/not-found)] - (if (= v :jolt/not-found) (get args 1) v)) - (and (table? f) (get f :jolt/deftype)) - (let [ifn-fn (find-protocol-method ctx (get f :jolt/deftype) "IFn" "-invoke")] - (if ifn-fn (apply ifn-fn f args) - (if (and (get f :jolt/protocol-methods) (get (f :jolt/protocol-methods) :-invoke)) - (apply (get (f :jolt/protocol-methods) :-invoke) f args) - # No IFn impl: fall back to map-like field access, e.g. (point :x) - (let [v (get f (get args 0) :jolt/not-found)] - (if (= v :jolt/not-found) (get args 1) v))))) - (and (table? f) (get f :jolt/protocol-methods)) - (let [invoke-fn (get (f :jolt/protocol-methods) :-invoke)] - (if invoke-fn (apply invoke-fn f args) - (error (string "Cannot call " (type f) " as a function")))) - (error (string "Cannot call " (type f) " as a function")))) - -(defn- sq-symbol - "Resolve a symbol inside syntax-quote. `foo#` becomes a stable auto-gensym - (per-expansion, via gsmap); special forms are left unqualified; a clojure.core - name is fully qualified to clojure.core/ (matching Clojure, for hygiene); other - symbols are qualified to the current namespace so they resolve when the macro is - used elsewhere." - [ctx form gsmap] - (if (nil? (form :ns)) - (let [nm (form :name)] - (cond - (string/has-suffix? "#" nm) - (or (get gsmap nm) - (let [g {:jolt/type :symbol :ns nil - :name (string (string/slice nm 0 -2) "__" (string (gensym)) "__auto")}] - (put gsmap nm g) g)) - (special-symbol? nm) form - (ns-find (ctx-find-ns ctx "clojure.core") nm) - {:jolt/type :symbol :ns "clojure.core" :name nm} - # Unresolved -> qualify to the namespace being COMPILED when set (the - # analyzer runs interpreted in jolt.analyzer, so ctx-current-ns is wrong - # mid-compile — the same seam resolve-var/h-current-ns use). Matters when - # a macro expander's template is lowered while a symbol it references is - # not yet defined (deftype's extend-type, defined later in the same tier): - # it must qualify to the macro's home ns, not jolt.analyzer. - {:jolt/type :symbol - :ns (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx)) - :name nm})) - # Alias-qualified (impl/foo): resolve the alias to its target namespace so the - # emitted symbol resolves at the macro's USE site, which has no such alias - # (jolt-9av). Matches Clojure's syntax-quote. A real ns name (not an alias) - # has no entry and is left as written. - (let [cur (ctx-find-ns ctx (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx))) - target (and cur (or (ns-alias-lookup cur (form :ns)) - (ns-import-lookup cur (form :ns))))] - (if target - {:jolt/type :symbol :ns target :name (form :name)} - form)))) - -(defn d-realize - "Realize a lazy-seq to an array for positional destructuring / splicing; pass - others (pvec/plist coerced to array, everything else unchanged). nil is an - empty seq, as everywhere in Clojure — ~@nil splices nothing (an interpreted - macro's empty & rest binds nil, which used to blow up `each`)." - [val] - (if (nil? val) @[] - (if (pvec? val) (pv->array val) - (if (plist? val) (pl->array val) - (if (lazy-seq? val) - (do - (var items @[]) (var cur val) (var go true) - (while go - (let [cell (realize-ls cur)] - (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) - (set go false) - (do (array/push items (in cell 0)) - (let [rt (in cell 1)] - (if (nil? rt) (set go false) (set cur (ls-rest-cached cur rt)))))))) - items) - val))))) - -(defn syntax-quote* - [ctx bindings form &opt gsmap] - (default gsmap @{}) - (cond - (and (array? form) (> (length form) 0) (sym-name? (first form) "unquote")) - (eval-form ctx bindings (in form 1)) - (and (array? form) (> (length form) 0) (sym-name? (first form) "unquote-splicing")) - (error "~@ used outside of a list or vector in syntax-quote") - (or (number? form) (string? form) (keyword? form) (nil? form) (= true form) (= false form)) - form - (and (struct? form) (= :symbol (form :jolt/type))) - (sq-symbol ctx form gsmap) - (tuple? form) - (do (var result @[]) (var i 0) (while (< i (length form)) - (let [item (in form i)] - (if (and (array? item) (> (length item) 0) (sym-name? (first item) "unquote-splicing")) - (let [sv (eval-form ctx bindings (in item 1))] - (each v (d-realize sv) (array/push result v))) - (array/push result (syntax-quote* ctx bindings item gsmap)))) - (++ i)) (tuple ;result)) - (array? form) - (do (var result @[]) (var i 0) (while (< i (length form)) - (let [item (in form i)] - (if (and (array? item) (> (length item) 0) (sym-name? (first item) "unquote-splicing")) - (let [sv (eval-form ctx bindings (in item 1))] - (each v (d-realize sv) (array/push result v))) - (array/push result (syntax-quote* ctx bindings item gsmap)))) - (++ i)) result) - # set literal: lower each element (processing ~/~@) and rebuild a set. - (and (struct? form) (= :jolt/set (form :jolt/type))) - (do (var result @[]) - (each item (form :value) - (if (and (array? item) (> (length item) 0) (sym-name? (first item) "unquote-splicing")) - (let [sv (eval-form ctx bindings (in item 1))] - (each v (d-realize sv) (array/push result v))) - (array/push result (syntax-quote* ctx bindings item gsmap)))) - (make-phs ;result)) - (and (struct? form) (get form :jolt/type)) form - (struct? form) - (do (var kvs @[]) - (def order (form-kv-order form)) - (if order - (each x order (array/push kvs (syntax-quote* ctx bindings x gsmap))) - (each k (keys form) - (array/push kvs (syntax-quote* ctx bindings k gsmap)) - (array/push kvs (syntax-quote* ctx bindings (get form k) gsmap)))) - # keep carrying source order through nested syntax-quote (jolt-p3c) - (struct/with-proto (struct :jolt/kv-order (tuple/slice kvs)) ;kvs)) - form)) - -# Syntax-quote LOWERING: instead of evaluating a `(...) form to a value (what -# syntax-quote* does), produce equivalent CONSTRUCTION CODE so a backtick body is -# plain compilable code (read -> macroexpand -> compile, zero runtime cost). -# Mirrors syntax-quote*/sq-symbol exactly; the canonical algorithm is -# tools.reader's syntax-quote*/expand-list. List forms build via __sqcat (-> array), -# vectors via __sqvec (-> tuple), maps via __sqmap; symbols become (quote resolved); -# ~ leaves the expr in place, ~@ passes the seq straight to __sqcat for splicing. -(defn- sqsym* [nm] {:jolt/type :symbol :ns nil :name nm}) - -(var syntax-quote-lower nil) - -(defn- sq-lower-part [ctx item gsmap] - (if (and (array? item) (> (length item) 0) (sym-name? (first item) "unquote-splicing")) - (in item 1) - @[(sqsym* "__sq1") (syntax-quote-lower ctx item gsmap)])) - -(set syntax-quote-lower - (fn syntax-quote-lower [ctx form &opt gsmap] - (default gsmap @{}) - (cond - (and (array? form) (> (length form) 0) (sym-name? (first form) "unquote")) - (in form 1) - (and (array? form) (> (length form) 0) (sym-name? (first form) "unquote-splicing")) - (error "~@ used outside of a list or vector in syntax-quote") - (or (number? form) (string? form) (keyword? form) (nil? form) (= true form) (= false form)) - form - (and (struct? form) (= :symbol (form :jolt/type))) - @[(sqsym* "quote") (sq-symbol ctx form gsmap)] - (array? form) - (array/concat @[(sqsym* "__sqcat")] (map (fn [it] (sq-lower-part ctx it gsmap)) form)) - (tuple? form) - (array/concat @[(sqsym* "__sqvec")] (map (fn [it] (sq-lower-part ctx it gsmap)) form)) - # set literal: lower each element (so ~/~@ are processed) and rebuild a set. - (and (struct? form) (= :jolt/set (form :jolt/type))) - (array/concat @[(sqsym* "__sqset")] (map (fn [it] (sq-lower-part ctx it gsmap)) (form :value))) - # other tagged structs (chars): returned as-is (no recursion) - (and (struct? form) (get form :jolt/type)) - @[(sqsym* "quote") form] - (struct? form) - (do (var parts @[(sqsym* "__sqmap")]) - (def order (form-kv-order form)) - (if order - (each x order (array/push parts (syntax-quote-lower ctx x gsmap))) - (each k (keys form) - (array/push parts (syntax-quote-lower ctx k gsmap)) - (array/push parts (syntax-quote-lower ctx (get form k) gsmap)))) - parts) - @[(sqsym* "quote") form]))) - -(defn resolve-var - [ctx bindings sym-s] - (let [name (sym-s :name) ns (sym-s :ns)] - (if (not (nil? ns)) - # Resolve ns aliases (e.g. `p/thrown?` where `p` is a require :as alias) so - # aliased refs/macros resolve. During compilation the analyzer (interpreted, - # in jolt.analyzer) rebinds ctx-current-ns to its own ns, so look up the alias - # against the COMPILE ns (:compile-ns, the user's ns) when set — otherwise an - # aliased ref like g/foo wouldn't resolve mid-compile. Same ns h-current-ns uses. - (let [cur-name (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx)) - current-ns (ctx-find-ns ctx cur-name) - aliased-ns (or (ns-alias-lookup current-ns ns) (ns-import-lookup current-ns ns)) - target-ns (ctx-find-ns ctx (or aliased-ns ns))] - (ns-find target-ns name)) - (if (get bindings name) nil - (let [current-ns (ctx-current-ns ctx) - ns (ctx-find-ns ctx current-ns) - v (ns-find ns name)] - (if v v - (let [core-ns (ctx-find-ns ctx "clojure.core")] - (ns-find core-ns name)))))))) - -(defn sym-name-str - [sym-s] - (if (sym-s :ns) (string (sym-s :ns) "/" (sym-s :name)) (sym-s :name))) - -(defn- ns->relpath - "Namespace name to its file-relative path (dots->dirs, dashes->_), no extension." - [ns-name] - (string/replace-all "." "/" (string/replace-all "-" "_" ns-name))) - -(defn- find-ns-file - "Search the context's source roots (stdlib first, then deps.edn dirs) for the - namespace's source, trying .clj then .cljc. Returns the path or nil." - [ctx ns-name] - (let [rel (ns->relpath ns-name) - roots (or (get (ctx :env) :source-paths) @["src/jolt"])] - (var found nil) - (each root roots - (each ext [".clj" ".cljc"] - (when (nil? found) - (let [p (string root "/" rel ext)] - (when (os/stat p) (set found p)))))) - found)) - -(defn- load-ns-source - "Parse and evaluate every form of a namespace's source in the given context. - Routes through the loader's eval-toplevel when the api has installed it - (the :toplevel-eval hook) so REQUIRED namespaces compile like everything - else — without it they ran interpreted-only: slower, and their fns were - anonymous closures in stack traces (jolt-2o7.1)." - [ctx src &opt file] - (default file "") - (def toplevel (get (ctx :env) :toplevel-eval)) - # a require runs nested inside an outer file's eval; save/restore the outer - # checker source so its later forms still convert offsets correctly (jolt-fqy) - (def checking (or (checker-enabled?) (get (ctx :env) :inline?))) - (def saved-src (and checking (get (ctx :env) :tc-source))) - (def saved-file (and checking (get (ctx :env) :tc-file))) - (when checking - (track-positions! true) - (put (ctx :env) :tc-source src) - (put (ctx :env) :tc-file file)) - (defer (when checking - (put (ctx :env) :tc-source saved-src) - (put (ctx :env) :tc-file saved-file)) - (each [f line] (parse-all-positioned src file) - (try - (if toplevel (toplevel ctx f) (eval-form ctx @{} f)) - ([err fib] - # innermost failing form wins; files unwound through form the - # 'while loading …' chain (mirrors loader/eval-forms-positioned, - # which this can't import — circularity) (jolt-2o7.4) - (def env (ctx :env)) - (when (nil? (get env :error-pos)) - (put env :error-pos {:file file :line line})) - (when (nil? (get env :error-loading)) (put env :error-loading @[])) - (def chain (get env :error-loading)) - (when (not= (last chain) file) (array/push chain file)) - (propagate err fib)))))) - -# jolt-87e: is a namespace loaded from `path` part of the APP (vs a dependency)? -# True when its file sits under one of the declared app source roots -# (:app-source-paths, from JOLT_APP_PATHS / jolt-deps). When NO app roots are -# declared (a bare program run, or jolt invoked without jolt-deps), everything -# counts as app so whole-program covers the whole program exactly as before. -# Only app namespaces defer into the one whole-program fixpoint; dependency -# namespaces infer per-ns at load, so a dep-heavy app's startup doesn't re-infer -# hundreds of transitive dependency namespaces in a single closed-world pass. -(defn- app-source-ns? - [ctx path] - (def roots (get (ctx :env) :app-source-paths)) - (if (or (nil? roots) (empty? roots)) - true - (and path (truthy? (some |(string/has-prefix? $ path) roots))))) - -(defn maybe-require-ns - "If namespace ns-name isn't populated yet, load its source — from a file on the - context's source roots, else from the stdlib baked into the image. Restores the - current namespace afterwards (a library's own `ns` form, or our manual switch - for ns-form-less stdlib files, changes it). No-op for already-loaded namespaces." - [ctx ns-name] - (let [ns (ctx-find-ns ctx ns-name)] - (when (and (= 0 (length (ns :mappings))) - (not (get (get (ctx :env) :loaded-namespaces @{}) ns-name)) - (not= ns-name "clojure.core")) - (let [path (find-ns-file ctx ns-name) - embedded (get (get (ctx :env) :embedded-sources @{}) ns-name) - stdlib? (not (nil? embedded))] - # Clojure throws FileNotFoundException here; succeeding silently leaves - # an empty namespace behind and defers the failure to the first - # unresolved symbol, far from the actual cause (a typo, a missing - # JOLT_PATH root). Best-effort loaders (the SCI bootstrap, which loads - # clj-targeted sources whose requires can't all exist on this host) - # opt out via :lenient-require? on the env. - (when (and (nil? path) (nil? embedded) - (not (get (ctx :env) :lenient-require?))) - (error (string "Could not locate " ns-name - " on the context's source paths (JOLT_PATH / :paths)"))) - (when (or path embedded) - (let [saved (ctx-current-ns ctx) - # jolt-87e: is this an app namespace, or a dependency/library? Only - # the app is the closed world the whole-program optimizer reasons - # over; dependencies are open-world libraries. - app? (app-source-ns? ctx path) - # Whole-program optimize is active for this load. - wp-active? (and (get (ctx :env) :inline?) - (get (ctx :env) :whole-program?) - (not (get (ctx :env) :infer-program-done?))) - # A dependency under whole-program optimize compiles at DEFAULT - # cost: :inline? off for its load, so the per-form inline + - # inference passes — the bulk of optimize-mode startup — don't run - # over hundreds of library forms. (Direct-linking + shape-recs stay - # on, exactly like a non-optimized direct-link build.) This is what - # makes JOLT_OPTIMIZE viable on dep-heavy apps; the app's own nses - # below keep full optimization. (jolt-87e) - dep-cheap? (and wp-active? (not app?)) - saved-inline (get (ctx :env) :inline?)] - # Stdlib files have no `ns` form, so switch into the target ns first - # (their defs intern there); a library's own `ns` form overrides this. - (ctx-set-current-ns ctx ns-name) - (when dep-cheap? (put (ctx :env) :inline? false)) - (if path - (load-ns-source ctx (slurp path) path) - (load-ns-source ctx embedded (string ns-name " (stdlib)"))) - (when dep-cheap? (put (ctx :env) :inline? saved-inline)) - # Inter-procedural collection-type inference (jolt-767): once the whole - # unit is loaded, run the closed-world fixpoint + recompile so param- - # dependent lookups specialize. Only in optimization mode; best-effort - # (a failure here must not break loading). Hook installed by the api to - # avoid an evaluator->backend circular import. - (when (get (ctx :env) :inline?) - (cond - # whole-program (jolt-t34), APP namespace: defer — record the ns and - # run ONE fixpoint over all app units later (the closed-world pass - # sees every caller, so cross-ns param types propagate). - (and wp-active? app?) - (let [lst (or (get (ctx :env) :inferred-nses) - (let [a @[]] (put (ctx :env) :inferred-nses a) a))] - (array/push lst ns-name)) - # whole-program, DEPENDENCY namespace (jolt-87e): nothing to do — - # it compiled cheaply above (no inference to run or defer). - wp-active? - nil - # per-ns mode (whole-program off), or a lazy require AFTER the batch - # ran: infer this unit on its own. - (when-let [iu (get (ctx :env) :infer-unit!)] - (protect (iu ctx ns-name))))) - # Record load order for tooling (uberscript): a dependency finishes - # loading before its requirer, so this is topological. Skip the - # baked-in stdlib — it's part of the runtime, not something to bundle. - (when (and path (not stdlib?)) - (when-let [lf (get (ctx :env) :loaded-files)] (array/push lf path))) - (ctx-set-current-ns ctx saved))))))) - -(defn eval-require - [ctx spec] - (let [ns-sym (in spec 0) - ns-name (sym-name-str ns-sym)] - (var alias nil) - (var refer-syms nil) - (var i 1) - (let [slen (length spec)] - # Scan ALL options — a spec may carry both :as and :refer, e.g. - # [clojure.string :as str :refer [blank?]]; don't stop at the first. - (while (< i slen) - (let [item (in spec i)] - (cond - (or (= item :as) (and (struct? item) (= :symbol (item :jolt/type)) (= "as" (item :name)))) - (do (set alias ((in spec (+ i 1)) :name)) (+= i 2)) - (or (= item :refer) (and (struct? item) (= :symbol (item :jolt/type)) (= "refer" (item :name)))) - (do (set refer-syms (in spec (+ i 1))) (+= i 2)) - (++ i))))) - (maybe-require-ns ctx ns-name) - (when alias - (let [current-ns (ctx-find-ns ctx (ctx-current-ns ctx))] - (ns-add-alias current-ns alias ns-name))) - (when refer-syms - (let [source-ns (ctx-find-ns ctx ns-name) - target-ns (ctx-find-ns ctx (ctx-current-ns ctx))] - (if (or (= refer-syms :all) - (and (struct? refer-syms) (= :symbol (refer-syms :jolt/type)) - (= "all" (refer-syms :name)))) - # :refer :all — share EVERY var (this used to each over the :all - # keyword itself and silently refer nothing; selmer's - # [selmer.util :refer :all] left *tag-open* & co unresolved) - (eachp [nm v] (source-ns :mappings) - (put (target-ns :mappings) nm v)) - (each refer-sym refer-syms - (let [name (if (struct? refer-sym) (refer-sym :name) refer-sym) - v (ns-find source-ns name)] - (when v - # Share the SOURCE var (the Clojure model): macro-ness travels with - # it and source-ns redefinitions propagate to the referer. - (put (target-ns :mappings) name v))))))) - nil)) - -(defn bind-put - "Put a value into bindings. Uses :jolt/nil sentinel for nil values - because Janet's (put table key nil) silently drops the key." - [bindings key value] - (put bindings key (if (nil? value) :jolt/nil value))) - -(defn binding-get - "Get a value from bindings, walking the prototype chain." - [bindings name] - (var result :jolt/not-found) - (var t bindings) - (while (not (nil? t)) - (when (in t name) - (set result (in t name)) - (break)) - (set t (table/getproto t))) - result) - -# Pluggable host-class shims (java.time etc. register here at module load): -# class-statics: "ClassName" -> {"member" value-or-fn} (Foo/bar resolution) -# tagged-methods: :jolt/tag -> {"method" (fn [self args...])} ((.m obj) dispatch) -(def class-statics @{}) -(def tagged-methods @{}) -(defn register-class-statics! [class-name tbl] (put class-statics class-name tbl)) -(defn register-tagged-methods! [tag tbl] (put tagged-methods tag tbl)) -# Constructor shims: (ClassName. args) resolves ClassName as a value, so the -# ctor fns are interned as clojure.core vars at init (install-stateful-fns!). -(def class-ctors @{}) -(defn register-class-ctor! [nm f] (put class-ctors nm f)) - -# java.util.Iterator shim: (.iterator coll) gives a jolt iterator over any -# seqable, with (.hasNext it) / (.next it). Some Clojure libs (e.g. hiccup's -# iterate!) loop with the Java Iterator protocol; this makes that work over jolt -# collections. The realizer (core/realize-for-iteration, which handles every -# collection type) is late-bound because core loads after this file. -(var coll-realizer nil) -(defn set-coll-realizer! [f] (set coll-realizer f)) -# Late-bound (wired in api): routes a Java collection-interop method call -# (.nth/.count/.valAt/.seq …) on a jolt persistent collection to the clojure.core -# equivalent. Returns :jolt/ci-none when it doesn't apply. Lets clj-targeted libs -# (malli) that use .nth/.count on vectors/maps in their :clj branches work. -(var coll-interop nil) -(defn set-coll-interop! [f] (set coll-interop f)) diff --git a/src/jolt/eval_resolve.janet b/src/jolt/eval_resolve.janet deleted file mode 100644 index d391bc7..0000000 --- a/src/jolt/eval_resolve.janet +++ /dev/null @@ -1,443 +0,0 @@ -# Jolt Evaluator — symbol/var resolution, params, destructuring, class lookup -# Extracted from evaluator.janet (jolt-oudv, phase 2a split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./pv) -(use ./plist) -(use ./config) -(use ./reader) -(use ./regex) -(use ./eval_base) -(register-tagged-methods! :jolt/iterator - @{"hasNext" (fn [self] (< (self :pos) (length (self :items)))) - "next" (fn [self] - (def x (in (self :items) (self :pos))) - (put self :pos (+ 1 (self :pos))) - x)}) -# Class names evaluate to their CANONICAL NAME STRING — the same value -# core-class returns — so (defmethod m String ...) keys match a -# (defmulti m (comp class :body)) dispatch (ring.util.request does this). -# `new` resolves the actual constructor from class-ctors by short name. -(def class-canonical-names - @{"String" "java.lang.String" "Number" "java.lang.Number" - "Boolean" "java.lang.Boolean" "Long" "java.lang.Long" - "Integer" "java.lang.Integer" "Double" "java.lang.Double" - "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"}) -# A class used as a VALUE should evaluate to what (clojure.core/type instance) -# returns for its instances, so a registry keyed by class (e.g. malli's -# class-schemas) matches a value's (type ...). For jolt's native tagged types the -# class maps to its :jolt/type keyword — Pattern <-> a compiled regex. -(def- class-value-overrides - @{"Pattern" :jolt/regex "java.util.regex.Pattern" :jolt/regex}) -(defn class-value-for - "The value a class-name symbol evaluates to: a type override, else its canonical - name string." - [nm] - (or (get class-value-overrides nm) - (get class-canonical-names nm) - # qualified already, or unknown: the name itself is the token - nm)) -(defn ctor-for-class-token - "Constructor fn for a class token (a canonical-name string): try the full - name, then the short name after the last dot." - [tok] - (or (in class-ctors tok) - (let [parts (string/split "." tok)] - (in class-ctors (last parts))))) - -# java.lang.String method surface for clj-compat interop: (.toLowerCase s), -# (.indexOf s x), ... — the methods portable cljc libraries actually call. -# Case mapping is ASCII (the whole engine is byte-based); indexOf returns -1 -# on miss, as on the JVM. -(defn- str-needle [x] - (cond - (and (struct? x) (= :jolt/char (get x :jolt/type))) (string/from-bytes (x :ch)) - # (.indexOf s 61): an int needle is a char CODE on the JVM, not its decimal - # text (ring-codec splits k=v pairs this way) - (number? x) (string/from-bytes (math/trunc x)) - (string x))) -# java.lang.Number surface (ring-codec: (.byteValue (Integer/valueOf s 16))). -(def number-methods - {"byteValue" (fn [n] (let [b (band (math/trunc n) 0xff)] (if (> b 127) (- b 256) b))) - "shortValue" (fn [n] (let [v (band (math/trunc n) 0xffff)] (if (> v 32767) (- v 65536) v))) - "intValue" (fn [n] (math/trunc n)) - "longValue" (fn [n] (math/trunc n)) - "floatValue" (fn [n] (* 1.0 n)) - "doubleValue" (fn [n] (* 1.0 n)) - "toString" (fn [n &opt radix] (if (= radix 16) (string/format "%x" (math/trunc n)) (string n)))}) - -# Universal java.lang.Object / exception / persistent-collection methods that -# reitit's :clj branches call on non-string targets: (.getMessage e), -# (.assoc m k v), (.get m k). Consulted in the method-dispatch fallthrough. -(def object-methods - {"getMessage" (fn [e] (cond (and (table? e) (= :jolt/ex-info (get e :jolt/type))) (get e :message) - (string? e) e - (string e))) - "getCause" (fn [e] (and (table? e) (get e :cause))) - "toString" (fn [x] (string x)) - "equals" (fn [a b] (deep= a b)) - "hashCode" (fn [x] (hash x)) - # (.iterator coll) -> a jolt iterator (see :jolt/iterator above). Materializes - # the collection to an indexable array via the late-bound core realizer. - "iterator" (fn [coll] @{:jolt/type :jolt/iterator :pos 0 - :items (if coll-realizer (coll-realizer coll) @[])})}) - -(def string-methods - {"getBytes" (fn [s &opt charset] (buffer s)) - "toString" (fn [s] s) - "toLowerCase" (fn [s] (string/ascii-lower s)) - "toUpperCase" (fn [s] (string/ascii-upper s)) - "trim" (fn [s] (string/trim s)) - "intern" (fn [s] s) - # file-path surface: io/file returns plain path strings, so the java.io.File - # / java.net.URL methods selmer's template cache calls land here - "toURI" (fn [s] s) - "toURL" (fn [s] s) - "getPath" (fn [s] s) - "getName" (fn [s] (if-let [i (string/find "/" (string/reverse s))] - (string/slice s (- (length s) i)) s)) - "exists" (fn [s] (not (nil? (os/stat s)))) - "lastModified" (fn [s] (if-let [st (os/stat s)] (math/floor (* 1000 (st :modified))) 0)) - # JVM String.split takes a REGEX string; trailing empties dropped like the JVM - "split" (fn [s re &opt limit] - (def parts (re-split (re-pattern re) s)) - (while (and (> (length parts) 0) (= "" (last parts))) - (array/pop parts)) - parts) - "length" (fn [s] (length s)) - "isEmpty" (fn [s] (= 0 (length s))) - "charAt" (fn [s i] {:jolt/type :jolt/char :ch (s i)}) - "codePointAt" (fn [s i] (s i)) - "indexOf" (fn [s x &opt from] (or (string/find (str-needle x) s (or from 0)) -1)) - "lastIndexOf" (fn [s x] - (let [n (str-needle x)] - (var found -1) (var i 0) - (while (< i (length s)) - (let [f (string/find n s i)] - (if f (do (set found f) (set i (+ f 1))) (set i (length s))))) - found)) - "substring" (fn [s start &opt end] (string/slice s start end)) - "startsWith" (fn [s p] (string/has-prefix? p s)) - "endsWith" (fn [s p] (string/has-suffix? p s)) - "contains" (fn [s sub] (not (nil? (string/find (str-needle sub) s)))) - "concat" (fn [s o] (string s o)) - "replace" (fn [s a b] (string/replace-all (str-needle a) (str-needle b) s)) - "replaceAll" (fn [s regex replacement] (re-replace-all (re-pattern regex) s replacement)) - "replaceFirst" (fn [s regex replacement] (re-replace-first (re-pattern regex) s replacement)) - "matches" (fn [s regex] (not (nil? (re-matches (re-pattern regex) s)))) - "compareTo" (fn [s o] (cond (< s o) -1 (> s o) 1 0)) - "equalsIgnoreCase" (fn [s o] (= (string/ascii-lower s) (string/ascii-lower (string o))))}) - -(defn resolve-sym - [ctx bindings sym-s] - (let [name (sym-s :name) ns (sym-s :ns)] - # Math/Thread/System/Long and every other class resolve through the generic - # class-statics registry (host_interop registers them at load); no special-case. - (if (get class-statics ns) - (let [v (get (get class-statics ns) name)] - (if (nil? v) (error (string "Unsupported member: " ns "/" name)) v)) - (if (not (nil? ns)) - (let [current-ns (ctx-find-ns ctx (ctx-current-ns ctx)) - aliased-ns (or (ns-alias-lookup current-ns ns) (ns-import-lookup current-ns ns)) - target-ns (ctx-find-ns ctx (or aliased-ns ns)) - v (and target-ns (ns-find target-ns name))] - (if v (var-get v) - # Explicit Janet interop. The `janet` namespace segment marks every - # crossing into host code, where Clojure semantics no longer hold: - # janet/ -> Janet root binding (janet/slurp, janet/type) - # janet./ -> Janet module binding (janet.net/server, - # janet.os/clock) - # This makes the whole Janet stdlib reachable from Clojure while keeping - # the interop boundary visible at the call site. - (if (or (= ns "janet") (string/has-prefix? "janet." ns)) - (let [jname (if (= ns "janet") name (string (string/slice ns 6) "/" name)) - # worker fibers may carry no env (fiber/new without :e inherit) - # — fall back to the env captured at module load - # four-step resolution: the runtime fiber's env (when it - # has one), the evaluator's module env (worker/connection - # fibers carry a foreign or empty env — net/server handler - # fibers resolve janet/struct through here), the autoload - # cache, then a jpm-module require on first miss - entry (or (when-let [fe (fiber/getenv (fiber/current))] - (in fe (symbol jname))) - (in module-load-env (symbol jname)) - (in janet-bridge-extras jname) - (bridge-autoload jname))] - (if (not (nil? entry)) - (if (table? entry) (entry :value) entry) - (error (string "Unable to resolve Janet symbol: " jname)))) - # syntax-quote ns-qualifies bare class names inside macros - # (selmer.util/StringBuilder); class names never belong to an ns — - # fall back to the constructor / statics shims before giving up. - (if (or (in class-ctors name) (get class-canonical-names name) (get class-value-overrides name)) - (class-value-for name) - (error (string "Unable to resolve symbol: " ns "/" name)))))) - # Use :jolt/not-found sentinel to distinguish nil binding from absent binding - (let [local (get bindings name :jolt/not-found-1) - local (if (= local :jolt/not-found-1) (binding-get bindings name) local)] - (if (not= local :jolt/not-found) - (if (= local :jolt/nil) nil local) - (let [current-ns (ctx-current-ns ctx) ns (ctx-find-ns ctx current-ns) v (ns-find ns name)] - (if v (var-get v) - # Check clojure.core as auto-referred fallback - (let [core-ns (ctx-find-ns ctx "clojure.core") - core-v (ns-find core-ns name)] - (if core-v - (var-get core-v) - # Try class-name resolution: Foo.Bar.Baz -> ns "Foo.Bar", name "Baz" - (let [dot-idx (string/find "." name)] - (if dot-idx - (let [last-dot (do - (var idx dot-idx) - (var next-dot (string/find "." name (+ idx 1))) - (while (not (nil? next-dot)) - (set idx next-dot) - (set next-dot (string/find "." name (+ idx 1)))) - idx) - class-ns (string/slice name 0 last-dot) - class-name (string/slice name (+ last-dot 1))] - (let [target-ns (ctx-find-ns ctx class-ns) tv (ns-find target-ns class-name)] - (if tv (var-get tv) tv))) - # No implicit Janet fallback (Stage 3): an unresolved - # Clojure symbol is an error. Host access is the explicit - # janet/ prefix above. - (if (or (in class-ctors name) (get class-canonical-names name) (get class-value-overrides name)) - (class-value-for name) - (error (string "Unable to resolve symbol: " name " in this context"))))))))))))))) -(defn- parse-arg-names - "Parse a parameter vector, handling & rest args. - Returns {:fixed [names...] :rest name-or-nil :all [names...]}" - [args-form] - (var fixed @[]) - (var rest-name nil) - (var i 0) - (while (< i (length args-form)) - (let [a (in args-form i)] - (if (and (struct? a) (= :symbol (a :jolt/type)) (= "&" (a :name))) - (do - (+= i 1) - (if (< i (length args-form)) - (do - (set rest-name ((in args-form i) :name)) - (+= i 1)) - (error "& without argument in parameter list"))) - (do - (if (and (struct? a) (= :symbol (a :jolt/type))) - (array/push fixed (a :name)) - # destructuring form: recurse into it - (when (indexed? a) - (var di 0) - (while (< di (length a)) - (def inner (in a di)) - (if (and (struct? inner) (= :symbol (inner :jolt/type)) (= "&" (inner :name))) - (do - (+= di 1) - (if (< di (length a)) - (do - (set rest-name ((in a di) :name)) - (+= di 1)) - (error "& without argument in parameter list"))) - (do - (if (and (struct? inner) (= :symbol (inner :jolt/type))) - (array/push fixed (inner :name)) - # nested destructuring - extract names - (when (indexed? inner) - (each sym inner - (when (and (struct? sym) (= :symbol (sym :jolt/type))) - (array/push fixed (sym :name)))))) - (+= di 1)))))) - (+= i 1))))) - (var all @[]) - (each n fixed (array/push all n)) - (if rest-name (array/push all rest-name)) - {:fixed (tuple/slice (tuple ;fixed)) :rest rest-name :all (tuple/slice (tuple ;all))}) - -# ============================================================ -# Destructuring (Clojure-compatible, recursive) -# ============================================================ - -(defn parse-params - "Parse a parameter vector into raw patterns: {:fixed [pat...] :rest pat-or-nil}. - Unlike parse-arg-names, patterns are kept intact (not flattened) so they can - be destructured against the corresponding argument." - [args-form] - (var fixed @[]) - (var rest-pat nil) - (var i 0) - (while (< i (length args-form)) - (let [a (in args-form i)] - (if (and (struct? a) (= :symbol (a :jolt/type)) (= "&" (a :name))) - (do (+= i 1) - (when (< i (length args-form)) (set rest-pat (in args-form i))) - (+= i 1)) - (do (array/push fixed a) (+= i 1))))) - {:fixed (tuple/slice (tuple ;fixed)) :rest rest-pat}) - -(defn rest-args-val - "What a rest param binds to: nil when no args remain (Clojure semantics — - (fn [& r]) called with nothing gives r = nil, never an empty seq)." - [args i] - (when (> (length args) i) (tuple/slice args i))) - -(defn plain-sym? [p] (and (struct? p) (= :symbol (p :jolt/type)))) - -(defn require-symbol-params - "fn* is a primitive: its params must be plain symbols. The fn/defn MACROS desugar - destructuring into plain params + a body let before emitting fn*, so fn* never - legitimately sees a pattern — matching Clojure, where (fn* [[a b]] ...) is the - compile error 'fn params must be Symbols'. Enforcing it here keeps the interpreter - consistent with the self-hosted analyzer (which also requires plain fn* params) - and with Clojure, instead of leniently destructuring a form Clojure rejects." - [param-info] - (each p (param-info :fixed) - (unless (plain-sym? p) (error "fn params must be Symbols"))) - (let [r (param-info :rest)] - (when (and r (not (plain-sym? r))) (error "fn params must be Symbols")))) - -(defn- d-get - "Look up key k in a map-like value (phm/struct/table/nil)." - [m k] - (cond - (phm? m) (phm-get m k) - (or (struct? m) (table? m)) (get m k) - true nil)) - -(defn- find-or-default - "Find the :or default expression for binding name nm, or :jolt/none." - [or-map nm] - (var result :jolt/none) - (when or-map - (each k (keys or-map) - (when (and (struct? k) (= :symbol (k :jolt/type)) (= nm (k :name))) - (set result (get or-map k))))) - result) - -(var destructure-bind nil) -(set destructure-bind - (fn dbind [ctx bindings pat val] - (cond - # plain symbol - (and (struct? pat) (= :symbol (pat :jolt/type))) - (bind-put bindings (pat :name) val) - # sequential pattern (vector of sub-patterns) - (indexed? pat) - (let [rv (d-realize val) - seqable? (indexed? rv)] - (var di 0) (var vi 0) - (def n (length pat)) - (while (< di n) - (let [elem (in pat di)] - (cond - # & rest - (and (struct? elem) (= :symbol (elem :jolt/type)) (= "&" (elem :name))) - (do - # rest binds a seq (jolt list = array), per Clojure semantics. - # For lazy-seqs, preserve laziness: walk vi steps via ls-rest - # instead of slicing the eagerly-realized array. - (destructure-bind ctx bindings (in pat (+ di 1)) - (if (lazy-seq? val) - (do - (var c val) (var i 0) - (while (< i vi) - (let [nxt (ls-rest c)] - (if (nil? nxt) (break) - (do (set c nxt) (++ i))))) - c) - (if (and seqable? (< vi (length rv))) - (array/slice (if (tuple? rv) (array/slice rv) rv) vi) - @[]))) - (set di (+ di 2))) - # :as whole - (= elem :as) - (do - (destructure-bind ctx bindings (in pat (+ di 1)) val) - (set di (+ di 2))) - # positional element - true - (do - (destructure-bind ctx bindings elem - (if (and seqable? (< vi (length rv))) (in rv vi) nil)) - (+= di 1) (+= vi 1)))))) - # map pattern (struct/table that isn't a symbol) - (or (struct? pat) (table? pat)) - (let [rv (d-realize val) - # Destructuring a sequential value as a map treats it as kwargs: - # alternating k/v pairs, or a single trailing map (Clojure's - # `[& {:keys ...}]`). A real map value is used as-is. - mval (if (and (indexed? rv) (not (or (struct? rv) (table? rv)))) - (if (and (= 1 (length rv)) - (let [e (in rv 0)] (or (struct? e) (table? e) (phm? e)))) - (in rv 0) - (let [m @{}] - (var i 0) - (while (< (+ i 1) (length rv)) - (put m (in rv i) (in rv (+ i 1))) - (+= i 2)) - m)) - val)] - (def or-map (get pat :or)) - (def as-sym (get pat :as)) - (when as-sym (destructure-bind ctx bindings as-sym mval)) - # :keys (keyword), :strs (string), :syms (symbol). A namespaced symbol - # in :keys/:syms (x/y) looks up the namespaced key but binds local y. - (each spec [[:keys :kw] [:strs :str] [:syms :sym]] - (let [kw (in spec 0) kind (in spec 1) names (get pat kw)] - (when (and names (indexed? names)) - (each s names - (let [sym? (and (struct? s) (= :symbol (s :jolt/type))) - local (if sym? (s :name) (string s)) - nsp (and sym? (s :ns)) - key (case kind - :kw (keyword (if nsp (string nsp "/" local) local)) - :str local - :sym {:jolt/type :symbol :ns nsp :name local}) - v (d-get mval key) - v (if (nil? v) - (let [d (find-or-default or-map local)] - (if (= d :jolt/none) nil (eval-form ctx bindings d))) - v)] - (bind-put bindings local v)))))) - # direct {local-pattern key-expr} entries (local may itself be a - # nested vector/map pattern). Special keys are keywords; skip them. - (each k (keys pat) - (when (not (keyword? k)) - (let [key-val (eval-form ctx bindings (get pat k)) - v (d-get mval key-val)] - (if (and (struct? k) (= :symbol (k :jolt/type))) - # symbol target: apply :or default if missing - (let [nm (k :name) - v (if (nil? v) - (let [d (find-or-default or-map nm)] - (if (= d :jolt/none) nil (eval-form ctx bindings d))) - v)] - (bind-put bindings nm v)) - # nested pattern target - (destructure-bind ctx bindings k v)))))) - true (error (string "Unsupported destructuring pattern: " (string/format "%q" pat)))))) - -# ---- host-type protocol extension (extend-protocol String/Number/... ) ---- -(def host-type-names - {"Long" true "Integer" true "Short" true "Byte" true "BigInteger" true "BigInt" true - "Double" true "Float" true "Number" true "BigDecimal" true "Ratio" true - "String" true "CharSequence" true "Boolean" true "Character" true - "Keyword" true "Symbol" true "Object" true "IFn" true "Fn" true - "PersistentVector" true "PersistentList" true "PersistentHashMap" true - "PersistentHashSet" true "IPersistentMap" true "IPersistentVector" true - "IPersistentSet" true "IPersistentCollection" true "ISeq" true "Atom" true "nil" true - # java.util interfaces + seq types ring & friends extend on - "Map" true "Set" true "List" true "Collection" true "LazySeq" true - "APersistentMap" true}) diff --git a/src/jolt/eval_runtime.janet b/src/jolt/eval_runtime.janet deleted file mode 100644 index d5980a6..0000000 --- a/src/jolt/eval_runtime.janet +++ /dev/null @@ -1,874 +0,0 @@ -# Jolt Evaluator — protocols, multimethods, deftype/reify, stateful fn install -# Extracted from evaluator.janet (jolt-oudv, phase 2a split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./pv) -(use ./plist) -(use ./config) -(use ./reader) -(use ./regex) -(use ./eval_base) -(use ./eval_resolve) -(defn- canonical-host-tag - "If type-name names a host type (optionally java.*/clojure.lang.* qualified), - return its bare canonical name; else nil (it's a deftype/record name)." - [type-name] - (let [base (cond - (string/has-prefix? "java.lang." type-name) (string/slice type-name 10) - (string/has-prefix? "java.util." type-name) (string/slice type-name 10) - (string/has-prefix? "clojure.lang." type-name) (string/slice type-name 13) - type-name)] - (if (get host-type-names base) base nil))) - -(defn- value-host-tags - "Candidate host type-tags for a runtime value, most-specific first." - [obj] - (cond - (number? obj) ["Long" "Integer" "Number" "Double" "Object"] - (string? obj) ["String" "CharSequence" "Object"] - (or (= true obj) (= false obj)) ["Boolean" "Object"] - (keyword? obj) ["Keyword" "Object"] - (and (struct? obj) (= :jolt/char (get obj :jolt/type))) ["Character" "Object"] - (and (struct? obj) (= :symbol (get obj :jolt/type))) ["Symbol" "Object"] - (plist? obj) ["PersistentList" "IPersistentList" "IPersistentCollection" "ISeq" "List" "Collection" "Object"] - (lazy-seq? obj) ["LazySeq" "ISeq" "IPersistentCollection" "Collection" "Object"] - # maps: phm / plain struct / sorted / records — java.util.Map covers them - # all in ring-style extend-protocol clauses - (or (phm? obj) - (shape-rec? obj) # plain shape maps AND records — both map-like - (and (struct? obj) (nil? (get obj :jolt/type))) - (and (table? obj) (or (get obj :jolt/deftype) - (= :jolt/sorted-map (get obj :jolt/type))))) - ["PersistentHashMap" "APersistentMap" "IPersistentMap" "Map" "IPersistentCollection" "Object"] - (or (set? obj) (and (table? obj) (= :jolt/sorted-set (get obj :jolt/type)))) - ["PersistentHashSet" "IPersistentSet" "Set" "IPersistentCollection" "Object"] - (or (tuple? obj) (array? obj) (pvec? obj)) ["PersistentVector" "IPersistentVector" "IPersistentCollection" "ISeq" "Object"] - (or (function? obj) (cfunction? obj)) ["IFn" "Fn" "Object"] - (nil? obj) ["nil" "Object"] - ["Object"])) - -# --------------------------------------------------------------------------- -# Stateful primitives as ordinary fns (Stage 2 jolt-eaa). These mutate/read the -# per-ctx protocol registry, so they need ctx. They're interned into clojure.core -# as closures over ctx (install-stateful-fns!), which makes them resolve + COMPILE -# as plain :var invokes — the back end embeds the per-ctx var cell, and the closure -# captures ctx so a compiled protocol dispatcher works even when called later. -# Both the interpreter and compiled code call these same closures; there is no -# longer a special-form handler for them. proto/method/type names arrive as -# STRINGS (the defprotocol/extend-type macros pass (name sym), not the symbol). -(defn protocol-dispatch-impl [ctx proto-name method-name obj rest-args] - # an empty jolt rest arg is NIL (Clojure semantics); janet apply needs a tuple - (default rest-args []) - (def type-tag (or (record-tag obj) - (if (and (table? obj) (get obj :jolt/protocol-methods)) (get obj :jolt/deftype)))) - (if (and (table? obj) (get obj :jolt/protocol-methods)) - (let [reified-fns (get obj :jolt/protocol-methods) - f (get reified-fns (keyword method-name))] - (if f (apply f obj rest-args) - (error (string "No reified method " method-name " for " type-tag)))) - (if type-tag - (let [f (find-protocol-method ctx type-tag proto-name method-name)] - (if f (apply f obj rest-args) - (error (string "No method " method-name " in " proto-name " for " type-tag)))) - # host value: try candidate host type-tags (Long/String/Object/...), with a - # generation-guarded inline cache (same walk for every value of a host class). - (let [env (ctx :env) - reg-gen (or (get env :type-registry-gen) 0) - pc (let [c (get env :proto-dispatch-cache)] - (if (and c (= (c :gen) reg-gen)) c - (let [n @{:gen reg-gen :map @{}}] - (put env :proto-dispatch-cache n) n))) - cands (value-host-tags obj) - ckey [(first cands) proto-name method-name] - cached (get (pc :map) ckey) - found (if (nil? cached) - (let [f (do (var r nil) - (each tag cands - (when (nil? r) - (set r (find-protocol-method ctx tag proto-name method-name)))) - r)] - (put (pc :map) ckey (if f f :jolt/none)) - f) - (if (= cached :jolt/none) nil cached))] - (if found (apply found obj rest-args) - (error (string "No dispatch for " method-name " on " (type obj)))))))) - -(defn register-method-impl [ctx type-name proto-name method-name f] - # host types register under a bare canonical tag; deftype/record names stay - # namespace-qualified to the ns the (extend-)type form runs in. - (def host (canonical-host-tag type-name)) - (def type-tag (if host host (string (ctx-current-ns ctx) "." type-name))) - (register-protocol-method ctx type-tag proto-name method-name f)) - -(defn make-reified-impl [ctx methods-map & rest-args] - # methods-map is the EVALUATED {keyword fn} map (a phm when compiled, a struct/ - # table when interpreted) — the fn* literals are already fns, just store them. - # proto-names are the (short) names of every protocol the reify implements. - (def proto-names (if (and (= 1 (length rest-args)) (indexed? (in rest-args 0))) - (in rest-args 0) # wiring passed the rest tuple as one arg - rest-args)) - (def obj @{:jolt/deftype (string "reified-" (if (> (length proto-names) 0) (in proto-names 0) "")) - :jolt/protocols (tuple ;proto-names) - :jolt/protocol-methods @{}}) - (def pairs (if (phm? methods-map) - (phm-entries methods-map) - (map (fn [k] [k (get methods-map k)]) (keys methods-map)))) - (each p pairs (put (obj :jolt/protocol-methods) (in p 0) (in p 1))) - obj) - -(defn require-impl - "(require '[ns :as a :refer [...]] ...) — load + alias/refer each spec. A fn, so - the args (quoted specs) arrive evaluated. Varargs (Clojure-compatible); each spec - is a vector [ns & opts] or a bare ns symbol (treated as [ns])." - [ctx & specs] - (each spec specs - (let [s (if (pvec? spec) (pv->array spec) spec)] - (cond - (and (indexed? s) (> (length s) 0)) (eval-require ctx s) - (and (struct? s) (= :symbol (s :jolt/type))) (eval-require ctx @[s]) - (error "require expects a vector spec or a namespace symbol")))) - nil) - -(defn in-ns-impl - "(in-ns 'foo) — switch the current namespace (creating it if needed). A fn; the - quoted symbol arrives evaluated." - [ctx sym] - (def ns-name (if (and (struct? sym) (= :symbol (sym :jolt/type))) (sym :name) (string sym))) - (def the-ns-obj (ctx-find-ns ctx ns-name)) - # An ns entered in-session counts as loaded (Clojure's ns macro commutes the - # name into *loaded-libs*), so a later require/use of it must not try to load - # a file — see maybe-require-ns. Namespace objects are immutable structs, so - # the set lives on the env. - (def loaded (or (get (ctx :env) :loaded-namespaces) - (let [t @{}] (put (ctx :env) :loaded-namespaces t) t))) - (put loaded ns-name true) - (ctx-set-current-ns ctx ns-name) - the-ns-obj) - -(defn use-impl - "(use '[ns ...] ...) — refer ALL public vars of each used ns into the CURRENT ns. - A fn; quoted specs arrive evaluated. Each spec is a ns symbol or a [ns & opts] - vector (a pvec/tuple, not a Janet array — coerce, then take the head as the ns)." - [ctx & specs] - (def target-ns (ctx-find-ns ctx (ctx-current-ns ctx))) - (each s specs - (let [spec (if (pvec? s) (pv->array s) s) - ns-sym (if (indexed? spec) (in spec 0) spec) - src-name (sym-name-str ns-sym)] - (maybe-require-ns ctx src-name) - (let [source-ns (ctx-find-ns ctx src-name)] - # Refer maps the SOURCE VAR itself (the Clojure model): redefinitions in - # the source ns propagate, the :macro flag travels for free, and - # ns-refers can identify refers by the var's home :ns. - (loop [[sym v] :pairs (source-ns :mappings)] - (put (target-ns :mappings) sym v))))) - nil) - -(defn import-impl - "(import 'pkg.Class ...) — register the short class name as an alias of the fully - qualified name in the current ns. A fn; quoted class symbols arrive evaluated." - [ctx & class-specs] - (def ns (ctx-find-ns ctx (ctx-current-ns ctx))) - (defn sym-name [x] (if (and (struct? x) (= :symbol (x :jolt/type))) (x :name) (string x))) - (defn import-one [class-name &opt pkg] - (def last-dot (do (var idx -1) (var pos 0) - (while (< pos (length class-name)) - (when (= (class-name pos) 46) (set idx pos)) (++ pos)) - idx)) - (def short-name (if (>= last-dot 0) (string/slice class-name (+ last-dot 1)) class-name)) - (def pkg-name (cond pkg pkg (>= last-dot 0) (string/slice class-name 0 last-dot) nil)) - (ns-import ns short-name class-name) - # a deftype "class" lives as a ctor var in its defining jolt ns — share it - # (the JVM import makes (TextNode. ...) resolvable; this is our analog) - (when pkg-name - (when-let [src-ns (get ((ctx :env) :namespaces) pkg-name) - v (ns-find src-ns short-name)] - (put (ns :mappings) short-name v)))) - (each class-spec class-specs - (if (or (array? class-spec) (tuple? class-spec) - (and (table? class-spec) (= :jolt/pvec (class-spec :jolt/type)))) - # vector spec: [pkg Class1 Class2 ...] - (let [items (if (table? class-spec) (pv->array class-spec) class-spec) - pkg (sym-name (in items 0))] - (for i 1 (length items) - (import-one (string pkg "." (sym-name (in items i))) pkg))) - (import-one (sym-name class-spec)))) - nil) - -(defn refer-clojure-impl - "(refer-clojure :exclude [a b]) — currently only :exclude is honored: unmap the - excluded names from the current ns. A fn; quoted args arrive evaluated." - [ctx & args] - (when (and (>= (length args) 2) (= (in args 0) :exclude)) - (let [ns (ctx-find-ns ctx (ctx-current-ns ctx)) - excl (in args 1)] - (each sym excl - (ns-unmap ns (if (and (struct? sym) (= :symbol (sym :jolt/type))) (sym :name) (string sym)))))) - nil) - -# Multimethod value -> its var. methods/get-method take the multimethod VALUE -# (Clojure semantics) and recover the var (hence :jolt/methods) through this, -# which works from a compiled fn in any namespace — resolving the symbol at call -# time in the current ns did not (a bare multifn ref in its defining ns saw an -# empty table once defmethods lived in other namespaces; migratus hit this). -(def multi-registry @{}) - -(defn defmulti-setup - "(defmulti name dispatch & opts) — intern a multimethod var. A fn; name arrives - quoted, dispatch + opts (:default key, :hierarchy h) arrive evaluated. The - defmulti macro is the thin wrapper. Builds the dispatch closure over the method - table (shared with the var's :jolt/methods so defmethod adds to it)." - [ctx name-sym dispatch-raw & opts] - (def dispatch-fn (if (keyword? dispatch-raw) (fn [x] (get x dispatch-raw)) dispatch-raw)) - (def default-key - (do (var dv :default) (var i 0) - (while (< i (length opts)) - (if (= :default (in opts i)) (do (set dv (in opts (+ i 1))) (set i (length opts))) (+= i 2))) - dv)) - (def hierarchy - (do (var h nil) (var i 0) - (while (< i (length opts)) - (if (= :hierarchy (in opts i)) (do (set h (in opts (+ i 1))) (set i (length opts))) (+= i 2))) - h)) - (def ns (ctx-find-ns ctx (ctx-current-ns ctx))) - (def methods @{}) - (def isa-cache @[nil]) - (def dispatch-cache @{}) - # the prefers table, shared with the var (prefer-method-setup mutates it) - (def v-box @[nil]) - (def mm-fn - (fn [& args] - (let [dv* (apply dispatch-fn args) - dv (if (nil? dv*) :jolt/nil-sentinel dv*) - method (get methods dv)] - (if method - (apply method args) - (let [cached (get dispatch-cache dv)] - (if cached - (apply cached args) - # isa? is the OVERLAY's (the hierarchy system is pure Clojure now, - # stage 3); resolve its var lazily, once. A :hierarchy option is an - # atom (deref per dispatch, like Clojure's var) or a plain map. - (let [isa-fn (do - (when (nil? (isa-cache 0)) - (put isa-cache 0 - (var-get (ns-find (ctx-find-ns ctx "clojure.core") "isa?")))) - (isa-cache 0)) - h (if hierarchy - (if (and (table? hierarchy) (= :jolt/atom (get hierarchy :jolt/type))) - (hierarchy :value) - hierarchy) - nil) - # Collect EVERY isa-matching method key, then pick the - # dominant one: x dominates y when x is prefer-method'd - # over y (direct preference) or (isa? x y). Two matches - # with no dominant is an ambiguity ERROR, as in Clojure — - # this used to silently take whichever key the table - # yielded first, ignoring prefer-method (jolt-heo). - found (do - (def matches @[]) - (each k (keys methods) - (when (if h (isa-fn h dv k) (isa-fn dv k)) - (array/push matches k))) - (defn pref? [x y] - (def px (get (or (get v-box 0) @{}) x)) - (and px (not (nil? (get px y))))) - (defn dom? [x y] - (or (pref? x y) (if h (isa-fn h x y) (isa-fn x y)))) - (case (length matches) - 0 nil - 1 (get methods (in matches 0)) - (do - (var best (in matches 0)) - (var i 1) - (while (< i (length matches)) - (when (dom? (in matches i) best) (set best (in matches i))) - (++ i)) - (var amb nil) - (each k matches - (when (and (nil? amb) (not (deep= k best)) (not (dom? best k))) - (set amb k))) - (when amb - (error (string "Multiple methods in multimethod '" (name-sym :name) - "' match dispatch value — neither is preferred"))) - (get methods best))))] - (if found - (do (put dispatch-cache dv found) (apply found args)) - (let [dm (get methods default-key)] - (if dm (apply dm args) - (error (string "No method in multimethod " (name-sym :name) - " for dispatch value: " dv)))))))))))) - (def v (ns-intern ns (name-sym :name) mm-fn)) - # pre-create the prefers store so the dispatch closure and - # prefer-method-setup share one table - (def prefs-tbl (or (get v :jolt/prefers) - (do (put v :jolt/prefers @{}) (get v :jolt/prefers)))) - (put v-box 0 prefs-tbl) - (put v :jolt/methods methods) - (put v :jolt/dispatch-cache dispatch-cache) - (put v :jolt/default default-key) - (when hierarchy (put v :jolt/hierarchy hierarchy)) - (put multi-registry mm-fn v) - (var-get v)) - -(defn defmethod-setup - "(defmethod mm dispatch-val impl) — add a method to a multimethod. A fn; mm - arrives quoted, dispatch-val evaluated, impl is the COMPILED method fn (the - defmethod macro builds (fn …)). Auto-creates the multimethod if it's missing." - [ctx mm-sym dispatch-val impl] - (def mm-var - (or (resolve-var ctx @{} mm-sym) - (let [ns (ctx-find-ns ctx (ctx-current-ns ctx)) - stub (fn [& args] nil)] - (def v (ns-intern ns (mm-sym :name) stub)) - (put v :jolt/methods @{}) - (put multi-registry stub v) - v))) - (def methods (or (get mm-var :jolt/methods) (let [m @{}] (put mm-var :jolt/methods m) m))) - # nil is a legal dispatch value (ring's body-string keys a method on it); - # janet tables can't hold nil keys, so it rides the sentinel - (put methods (if (nil? dispatch-val) :jolt/nil-sentinel dispatch-val) impl) - (let [dc (get mm-var :jolt/dispatch-cache)] - (when dc (each k (keys dc) (put dc k nil)))) - mm-var) - -(defn- hint-cross-ns-key - "Resolve a record-typed field hint (\"Vec3\", \"v/Vec3\", \"rt.vec/Vec3\") to the - home namespace's ctor key (\"rt.vec/->Vec3\") when the type is defined in a - DIFFERENT namespace and referred/aliased into the one being defined. The local - current-ns/->Type lookup misses those; this resolves the hint name through the - ns's :refer/:as bindings to the type var, then maps its root ctor value back to - the home key via the ctor-value index. Using the ctor VALUE, not the var's :ns, - is what makes :refer work — a :refer re-interns a fresh var whose :ns is the - referring ns, but its root is the same shared ctor closure. nil if unresolved." - [ctx t cix] - # Resolve against the COMPILE ns (the user ns being analyzed), not ctx-current-ns - # — during compilation the analyzer rebinds ctx-current-ns to jolt.analyzer, so a - # bare referred name would otherwise miss. Qualified alias/Name resolves the alias - # against the compile ns; a bare name looks up the compile ns's own mappings - # (which include :refer-interned vars). - (def cur-name (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx))) - (def cur-ns (ctx-find-ns ctx cur-name)) - (def slash (string/find "/" t)) - (def v (when cur-ns - (if slash - (let [a (string/slice t 0 slash) nm (string/slice t (inc slash)) - home (or (ns-alias-lookup cur-ns a) (ns-import-lookup cur-ns a))] - (when home (ns-find (ctx-find-ns ctx home) nm))) - (ns-find cur-ns t)))) - (when (and v (table? v)) (get cix (v :root)))) - -(defn record-hint-ctor-key - "Resolve a record-type hint NAME (as written on a ^Type field/param — bare, - aliased, or fully qualified) to its home ctor key in the record-shapes registry - (\"rt.vec/->Vec3\"), or nil if it is not a known record type. Local - current-ns/->Name wins; otherwise cross-ns via the ctor-value index. Public so - the analyzer (through jolt.host) can type a ^Type PARAM hint exactly as a field - hint resolves, which is what carries a record param's type across a namespace - boundary without whole-program inference." - [ctx name] - (def rs (get (ctx :env) :record-shapes)) - (when rs - (def cur (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx))) - (def local (string cur "/->" name)) - (if (get rs local) - local - (let [cix (get (ctx :env) :record-ctor-index)] - (when cix (hint-cross-ns-key ctx name cix)))))) - -(defn make-deftype-ctor-impl - "Build a deftype constructor closure. The ns-qualified type tag is baked at - definition time (this runs during the deftype's (def …), in the type's ns), so - instances carry a stable tag matching what extend-type registers methods under. - field-kws is the [:f1 :f2 …] keyword vector; the ctor maps positional args to - those keys. A ctx-capturing closure (make-deftype-ctor) is the public handle." - [ctx type-name-sym field-kws &opt field-tags field-muts] - (def type-tag (string (ctx-current-ns ctx) "." (type-name-sym :name))) - (def kws (d-realize field-kws)) - # per-field type hints (jolt-3ko): a tuple parallel to kws — "Vec3" (a record - # type name), "num", or nil. The inference resolves these to the field's exact - # type so reading a field back carries it (a nested record stays typed). - (def tags (if field-tags (d-realize field-tags) (array/new-filled (length kws)))) - # jolt-c3q: a type with any ^:unsynchronized-mutable / ^:volatile-mutable field - # is set!-able, so it CAN'T be an immutable shape-rec tuple. Such a type uses - # the mutable :jolt/deftype table form regardless of :shapes? (set! mutates it, - # field reads route through the tagged-table path), and is NOT registered as a - # shape so the inference never emits a bare-index read against the table. - (def mutable? (and field-muts (some |(identity $) (d-realize field-muts)))) - # The ctor closure itself. Built FIRST so it can be indexed by value below. - # Records are shape-recs when shapes are active (:shapes? = direct-link, where - # the inference proves the reads) — the whole field-access pipeline handles - # them; otherwise (or when mutable) the original :jolt/deftype tables. Read at - # ctor-BUILD time so a type is consistently one representation or the other. - (def the-ctor - (if (and (get (ctx :env) :shapes?) (not mutable?)) - (fn [& args] (make-record type-tag kws args)) - (fn [& args] - (var inst @{:jolt/deftype type-tag}) - (var i 0) (each kw kws (put inst kw (in args i)) (++ i)) - inst))) - # jolt-t34: register this record's ctor return shape (DECLARED field order) so - # the inference types (->Name ...) as a struct of these fields and field reads - # on the result bare-index. Keyed by the ctor var-key "ns/->Name" to match how - # the IR names the call head. Harmless when records aren't shaped (sidx gated). - # Skipped for mutable types — they're tables, not shape-recs (jolt-c3q). - (unless mutable? - (let [rs (or (get (ctx :env) :record-shapes) - (let [t @{}] (put (ctx :env) :record-shapes t) t)) - # ctor-value index: maps each ctor closure to its rs key, so a ^Type hint - # in another namespace can resolve home through the type var's root value - # (jolt-3ko cross-ns hints; see hint-cross-ns-key). - cix (or (get (ctx :env) :record-ctor-index) - (let [t @{}] (put (ctx :env) :record-ctor-index t) t)) - # resolve a record-typed hint ("Vec3") to its ctor-key ("ns/->Vec3") so - # the inference resolves it with a direct lookup. "num" stays as-is; a - # local def wins; else try cross-ns resolution; an unresolved name (not a - # known record type) stays bare -> :any. - resolved (map (fn [t] - (cond (nil? t) nil - (= t "num") "num" - (let [ck (string (ctx-current-ns ctx) "/->" t)] - (if (get rs ck) ck - (or (hint-cross-ns-key ctx t cix) t))))) - tags)] - (put rs (string (ctx-current-ns ctx) "/->" (type-name-sym :name)) - {:fields (tuple ;kws) :type type-tag :tags (tuple ;resolved)}) - (put cix the-ctor (string (ctx-current-ns ctx) "/->" (type-name-sym :name))))) - the-ctor) - -(defn install-stateful-fns! - "Intern ctx-capturing closures for the stateful primitives into clojure.core, so - both the interpreter and the compiler reach them as ordinary fns. Called by - api/init after init-core! and before the overlay loads (the protocol macros - expand to calls of these)." - [ctx] - (def core (ctx-find-ns ctx "clojure.core")) - # current-ns get/set for compiled code (emit-try restores the ns on a caught - # throw — an interpreted fn that throws leaves ctx-current-ns set to its - # defining ns, since it can't restore on unwind; the interpreted try already - # repairs this, the compiled try did not, leaking the ns past a catch). - (ns-intern core "__current-ns" (fn [] (ctx-current-ns ctx))) - (ns-intern core "__set-current-ns!" (fn [ns-sym] (ctx-set-current-ns ctx ns-sym) nil)) - (ns-intern core "protocol-dispatch" - (fn [proto-name method-name obj rest-args] - (protocol-dispatch-impl ctx proto-name method-name obj rest-args))) - # Devirtualization registry (jolt-41m): defprotocol calls this at load so the - # inference can recognize a protocol-method call site. Maps the method's - # var-key "ns/method" -> [proto-name method-name]. - (ns-intern core "register-protocol-methods!" - (fn [proto-name method-names] - (def reg (or (get (ctx :env) :protocol-methods) - (let [t @{}] (put (ctx :env) :protocol-methods t) t))) - (def ns (ctx-current-ns ctx)) - (each m (d-realize method-names) (put reg (string ns "/" m) (tuple proto-name m))) - nil)) - (ns-intern core "extenders" - (fn [proto] - # All type-tags whose registry entry implements this protocol, as symbols - # (closest analog to Clojure's class list); nil when none. - (let [pname (get (get proto :name) :name) - registry (get (ctx :env) :type-registry) - out @[]] - (each tag (keys registry) - (when (get (get registry tag) pname) - (array/push out {:jolt/type :symbol :ns nil :name tag}))) - (if (empty? out) nil (tuple ;out))))) - (ns-intern core "register-method" - (fn [type-name proto-name method-name f] - (register-method-impl ctx type-name proto-name method-name f))) - (ns-intern core "make-reified" - (fn [methods-map & proto-names] (make-reified-impl ctx methods-map proto-names))) - # Host-class shim registration, exposed to Clojure so a library can mirror a - # Java class jolt doesn't ship (e.g. reitit.Trie). __register-class-statics! - # makes (Class/method ...) resolve; __register-class-methods! makes (.method - # tagged-value ...) dispatch; __register-class-ctor! makes (Class. ...) build. - # Reader-conditional feature toggle, exposed to Clojure so a namespace can - # load a clj-targeted library (e.g. reitit, under :clj) WITHOUT forcing the - # whole process to :clj — set features, require the lib, restore. Returns the - # previous feature set (a list of name strings) for restoration. - (ns-intern core "__reader-features" - (fn [] (tuple ;(map (fn [k] (string k)) (keys reader-features))))) - (ns-intern core "__reader-features-set!" - (fn [names] - # names arrives as a jolt vector (pvec) or list — coerce to a janet array - (def arr (cond (pvec? names) (pv->array names) - (or (tuple? names) (array? names)) names - @[names])) - (reader-features-set! (map (fn [n] (if (keyword? n) n (string n))) arr)) - nil)) - (ns-intern core "__register-class-statics!" - (fn [nm tbl] (register-class-statics! nm tbl) nil)) - (ns-intern core "__register-class-methods!" - (fn [tag tbl] (register-tagged-methods! tag tbl) nil)) - (ns-intern core "__register-class-ctor!" - (fn [nm f] (register-class-ctor! nm f) (ns-intern core nm (class-value-for nm)) nil)) - (ns-intern core "require" (fn [& specs] (require-impl ctx ;specs))) - (ns-intern core "in-ns" (fn [sym] (in-ns-impl ctx sym))) - (ns-intern core "use" (fn [& specs] (use-impl ctx ;specs))) - (ns-intern core "import" (fn [& specs] (import-impl ctx ;specs))) - (ns-intern core "refer-clojure" (fn [& args] (refer-clojure-impl ctx ;args))) - (ns-intern core "defmulti-setup" (fn [name-sym dispatch & opts] (defmulti-setup ctx name-sym dispatch ;opts))) - (ns-intern core "defmethod-setup" (fn [mm-sym dval impl] (defmethod-setup ctx mm-sym dval impl))) - (ns-intern core "make-deftype-ctor" (fn [name-sym field-kws &opt field-tags field-muts] (make-deftype-ctor-impl ctx name-sym field-kws field-tags field-muts))) - # Var/namespace lookups that need the ctx (the rest of the var fns — var-get/ - # var-set/var?/alter-var-root/alter-meta!/reset-meta! — are plain core-bindings). - (ns-intern core "find-var" (fn [sym] (find-var ctx sym))) - # *ns*: the current-namespace dynamic var. Its root is kept in sync by - # ctx-set-current-ns via the cached var table (env :ns-var); a thread - # binding (binding [*ns* ...]) shadows the root through var-get as usual. - (def ns-var (ns-intern core "*ns*" (ctx-find-ns ctx (ctx-current-ns ctx)))) - (put ns-var :dynamic true) - (put (ctx :env) :ns-var ns-var) - (ns-intern core "intern" - (fn [ns-name sym-name &opt val] - (def ns (ctx-find-ns ctx (if (struct? ns-name) (ns-name :name) ns-name))) - (ns-intern ns (if (struct? sym-name) (sym-name :name) sym-name) val))) - # --- ns introspection (Stage 2 tier 6b) — evaluated-arg Clojure semantics. - # A namespace designator is an ns object (passes through) or a symbol/string - # naming one. find-ns is a pure lookup (nil when absent); create-ns creates - # (ctx-find-ns is create-on-demand). The optional-arg forms default to the - # current ns, preserving the prior 0-arg interpreter behavior. - (def ns-name-of (fn [x] - (cond - (and (struct? x) (= :symbol (x :jolt/type))) (x :name) - (string? x) x - (keyword? x) (string x) - nil))) - (def ns-of (fn [x] - (if (= :jolt/namespace (get x :jolt/type)) - x - (let [nm (ns-name-of x)] - (if nm (get (get (ctx :env) :namespaces) nm) nil))))) - (def ns-or-current (fn [x] - (if (nil? x) - (ctx-find-ns ctx (ctx-current-ns ctx)) - (or (ns-of x) (error (string "No namespace: " (ns-name-of x))))))) - (ns-intern core "find-ns" (fn [x] (ns-of x))) - (ns-intern core "create-ns" (fn [x] (ctx-find-ns ctx (ns-name-of x)))) - (ns-intern core "remove-ns" (fn [x] (remove-ns ctx (ns-name-of x)))) - (ns-intern core "all-ns" (fn [] (all-ns ctx))) - (ns-intern core "the-ns" (fn [&opt x] (ns-or-current x))) - # interns/imports return a jolt MAP (struct), not the live host table — so - # count/seq/keys work on them, and callers can't mutate the ns through them. - (ns-intern core "ns-interns" (fn [&opt x] (table/to-struct ((ns-or-current x) :mappings)))) - # {alias-symbol -> namespace object}, Clojure's shape, from the string store. - (ns-intern core "ns-aliases" - (fn [&opt x] - (def ns (ns-or-current x)) - (def out @{}) - (eachp [a target] (ns :aliases) - (put out {:jolt/type :symbol :ns nil :name a} (ctx-find-ns ctx target))) - (table/to-struct out))) - (ns-intern core "ns-imports" (fn [&opt x] (table/to-struct ((ns-or-current x) :imports)))) - # (ns-resolve ns sym) -> the var or nil. Unqualified syms look in ns's own - # mappings; ns-qualified syms resolve through ns's aliases. (types/ns-resolve - # keys ns-find with the symbol struct instead of its name string, so it never - # finds anything — do the lookup here.) - (ns-intern core "ns-resolve" - (fn [ns-d sym] - (def ns (ns-or-current ns-d)) - (def nm (if (struct? sym) (sym :name) (string sym))) - (def nsp (if (struct? sym) (sym :ns) nil)) - (if nsp - (let [target (or (ns-alias-lookup ns nsp) nsp) - target-ns (ctx-find-ns ctx target)] - (when target-ns (ns-find target-ns nm))) - (ns-find ns nm)))) - (ns-intern core "resolve" - (fn [sym] - (when (and (struct? sym) (= :symbol (sym :jolt/type))) - (def r (protect (resolve-var ctx @{} sym))) - (if (r 0) (r 1) nil)))) - # refer: bring another ns's public vars into the current ns. Reuses use-impl's - # refer-all behavior; the :only/:exclude/:rename filters are not yet honored. - (ns-intern core "refer" (fn [ns-sym & filters] (use-impl ctx ns-sym))) - # --- dispatch-table / type fns (Stage 2 tier 6c) ------------------------ - # A multimethod's method table lives on its VAR (the value is the dispatch - # closure), so the overlay macros pass the NAME quoted — the defmulti/ - # defmethod pattern — and these resolve the var. prefer-method auto-creates - # a missing multimethod (matching the prior interpreter arm). - (def mm-var-of (fn [mm-sym auto-create?] - (def r (protect (resolve-var ctx @{} mm-sym))) - (def found (if (r 0) (r 1) nil)) - (if found - found - (when auto-create? - (def ns (ctx-find-ns ctx (ctx-current-ns ctx))) - (def stub (fn [& args] nil)) - (def nv (ns-intern ns (mm-sym :name) stub)) - (put nv :jolt/methods @{}) - (put multi-registry stub nv) - nv)))) - (def clear-dispatch-cache! (fn [mm-var] - (let [dc (get mm-var :jolt/dispatch-cache)] - (when dc (each k (keys dc) (put dc k nil)))))) - (ns-intern core "prefer-method-setup" - (fn [mm-sym dval-a dval-b] - (def mm-var (mm-var-of mm-sym true)) - (def prefs (or (get mm-var :jolt/prefers) - (do (put mm-var :jolt/prefers @{}) (mm-var :jolt/prefers)))) - # {x -> {y true ...}}: x is preferred over each y (Clojure's {x #{y}}) - (def sub (or (get prefs dval-a) - (do (put prefs dval-a @{}) (get prefs dval-a)))) - (put sub dval-b true) - (clear-dispatch-cache! mm-var) - mm-var)) - (ns-intern core "remove-method-setup" - (fn [mm-sym dval] - (def dval (if (nil? dval) :jolt/nil-sentinel dval)) - (def mm-var (mm-var-of mm-sym false)) - (when mm-var - (let [methods (get mm-var :jolt/methods)] - (when methods (put methods dval nil))) - (clear-dispatch-cache! mm-var)) - mm-var)) - (ns-intern core "remove-all-methods-setup" - (fn [mm-sym] - (def mm-var (mm-var-of mm-sym false)) - (when mm-var - # clear IN PLACE: the dispatch closure captured this table at defmulti - # time, so swapping in a fresh one leaves dispatch seeing stale methods - (let [methods (get mm-var :jolt/methods)] - (when methods (each k (keys methods) (put methods k nil)))) - (clear-dispatch-cache! mm-var)) - mm-var)) - (ns-intern core "prefers-setup" - (fn [mm-sym] - (def mm-var (mm-var-of mm-sym false)) - (or (and mm-var (get mm-var :jolt/prefers)) {}))) - # methods/get-method receive the multimethod VALUE (Clojure semantics): map it - # back to its var via multi-registry. A symbol arg still works (mm-var-of), for - # any caller that passes one. - (def mm-var-of-val (fn [mm] - (if (function? mm) (get multi-registry mm) (mm-var-of mm false)))) - (ns-intern core "get-method-setup" - (fn [mm dval] - (def dval (if (nil? dval) :jolt/nil-sentinel dval)) - (def mm-var (mm-var-of-val mm)) - (when mm-var - (let [methods (get mm-var :jolt/methods)] - (or (get methods dval) (get methods :default)))))) - (ns-intern core "methods-setup" - (fn [mm] - (def mm-var (mm-var-of-val mm)) - (when mm-var - # a jolt map, not the live host table (and phm so vector dispatch - # values look up by value, same reason build-eval-map promotes) - (var m (make-phm)) - (let [tbl (get mm-var :jolt/methods)] - (when tbl (each k (keys tbl) (set m (phm-assoc m k (get tbl k)))))) - m))) - # satisfies?: evaluated protocol value + instance. Recognizes a reify the same - # way instance? does — by the protocols it records on itself (a reify's methods - # are instance-local, so they aren't in the global type registry that - # type-satisfies? consults). - (ns-intern core "satisfies?" - (fn [proto obj] - (def pn (proto :name)) - (def pn-str (if (struct? pn) (pn :name) pn)) - (def protos (if (table? obj) (get obj :jolt/protocols))) - (def type-tag (or (record-tag obj) - (if (and (table? obj) (get obj :jolt/protocol-methods)) - (get obj :jolt/deftype)))) - (cond - (and protos (string? pn-str) - (truthy? (some (fn [p] (= (last (string/split "." p)) - (last (string/split "." pn-str)))) - protos))) true - type-tag (type-satisfies? ctx type-tag pn-str) - false))) - # instance?: the overlay macro passes the TYPE NAME quoted (class names don't - # evaluate to values on jolt); the value arg arrives evaluated. - # Generic hook so an external host-shim library (e.g. jolt-lang/http-client) - # can teach instance? about its own shim types without editing core. Each hook - # is (fn [class-name val] -> truthy|nil); consulted when no built-in matches. - (var instance-check-hooks @[]) - (ns-intern core "__register-instance-check!" - (fn [f] (array/push instance-check-hooks f) nil)) - (ns-intern core "instance-check" - (fn [type-sym val] - (if (record-tag val) - (let [type-tag (record-tag val) - type-name (type-sym :name)] - (or (= type-tag type-name) - (and (> (length type-tag) (length type-name)) - (= (string/slice type-tag (- (length type-tag) (length type-name))) - type-name)) - # instance? of a PROTOCOL works like satisfies?: a reify implementing - # it is an instance. The reify records every protocol it implements - # (short names); (instance? a.b.Proto x) passes a qualified name, so - # match by short name against any of them. (malli relies on this.) - (let [protos (if (table? val) (get val :jolt/protocols)) - tn-short (last (string/split "." type-name))] - (and protos (truthy? (some (fn [p] (= (last (string/split "." p)) tn-short)) protos)))))) - (match (type-sym :name) - "Number" (number? val) - "java.lang.Number" (number? val) - "Long" (number? val) - "java.lang.Long" (number? val) - "Integer" (number? val) - "Double" (number? val) - "String" (string? val) - "java.lang.String" (string? val) - # String implements CharSequence — malli's :re validator gates on - # (instance? CharSequence x) before matching (jolt-ltwk). - "CharSequence" (string? val) - "java.lang.CharSequence" (string? val) - "Boolean" (or (= true val) (= false val)) - "Keyword" (keyword? val) - # regex patterns (cuerdas-style (instance? Pattern x) checks) - "Pattern" (and (table? val) (= :jolt/regex (val :jolt/type))) - "java.util.regex.Pattern" (and (table? val) (= :jolt/regex (val :jolt/type))) - "Character" (and (struct? val) (= :jolt/char (get val :jolt/type))) - "java.lang.Character" (and (struct? val) (= :jolt/char (get val :jolt/type))) - # java.time shims (host_interop.janet); #inst IS java.util.Date in Clojure - "java.util.Date" (and (struct? val) (= :jolt/inst (get val :jolt/type))) - "Date" (and (struct? val) (= :jolt/inst (get val :jolt/type))) - "Instant" (and (table? val) (= :jolt/instant (get val :jolt/type))) - "java.time.Instant" (and (table? val) (= :jolt/instant (get val :jolt/type))) - "LocalDateTime" (and (table? val) (= :jolt/local-dt (get val :jolt/type))) - "java.time.LocalDateTime" (and (table? val) (= :jolt/local-dt (get val :jolt/type))) - "ZonedDateTime" (and (table? val) (= :jolt/zoned-dt (get val :jolt/type))) - "java.time.ZonedDateTime" (and (table? val) (= :jolt/zoned-dt (get val :jolt/type))) - "LocalTime" false - "LocalDate" false - "java.sql.Time" false - "java.sql.Timestamp" false - "java.sql.Date" false - "DateTimeFormatter" (and (table? val) (= :jolt/dt-formatter (get val :jolt/type))) - "URL" (and (table? val) (= :jolt/url (get val :jolt/type))) - "java.net.URL" (and (table? val) (= :jolt/url (get val :jolt/type))) - # next.jdbc host shim: a wrapped jdbc.core connection (core.janet). - # migratus's do-commands only runs SQL through its (instance? Connection) - # branch, so the wrapped conn must answer true here. - "Connection" (and (table? val) (= :jolt/jdbc-conn (get val :jolt/type))) - "java.sql.Connection" (and (table? val) (= :jolt/jdbc-conn (get val :jolt/type))) - # java.io.File model (jolt-hjw): io/file and (File. …) build :jolt/file, - # so migratus's (instance? File migration-dir) takes the filesystem path. - "File" (and (table? val) (= :jolt/file (get val :jolt/type))) - "java.io.File" (and (table? val) (= :jolt/file (get val :jolt/type))) - # JVM char[] class — (Class/forName "[C"); jolt char arrays are Janet - # arrays of char structs - "[C" (and (array? val) - (or (= 0 (length val)) - (and (struct? (val 0)) (= :jolt/char ((val 0) :jolt/type))))) - "clojure.lang.Atom" (and (table? val) (= :jolt/atom (val :jolt/type))) - "clojure.lang.Volatile" (and (table? val) (= :jolt/volatile (val :jolt/type))) - "clojure.lang.Delay" (and (table? val) (= :jolt/delay (val :jolt/type))) - "clojure.lang.IPersistentMap" (or (phm? val) (struct? val)) - "clojure.lang.IPersistentVector" (or (tuple? val) (pvec? val)) - "clojure.lang.IPersistentSet" (set? val) - "Object" true - # no built-in match — consult library-registered instance? hooks - (do (var r false) - (each h instance-check-hooks - (when (h (type-sym :name) val) (set r true) (break))) - r))))) - # Reader / expansion as plain fns: read-string parses one form; macroexpand-1 - # expands a (quoted, already-evaluated) call form once via its macro var. - (ns-intern core "read-string" (fn [s] (parse-string s))) - # Strip the interpreter's {:jolt/type :jolt/exception :value v} throw envelope. - # Compiled catch uses this so a caught value matches what the interpreter binds - # (interpreted throw wraps; compiled throw raises raw) — keeps (class e) / - # ex-message / catch consistent across the compiled⇄interpreted boundary. - (ns-intern core "__unwrap-ex" - (fn [e] (if (and (or (table? e) (struct? e)) (= :jolt/exception (get e :jolt/type))) - (get e :value) e))) - # The *in* reader family's host seams. __stdin-read-line: one line from real - # stdin, newline stripped, nil at EOF. __parse-next: one form off a string -> - # [form rest-of-string], nil when only whitespace remains. *in*, read-line, - # read, with-in-str, and line-seq are Clojure over these (core/50-io.clj). - # The loader's registered source roots (the closest thing to a classpath) — - # io/resource searches these for relative resource paths. - # registered constructor shims: the NAME evaluates to the canonical class - # string (so class-dispatch defmultis match); `new` finds the ctor fn. - (eachp [nm f] class-ctors (ns-intern core nm (class-value-for nm))) - # dispatch-only type names (no ctor): InputStream, File, ISeq, ... - (eachp [nm canon] class-canonical-names - (unless (or (in class-ctors nm) (ns-find core nm)) - (ns-intern core nm canon))) - (ns-intern core "__source-roots" - (fn [] (tuple ;(get (ctx :env) :source-paths)))) - (ns-intern core "__stdin-read-line" - (fn [] - (let [l (file/read stdin :line)] - (if (nil? l) nil - (let [s (string l)] - (if (string/has-suffix? "\n" s) (string/slice s 0 -2) s)))))) - (ns-intern core "__parse-next" - (fn [s] - (if (= 0 (length (string/trim s))) nil - (let [r (parse-next s)] (tuple (r 0) (r 1)))))) - (def expand-1 (fn [the-form] - (if (and (array? the-form) (> (length the-form) 0) - (struct? (first the-form)) (= :symbol ((first the-form) :jolt/type))) - (let [v (resolve-var ctx @{} (first the-form))] - (if (and v (var-macro? v)) - (apply (var-get v) (tuple/slice the-form 1)) - the-form)) - the-form))) - (ns-intern core "macroexpand-1" expand-1) - # Apply a registered data reader to an already-read form (EDN built-in tags - # #uuid/#inst and any registered reader). Throws on an unknown tag. - (ns-intern core "__read-tagged" - (fn [tag form] - (def data-readers (get (ctx :env) :data-readers)) - (def reader-fn (if data-readers (get data-readers tag))) - (if reader-fn - (reader-fn form) - (error (string "No reader function for tag " tag))))) - # macroexpand: expand repeatedly until the head is no longer a macro (the - # form's SUBFORMS are not expanded, matching Clojure). - (ns-intern core "macroexpand" - (fn [the-form] - (var cur the-form) - (var nxt (expand-1 cur)) - (while (not= cur nxt) (set cur nxt) (set nxt (expand-1 cur))) - cur)) - # alias bookkeeping is UNIFIED (jolt-ark): :aliases (alias-name string -> - # ns-name string) is the one store, read by resolution and ns-aliases; - # :imports holds class imports only. - (ns-intern core "alias" - (fn [alias-sym ns-sym] - (def cur (ctx-find-ns ctx (ctx-current-ns ctx))) - (ns-add-alias cur (alias-sym :name) (ns-sym :name)) - nil)) - (ns-intern core "ns-unalias" - (fn [ns-d alias-sym] - (def ns (ns-or-current ns-d)) - (put (ns :aliases) (alias-sym :name) nil) - nil)) - # ns-publics: {symbol -> var} (jolt has no private vars, so publics = interns). - # Keys are symbol structs (value-hashed), matching Clojure's symbol keys. - (def mappings->symbol-map (fn [ns pred] - (var m (make-phm)) - (loop [[nm v] :pairs (ns :mappings)] - (when (pred nm v) - (set m (phm-assoc m {:jolt/type :symbol :ns nil :name nm} v)))) - m)) - (ns-intern core "ns-publics" - (fn [&opt ns-d] - (mappings->symbol-map (ns-or-current ns-d) (fn [nm v] true)))) - # ns-map: all mappings (interns + refers; jolt has no class imports in maps). - (ns-intern core "ns-map" - (fn [&opt ns-d] - (mappings->symbol-map (ns-or-current ns-d) (fn [nm v] true)))) - # ns-refers: mappings whose var's HOME ns differs from this ns (copied in by - # refer/use/require :refer). - (ns-intern core "ns-refers" - (fn [&opt ns-d] - (def ns (ns-or-current ns-d)) - (def my-name (ns :name)) - (mappings->symbol-map ns (fn [nm v] - (and (table? v) (not= (get v :ns) my-name)))))) - (ns-intern core "ns-unmap" - (fn [ns-d sym] - (def ns (ns-or-current ns-d)) - (put (ns :mappings) (if (struct? sym) (sym :name) (string sym)) nil) - nil)) - core) - -# Dispatch a special form by its string name. diff --git a/src/jolt/eval_special.janet b/src/jolt/eval_special.janet deleted file mode 100644 index d748f1e..0000000 --- a/src/jolt/eval_special.janet +++ /dev/null @@ -1,773 +0,0 @@ -# Jolt Evaluator — special forms (eval-list dispatch) -# Extracted from evaluator.janet (jolt-oudv, phase 2a split). - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./pv) -(use ./plist) -(use ./config) -(use ./reader) -(use ./regex) -(use ./eval_base) -(use ./eval_resolve) -(use ./eval_runtime) -(defn- unwrap-meta-name - "Recursively unwrap (with-meta sym meta) forms to extract the underlying symbol. - Returns the symbol struct, or the original form if it's not a with-meta wrapper." - [form] - (if (and (array? form) (> (length form) 0) - (struct? (in form 0)) - (= :symbol ((in form 0) :jolt/type)) - (= "with-meta" ((in form 0) :name))) - (unwrap-meta-name (in form 1)) - form)) - - -# --- special-form handlers (exploded from eval-list, jolt-oudv) --- -(defn eval-do [ctx bindings form] - (do - (var result nil) - (var i 1) - (let [len (length form)] - (while (< i len) - (set result (eval-form ctx bindings (in form i))) - (++ i))) - result)) - -(defn eval-if [ctx bindings form] - (do - # 2 or 3 argument forms only (spec 03-special-forms X1) - (when (or (< (length form) 3) (> (length form) 4)) - (error (string "Wrong number of args (" (dec (length form)) ") passed to: if"))) - (let [test-val (eval-form ctx bindings (in form 1))] - (if (and (not (nil? test-val)) (not (= false test-val))) - (eval-form ctx bindings (in form 2)) - (if (> (length form) 3) (eval-form ctx bindings (in form 3)) nil))))) - -(defn eval-def [ctx bindings form] - (let [raw-name (in form 1) - name-sym (unwrap-meta-name raw-name) - # Metadata on the name: keyword/type-hint metadata rides on the - # symbol (:meta); a ^{:map} reads as a with-meta form we evaluate. - sym-meta (or (and (struct? name-sym) (get name-sym :meta)) {}) - wm-meta (if (and (array? raw-name) (> (length raw-name) 0) - (sym-name? (first raw-name) "with-meta")) - (let [mv (protect (eval-form ctx bindings (last raw-name)))] - (if (and (mv 0) (or (table? (mv 1)) (struct? (mv 1)))) (mv 1) {})) - {}) - name-meta (merge wm-meta sym-meta) - dynamic? (truthy? (get name-meta :dynamic)) - ns-name (ctx-current-ns ctx) - ns (ctx-find-ns ctx ns-name) - # Create var first (unbound) so self-referencing defs resolve - v (ns-intern ns (name-sym :name))] - # (def name) with no init interns the var and leaves any existing - # root binding alone (Clojure semantics — this is what declare - # expands to, so compiled forward refs bind to the var instead of - # falling through to a like-named host builtin). - (if (= 2 (length form)) - (do - (when (not (empty? name-meta)) - (put v :meta (merge (or (get v :meta) {}) name-meta))) - (when dynamic? (put v :dynamic true)) - v) - (let [# (def name docstring value): docstring form 2, value form 3 - has-doc (and (> (length form) 3) (string? (in form 2))) - val-form (in form (if has-doc 3 2)) - val (eval-form ctx bindings val-form)] - (bind-root v val) - # Staged bootstrap (jolt-4j3): pre/at-kernel overlay defns load - # interpreted; stash the fn source so backend/recompile-defns! can - # compile them once the analyzer is alive — the defn analog of - # :macro-src. Only set while api/load-core-overlay! loads the early - # tiers (the flag scopes it away from user code). - (when (and (get (ctx :env) :stash-defn-src?) - (function? val) - (array? val-form) (> (length val-form) 0) - (or (sym-name? (first val-form) "fn") - (sym-name? (first val-form) "fn*"))) - (put v :defn-src val-form)) - (let [extra (if has-doc (merge name-meta {:doc (in form 2)}) name-meta)] - (when (not (empty? extra)) - (put v :meta (merge (or (get v :meta) {}) extra)))) - (when dynamic? - (put v :dynamic true)) - # def returns the var (Clojure semantics); REPL prints #'ns/name - v)))) - -(defn eval-defmacro [ctx bindings form] - (let [# ^{:map} metadata on the name reads as a (with-meta sym …) - # form (jolt-8w2); unwrap to the bare symbol like def does. - name-sym (unwrap-meta-name (in form 1)) - after-name (tuple/slice form 2) - # Skip an optional leading docstring (string) then an optional - # attr-map (a struct that is not a symbol — a map literal reads - # as a struct), matching defn. Real macros use both, e.g. - # (defmacro info "doc" {:arglists '(...)} [& args] …). - a1 (if (and (> (length after-name) 0) (string? (first after-name))) - (tuple/slice after-name 1) after-name) - after-meta (if (and (> (length a1) 0) - (struct? (first a1)) - (not= :symbol (get (first a1) :jolt/type))) - (tuple/slice a1 1) a1) - # What remains is either a params VECTOR (tuple) + body, or one - # or more arity CLAUSES (each a list, i.e. a janet array). Build - # a uniform arity list [{:params … :body …} …]. - multi? (and (> (length after-meta) 0) (array? (first after-meta))) - arities (if multi? - (map (fn [cl] {:params (first cl) :body (tuple/slice cl 1)}) - after-meta) - @[{:params (first after-meta) :body (tuple/slice after-meta 1)}]) - defining-ns (ctx-current-ns ctx)] - (def interp-fn (fn [& macro-args] - (def n (length macro-args)) - # Pick the arity: an exact fixed-count match wins; otherwise the - # first variadic arity that accepts n args (Clojure fn dispatch). - (var chosen nil) - (each ar arities - (def pi (parse-params (ar :params))) - (when (and (nil? chosen) (not (pi :rest)) (= n (length (pi :fixed)))) - (set chosen [pi (ar :body)]))) - (when (nil? chosen) - (each ar arities - (def pi (parse-params (ar :params))) - (when (and (nil? chosen) (pi :rest) (>= n (length (pi :fixed)))) - (set chosen [pi (ar :body)])))) - (when (nil? chosen) - (error (string "no matching arity for macro " (name-sym :name) - " (" n " args)"))) - (def pi (chosen 0)) - (def body (chosen 1)) - (var new-bindings @{}) - (table/setproto new-bindings bindings) - (put new-bindings "&env" @{}) # implicit &env for macro bodies (table — nil-safe) - (var i 0) - # Destructure macro params (like fn), so [& [a & more :as all]] - # and {:keys …} rest forms work in macro arglists. - (each pat (pi :fixed) - (destructure-bind ctx new-bindings pat (macro-args i)) - (++ i)) - (when (pi :rest) - (destructure-bind ctx new-bindings (pi :rest) (rest-args-val macro-args i))) - # Use defining namespace for symbol resolution - (def saved-ns (ctx-current-ns ctx)) - (ctx-set-current-ns ctx defining-ns) - # Plain trailing restore (NOT defer/try — those build a fiber per - # call and blow the C stack on deep interpreted recursion). An - # unwinding throw is repaired once at the TOP-LEVEL boundary - # (loader/eval-toplevel restores the ns on error). - (var result nil) - (each bf body - (set result (eval-form ctx new-bindings bf))) - (ctx-set-current-ns ctx saved-ns) - result)) - # A COMPILED expander (native-speed) is only built for the - # single-arity case (the compile hook + recompile path take one - # [args body]); multi-arity macros use the interpreted expander. - (def single? (= 1 (length arities))) - (def args-form (and single? ((first arities) :params))) - (def body (and single? ((first arities) :body))) - (def uses-env (do (var u false) - (each ar arities - (when (or (form-uses-sym? (ar :body) "&env") - (form-uses-sym? (ar :body) "&form")) - (set u true))) - u)) - (def compiled-fn - (when (and macro-compile-hook single? (not uses-env)) - (macro-compile-hook ctx args-form body))) - (def macro-fn (or compiled-fn interp-fn)) - (let [ns-name (ctx-current-ns ctx) - ns (ctx-find-ns ctx ns-name)] - (def v (ns-intern ns (name-sym :name) macro-fn)) - (put v :macro true) - # Stash the expander source so backend/recompile-macros! can - # compile it once the analyzer is alive (staged bootstrap): a - # macro defined WHILE the analyzer is still being built gets an - # interpreted closure now, a compiled expander later. uses-env - # macros stay interpreted (the compiled fn* has no &env/&form); - # multi-arity macros keep the interpreted dispatch (no single - # [args body] to recompile). - (when single? (put v :macro-src @[args-form body])) - (put v :macro-uses-env uses-env) - (when compiled-fn (put v :macro-compiled true)) - # A (re)defined macro invalidates any cached expansions. - (table/clear macro-cache) - (var-get v)))) - -(defn eval-fn* [ctx bindings form] - (let [# optional name: (fn* name [args] ...) / (fn* name ([args] ...)...) - named? (and (struct? (in form 1)) (= :symbol ((in form 1) :jolt/type))) - fn-name (if named? ((in form 1) :name) nil) - form (if named? (array/concat @[(in form 0)] (tuple/slice form 2)) form)] - (if (array? (in form 1)) - # Multi-arity: (fn* ([args] body...) ([args] body...)...) - (let [pairs (tuple/slice form 1) - arities @{} - defining-ns (ctx-current-ns ctx)] - (var self nil) - # The (single) variadic clause is dispatched separately: it handles - # any arg count >= its fixed count. Storing it in `arities` by - # fixed-count would collide with a same-fixed-count fixed clause and - # only match that exact count. - (var variadic-fn nil) - (var variadic-min 0) - (each pair pairs - (let [args-form (in pair 0) - body (tuple/slice pair 1) - param-info (parse-params args-form) - _ (require-symbol-params param-info) - fixed-pats (param-info :fixed) - rest-pat (param-info :rest) - n-fixed (length fixed-pats) - # recur-entry: where (recur ...) re-enters THIS arity. For - # a fixed arity it's the dispatcher (exact count re-selects - # it). For the VARIADIC arity, recur takes n-fixed + 1 args - # with the LAST bound DIRECTLY as the rest seq (Clojure) — - # re-entering through the varargs collector would wrap it - # in a fresh 1-element rest list and the seq never empties - # (the jolt-4df hang). - recur-entry-box @[nil] - run-clause (fn [fn-bindings] - (put fn-bindings :jolt/loop-fn (in recur-entry-box 0)) - (when fn-name (bind-put fn-bindings fn-name self)) - # Use defining namespace for symbol resolution - (def saved-ns (ctx-current-ns ctx)) - (ctx-set-current-ns ctx defining-ns) - # Plain trailing restore (NOT defer/try — those build a fiber per - # call and blow the C stack on deep interpreted recursion). An - # unwinding throw is repaired once at the TOP-LEVEL boundary - # (loader/eval-toplevel restores the ns on error). - (var result nil) - (each body-form body - (set result (eval-form ctx fn-bindings body-form))) - (ctx-set-current-ns ctx saved-ns) - result) - f (fn [& fn-args] - (var fn-bindings @{}) - (table/setproto fn-bindings bindings) - (var i 0) - (each pat fixed-pats - (destructure-bind ctx fn-bindings pat (fn-args i)) - (++ i)) - (when rest-pat - (destructure-bind ctx fn-bindings rest-pat (rest-args-val fn-args i))) - (run-clause fn-bindings))] - (if rest-pat - (do - (put recur-entry-box 0 - (fn [& recur-args] - (var fn-bindings @{}) - (table/setproto fn-bindings bindings) - (var i 0) - (each pat fixed-pats - (destructure-bind ctx fn-bindings pat (recur-args i)) - (++ i)) - (destructure-bind ctx fn-bindings rest-pat (get recur-args i)) - (run-clause fn-bindings))) - (set variadic-fn f) (set variadic-min n-fixed)) - (do - (put recur-entry-box 0 (fn [& recur-args] (apply self recur-args))) - (put arities n-fixed f))))) - (set self (fn [& fn-args] - (let [n (length fn-args) - f (get arities n)] - (cond - f (apply f fn-args) - (and variadic-fn (>= n variadic-min)) (apply variadic-fn fn-args) - (error (string "Wrong number of args (" n ") passed to: " - (or fn-name "fn"))))))) - self) - # Single-arity: (fn* [args] body...) - (let [args-form (in form 1) - body (tuple/slice form 2) - param-info (parse-params args-form) - _ (require-symbol-params param-info) - fixed-pats (param-info :fixed) - rest-pat (param-info :rest) - defining-ns (ctx-current-ns ctx)] - (var self nil) - (var recur-entry nil) - (def run-body (fn [fn-bindings] - (put fn-bindings :jolt/loop-fn recur-entry) - (when fn-name (bind-put fn-bindings fn-name self)) - # Use defining namespace for symbol resolution - (def saved-ns (ctx-current-ns ctx)) - (ctx-set-current-ns ctx defining-ns) - # Plain trailing restore (NOT defer/try — those build a fiber per - # call and blow the C stack on deep interpreted recursion). An - # unwinding throw is repaired once at the TOP-LEVEL boundary - # (loader/eval-toplevel restores the ns on error). - (var result nil) - (each body-form body - (set result (eval-form ctx fn-bindings body-form))) - (ctx-set-current-ns ctx saved-ns) - result)) - (def n-fixed (length fixed-pats)) - (set self (fn [& fn-args] - # ArityException semantics (jolt-6xn): a fixed arity takes - # exactly its params, a variadic one at least its fixed params. - # The compiled path enforces this natively (janet fn arity); - # this keeps the interpreter oracle in agreement. - (def n (length fn-args)) - (when (if rest-pat (< n n-fixed) (not= n n-fixed)) - (error (string "Wrong number of args (" n ") passed to: " - (or fn-name "fn")))) - (var fn-bindings @{}) - (table/setproto fn-bindings bindings) - (var i 0) - (each pat fixed-pats - (destructure-bind ctx fn-bindings pat (fn-args i)) - (++ i)) - (when rest-pat - (destructure-bind ctx fn-bindings rest-pat (rest-args-val fn-args i))) - (run-body fn-bindings))) - # recur re-enters here: for a variadic fn it takes n-fixed + 1 - # args, the LAST bound DIRECTLY as the rest seq (Clojure) — going - # back through the varargs collector wrapped the seq in a fresh - # 1-element rest list, so it never emptied (the jolt-4df hang). - (set recur-entry - (if rest-pat - (fn [& recur-args] - (var fn-bindings @{}) - (table/setproto fn-bindings bindings) - (var i 0) - (each pat fixed-pats - (destructure-bind ctx fn-bindings pat (recur-args i)) - (++ i)) - (destructure-bind ctx fn-bindings rest-pat (get recur-args i)) - (run-body fn-bindings)) - self)) - self)))) - -(defn eval-let* [ctx bindings form] - (let [bind-vec (in form 1) - body (tuple/slice form 2)] - (var new-bindings @{}) - (table/setproto new-bindings bindings) - (var i 0) - (let [len (length bind-vec)] - (while (< i len) - (let [pat (bind-vec i)] - # let* is a primitive (the let macro desugars destructuring); - # its binding names must be plain symbols, as in Clojure. - (unless (plain-sym? pat) (error "Bad binding form, expected symbol")) - (def val (eval-form ctx new-bindings (bind-vec (+ i 1)))) - (destructure-bind ctx new-bindings pat val) - (+= i 2)))) - (var result nil) - (each body-form body - (set result (eval-form ctx new-bindings body-form))) - result)) - -(defn eval-loop* [ctx bindings form] - (let [bind-vec (in form 1) - body (tuple/slice form 2) - init-vals @[] - patterns @[] - # Inits are evaluated sequentially in an accumulating scope (like - # let*), so a later init can reference an earlier binding — - # matching Clojure's loop. - seq-bindings @{}] - (table/setproto seq-bindings bindings) - (var i 0) - (while (< i (length bind-vec)) - # loop* is a primitive (the loop macro desugars destructuring); - # its binding names must be plain symbols, as in Clojure. - (unless (plain-sym? (bind-vec i)) (error "Bad binding form, expected symbol")) - (def v (eval-form ctx seq-bindings (bind-vec (+ i 1)))) - (bind-put seq-bindings ((bind-vec i) :name) v) - (array/push init-vals v) - (array/push patterns (bind-vec i)) - (+= i 2)) - (var loop-fn nil) - (set loop-fn (fn [& args] - (var loop-bindings @{}) - (table/setproto loop-bindings bindings) - (var j 0) - (each pat patterns - (destructure-bind ctx loop-bindings pat (in args j)) - (++ j)) - (put loop-bindings :jolt/loop-fn loop-fn) - (var result nil) - (each body-form body - (set result (eval-form ctx loop-bindings body-form))) - result)) - (apply loop-fn init-vals))) - -(defn eval-recur [ctx bindings form] - (let [loop-fn (get bindings :jolt/loop-fn)] - (if (nil? loop-fn) - (error "recur used outside of loop* or fn*") - (let [args (map |(eval-form ctx bindings $) (tuple/slice form 1))] - (apply loop-fn args))))) - -(defn eval-try [ctx bindings form] - (let [# The body is EVERY form between `try` and the first catch/finally - # clause (not just form 1 — a multi-form body before the clauses, - # e.g. (try (foo) (bar) (catch …)), dropped all but the first). - forms (tuple/slice form 1) - clause? (fn [c] - (and (array? c) (> (length c) 0) - (struct? (first c)) (= :symbol ((first c) :jolt/type)) - (or (= "catch" ((first c) :name)) - (= "finally" ((first c) :name))))) - split (do (var k 0) - (while (and (< k (length forms)) (not (clause? (in forms k)))) (++ k)) - k) - body-forms (tuple/slice forms 0 split) - clauses (tuple/slice forms split) - # current-ns is dynamic state. The interpreter rebinds it to a - # fn's defining ns while that fn runs and restores it on normal - # return, but a fn that THROWS unwinds past its own restore — so - # the ns can leak. try is the unwind boundary: restore the ns that - # was current at try entry before running catch/finally, so caught - # code (and the harness's is/thrown?) sees the right namespace. - try-ns (ctx-current-ns ctx)] - (var catch-sym nil) - (var catch-body nil) - (var finally-body nil) - (each clause clauses - (when (and (array? clause) (> (length clause) 0)) - (let [head (first clause)] - (when (and (struct? head) (= :symbol (head :jolt/type))) - (match (head :name) - "catch" (do - (set catch-sym (in clause 2)) - (set catch-body (tuple/slice clause 3))) - "finally" (set finally-body (tuple/slice clause 1))))))) - (defn eval-body [] - (var result nil) - (each bf body-forms (set result (eval-form ctx bindings bf))) - result) - (defn run-finally [] - (when finally-body - (each fb finally-body (eval-form ctx bindings fb)))) - (defn run-protected [] - (if catch-sym - (try - (eval-body) - ([err] - (ctx-set-current-ns ctx try-ns) - (var new-bindings @{}) - (table/setproto new-bindings bindings) - # bind the originally-thrown value (unwrap the :jolt/exception - # envelope) so (catch … e (throw e)) rethrows the same value - # rather than nesting another envelope - (def caught - (if (and (or (table? err) (struct? err)) (= :jolt/exception (get err :jolt/type))) - (get err :value) - err)) - (put new-bindings (catch-sym :name) caught) - (var result nil) - (each cb catch-body - (set result (eval-form ctx new-bindings cb))) - result)) - # no catch: restore the ns on an unwinding error, then re-raise - (try (eval-body) ([err] (ctx-set-current-ns ctx try-ns) (error err))))) - # finally ALWAYS runs (success, caught error, or rethrow) — defer so it - # fires even if a catch body throws. Without a finally, just run. - (if finally-body - (defer (run-finally) (run-protected)) - (run-protected)))) - -(defn eval-set! [ctx bindings form] - (let [target (in form 1) - val (eval-form ctx bindings (in form 2))] - # Handle (set! (.-field obj) val) — .-field shorthand as a list - (if (and (array? target) (> (length target) 1) - (struct? (first target)) (= :symbol ((first target) :jolt/type)) - (> (length ((first target) :name)) 1) - (= (string/slice ((first target) :name) 0 2) ".-")) - (let [obj (eval-form ctx bindings (in target 1)) - field-name (string/slice ((first target) :name) 2) - field-key (keyword field-name)] - (if (get obj :jolt/deftype) - (do (put obj field-key val) val) - (error (string "Can't set! field on non-deftype: " (type obj))))) - # (set! (. obj -field) val) — instance field mutation - (if (and (array? target) (> (length target) 0) - (struct? (first target)) - (= :symbol ((first target) :jolt/type)) - (= "." ((first target) :name))) - (let [obj (eval-form ctx bindings (in target 1)) - field-sym (in target 2) - field-name (field-sym :name) - field-key (keyword (if (and (> (length field-name) 0) (= "-" (string/slice field-name 0 1))) - (string/slice field-name 1) - field-name))] - (if (get obj :jolt/deftype) - (do (put obj field-key val) val) - (error (string "Can't set! field on non-deftype: " (type obj))))) - # (set! var val) — normal var mutation - (let [target-sym target - v (resolve-var ctx bindings target-sym)] - (if v - (do (var-set v val) val) - # Auto-create var if it doesn't exist - (let [ns-name (ctx-current-ns ctx) - ns (ctx-find-ns ctx ns-name)] - (def new-v (ns-intern ns (target-sym :name) val)) - val))))))) - -(defn eval-new [ctx bindings form] - (let [type-sym (in form 1) - args (map |(eval-form ctx bindings $) (tuple/slice form 2)) - ctor (eval-form ctx bindings type-sym) - ctor (if (string? ctor) (or (ctor-for-class-token ctor) ctor) ctor)] - (apply ctor args))) - -# Member dispatch shared by the two `.` forms (jolt-eos3). `args` is the -# (possibly empty) tuple of already-evaluated arguments; `has-args` is true for -# the call form `(. obj method arg...)` and false for the bare form -# `(. obj member)`. The two forms agree on the string/number/object/tagged-shim -# dispatch chain (single-sourced here, so an interop change touches one place) -# but diverge in the tail: the call form tries record → native-field → -# coll-interop(args); the bare form tries zero-arg coll-interop → field / -# zero-arg method. The guards that differed between the old copy-pasted arms are -# keyed off `has-args` so behavior is identical (note: the object-methods guard -# checks `table?` only, while tagged dispatch checks table-or-struct — both kept -# verbatim from the original arms). -# A record's own implementation of `field-name` (its instance fn, a reified fn, -# or a protocol method from the type registry), or nil. A deftype/defrecord -# method must win over the generic object-methods table — e.g. a custom -# (Object (toString [_] ...)) over the default toString (jolt-rt6n). -(defn- record-member [ctx target field-name] - (when (record-tag target) - (let [mk (keyword field-name) - own (get target mk) - reified (get (get target :jolt/protocol-methods) mk)] - (cond - (or (function? own) (cfunction? own)) own - (or (function? reified) (cfunction? reified)) reified - (find-method-any-protocol ctx (record-tag target) field-name))))) - -(defn dispatch-member [ctx bindings target member-raw member-name field-name args has-args] - (cond - # java.lang.String surface for string/buffer targets - (or (string? target) (buffer? target)) - (let [m (get string-methods field-name)] - (if m - (m (string target) ;args) - (if-let [om (get object-methods field-name)] - (om (string target) ;args) - (error (string "Unsupported String method ." field-name))))) - # numeric methods - (and (number? target) (get number-methods field-name)) - ((get number-methods field-name) target ;args) - # universal object methods — skipped when a shim tag-table owns the member, - # OR when the target is a record that implements the member itself (so a - # deftype's own toString/equals/hashCode wins over the generic one, jolt-rt6n). - # Call form defers to tagged dispatch whenever a tag-table exists; bare form - # only when the tag-table actually carries this member, so zero-arg - # toString/hashCode still reach object-methods on shim objects. - (and (get object-methods field-name) - (not (and (table? target) (get tagged-methods (get target :jolt/type)) - (or has-args (get (get tagged-methods (get target :jolt/type)) field-name)))) - (not (record-member ctx target field-name))) - ((get object-methods field-name) target ;args) - # registered shim objects (java.time etc.): tag-keyed method tables - (and (or (table? target) (struct? target)) - (get tagged-methods (get target :jolt/type)) - (or has-args (get (get tagged-methods (get target :jolt/type)) field-name))) - (let [m (get (get tagged-methods (get target :jolt/type)) field-name)] - (if m - (m target ;args) - (error (string "Unsupported method ." field-name " on " (string (get target :jolt/type)))))) - # --- divergent tail --- - has-args - # (. obj method args...): record protocol dispatch, else native field/method - (if (record-tag target) - # deftype/reify methods live in the protocol registry (or the instance's - # reified-fns table), not on the instance. get is safe on a shape-rec - # tuple (returns nil for the method/protocol keys). - (let [method-key (keyword field-name) - own (get target method-key) - reified (get (get target :jolt/protocol-methods) method-key) - m (cond - (or (function? own) (cfunction? own)) own - (or (function? reified) (cfunction? reified)) reified - (find-method-any-protocol ctx (record-tag target) field-name))] - (if m - (apply m target args) - (error (string "No method ." field-name " on " (record-tag target))))) - # Janet-native interop: try field lookup + call - (if (or (table? target) (struct? target)) - (let [method (get target (keyword field-name))] - (if (or (function? method) (cfunction? method)) - (method target ;args) - # If stored as fn* form (array), compile to function then call - (if (array? method) - (let [method-fn (eval-form ctx bindings method)] - (if (or (function? method-fn) (cfunction? method-fn)) - (method-fn target ;args) - (error (string "Cannot call non-function " field-name " on " (type target))))) - (let [r (if coll-interop (coll-interop target field-name args) :jolt/ci-none)] - (if (= r :jolt/ci-none) - (error (string "Cannot call non-function " field-name " on " (type target))) - r))))) - (error (string "Cannot call method " field-name " on " (type target))))) - # (. obj member) with no extra args: a symbol member naming a function is a - # zero-arg method call (receiver passed as self); a keyword or `-field` - # member is plain field access. - true - # zero-arg Java collection interop (.count/.seq/… on a jolt collection) - # before field lookup — coll-interop returns :jolt/ci-none if not its kind - (let [ci (if coll-interop (coll-interop target field-name @[]) :jolt/ci-none)] - (if (not= ci :jolt/ci-none) ci - (let [v (if (record-tag target) - (coll-lookup target (keyword field-name) nil) - (get target (keyword field-name)))] - (if (and (struct? member-raw) (= :symbol (member-raw :jolt/type)) - (not (string/has-prefix? "-" member-name))) - (cond - (or (function? v) (cfunction? v)) (v target) - # zero-arg deftype/reify method via the protocol registry - (record-tag target) - (let [reified (get (get target :jolt/protocol-methods) (keyword field-name)) - m (if (or (function? reified) (cfunction? reified)) reified - (find-method-any-protocol ctx (record-tag target) field-name))] - (if m (m target) v)) - # value stored as an unevaluated fn* form: compile then call - (array? v) (let [f (eval-form ctx bindings v)] - (if (or (function? f) (cfunction? f)) (f target) f)) - v) - v)))))) - -(defn eval-dot [ctx bindings form] - (let [target (eval-form ctx bindings (in form 1)) - member-raw (in form 2) - # Resolve member name: symbols have :name, keywords use string, strings as-is - member-name (if (and (struct? member-raw) (= :symbol (member-raw :jolt/type))) - (member-raw :name) - (if (keyword? member-raw) - (string member-raw) - member-raw)) - field-name (if (and (string? member-name) (> (length member-name) 0) (= "-" (string/slice member-name 0 1))) - (string/slice member-name 1) - member-name) - has-args (> (length form) 3) - args (if has-args (map |(eval-form ctx bindings $) (tuple/slice form 3)) @[])] - (dispatch-member ctx bindings target member-raw member-name field-name args has-args))) - -(defn eval-list - [ctx bindings form] - (def first-form (first form)) - # Safe name extraction: non-symbol heads (e.g. keywords) fall through to default. - # A head qualified to a NON-core namespace (e.g. clojure.edn/read-string) must - # resolve to that var, not the like-named clojure.core special form — so only - # unqualified or clojure.core-qualified heads dispatch as special forms. - (def name (if (and (struct? first-form) (= :symbol (first-form :jolt/type))) - (let [ns (first-form :ns)] - (if (or (nil? ns) (= ns "clojure.core")) (first-form :name) nil)) - nil)) - (match name - "quote" (in form 1) - # Interpreter builds the form directly (self-contained, no core dependency). - # The COMPILE path instead lowers syntax-quote to construction code (via - # syntax-quote-lower) so a backtick body is compilable; the two are kept in - # sync and cross-checked by conformance (interpret vs compile modes). - "syntax-quote" (syntax-quote* ctx bindings (in form 1)) - "unquote" (error "Unquote not valid outside of syntax-quote") - "unquote-splicing" (error "Unquote-splicing not valid outside of syntax-quote") - "eval" (eval-form ctx bindings (eval-form ctx bindings (in form 1))) - # read-string/macroexpand-1 are ctx-capturing clojure.core fns and defonce - # an overlay macro now (Stage 2 tier 6c) — no special-form arms. - "do" (eval-do ctx bindings form) - "if" (eval-if ctx bindings form) - "def" (eval-def ctx bindings form) - "defmacro" (eval-defmacro ctx bindings form) - # ns is now a macro (clojure.core, 30-macros) expanding to in-ns + require/use/ - # import/refer-clojure calls — all ctx-capturing fns — so it compiles. No - # special-form arm; an (ns ...) head falls through to the macro-expansion path. - # require / in-ns are now ordinary clojure.core fns (install-stateful-fns!) — - # no special-form arm; they compile + interpret as plain invokes. - # all-ns/the-ns/create-ns/remove-ns/ns-interns/ns-aliases/ns-imports/ - # ns-resolve/resolve/find-ns/refer are ctx-capturing clojure.core fns now - # (install-stateful-fns!) with evaluated-arg Clojure semantics — they fall - # through to the function-call default and compile as plain invokes - # (Stage 2 tier 6b). - "fn*" (eval-fn* ctx bindings form) - "let*" (eval-let* ctx bindings form) - "loop*" (eval-loop* ctx bindings form) - "recur" (eval-recur ctx bindings form) - "throw" (let [val (eval-form ctx bindings (in form 1))] - (error {:jolt/type :jolt/exception :value val})) - "try" (eval-try ctx bindings form) - "set!" (eval-set! ctx bindings form) - "var" (let [target-sym (in form 1) - v (resolve-var ctx bindings target-sym)] - (if v v (error (string "Unable to resolve var: " (sym-name-str target-sym) " in var")))) - # var-get/var-set/var?/alter-var-root/alter-meta!/reset-meta! are plain - # clojure.core fns; find-var/intern are ctx-capturing clojure.core fns - # (install-stateful-fns!) — they fall through to the function-call default - # and compile as ordinary invokes (Stage 2 tier 6). - # set?/disj are plain clojure.core fns now (core-set?/core-disj) — no longer - # special-cased here, the analyzer, or compiler.janet (jolt-g3h). - # protocol-dispatch / register-method / make-reified are now ordinary - # clojure.core fns (install-stateful-fns!) — the defprotocol/extend-type/reify - # macros call them with name STRINGS, so they compile + interpret as plain - # invokes (no special-form arms). - # satisfies?/instance?/locking and the multimethod table ops - # (prefer-method/remove-method/remove-all-methods/get-method/methods) are - # clojure.core fns / overlay macros now (Stage 2 tier 6c) — no special arms. - # deftype is now a macro (30-macros) over make-deftype-ctor + extend-type — - # compiles as a plain (do …); no special-form arm. - "new" (eval-new ctx bindings form) - "." (eval-dot ctx bindings form) - # default: function application — check for macros - (if (and (struct? first-form) (= :symbol (first-form :jolt/type))) - (let [sym-name (first-form :name)] - # Handle .-fieldName accessor: (.-cnt obj) → (. obj -cnt) - (if (and (> (length sym-name) 1) (= (string/slice sym-name 0 2) ".-") - (> (length form) 1)) - (let [field-name (string/slice sym-name 2) - target (eval-form ctx bindings (in form 1))] - (get target (keyword field-name))) - # (.method obj args...) sugar -> (. obj method args...): desugar and - # re-enter the dot special form (which holds the String surface, the - # deftype method path, and the map-fn fallback). - (if (and (> (length sym-name) 1) - (= (string/slice sym-name 0 1) ".") - (not= sym-name "..") - (> (length form) 1)) - (eval-form ctx bindings - (array/concat @[{:jolt/type :symbol :ns nil :name "."} - (in form 1) - {:jolt/type :symbol :ns nil :name (string/slice sym-name 1)}] - (tuple/slice form 2))) - # Handle ClassName. constructor syntax (".." is the member-threading - # macro, not a constructor named ".") - (if (and (> (length sym-name) 1) (not= sym-name "..") - (= (sym-name (- (length sym-name) 1)) 46)) - (let [type-name (string/slice sym-name 0 (- (length sym-name) 1)) - type-sym {:jolt/type :symbol :ns (first-form :ns) :name type-name} - ctor (eval-form ctx bindings type-sym) - # class names evaluate to canonical-name STRINGS now; the - # constructor itself comes from the ctor registry - ctor (if (string? ctor) (or (ctor-for-class-token ctor) ctor) ctor) - args (map |(eval-form ctx bindings $) (tuple/slice form 1))] - (apply ctor args)) - (let [v (resolve-var ctx bindings first-form)] - (if (and v (var-macro? v)) - # Expand once (cached by call-form identity), then evaluate the - # macro-free expansion with the current bindings each call. - (let [cached (in macro-cache form)] - (if (not (nil? cached)) - (eval-form ctx bindings cached) - (let [expanded (apply (var-get v) (tuple/slice form 1))] - (put macro-cache form expanded) - (eval-form ctx bindings expanded)))) - (let [f (eval-form ctx bindings first-form) - args (map |(eval-form ctx bindings $) (tuple/slice form 1))] - (jolt-invoke ctx f args)))))))) - (let [f (eval-form ctx bindings first-form) - args (map |(eval-form ctx bindings $) (tuple/slice form 1))] - (jolt-invoke ctx f args))))) - -# Build a map value from an array of evaluated [k v k v ...]. A phm (not a Janet -# struct) is used when a key is a collection (value-based hashing) OR a key/value -# is nil (Janet structs drop nil; phm preserves it, matching Clojure). The common -# scalar/nil-free case stays a struct. diff --git a/src/jolt/evaluator.janet b/src/jolt/evaluator.janet deleted file mode 100644 index 6ebf868..0000000 --- a/src/jolt/evaluator.janet +++ /dev/null @@ -1,109 +0,0 @@ -# Jolt Evaluator -# Direct interpreter for Clojure forms on Janet. -# -# This file is the AGGREGATOR (jolt-oudv, phase 2a): the interpreter is now split -# into cluster modules, loaded here in dependency order and re-exported -# (:export true) so every consumer keeps a single `(use ./evaluator)`. The -# eval-form entry (set at the bottom) ties resolution, special forms and the -# collection/map literal evaluation together. - -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./pv) -(use ./plist) -(use ./config) -(use ./reader) -(use ./regex) - -(import ./eval_base :prefix "" :export true) -(import ./eval_resolve :prefix "" :export true) -(import ./eval_runtime :prefix "" :export true) -(import ./eval_special :prefix "" :export true) - -(defn- map-needs-phm? [kvs] - (var need false) (var i 0) - (while (< i (length kvs)) - (let [k (in kvs i) v (in kvs (+ i 1))] - (when (or (table? k) (array? k) (nil? k) (nil? v)) (set need true) (break))) - (+= i 2)) - need) - -(defn- build-eval-map [kvs] - (if (map-needs-phm? kvs) - (do (var m (make-phm)) (var j 0) - (while (< j (length kvs)) (set m (phm-assoc m (in kvs j) (in kvs (+ j 1)))) (+= j 2)) m) - (struct ;kvs))) - -(set eval-form (fn [ctx bindings form] - (cond - (nil? form) nil - (number? form) form - (string? form) form - (keyword? form) form - (bytes? form) form - (buffer? form) form - (tuple? form) - (let [els (map |(eval-form ctx bindings $) form)] - (if mutable? (array ;els) (pv-from-indexed els))) - (struct? form) - (if (= :symbol (form :jolt/type)) - (resolve-sym ctx bindings form) - (if (= :jolt/char (form :jolt/type)) - form - # a UUID/inst value flowing back through eval (macro expansion, eval of a - # read form) is a self-evaluating literal, like chars. A namespace object - # does too: `~*ns*` in a syntax-quote (clojure.tools.logging) splices the - # live ns into the expansion. - (if (or (= :jolt/uuid (form :jolt/type)) (= :jolt/inst (form :jolt/type)) - (= :jolt/namespace (form :jolt/type))) - form - (if (= :jolt/set (form :jolt/type)) - # evaluate each element (set literals like #{(inc 1)} must compute) - (apply make-phs (map |(eval-form ctx bindings $) (form :value))) - (if (= :jolt/tagged (form :jolt/type)) - (let [tag (form :tag) - data-readers (get (ctx :env) :data-readers) - reader-fn (if data-readers (get data-readers tag))] - (cond - # #"..." regex literal -> a regex value (Janet PEG-backed) - (= tag :regex) (compile-regex (form :form)) - reader-fn (reader-fn (form :form)) - (error (string "No reader function for tag " tag)))) - (if (get form :jolt/type) - (error (string "Unexpected tagged form: " (form :jolt/type))) - # plain map literal: evaluate keys and values in SOURCE order when - # the reader order rides along (jolt-p3c), hash order otherwise - (let [kvs @[] - order (form-kv-order form)] - (if order - (each x order (array/push kvs (eval-form ctx bindings x))) - (each k (keys form) - (array/push kvs (eval-form ctx bindings k)) - (array/push kvs (eval-form ctx bindings (get form k))))) - (build-eval-map kvs)))))))) - # A phm map-literal FORM (reader emits one for {:a nil} etc., which a struct - # would have dropped): evaluate its key/value forms and rebuild, preserving nil. - (phm? form) - (let [kvs @[] - order (form-kv-order form)] - (if order - (each x order (array/push kvs (eval-form ctx bindings x))) - (each e (phm-entries form) - (array/push kvs (eval-form ctx bindings (in e 0))) - (array/push kvs (eval-form ctx bindings (in e 1))))) - (build-eval-map kvs)) - (array? form) - (if (= 0 (length form)) - @[] - (eval-list ctx bindings form)) - # A non-array ISeq used as a form is a CALL too (jolt-2rx): cons/concat/list - # and ~@ build a plist or lazy-seq (list?/seq? true, array? false) — without - # this they fell through to self-eval, so (eval (cons '+ '(1 2))) returned the - # list as data instead of 3, and macro output containing such subforms never - # evaluated. d-realize coerces to the element array; an empty list self-evals. - (or (plist? form) (lazy-seq? form)) - (let [arr (d-realize form)] - (if (= 0 (length arr)) form (eval-list ctx bindings arr))) - form))) diff --git a/src/jolt/host_iface.janet b/src/jolt/host_iface.janet deleted file mode 100644 index 767821a..0000000 --- a/src/jolt/host_iface.janet +++ /dev/null @@ -1,270 +0,0 @@ -# Janet implementation of the Jolt host contract (ns `jolt.host`). -# -# This is the seam between the portable jolt-core (analyzer/IR/core, pure Clojure -# under jolt-core/) and the Janet runtime. jolt-core calls ONLY these functions — -# never Janet directly. Re-hosting Jolt to another runtime means reimplementing -# this contract (+ the back end and RT) for that runtime. -# -# Lives in src/jolt/ (with the rest of the Janet host) rather than a separate -# host/janet/ dir: Janet resolves relative imports per-file, so a host/janet -# module importing ../../src/jolt/* loads SECOND instances of compiler/types/core -# (inconsistent state). The portability boundary is the `jolt.host` namespace -# contract + jolt-core/, not the directory. -# -# Two groups: -# 1. Form introspection — reader forms are host-specific (the reader is the -# host's), so shape predicates/accessors live here. Returns jolt values the -# analyzer walks with ordinary Clojure. -# 2. Compile-time environment — resolve symbols to vars/macros, expand macros, -# the current namespace. These take ctx (an opaque host handle). - -(use ./types) -(use ./evaluator) -(use ./core) -(import ./phm :as phm) -(import ./reader :as rdr) - -# --------------------------------------------------------------------------- -# Form introspection -# --------------------------------------------------------------------------- - -(defn h-sym? [form] (and (struct? form) (= :symbol (form :jolt/type)))) -(defn h-sym-name [form] (form :name)) -(defn h-sym-ns [form] (form :ns)) -# Reader metadata on a symbol (e.g. ^:dynamic / ^:redef / ^:private on a def -# name). Returns the meta map or nil. Lets the analyzer carry def metadata that -# the back end applies to the var — without it, compiled defs drop all var meta. -(defn h-sym-meta [form] (form :meta)) - -(defn h-list? [form] (array? form)) # a call / list (reader: array) -(defn h-vector? [form] (tuple? form)) # a vector literal (reader: tuple) -# A map-literal form is a plain struct, or a phm when the reader preserved a nil -# key/value (Janet structs drop nil). Sets/chars/symbols are tagged structs (have -# :jolt/type); phm carries :jolt/deftype, distinct from those. -(defn h-map? [form] - (or (and (struct? form) (nil? (form :jolt/type))) - (phm/phm? form))) -(defn h-set? [form] (and (struct? form) (= :jolt/set (form :jolt/type)))) -(defn h-char? [form] (and (struct? form) (= :jolt/char (form :jolt/type)))) - -(defn h-literal? [form] - (or (nil? form) (boolean? form) (number? form) (string? form) - (keyword? form) (h-char? form))) - -# Items of a list/vector as a jolt vector, so the analyzer walks them with Clojure. -(defn h-elements [form] (make-vec form)) -(defn h-vector-items [form] (make-vec form)) -(defn h-map-pairs [form] - # reader forms carry source order (jolt-p3c) — Clojure evaluates literal - # entries left to right; hash order only for constructed maps - (def order (rdr/form-kv-order form)) - (cond - order - (do (def out @[]) - (var i 0) - (while (< i (length order)) - (array/push out (make-vec [(in order i) (in order (+ i 1))])) - (+= i 2)) - (make-vec out)) - (phm/phm? form) - (make-vec (map (fn [e] (make-vec [(in e 0) (in e 1)])) (phm/phm-entries form))) - (make-vec (map (fn [k] (make-vec [k (get form k)])) (keys form))))) -(defn h-set-items [form] (make-vec (form :value))) - -# --------------------------------------------------------------------------- -# Compile-time environment -# --------------------------------------------------------------------------- - -# Names the analyzer must NOT treat as a function call: interpreter special forms -# plus definitional/host macros the compiler doesn't lower. The analyzer handles -# a subset (quote/if/do/def/fn*/let*/loop*/recur/throw/try) and falls back to the -# interpreter for the rest. Kept in sync with evaluator/special-symbol? and -# compiler/uncompilable-heads. -(def- special-names - (let [t @{}] - (each n ["quote" "syntax-quote" "unquote" "unquote-splicing" "do" "if" "def" - "defmacro" "fn*" "let*" "loop*" "recur" "throw" "try" "set!" - # defmulti/defmethod/deftype now compile (macros over *-setup fns). - "eval" "new" - # var-get/var-set/var?/alter-var-root/alter-meta!/reset-meta! are - # plain core fns; find-var/intern are ctx-capturing core fns — all - # compile as ordinary invokes now (Stage 2 tier 6). - "." - # satisfies?/instance?/locking/defonce/read-string/macroexpand-1 and - # the multimethod table ops (prefer-method/remove-method/ - # remove-all-methods/get-method/methods) are clojure.core fns / - # overlay macros now (Stage 2 tier 6c) — ordinary invokes. - # create-ns/remove-ns/find-ns/all-ns/the-ns/resolve/ns-resolve/ - # ns-aliases/ns-imports/ns-interns/refer are ctx-capturing - # clojure.core fns now (compile as plain invokes — tier 6b), like - # ns/require/in-ns/use/import/refer-clojure before them. - # defprotocol/extend-type/extend-protocol/reify/defrecord now expand to - # plain def + protocol-dispatch/register-method/make-reified/deftype. - "gen-class" - # letfn stays: its let* expansion needs letrec semantics (mutual - # recursion between the fns), which compiled sequential let* lacks. - "monitor-enter" "monitor-exit" "letfn"] - (put t n true)) - t)) - -# Interop-shaped heads the interpreter lowers but the back end doesn't model: -# (.method obj …) / (.-field obj) — member access (name starts with ".") -# (Foo. …) — constructor (name ends with "." ) -# Treated as special so the analyzer marks them uncompilable and falls back. -(defn- interop-head? [name] - (def n (length name)) - (and (> n 1) - (or (= (string/slice name 0 1) ".") - (= (string/slice name (- n 1)) ".")))) - -(defn h-special? [name] - (if (or (get special-names name) (interop-head? name)) true false)) - -# The namespace being compiled. NOT ctx-current-ns directly: the interpreter -# rebinds current-ns to a fn's defining ns while that fn runs, so an interpreted -# analyzer (defined in jolt.analyzer) would otherwise see jolt.analyzer. The back -# end stashes the real compile ns in :compile-ns before invoking the analyzer. -(defn h-current-ns [ctx] (or (get (ctx :env) :compile-ns) (ctx-current-ns ctx))) - -(defn h-macro? [ctx sym] - (let [v (resolve-var ctx @{} sym)] - (if (and v (var-macro? v)) true false))) - -(defn h-expand-1 [ctx form] - (let [head (in form 0) - v (resolve-var ctx @{} head) - macro-fn (var-get v)] - (apply macro-fn (tuple/slice form 1)))) - -# Classify a global (non-local) symbol reference: -# {:kind :var :ns NS :name NAME} — a Jolt var (current ns / clojure.core) -# {:kind :host :name NAME} — resolves only via the host env (+, int?, …), -# same fallback the interpreter's resolve-sym uses -# {:kind :unresolved :name NAME} — not yet defined (forward reference) -(defn h-resolve-global [ctx sym] - # Unqualified syms must resolve against the COMPILE ns (h-current-ns), not - # ctx-current-ns: the analyzer runs interpreted in jolt.analyzer, so during - # analysis resolve-var's unqualified branch looks in the wrong namespace. - # Before jolt-2o7.3 the analyzer's lenient fallthrough masked this (it - # emitted a var-ref against compile-ns for everything 'unresolved'). - (def v (if (sym :ns) - (resolve-var ctx @{} sym) - (let [cns (ctx-find-ns ctx (h-current-ns ctx))] - (or (and cns (ns-find cns (sym :name))) - (ns-find (ctx-find-ns ctx "clojure.core") (sym :name)))))) - (if v - {:kind :var :ns (var-ns v) :name (var-name v)} - (let [nm (sym :name) - entry (in (fiber/getenv (fiber/current)) (symbol nm))] - (if (not (nil? entry)) - {:kind :host :name nm} - {:kind :unresolved :name nm})))) - -(defn h-intern! [ctx ns-name nm] - (ns-intern (ctx-find-ns ctx ns-name) nm) - nil) - -# --------------------------------------------------------------------------- -# Installation: bind these fns as vars in the `jolt.host` namespace so jolt-core -# can call them. Idempotent per context. -# --------------------------------------------------------------------------- - -# Form predicates use `form-*` names (not list?/vector?/map?/set?/char?) so the -# analyzer can refer them unqualified without the bootstrap's core-renames -# intercepting them as the value-level predicates. -# Lower a syntax-quote's inner form to construction code (so the analyzer can -# compile it). The portable analyzer calls this and analyzes the result. -(defn h-syntax-quote-lower [ctx inner] - (syntax-quote-lower ctx inner)) - -# Runtime host primitive: set a key on a mutable reference cell (an atom, the -# watches sub-table, ...). The minimal mutation kernel the overlay can't express -# over core fns — putting nil removes the key (Janet table semantics). Returns the -# table so callers can thread; overlay wrappers return the Clojure-meaningful value. -(defn h-ref-put! [tab key val] (put tab key val) tab) - -# Runtime host primitive: mint a fresh tagged host table — the value-layer -# constructor the overlay uses to define host-dispatched values (sorted colls). -# Fields are attached with ref-put!. -(defn h-tagged-table [kw] @{:jolt/type kw}) - -# Raw field read on a host table, BYPASSING collection semantics. The overlay -# needs this to read its own wrappers' fields: plain (get sorted-coll k) is the -# comparator lookup (it dispatches back into the overlay), so reading :entries -# with it would recurse forever. -(defn h-ref-get [tab key] (get tab key)) - -# Absolute source offset of a list FORM (jolt-fqy), or nil. The analyzer stamps -# it onto :invoke nodes so the success checker can report file:line:col. -(defn h-form-position [form] (rdr/form-pos form)) - -# --------------------------------------------------------------------------- -# Inline registry (jolt-87f, Route 1 AOT escape analysis). The inline pass -# (jolt.passes) is portable Clojure and can't read Janet var cells, so it asks -# the host whether a given global is inline-eligible and, if so, for its body IR. -# --------------------------------------------------------------------------- - -# Is inlining enabled for the unit currently being compiled? :inline? is OFF for -# all of init (core tiers + self-hosted compiler recompile) and flipped on at the -# end of init to the user direct-linking setting, so core compiles exactly as -# before (const-fold only) and only opted-in user code inlines. -(defn h-inline-enabled? [ctx] (if (get (ctx :env) :inline?) true false)) - -# The stashed inline body for global ns/name, or nil. Returns it only when the -# target is inline-SAFE: a defined var that won't be redefined (not ^:redef / -# ^:dynamic) and that carries a stashed :inline-ir (set by the back end when the -# var's defn compiled as a small, side-effect-bounded fn). The stash is -# {:params [name ...] :body } — a single fixed arity. -(defn h-inline-ir [ctx ns-name nm] - (when (get (ctx :env) :inline?) - (def cell (let [n (ctx-find-ns ctx ns-name)] (and n (ns-find n nm)))) - (when (and cell (table? cell) - (not (cell :dynamic)) - (not (let [m (cell :meta)] (and m (get m :redef))))) - (cell :inline-ir)))) - -# Is `name` (a bare type-name string, e.g. "Vec3") a defrecord/deftype? Both -# expand to define a ->Name positional constructor var (30-macros.clj), so its -# presence is the marker. Lets the analyzer resolve a ^Record type hint to the -# struct fast path: record instances are tables tagged :jolt/deftype (NOT -# :jolt/type), so a raw keyword get is correct for them (jolt-94n). -(defn h-record-ctor-key [ctx name] - # The home ctor key ("ns/->Name") for a ^Type hint, resolving cross-ns - # (referred/aliased) records too — nil if `name` is not a known record type. - (record-hint-ctor-key ctx name)) - -(defn h-record-type? [ctx name] - # A ^Type hint names a record iff it resolves to a ctor key (local OR cross-ns, - # via record-hint-ctor-key — so a referred/aliased foreign record is recognized, - # not just one whose ->Name happens to be interned in the current ns). - (if (record-hint-ctor-key ctx name) true false)) - -# The record-ctor shape registry ("ns/->Name" -> {:fields (:k ..) :type tag ..}), -# or an empty table. Lets scalar-replace (jolt-15jq) recognize a (->Rec ..) call -# and map its positional args to the declared field order — the record analogue -# of the inline map-literal keys the map fold already sees in the IR. -(defn h-record-shapes [ctx] - (or (get (ctx :env) :record-shapes) @{})) - -(def- exports - {"form-sym?" h-sym? "form-sym-name" h-sym-name "form-sym-ns" h-sym-ns - "ref-put!" h-ref-put! - "ref-get" h-ref-get - "tagged-table" h-tagged-table - "form-sym-meta" h-sym-meta - "form-list?" h-list? "form-vec?" h-vector? "form-map?" h-map? - "form-set?" h-set? "form-char?" h-char? "form-literal?" h-literal? - "form-elements" h-elements "form-vec-items" h-vector-items - "form-map-pairs" h-map-pairs "form-set-items" h-set-items - "form-special?" h-special? "compile-ns" h-current-ns "form-macro?" h-macro? - "form-expand-1" h-expand-1 "resolve-global" h-resolve-global - "form-syntax-quote-lower" h-syntax-quote-lower - "host-intern!" h-intern! - "inline-enabled?" h-inline-enabled? "inline-ir" h-inline-ir - "record-type?" h-record-type? "form-position" h-form-position - "record-ctor-key" h-record-ctor-key "record-shapes" h-record-shapes}) - -(defn install! [ctx] - (def ns (ctx-find-ns ctx "jolt.host")) - (eachp [nm f] exports (ns-intern ns nm f)) - ns) diff --git a/src/jolt/host_interop.janet b/src/jolt/host_interop.janet deleted file mode 100644 index 1bd9b41..0000000 --- a/src/jolt/host_interop.janet +++ /dev/null @@ -1,19 +0,0 @@ -# Host interop aggregator (jolt-jx5l, phase 1 subdir split). -# -# The JVM class/method shim surface that portable cljc libraries call now lives in -# src/jolt/interop/ split by area: java_base (java.lang statics + java.time + -# shared coercion helpers), host_io (java.io/util/net/sql/text), collections -# (the late-bound .iterator/.nth/... hooks over jolt values). The registry -# MACHINERY (class-statics / tagged-methods / register-*!) still lives in the -# evaluator, which loads before this module — so the registries exist before any -# install! runs here. -# -# api imports this module (import ./host_interop) to trigger registration at load. -# Adding a JDK-area shim is now a one-file change under interop/ plus a line here. -(use ./interop/java_base) -(use ./interop/host_io) -(use ./interop/collections) - -(install!) -(install-io!) -(install-collections!) diff --git a/src/jolt/interop/collections.janet b/src/jolt/interop/collections.janet deleted file mode 100644 index 665d6a6..0000000 --- a/src/jolt/interop/collections.janet +++ /dev/null @@ -1,49 +0,0 @@ -# Host interop — collection interop: wires the evaluator's late-bound hooks to -# core's collection ops so Java-style interop (.iterator/.nth/.count/.seq/...) -# works over jolt values. Split from host_interop.janet (jolt-jx5l, phase 1). -# Late-bound because the evaluator loads before core. -(use ../evaluator) -(use ../core) -(use ../types) -(use ../lazyseq) -(use ../pv) -(use ../plist) -(import ../phm) - -# Collection interop: wires the evaluator's late-bound hooks to core's -# collection ops so Java-style interop works over jolt values (moved here from -# api — jolt-jx5l). Late-bound because the evaluator loads before core. -(defn install-collections! [] - # (.iterator coll) -> a jolt iterator over any seqable (hiccup's iterate!). - (set-coll-realizer! realize-for-iteration) - # clj-targeted libs build collections via JVM statics in their :clj branches; - # malli's entry parser uses these. createOwning takes ownership of an object - # array -> a vector; createWithCheck builds a map and throws on duplicate keys - # (malli catches that), detected by the built map being smaller than the kvs. - (register-class-statics! "LazilyPersistentVector" - @{"createOwning" (fn [arr] (make-vec arr))}) - (register-class-statics! "PersistentArrayMap" - @{"createWithCheck" - (fn [arr] - (def m (phm/make-phm arr)) - (if (= (* 2 (phm/phm-count m)) (length arr)) m - (error "PersistentArrayMap: duplicate key")))}) - # .nth/.count/.valAt/.get/.seq/.containsKey on a jolt collection -> the - # clojure.core equivalent. :jolt/ci-none means "not a collection method here". - (set-coll-interop! - (fn [target name args] - (if-not (or (pvec? target) (phm/phm? target) (plist? target) (lazy-seq? target) - (and (table? target) (= :jolt/set (get target :jolt/type))) - (shape-rec? target) # map-as-tuple record - (and (struct? target) (nil? (get target :jolt/type)))) # plain map literal - :jolt/ci-none - (cond - (= name "nth") (if (>= (length args) 2) (core-nth target (in args 0) (in args 1)) - (core-nth target (in args 0))) - (= name "count") (core-count target) - (or (= name "valAt") (= name "get")) - (if (>= (length args) 2) (core-get target (in args 0) (in args 1)) - (core-get target (in args 0))) - (= name "seq") (core-seq target) - (= name "containsKey") (core-contains? target (in args 0)) - :jolt/ci-none))))) diff --git a/src/jolt/interop/host_io.janet b/src/jolt/interop/host_io.janet deleted file mode 100644 index 4186233..0000000 --- a/src/jolt/interop/host_io.janet +++ /dev/null @@ -1,537 +0,0 @@ -# Host interop — java.io / java.util / java.net / java.sql / java.text shims that -# carry portable cljc libraries (Selmer's char-by-char reader, ring-codec, -# migratus, yogthos/config). Split from host_interop.janet (jolt-jx5l, phase 1). -# install-io! registers them; depends on java_base for the shared chr/pad2 -# coercion helpers and the java.time `formatter` (SimpleDateFormat et al.). -(use ../evaluator) -(use ../regex) -(use ../core) -(use ../pv) -(use ../plist) -(use ../types) -(use ../lazyseq) -(import ../phm) -(use ./java_base) - -# --- java.io / java.lang shims (Selmer's template reader) --------------------- - -(defn- string-reader [src] - # :close makes with-open's __close happy (it calls (get x :close) when - # present); :read-line-fn matches the 50-io reader convention so line-seq - # works over readers io/reader hands back - (def self @{:jolt/type :jolt/jio-string-reader :s (string src) :pos 0 - :close (fn [] nil)}) - (put self :read-line-fn - (fn [] - (def {:s s :pos pos} self) - (when (< pos (length s)) - (def i (string/find "\n" s pos)) - (if (nil? i) - (do (put self :pos (length s)) (string/slice s pos)) - (do (put self :pos (+ i 1)) (string/slice s pos i)))))) - self) -(defn- string-builder [&opt init] - # a numeric arg is a CAPACITY (java.lang.StringBuilder(int)), not content - @{:jolt/type :jolt/string-builder - :buf (cond (nil? init) @"" (number? init) (buffer/new init) (buffer init))}) - -(defn make-string-writer [] - # :close lets with-open close the writer (core-close-resource calls :close); - # it's a no-op so .toString after with-open still sees the buffer. - @{:jolt/type :jolt/writer :buf @"" :sink nil :close (fn [] nil)}) -(defn make-out-writer [] - @{:jolt/type :jolt/writer :buf nil :sink prin}) - -(defn- render-piece [x] - (cond - (nil? x) "null" - (and (struct? x) (= :jolt/char (get x :jolt/type))) (string/from-bytes (x :ch)) - (string x))) - -# Writer.write(int) writes the CHAR for that code (unlike StringBuilder.append(int), -# which appends the int's digits). jolt chars are bytes, so this round-trips UTF-8 -# byte-for-byte with readLine. -(defn- writer-piece [x] - (if (number? x) (string/from-bytes (math/trunc x)) (render-piece x))) - -# Read one unit from any reader-ish value: our shims dispatch through their -# tagged "read"; a janet core/file reads one byte. -1 at EOF. -(defn- read-unit [r] - (cond - (and (or (table? r) (struct? r)) (get r :jolt/type)) - (((get tagged-methods (r :jolt/type)) "read") r) - (= :core/file (type r)) - (let [b (file/read r 1)] (if (or (nil? b) (= 0 (length b))) -1 (b 0))) - (error (string "not a reader: " (type r))))) - -(defn- pushback-reader [rdr] - # java.io.PushbackReader: read delegates to the wrapped reader unless - # something was unread; unread takes a char (or char code) and pushes it back - (def self @{:jolt/type :jolt/pushback-reader :rdr rdr :pushed @[] - :close (fn [] nil)}) - self) - -(defn install-io! [] - (register-tagged-methods! :jolt/pushback-reader - @{"read" (fn [self] - (if (> (length (self :pushed)) 0) - (array/pop (self :pushed)) - (read-unit (self :rdr)))) - "unread" (fn [self ch] - (array/push (self :pushed) - (if (number? ch) ch (get ch :ch))) - nil) - "close" (fn [self] nil)}) - (register-tagged-methods! :jolt/jio-string-reader - @{"read" (fn [self] - (if (>= (self :pos) (length (self :s))) - -1 - (let [b ((self :s) (self :pos))] - (put self :pos (+ 1 (self :pos))) - b))) - "readLine" (fn [self] ((self :read-line-fn))) - "mark" (fn [self &opt limit] (put self :marked (self :pos)) nil) - "reset" (fn [self] (put self :pos (or (self :marked) 0)) nil) - "skip" (fn [self n] (put self :pos (min (length (self :s)) (+ (self :pos) n))) n) - "close" (fn [self] nil)}) - # java.io.Writer / StringWriter — the print-method protocol surface - # (jolt-g1r). A writer either pushes to a sink fn (stdout/custom) or - # accumulates in a buffer (StringWriter). write/append coerce chars the - # same way StringBuilder does. - (register-tagged-methods! :jolt/writer - @{"write" (fn [self x] - (if (self :sink) - ((self :sink) (writer-piece x)) - (buffer/push-string (self :buf) (writer-piece x))) - nil) - "append" (fn [self x] - (if (self :sink) - ((self :sink) (render-piece x)) - (buffer/push-string (self :buf) (render-piece x))) - self) - "flush" (fn [self] nil) - "close" (fn [self] nil) - "toString" (fn [self] (string (or (self :buf) "")))}) - (register-tagged-methods! :jolt/string-builder - @{"append" (fn [self x] (buffer/push (self :buf) (render-piece x)) self) - "toString" (fn [self] (string (self :buf))) - "length" (fn [self] (length (self :buf))) - "setLength" (fn [self n] - (def buf (self :buf)) - (if (< n (length buf)) - (buffer/popn buf (- (length buf) n)) - (while (< (length buf) n) (buffer/push buf "\0"))) - nil) - "charAt" (fn [self i] {:jolt/type :jolt/char :ch ((self :buf) i)})}) - (each nm ["File" "java.io.File"] - (register-class-statics! nm @{"separator" "/" "separatorChar" {:jolt/type :jolt/char :ch 47}})) - (register-class-statics! "Boolean" - @{"parseBoolean" (fn [s] (= "true" (string/ascii-lower (string s)))) - "TRUE" true "FALSE" false}) - (register-class-statics! "Class" - @{"forName" (fn [nm] @{:jolt/type :jolt/class :name nm})}) - (each nm ["StringReader" "java.io.StringReader"] - (register-class-ctor! nm string-reader)) - (each nm ["StringBuilder" "java.lang.StringBuilder"] - (register-class-ctor! nm string-builder)) - (each nm ["StringWriter" "java.io.StringWriter"] - (register-class-ctor! nm make-string-writer)) - # --- java.net / java.util surface for ring-codec (ring-core enablement) --- - # URLEncoder/URLDecoder: www-form-urlencoded (space <-> +, %XX bytes, - # [A-Za-z0-9.*_-] literal). Charset args are accepted and ignored beyond - # the name (everything is UTF-8 bytes here). - (defn- 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))) - (defn- url-encode-www [s & _] - (def out @"") - (each b (string/bytes (string s)) - (cond - (url-unreserved? b) (buffer/push-byte out b) - (= b 32) (buffer/push-string out "+") - (buffer/push-string out (string/format "%%%02X" b)))) - (string out)) - (defn- hexv [b] - (cond (and (>= b 48) (<= b 57)) (- b 48) - (and (>= b 65) (<= b 70)) (- b 55) - (and (>= b 97) (<= b 102)) (- b 87) - (error "URLDecoder: malformed escape"))) - (defn- url-decode-www [s & _] - (def bytes (string/bytes (string s))) - (def n (length bytes)) - (def out @"") - (var i 0) - (while (< i n) - (def b (in bytes i)) - (cond - (= b 43) (do (buffer/push-string out " ") (++ i)) - (= b 37) (if (< (+ i 2) n) - (do (buffer/push-byte out (+ (* 16 (hexv (in bytes (+ i 1)))) (hexv (in bytes (+ i 2))))) - (+= i 3)) - (error "URLDecoder: incomplete escape")) - (do (buffer/push-byte out b) (++ i)))) - (string out)) - (each nm ["URLEncoder" "java.net.URLEncoder"] - (register-class-statics! nm @{"encode" url-encode-www})) - (each nm ["URLDecoder" "java.net.URLDecoder"] - (register-class-statics! nm @{"decode" url-decode-www})) - (each nm ["Charset" "java.nio.charset.Charset"] - (register-class-statics! nm @{"forName" (fn [nm*] @{:jolt/type :jolt/charset :name nm*})})) - # Base64 (RFC 4648): encoder/decoder singletons with encode/decode methods. - (def- b64-alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") - (defn- b64-encode [bs] - (def bytes (if (bytes? bs) bs (string bs))) - (def n (length bytes)) - (def out @"") - (var i 0) - (while (< i n) - (def b0 (in bytes i)) - (def b1 (if (< (+ i 1) n) (in bytes (+ i 1)))) - (def b2 (if (< (+ i 2) n) (in bytes (+ i 2)))) - (buffer/push-byte out (in b64-alphabet (brshift b0 2))) - (buffer/push-byte out (in b64-alphabet (bor (blshift (band b0 3) 4) (brshift (or b1 0) 4)))) - (buffer/push-string out (if (nil? b1) "=" (string/from-bytes (in b64-alphabet (bor (blshift (band b1 0xf) 2) (brshift (or b2 0) 6)))))) - (buffer/push-string out (if (nil? b2) "=" (string/from-bytes (in b64-alphabet (band b2 0x3f))))) - (+= i 3)) - (string out)) - (def- b64-rev (do (def t @{}) (eachp [i c] b64-alphabet (put t c i)) t)) - (defn- b64-decode [s] - (def cleaned (string/replace-all "=" "" (string s))) - (def out @"") - (var acc 0) (var bits 0) - (each c (string/bytes cleaned) - (def v (get b64-rev c)) - (when (nil? v) (error "Base64: illegal character")) - (set acc (bor (blshift acc 6) v)) - (+= bits 6) - (when (>= bits 8) - (-= bits 8) - (buffer/push-byte out (band (brshift acc bits) 0xff)))) - out) - (register-tagged-methods! :jolt/base64-encoder @{"encode" (fn [self bs] (b64-encode bs)) "encodeToString" (fn [self bs] (b64-encode bs))}) - (register-tagged-methods! :jolt/base64-decoder @{"decode" (fn [self s] (b64-decode s))}) - (each nm ["Base64" "java.util.Base64"] - (register-class-statics! nm - @{"getEncoder" (fn [] @{:jolt/type :jolt/base64-encoder}) - "getDecoder" (fn [] @{:jolt/type :jolt/base64-decoder})})) - # Integer statics: valueOf with optional radix. Returns a plain number — - # byteValue/intValue live on the number method surface in the evaluator. - (register-class-statics! "Integer" - @{"valueOf" (fn [x &opt radix] - (cond - (number? x) x - (nil? radix) (or (scan-number (string x)) (error (string "NumberFormatException: " x))) - (= radix 16) (or (scan-number (string "16r" x)) (error (string "NumberFormatException: " x))) - (= radix 8) (or (scan-number (string "8r" x)) (error (string "NumberFormatException: " x))) - (= radix 2) (or (scan-number (string "2r" x)) (error (string "NumberFormatException: " x))) - (error (string "Integer/valueOf: unsupported radix " radix)))) - "parseInt" (fn [x &opt radix] - (or (scan-number (string (case radix 16 "16r" 8 "8r" 2 "2r" "") x)) - (error (string "NumberFormatException: " x)))) - "MAX_VALUE" 2147483647 - "MIN_VALUE" -2147483648}) - # StringTokenizer: eager split on any delimiter char, empty tokens skipped. - (defn- tokenize [s delims] - (def dset @{}) - (each b (string/bytes delims) (put dset b true)) - (def toks @[]) - (def cur @"") - (each b (string/bytes (string s)) - (if (get dset b) - (when (> (length cur) 0) (array/push toks (string cur)) (buffer/clear cur)) - (buffer/push-byte cur b))) - (when (> (length cur) 0) (array/push toks (string cur))) - toks) - (register-tagged-methods! :jolt/string-tokenizer - @{"hasMoreTokens" (fn [self] (< (self :pos) (length (self :toks)))) - "countTokens" (fn [self] (- (length (self :toks)) (self :pos))) - "nextToken" (fn [self] - (if (< (self :pos) (length (self :toks))) - (let [t (in (self :toks) (self :pos))] - (put self :pos (+ 1 (self :pos))) t) - (error "NoSuchElementException")))}) - (each nm ["StringTokenizer" "java.util.StringTokenizer"] - (register-class-ctor! nm (fn [s &opt delims] - @{:jolt/type :jolt/string-tokenizer - :toks (tokenize s (or delims " \t\n\r\f")) - :pos 0}))) - # clojure.lang.MapEntry: a 2-tuple, jolt's map-entry representation. - # java.util.HashMap: a mutable wrapper over a janet table, keyed by canonical - # key (so jolt collection keys compare by value). reitit uses it as a fast - # read cache: (HashMap. m) copies a map's entries, (.get hm k) reads. - # raw value-keys: reitit's HashMap keys are strings/keywords/tuples, all of - # which janet tables key by value — no canonicalization needed here. - (defn- hm-entries [m] - (cond (phm/phm? m) (phm/phm-entries m) - (struct? m) (pairs m) - (table? m) (pairs m) - @[])) - (register-tagged-methods! :jolt/hashmap - @{"get" (fn [self k] (get (self :tbl) k)) - "put" (fn [self k v] (put (self :tbl) k v) v) - "putAll" (fn [self m] (each pair (hm-entries m) (put (self :tbl) (in pair 0) (in pair 1))) nil) - "containsKey" (fn [self k] (not (nil? (get (self :tbl) k)))) - "size" (fn [self] (length (self :tbl)))}) - (each nm ["HashMap" "java.util.HashMap"] - # java.util.HashMap constructors: (), (initialCapacity), (initialCapacity, - # loadFactor) all start empty; (Map m) copies entries. A numeric first arg is - # a capacity (sizing hint we ignore), not content. - (register-class-ctor! nm - (fn [& args] - (def tbl @{}) - (def init (if (> (length args) 0) (in args 0) nil)) - (when (and init (not (number? init))) - (each pair (hm-entries init) (put tbl (in pair 0) (in pair 1)))) - @{:jolt/type :jolt/hashmap :tbl tbl}))) - (each nm ["MapEntry" "clojure.lang.MapEntry"] - (register-class-ctor! nm (fn [k v] [k v]))) - # (String. bytes) / (String. bytes charset): UTF-8 bytes to string. - (each nm ["String" "java.lang.String"] - (register-class-ctor! nm (fn [x &opt charset] (string x)))) - # String statics. valueOf(Object) yields "null" for nil, else toString — - # hiccup's compiler emits (String/valueOf (or arg "")) to stringify attribute - # values; core-str gives jolt's str semantics for keywords/numbers/etc. - (each nm ["String" "java.lang.String"] - (register-class-statics! nm - @{"valueOf" (fn [x &opt off cnt] (if (nil? x) "null" (core-str x)))})) - # java.net.URL: enough for selmer's template cache — file: URLs only. - # A protocol-less spec throws (selmer catches MalformedURLException and - # prepends file:///), and getPath hands back a stat-able filesystem path. - (defn url-path [spec] - (var p (if (string/has-prefix? "file:" spec) (string/slice spec 5) spec)) - (while (and (> (length p) 1) (string/has-prefix? "//" p)) - (set p (string/slice p 1))) - p) - (register-tagged-methods! :jolt/url - @{"getPath" (fn [self] (url-path (self :spec))) - "getFile" (fn [self] (url-path (self :spec))) - "toString" (fn [self] (self :spec)) - "toExternalForm" (fn [self] (self :spec))}) - (each nm ["URL" "java.net.URL"] - (register-class-ctor! nm - (fn [spec & _] - (def s (string spec)) - (def colon (string/find ":" s)) - (if (or (nil? colon) (= colon 0) - (string/find "/" (string/slice s 0 colon))) - (error (string "MalformedURLException: no protocol: " s)) - @{:jolt/type :jolt/url :spec s})))) - (each nm ["PushbackReader" "java.io.PushbackReader"] - (register-class-ctor! nm (fn [rdr &opt size] (pushback-reader rdr)))) - (each nm ["BigInteger" "java.math.BigInteger"] - (register-class-ctor! nm - (fn [v] - (or (scan-number (string/trim (string v))) - (error (string "NumberFormatException: For input string: \"" v "\"")))))) - (each nm ["Locale" "java.util.Locale"] - (register-class-ctor! nm (fn [id &opt _country] @{:jolt/type :jolt/locale :id (string id)}))) - # java.util.regex.Pattern statics: Pattern/compile, Pattern/quote, Pattern/MULTILINE. - # Pattern/compile returns jolt's native :jolt/regex compiled value so that - # str/replace, re-matches, .split etc accept it transparently. - (defn- pattern-quote [s] - (def meta "\\.[]{}()*+-?^$|&") - (def buf @"") - (var i 0) - (while (< i (length s)) - (def c (s i)) - (if (string/find (string/from-bytes c) meta) - (buffer/push buf (chr "\\"))) - (buffer/push buf (string/from-bytes c)) - (++ i)) - (string buf)) - (def pattern-multiline 8) - (each nm ["Pattern" "java.util.regex.Pattern"] - (register-class-statics! nm - @{"compile" (fn [s &opt flags] - (if (and flags (= (band flags pattern-multiline) pattern-multiline)) - (re-pattern (string "(?m)" s)) - (re-pattern s))) - "quote" (fn [s] (pattern-quote s)) - "MULTILINE" pattern-multiline})) - # .split on compiled regex values: delegates to re-split, drops trailing empties - (register-tagged-methods! :jolt/regex - @{"split" (fn [self s &opt limit] - (def parts (re-split self s)) - (while (and (> (length parts) 0) (= "" (last parts))) - (array/pop parts)) - parts)}) - # JVM exception constructors: (Exception. msg), (IllegalArgumentException. msg), - # (InterruptedException. msg). Return the message string so getMessage works. - (each nm ["Exception" "java.lang.Exception"] - (register-class-ctor! nm (fn [msg] (string msg)))) - (each nm ["IllegalArgumentException" "java.lang.IllegalArgumentException"] - (register-class-ctor! nm (fn [msg] (string msg)))) - (each nm ["InterruptedException" "java.lang.InterruptedException"] - (register-class-ctor! nm (fn [msg] (string msg)))) - # Character class statics (ASCII — the engine is byte-based). - (register-class-statics! "Character" - @{"isUpperCase" (fn [ch] (and (>= (ch :ch) 65) (<= (ch :ch) 90))) - "isLowerCase" (fn [ch] (and (>= (ch :ch) 97) (<= (ch :ch) 122)))}) - # java.net.URI constructor: stores the spec string, rounds-trips through str. - (each nm ["URI" "java.net.URI"] - (register-class-ctor! nm (fn [spec] (string spec)))) - # java.util.Date: millis-valued instants; no-arg = now. - (defn- make-date [&opt ms] - @{:jolt/type :jolt/date :ms (or ms (math/floor (* 1000 (os/clock :realtime))))}) - (each nm ["Date" "java.util.Date"] - (register-class-ctor! nm make-date)) - (register-tagged-methods! :jolt/date - @{"getTime" (fn [self] (self :ms)) - "toString" (fn [self] (string (self :ms)))}) - # java.util.TimeZone: getTimeZone(id) -> a tz value. - (defn- make-tz [id] @{:jolt/type :jolt/tz :id (string id)}) - (register-class-statics! "TimeZone" - @{"getTimeZone" (fn [id] (make-tz id))}) - (register-class-statics! "java.util.TimeZone" - @{"getTimeZone" (fn [id] (make-tz id))}) - # java.text.SimpleDateFormat: minimal formatter supporting y M d H m s tokens. - # (pad2 is the module-level helper above.) - (defn- sdf-format [pattern ms utc?] - (def d (os/date (math/floor (/ ms 1000)) (not utc?))) - (def out @"") - (var i 0) - (while (< i (length pattern)) - (def c (pattern i)) - (def k (do (var j i) - (while (and (< j (length pattern)) (= (pattern j) c)) (++ j)) - (- j i))) - (cond - (= c (chr "y")) (do (buffer/push out (if (>= k 4) (string (d :year)) (pad2 (mod (d :year) 100)))) (+= i k)) - (= c (chr "M")) (do (buffer/push out (if (= k 1) (string (+ 1 (d :month))) (pad2 (+ 1 (d :month))))) (+= i k)) - (= c (chr "d")) (do (buffer/push out (if (= k 1) (string (+ 1 (d :month-day))) (pad2 (+ 1 (d :month-day))))) (+= i k)) - (= c (chr "H")) (do (buffer/push out (if (= k 1) (string (d :hours)) (pad2 (d :hours)))) (+= i k)) - (= c (chr "m")) (do (buffer/push out (if (= k 1) (string (d :minutes)) (pad2 (d :minutes)))) (+= i k)) - (= c (chr "s")) (do (buffer/push out (if (= k 1) (string (d :seconds)) (pad2 (d :seconds)))) (+= i k)) - (do (buffer/push out (string/from-bytes c)) (++ i)))) - (string out)) - (defn- make-sdf [pattern] - @{:jolt/type :jolt/sdf :pattern pattern :utc true}) - (each nm ["SimpleDateFormat" "java.text.SimpleDateFormat"] - (register-class-ctor! nm make-sdf)) - (register-tagged-methods! :jolt/sdf - @{"setTimeZone" (fn [self tz] - (put self :utc (= "UTC" (get tz :id))) - self) - "format" (fn [self date] - (sdf-format (self :pattern) (date :ms) (self :utc)))}) - # Thread stub: getContextClassLoader returns a stub so migratus jar/create code - # that walks Thread/currentThread doesn't crash. - (register-tagged-methods! :jolt/thread - @{"getContextClassLoader" (fn [self] @{:jolt/type :jolt/classloader})}) - # ClassLoader degrade (jolt-hjw): there is no classpath, so getResource returns - # nil and migratus's find-migration-dir falls through to the filesystem branch - # (resources/). getSystemClassLoader yields the same stub. - (each nm ["ClassLoader" "java.lang.ClassLoader"] - (register-class-statics! nm @{"getSystemClassLoader" (fn [] @{:jolt/type :jolt/classloader})})) - # No STM on jolt: a transaction is never running, so logging libraries that - # gate agent-vs-direct on it (clojure.tools.logging/log*) always log directly. - (register-class-statics! "clojure.lang.LockingTransaction" @{"isRunning" (fn [] false)}) - (register-tagged-methods! :jolt/classloader - @{"getResource" (fn [self path] nil) - "getResources" (fn [self path] nil) - "getResourceAsStream" (fn [self path] nil)}) - # next.jdbc host shims (paired with the __jdbc-* builtins in core.janet and the - # instance? Connection case in evaluator.janet). The wrapped connection carries - # a clj :exec callback (run one SQL string) and a :close callback. - # java.sql.Timestamp: migratus builds (Timestamp. millis) for the applied - # column; represent it as the millis number so it stores and sorts directly. - (each nm ["Timestamp" "java.sql.Timestamp"] - (register-class-ctor! nm (fn [ms] ms))) - (register-tagged-methods! :jolt/jdbc-conn - @{"setAutoCommit" (fn [self _] self) - "isClosed" (fn [self] (get (get self :closed) 0)) - "close" (fn [self] - (unless (get (get self :closed) 0) - ((get self :close)) - (put (get self :closed) 0 true)) - nil) - "getMetaData" (fn [self] @{:jolt/type :jolt/jdbc-meta :product (get self :product)})}) - (register-tagged-methods! :jolt/jdbc-meta - @{"getDatabaseProductName" (fn [self] (get self :product))}) - # Statement batch: addBatch accumulates SQL strings, executeBatch runs each via - # the connection's clj :exec callback (which executes inside the transaction). - (register-tagged-methods! :jolt/jdbc-stmt - @{"addBatch" (fn [self sql] (array/push (get self :cmds) sql) nil) - "executeBatch" (fn [self] - (def out @[]) - (each c (get self :cmds) (array/push out ((get self :exec) c))) - out) - "close" (fn [self] nil)}) - # java.io.File model (jolt-hjw). A :jolt/file carries its path; io/file and the - # File. ctor build it (see core.janet's __make-file). The method surface below - # is backed by os/ and file/. listFiles returns child :jolt/file values so - # file-seq (File-aware) yields :jolt/file leaves migratus can call methods on. - (defn- jfile-path [x] - (if (and (table? x) (= :jolt/file (get x :jolt/type))) (get x :path) (string x))) - (defn- make-jfile [path &opt child] - @{:jolt/type :jolt/file - :path (if child (string (jfile-path path) "/" (jfile-path child)) (jfile-path path))}) - (defn- last-slash [p] - (var idx nil) (var i 0) - (while (< i (length p)) (when (= (p i) 47) (set idx i)) (++ i)) - idx) - (defn- jfile-name [p] - (if-let [i (last-slash p)] (string/slice p (+ i 1)) p)) - (defn- jfile-abs [p] - (if (string/has-prefix? "/" p) p (string (os/cwd) "/" p))) - (each nm ["File" "java.io.File"] - (register-class-ctor! nm make-jfile)) - (register-tagged-methods! :jolt/file - @{"getPath" (fn [self] (get self :path)) - "toString" (fn [self] (get self :path)) - "getName" (fn [self] (jfile-name (get self :path))) - "getParent" (fn [self] (let [p (get self :path)] - (if-let [i (last-slash p)] (string/slice p 0 i) nil))) - "getAbsolutePath" (fn [self] (jfile-abs (get self :path))) - "getCanonicalPath" (fn [self] (jfile-abs (get self :path))) - "getAbsoluteFile" (fn [self] (make-jfile (jfile-abs (get self :path)))) - "exists" (fn [self] (not (nil? (os/stat (get self :path))))) - "isFile" (fn [self] (= :file (os/stat (get self :path) :mode))) - "isDirectory" (fn [self] (= :directory (os/stat (get self :path) :mode))) - "canRead" (fn [self] (not (nil? (os/stat (get self :path))))) - # listFiles: child File values, or nil when not a directory (Clojure null) - "listFiles" (fn [self] - (let [p (get self :path)] - (when (= :directory (os/stat p :mode)) - (map (fn [e] (make-jfile p e)) (os/dir p))))) - "list" (fn [self] - (let [p (get self :path)] - (when (= :directory (os/stat p :mode)) (os/dir p)))) - "toPath" (fn [self] @{:jolt/type :jolt/nio-path :s (get self :path)}) - "toURI" (fn [self] (string "file:" (jfile-abs (get self :path)))) - "toURL" (fn [self] @{:jolt/type :jolt/url :spec (string "file:" (jfile-abs (get self :path)))}) - "delete" (fn [self] (let [r (protect (os/rm (get self :path)))] (truthy? (r 0)))) - "mkdir" (fn [self] (truthy? ((protect (os/mkdir (get self :path))) 0))) - "mkdirs" (fn [self] (truthy? ((protect (os/mkdir (get self :path))) 0))) - "createNewFile" (fn [self] - (let [p (get self :path)] - (if (os/stat p) false - (do (def f (file/open p :w)) (file/close f) true)))) - "equals" (fn [self o] (and (table? o) (= (get self :path) (get o :path)))) - "hashCode" (fn [self] (hash (get self :path)))}) - # java.nio.file degrade for migratus's script-excluded? glob check: just enough - # of Path / FileSystem / PathMatcher to match a filename against a glob, with a - # simple recursive * / ? matcher (no path-segment semantics — filenames only). - (defn- glob-matches? [glob s] - (defn m [gi si] - (cond - (= gi (length glob)) (= si (length s)) - (= (glob gi) 42) # * - (or (m (+ gi 1) si) - (and (< si (length s)) (m gi (+ si 1)))) - (and (< si (length s)) - (or (= (glob gi) 63) (= (glob gi) (s si)))) # ? or literal - (m (+ gi 1) (+ si 1)) - false)) - (m 0 0)) - (register-tagged-methods! :jolt/nio-path - @{"getFileSystem" (fn [self] @{:jolt/type :jolt/nio-fs}) - "toString" (fn [self] (get self :s))}) - (register-tagged-methods! :jolt/nio-fs - @{"getPath" (fn [self s & _] @{:jolt/type :jolt/nio-path :s s}) - "getPathMatcher" (fn [self spec] - @{:jolt/type :jolt/nio-matcher - :glob (if (string/has-prefix? "glob:" spec) - (string/slice spec 5) spec)})}) - (register-tagged-methods! :jolt/nio-matcher - @{"matches" (fn [self path] (glob-matches? (get self :glob) (get path :s)))})) diff --git a/src/jolt/interop/java_base.janet b/src/jolt/interop/java_base.janet deleted file mode 100644 index 5488545..0000000 --- a/src/jolt/interop/java_base.janet +++ /dev/null @@ -1,250 +0,0 @@ -# Host interop — java.lang static surfaces (Math/Thread/System/Long) + the -# java.time shim (epoch-ms values + a DateTimeFormatter pattern subset). Split -# from host_interop.janet (jolt-jx5l, phase 1). Everything registers through the -# evaluator's class-statics / tagged-methods registries via install!. Also the -# home of the shared coercion helpers (chr/pad2) that host_io reuses. -(use ../evaluator) -(use ../regex) -(use ../core) -(use ../pv) -(use ../plist) -(use ../types) -(use ../lazyseq) -(import ../phm) - -(defn chr [s] (get s 0)) - -# --- java.lang static surfaces (Math/Thread/System/Long) ---------------------- -# Registered through the generic class-statics registry below, same as every -# other class — there is no special-case dispatch (jolt-jx5l). -(def- math-statics - @{"sqrt" math/sqrt "pow" math/pow "floor" math/floor "ceil" math/ceil - "abs" (fn [x] (if (< x 0) (- x) x)) - "round" (fn [x] (math/round x)) - "sin" math/sin "cos" math/cos "tan" math/tan - "asin" math/asin "acos" math/acos "atan" math/atan - "log" math/log "log10" math/log10 "exp" math/exp - "max" (fn [a b] (if (> a b) a b)) "min" (fn [a b] (if (< a b) a b)) - "signum" (fn [x] (cond (< x 0) -1.0 (> x 0) 1.0 0.0)) - "PI" math/pi "E" math/e - "random" (fn [&] (math/random))}) - -# sleep parks the CURRENT thread's event loop — inside a future body that's the -# worker OS thread (ev/spawn-thread gives each worker its own loop), so a -# sleeping future doesn't block the parent. -(def- thread-statics - {"sleep" (fn [ms] (ev/sleep (/ ms 1000)) nil) - "yield" (fn [] (ev/sleep 0) nil) - "interrupted" (fn [] false) - "currentThread" (fn [] @{:jolt/type :jolt/thread :id "main"})}) - -# wall/monotonic clocks + properties/env (what portable timing/config code uses). -(def- system-statics - # realtime clock (sub-ms float epoch seconds) — os/time is whole seconds, - # which quantized every elapsed-time measurement to 1000ms. - {"currentTimeMillis" (fn [] (math/floor (* 1000 (os/clock :realtime)))) - "nanoTime" (fn [] (math/floor (* 1e9 (os/clock :monotonic)))) - "getProperty" (fn [k &opt dflt] - (case k - "os.name" (case (os/which) - :windows "Windows" :macos "Mac OS X" "Linux") - "line.separator" "\n" - "file.separator" "/" - "user.dir" (os/cwd) - "user.home" (os/getenv "HOME") - "java.io.tmpdir" (or (os/getenv "TMPDIR") "/tmp") - dflt)) - # JOLT_BAKE_ENV_ALLOWLIST (jolt-s3j): during an image bake (jpm build of a - # native executable, set by the project's build.sh) the env snapshot that - # libraries like config.core capture at load gets MARSHALED INTO THE BINARY - # — GitHub push protection once flagged real API tokens inside an example's - # build output. With the var set, System/getenv serves only the listed - # comma-separated names (single-var reads of unlisted names return nil), so - # nothing secret can bake. Unset (the normal runtime case), reads are live - # and unfiltered. - "getenv" (fn [&opt k] - (def allow (os/getenv "JOLT_BAKE_ENV_ALLOWLIST")) - (if (nil? allow) - (if k (os/getenv k) (os/environ)) - (let [names (string/split "," allow) - ok @{}] - (each n names (put ok (string/trim n) true)) - (if k - (when (get ok k) (os/getenv k)) - (let [e (os/environ) out @{}] - (eachp [ek ev] e (when (get ok ek) (put out ek ev))) - out))))) - # the property subset getProperty serves, as an iterable map - "getProperties" (fn [] - {"os.name" (case (os/which) - :windows "Windows" :macos "Mac OS X" "Linux") - "line.separator" "\n" - "file.separator" "/" - "user.dir" (os/cwd) - "user.home" (or (os/getenv "HOME") "") - "java.io.tmpdir" (or (os/getenv "TMPDIR") "/tmp")}) - # terminate the process with the given status code - "exit" (fn [&opt status] (os/exit (if (nil? status) 0 status)))}) - -# sentinels portable code compares against. jolt numbers are doubles, so these -# are the f64 approximations. -(def- long-statics - {"MAX_VALUE" 9223372036854775807 - "MIN_VALUE" -9223372036854775808 - "parseLong" (fn [s &opt radix] - (def n (scan-number (string/trim (string s)) (or radix 10))) - (if (and n (= n (math/floor n))) - n - (error (string "NumberFormatException: For input string: \"" s "\"")))) - "valueOf" (fn [s &opt radix] - (def n (scan-number (string/trim (string s)) (or radix 10))) - (if (and n (= n (math/floor n))) - n - (error (string "NumberFormatException: For input string: \"" s "\""))))}) - -# --- values ------------------------------------------------------------------- - -(defn- instant [ms] @{:jolt/type :jolt/instant :ms ms}) -(defn- zoned [ms zone] @{:jolt/type :jolt/zoned-dt :ms ms :zone zone}) -(defn- local-dt [ms] @{:jolt/type :jolt/local-dt :ms ms}) -(defn formatter [pattern &opt locale] @{:jolt/type :jolt/dt-formatter :pattern pattern :locale locale}) - -(def- zone-default @{:jolt/type :jolt/zone-id :id "system"}) - -# ms of any date-ish shim value (or a :jolt/inst) -(defn- ms-of [d] - (cond - (number? d) d - (and (or (table? d) (struct? d)) - (or (= :jolt/inst (get d :jolt/type)) - (= :jolt/instant (get d :jolt/type)) - (= :jolt/zoned-dt (get d :jolt/type)) - (= :jolt/local-dt (get d :jolt/type)))) - (get d :ms) - (error (string "not a date value: " (type d))))) - -# --- formatting ---------------------------------------------------------------- - -(def- month-names ["January" "February" "March" "April" "May" "June" "July" - "August" "September" "October" "November" "December"]) -(def- day-names ["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"]) - -(defn pad2 [n] (if (< n 10) (string "0" n) (string n))) - -# Format epoch-ms with a (subset of the) JVM DateTimeFormatter pattern: -# yyyy yy MMMM MMM MM M dd d EEEE EEE HH H hh h mm m ss s a, quoted literals -# with '...'. Unknown letters pass through. -(defn- format-ms [pattern ms] - (def d (os/date (math/floor (/ ms 1000)) true)) - (def out @"") - (var i 0) - (def n (length pattern)) - (defn run-len [c] - (var j i) - (while (and (< j n) (= (pattern j) c)) (++ j)) - (- j i)) - (while (< i n) - (def c (pattern i)) - (def k (run-len c)) - (cond - (= c (chr "'")) - # quoted literal up to the closing quote ('' = literal quote) - (if (and (< (+ i 1) n) (= (pattern (+ i 1)) (chr "'"))) - (do (buffer/push out "'") (+= i 2)) - (let [close (string/find "'" pattern (+ i 1))] - (buffer/push out (string/slice pattern (+ i 1) close)) - (set i (+ close 1)))) - (= c (chr "y")) - (do (buffer/push out (if (>= k 4) (string (d :year)) - (pad2 (mod (d :year) 100)))) - (+= i k)) - (= c (chr "M")) - (do (buffer/push out (case k - 1 (string (+ 1 (d :month))) - 2 (pad2 (+ 1 (d :month))) - 3 (string/slice (in month-names (d :month)) 0 3) - (in month-names (d :month)))) - (+= i k)) - (= c (chr "d")) - (do (buffer/push out (if (= k 1) (string (+ 1 (d :month-day))) (pad2 (+ 1 (d :month-day))))) - (+= i k)) - (= c (chr "E")) - (do (buffer/push out (if (>= k 4) (in day-names (d :week-day)) - (string/slice (in day-names (d :week-day)) 0 3))) - (+= i k)) - (= c (chr "H")) - (do (buffer/push out (if (= k 1) (string (d :hours)) (pad2 (d :hours)))) (+= i k)) - (= c (chr "h")) - (let [h12 (let [h (mod (d :hours) 12)] (if (= h 0) 12 h))] - (buffer/push out (if (= k 1) (string h12) (pad2 h12))) (+= i k)) - (= c (chr "m")) - (do (buffer/push out (if (= k 1) (string (d :minutes)) (pad2 (d :minutes)))) (+= i k)) - (= c (chr "s")) - (do (buffer/push out (if (= k 1) (string (d :seconds)) (pad2 (d :seconds)))) (+= i k)) - (= c (chr "a")) - (do (buffer/push out (if (< (d :hours) 12) "AM" "PM")) (+= i k)) - (do (buffer/push out (string/from-bytes c)) (++ i)))) - (string out)) - -# Localized FormatStyle approximations (no locale database on this host). -(def- style-patterns - {[:date :short] "M/d/yy" [:date :medium] "MMM d, yyyy" - [:date :long] "MMMM d, yyyy" [:date :full] "EEEE, MMMM d, yyyy" - [:time :short] "h:mm a" [:time :medium] "h:mm:ss a" - [:time :long] "h:mm:ss a" [:time :full] "h:mm:ss a" - [:datetime :short] "M/d/yy, h:mm a" - [:datetime :medium] "MMM d, yyyy, h:mm:ss a" - [:datetime :long] "MMMM d, yyyy, h:mm:ss a" - [:datetime :full] "EEEE, MMMM d, yyyy, h:mm:ss a"}) - -(defn- style-fmt [kind style] - (formatter (get style-patterns [kind (get style :style)] "yyyy-MM-dd HH:mm:ss"))) - -# --- registration -------------------------------------------------------------- - -(defn install! [] - # java.lang statics through the generic registry (no resolve-sym special-case). - (register-class-statics! "Math" math-statics) - (register-class-statics! "Thread" thread-statics) - (register-class-statics! "System" system-statics) - (register-class-statics! "Long" long-statics) - (def fs (fn [style] @{:jolt/type :jolt/format-style :style style})) - (register-class-statics! "FormatStyle" - @{"SHORT" (fs :short) "MEDIUM" (fs :medium) "LONG" (fs :long) "FULL" (fs :full)}) - (register-class-statics! "DateTimeFormatter" - @{"ofPattern" (fn [p &opt locale] (formatter p locale)) - "ISO_LOCAL_DATE" (formatter "yyyy-MM-dd") - "ISO_LOCAL_DATE_TIME" (formatter "yyyy-MM-dd'T'HH:mm:ss") - "ofLocalizedDate" (fn [style] (style-fmt :date style)) - "ofLocalizedTime" (fn [style] (style-fmt :time style)) - "ofLocalizedDateTime" (fn [style] (style-fmt :datetime style))}) - (register-class-statics! "Instant" - @{"ofEpochMilli" (fn [ms] (instant ms)) - "now" (fn [] (instant (math/floor (* 1000 (os/clock :realtime)))))}) - (register-class-statics! "ZoneId" - @{"systemDefault" (fn [] zone-default)}) - (register-class-statics! "LocalDateTime" - @{"ofInstant" (fn [inst zone] (local-dt (ms-of inst))) - "now" (fn [] (local-dt (math/floor (* 1000 (os/clock :realtime)))))}) - (let [locale-statics @{"getDefault" (fn [] @{:jolt/type :jolt/locale :id "default"}) - "ENGLISH" @{:jolt/type :jolt/locale :id "en"} - "US" @{:jolt/type :jolt/locale :id "en-US"} - "ROOT" @{:jolt/type :jolt/locale :id "root"}}] - (each nm ["Locale" "java.util.Locale"] - (register-class-statics! nm locale-statics))) - (register-tagged-methods! :jolt/instant - @{"atZone" (fn [self zone] (zoned (self :ms) zone)) - "toEpochMilli" (fn [self] (self :ms))}) - (register-tagged-methods! :jolt/zoned-dt - @{"toLocalDateTime" (fn [self] (local-dt (self :ms))) - "toInstant" (fn [self] (instant (self :ms)))}) - (register-tagged-methods! :jolt/local-dt - @{"atZone" (fn [self zone] (zoned (self :ms) zone))}) - # a :jolt/inst (#inst — Clojure's java.util.Date) supports the Date methods - # Selmer's fix-date path calls - (register-tagged-methods! :jolt/inst - @{"toInstant" (fn [self] (instant (self :ms))) - "getTime" (fn [self] (self :ms))}) - (register-tagged-methods! :jolt/dt-formatter - @{"withLocale" (fn [self locale] (formatter (self :pattern) locale)) - "format" (fn [self d] (format-ms (self :pattern) (ms-of d)))})) diff --git a/src/jolt/jolt/interop.clj b/src/jolt/jolt/interop.clj deleted file mode 100644 index 28073c8..0000000 --- a/src/jolt/jolt/interop.clj +++ /dev/null @@ -1,26 +0,0 @@ -; Jolt Standard Library: jolt.interop -; Janet interop helpers for Jolt. - -(defn janet-eval - [s] - (eval (parse s))) - -(defn janet-type - [x] - (janet/type x)) - -(defn janet-describe - [x] - (describe x)) - -(defn janet-table-keys - [t] - (keys t)) - -(defn janet-table-vals - [t] - (vals t)) - -(defn janet-table->map - [t] - (into {} (map (fn [k] [k (get t k)]) (keys t)))) diff --git a/src/jolt/jolt/nrepl.clj b/src/jolt/jolt/nrepl.clj deleted file mode 100644 index 55bb4a6..0000000 --- a/src/jolt/jolt/nrepl.clj +++ /dev/null @@ -1,236 +0,0 @@ -; Jolt Standard Library: jolt.nrepl -; -; An nREPL (https://nrepl.org) server and client written in Clojure, on top of -; Jolt's Janet interop bridge (the `janet.*` namespace segment). The bencode -; codec follows nrepl.bencode and the op/response shapes follow babashka.nrepl -; (the SCI-targeted nREPL server). Because the whole thing is ordinary Clojure -; over `janet.net/*`, the networking it uses is reusable for anything else. -; -; Notes: -; - One Jolt runtime backs the server; sessions are tracked ids and share the -; runtime (defs persist across a connection, like a dev REPL). -; - eval uses Jolt's own `eval`/`read-string`; printed output is captured by -; rebinding Janet's :out dynamic. -; - No true interrupt: an in-flight synchronous eval can't be stopped. - -;; ───────────────────────── bencode ───────────────────────── - -(defn benc - "Encode `x` (integer, string, keyword, sequential, or map) to a bencode string." - [x] - (cond - (integer? x) (str "i" x "e") - (string? x) (str (count x) ":" x) - (keyword? x) (benc (name x)) - (symbol? x) (benc (name x)) - (map? x) (let [ks (sort (fn [a b] (compare (name a) (name b))) (keys x))] - (str "d" (apply str (mapcat (fn [k] [(benc (name k)) (benc (get x k))]) ks)) "e")) - (sequential? x) (str "l" (apply str (map benc x)) "e") - (nil? x) "le" - :else (throw (ex-info "bencode: cannot encode" {:value x})))) - -(defn encode [x] (benc x)) - -; A reader buffers bytes from a janet.net connection (or a preloaded string for -; tests) and refills via janet.net/read. -(defn reader [conn buf] (atom {:conn conn :buf (or buf "") :pos 0})) - -(defn- rd-ensure [r n] - (loop [] - (let [{:keys [conn buf pos]} @r] - (when (< (count buf) (+ pos n)) - (let [chunk (janet.net/read conn 4096)] - (when (nil? chunk) (throw (ex-info "eof" {}))) - (swap! r assoc :buf (str buf (str chunk))) - (recur)))))) - -(defn- take-n [r n] - (rd-ensure r n) - (let [{:keys [buf pos]} @r] - (swap! r assoc :pos (+ pos n)) - (subs buf pos (+ pos n)))) - -(defn- take-ch [r] (take-n r 1)) - -(def ^:private digits #{"0" "1" "2" "3" "4" "5" "6" "7" "8" "9"}) - -(defn decode - "Read one bencode value from reader `r`. Throws on EOF. Dict keys come back as - strings; the top-level nREPL message is a dict (map)." - [r] - (let [c (take-ch r)] - (cond - (= c "i") (loop [acc ""] (let [d (take-ch r)] (if (= d "e") (janet/scan-number acc) (recur (str acc d))))) - (= c "l") (loop [out []] (let [v (decode r)] (if (= v ::end) out (recur (conj out v))))) - (= c "d") (loop [out {}] (let [k (decode r)] (if (= k ::end) out (recur (assoc out k (decode r)))))) - (= c "e") ::end - (contains? digits c) - (loop [acc c] (let [d (take-ch r)] (if (= d ":") (take-n r (janet/scan-number acc)) (recur (str acc d))))) - :else (throw (ex-info "bad bencode byte" {:byte c}))))) - -;; ───────────────────────── server ───────────────────────── - -(def version "0.1.0") - -(def ^:private session-counter (atom 0)) -(defn- new-session [] - (str "jolt-" (swap! session-counter inc) "-" (janet.math/floor (* 1000000 (janet.math/random))))) - -(defn- resp-for - "Build a response by echoing the request's id/session (an nREPL requirement)." - [msg extra] - (assoc extra "session" (get msg "session" "none") "id" (get msg "id" "unknown"))) - -; Jolt resolves a function body's unqualified symbols against the *dynamic* -; current-ns, not the function's home ns. So evaluating user code (which switches -; ns) would break jolt.nrepl's own later symbol lookups. eval-in-ns confines the -; switch: it evaluates one form in `ns-str` and ALWAYS restores current-ns to -; jolt.nrepl before returning, reporting the form's value/error and resulting ns. -; It uses only special forms (in-ns/eval/the-ns/try) + keywords, so it resolves -; regardless of the ambient ns. -(defn- eval-in-ns [ns-str form] - (in-ns (symbol ns-str)) - ; Bind the value before reading the ns: jolt evaluates map-literal values - ; right-to-left, so the result ns must be captured *after* eval runs any in-ns. - (let [result (try (let [v (eval form)] {:val v :ns (:name (the-ns))}) - (catch Throwable e {:err e :ns (:name (the-ns))}))] - (in-ns 'jolt.nrepl) - result)) - -(defn- eval-handler [server msg send!] - ; current-ns is global ctx state shared by all fibers, so set the eval ns - ; explicitly each time: requested :ns, else the session's last ns, else user. - ; `respond` / `flush-out` are locals (lexical, ns-independent) on purpose. - (let [code (get msg "code" "") - out-buf (janet/buffer "") - old-out (janet/dyn :out) - respond (fn [extra] (send! (assoc extra "session" (get msg "session" "none") - "id" (get msg "id" "unknown")))) - flush-out (fn [] (when (pos? (count out-buf)) - (respond {"out" (str out-buf)}) - (janet.buffer/clear out-buf)))] - (try - (do - (janet/setdyn :out out-buf) - (loop [forms (seq (read-string (str "[" code "]"))) - cur-ns (or (get msg "ns") (:eval-ns @server) "user")] - (when forms - (let [{:keys [val ns err]} (eval-in-ns cur-ns (first forms))] - (flush-out) - (swap! server assoc :eval-ns ns) - (when err (throw err)) - (respond {"ns" ns "value" (pr-str val)}) - (recur (next forms) ns)))) - (janet/setdyn :out old-out) - (respond {"status" ["done"]})) - (catch Throwable e - (janet/setdyn :out old-out) - (flush-out) - (respond {"err" (str e "\n")}) - (respond {"ex" "class jolt/Exception" - "root-ex" "class jolt/Exception" - "status" ["eval-error"]}) - (respond {"status" ["done"]}))))) - -(def ^:private describe-ops - {"clone" {} "close" {} "describe" {} "eval" {} "load-file" {} - "ls-sessions" {} "interrupt" {} "eldoc" {}}) - -(defn- dispatch [server msg send!] - (case (get msg "op") - "clone" (let [id (new-session)] - (swap! server update :sessions conj id) - (send! (resp-for msg {"new-session" id "status" ["done"]}))) - "describe" (send! (resp-for msg {"ops" describe-ops - "versions" {"jolt" {"version-string" version} - "nrepl" {"version-string" version}} - "status" ["done"]})) - "eval" (eval-handler server msg send!) - "load-file" (eval-handler server (assoc msg "code" (get msg "file" "")) send!) - "close" (do (swap! server update :sessions disj (get msg "session")) - (send! (resp-for msg {"status" ["done" "session-closed"]}))) - "ls-sessions" (send! (resp-for msg {"sessions" (vec (:sessions @server)) "status" ["done"]})) - "interrupt" (send! (resp-for msg {"status" ["done"]})) - "eldoc" (send! (resp-for msg {"status" ["done" "no-eldoc"]})) - (send! (resp-for msg {"status" ["error" "unknown-op" "done"]})))) - -(defn- handle-conn [server conn] - (let [r (reader conn nil) - send! (fn [resp] (janet.net/write conn (encode resp)))] - (try - (loop [] - (let [msg (decode r)] - (when (map? msg) - (try (dispatch server msg send!) - (catch Throwable e - (send! (resp-for msg {"err" (str e "\n") "status" ["done"]})))) - (recur)))) - (catch Throwable _ nil)) - (try (janet.net/close conn) (catch Throwable _ nil)))) - -; We run the accept loop ourselves with janet.net/accept rather than passing a -; handler to janet.net/server: Janet's built-in accept loop arity-checks the -; handler, which a Jolt closure doesn't satisfy. janet.ev/call schedules each -; connection (and the loop itself) on a fiber. -(defn- accept-loop [server] - (loop [] - (let [conn (try (janet.net/accept (:sock @server)) (catch Throwable _ nil))] - (when conn - (janet.ev/call handle-conn server conn) - (recur))))) - -(defn start-server! - "Start an nREPL server. opts: :host (default \"127.0.0.1\"), :port (default - 7888). Returns a server handle (an atom). Non-blocking — connections are served - on the event loop." - [opts] - (let [host (get opts :host "127.0.0.1") - port (get opts :port 7888) - sock (janet.net/server host (str port)) - server (atom {:sessions #{} :host host :port port :sock sock :eval-ns "user"})] - (janet.ev/call accept-loop server) - server)) - -(defn stop-server! - "Stop accepting new connections." - [server] - (when-let [sock (:sock @server)] (janet.net/close sock)) - server) - -;; ───────────────────────── client ───────────────────────── - -(defn connect - "Connect to an nREPL server. opts: :host (default \"127.0.0.1\"), :port - (default 7888). Returns a client handle." - [opts] - (let [conn (janet.net/connect (get opts :host "127.0.0.1") (str (get opts :port 7888)))] - {:conn conn :reader (reader conn nil)})) - -(defn send-msg [client msg] (janet.net/write (:conn client) (encode msg))) -(defn read-msg [client] (decode (:reader client))) - -(defn- status-done? [resp] - (when-let [st (get resp "status")] - (and (sequential? st) (some (fn [s] (= "done" (str s))) st)))) - -(defn request - "Send `msg` (a map with at least an \"op\") and collect responses until one - carries the \"done\" status. Returns the vector of responses." - [client msg] - (send-msg client msg) - (loop [out []] - (let [resp (read-msg client) - out (conj out resp)] - (if (status-done? resp) out (recur out))))) - -(defn client-clone - "Send a clone op; return the new session id." - [client] - (some (fn [r] (get r "new-session")) (request client {"op" "clone"}))) - -(defn client-eval - "Eval `code`; returns the responses. Pass `session` to eval in a cloned session." - ([client code] (request client {"op" "eval" "code" code})) - ([client code session] (request client {"op" "eval" "code" code "session" session}))) - -(defn client-close [client] (janet.net/close (:conn client))) diff --git a/src/jolt/jolt/png.clj b/src/jolt/jolt/png.clj deleted file mode 100644 index ecb72eb..0000000 --- a/src/jolt/jolt/png.clj +++ /dev/null @@ -1,35 +0,0 @@ -; Jolt Standard Library: jolt.png -; -; Write PNG images from Clojure. Build an image, push RGB pixels in row-major -; order (top row first), then write to disk: -; -; (require '[jolt.png :as png]) -; (let [img (png/image w h)] -; (doseq [y (range h)] -; (doseq [x (range w)] -; (png/put! img r g b))) ; r g b are ints 0-255 -; (png/write img w h "out.png")) -; -; The byte-level encoding (filtering, stored-DEFLATE/zlib, CRC32) runs in the -; host (the Janet `png` module, reached via the `janet.*` bridge): per-byte work -; in the overlay is far too slow, so the overlay only produces pixels and the -; host encodes them in one pass. -(ns jolt.png) - -(defn image - "A blank w×h RGB pixel sink (a host byte buffer). Push exactly w*h pixels with - put!, in row-major / top-row-first order, then write." - [w h] - (janet.buffer/new (* w h 3))) - -(defn put! - "Append one RGB pixel — each of r g b an int in 0-255 — to the image. Returns - the image so calls can be threaded." - [img r g b] - (janet.buffer/push-byte img r g b) - img) - -(defn write - "Encode the filled w×h image as a PNG and write it to path. Returns path." - [img w h path] - (janet.png/write path w h img)) diff --git a/src/jolt/jolt/shell.clj b/src/jolt/jolt/shell.clj deleted file mode 100644 index bb2caf1..0000000 --- a/src/jolt/jolt/shell.clj +++ /dev/null @@ -1,12 +0,0 @@ -; Jolt Standard Library: jolt.shell -; Shell command execution via Janet's os/shell. - -(defn sh - [& args] - (let [cmd (apply str (interpose " " args)) - result (os/shell cmd)] - {:exit (result 0) :out (result 1) :err (result 2)})) - -(defn shell - [& args] - (:out (apply sh args))) diff --git a/src/jolt/lazyseq.janet b/src/jolt/lazyseq.janet deleted file mode 100644 index 097072a..0000000 --- a/src/jolt/lazyseq.janet +++ /dev/null @@ -1,86 +0,0 @@ -# LazySeq — cell-by-cell lazy sequence (Clojure-compatible) -# -# Model: a thunk returns nil (empty) or a [first-val, rest-thunk] pair; each -# step produces one element + a thunk for the rest. Supports self-referencing -# sequences like fib-seq. Self-contained (janet builtins only) — the Clojure -# seq layer (core_coll.janet) and the interpreter build on these primitives. -# -# REP vs API: this file is ONLY the lazy-cell representation (ls-* primitives). -# The Clojure-facing seq ops (first/rest/seq/cons/count dispatch, realization) -# live in core_coll.janet, branching on `:jolt/type :jolt/lazy-seq`. -# -# Extracted from phm.janet (jolt-bvek): a lazy sequence has nothing to do with -# hash maps; both were tagged tables, which is why they shared a file. - -(defn lazy-seq? - "Check if x is a LazySeq." - [x] - (and (table? x) (= :jolt/lazy-seq (x :jolt/type)))) - -(defn make-lazy-seq [thunk] - @{:jolt/type :jolt/lazy-seq :fn thunk :realized false :val nil}) - -(defn realize-ls - "Force a LazySeq cell. Returns nil (empty) or [first-val, rest-thunk]. - If the thunk returns another lazy-seq, recursively realize it. - Uses :jolt/pending sentinel to detect self-referencing cycles." - [ls] - (if (get ls :realized) - (ls :val) - (do - (put ls :val :jolt/pending) - (put ls :realized true) - (let [raw ((ls :fn)) - v (if (lazy-seq? raw) (realize-ls raw) raw)] - (put ls :val v) - v)))) - -(defn ls-first [ls] - (let [cell (realize-ls ls)] - (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) nil (in cell 0)))) - -# The memoized rest wrapper for a node whose cell yielded rest-thunk rt. -# EVERY walk must go through this (not a fresh make-lazy-seq) or independent -# walks re-run the shared thunks and side effects duplicate. -(defn ls-rest-cached [ls rt] - (or (get ls :rest-ls) - (let [w (make-lazy-seq rt)] - (put ls :rest-ls w) - w))) - -(defn ls-rest [ls] - (let [cell (realize-ls ls)] - (if (or (nil? cell) (= 0 (length cell))) nil - (let [rt (in cell 1)] - (if (nil? rt) nil - # Memoized wrapper (see ls-rest-cached): a fresh table per call gave - # every independent walk its own realization state, so the shared - # rest-thunks re-ran — duplicating side effects (a doall'd seq of - # futures re-spawned them on the deref walk, serializing pmap). - (ls-rest-cached ls rt)))))) - -(defn ls-seq [ls] - (var result @[]) - (var cur ls) - (while (not (nil? cur)) - (let [cell (realize-ls cur)] - (if (nil? cell) (break)) - (array/push result (in cell 0)) - (set cur (ls-rest cur)))) - (if (= 0 (length result)) nil result)) - -(defn ls-count [ls] - (var cnt 0) - (var cur ls) - (while (not (nil? cur)) - (let [cell (realize-ls cur)] - (if (nil? cell) (break)) - (++ cnt) - (set cur (ls-rest cur)))) - cnt) - -(defn lazy-cons - "Returns a LazySeq whose first element is x and whose rest is produced by - rest-thunk (a 0-arg function returning nil or a LazySeq)." - [x rest-thunk] - (make-lazy-seq (fn [] @[x rest-thunk]))) diff --git a/src/jolt/loader.janet b/src/jolt/loader.janet deleted file mode 100644 index 7c82476..0000000 --- a/src/jolt/loader.janet +++ /dev/null @@ -1,136 +0,0 @@ -# Jolt Loader -# Namespace loading with optional compilation. -# Supports in-memory bytecode caching when :compile? is enabled. - -(use ./reader) -(use ./types) -(use ./evaluator) -(import ./backend :as backend) - -# Stateful / context-modifying forms always interpret: they mutate the context -# (namespaces, macros, types, multimethods, dynamic vars, …) in ways the compiler -# doesn't model. Kept here so the compile/interpret routing lives in one place, -# used by both load-ns and the public eval-one. Shrinking toward the frozen -# host-coupled set (Stage 2 jolt-eaa): forms move off this list as they gain a -# compile path; syntax-quote already compiles via the analyzer's `handled` set. -(defn- stateful-head? [head-name] - (or (= head-name "defmacro") - (= head-name "set!") - (= head-name ".") (= head-name "new") - (= head-name "eval"))) - -(defn- form-head-name [form] - (when (array? form) - (let [ff (first form)] - (when (and (struct? ff) (= :symbol (ff :jolt/type))) (ff :name))))) - -(defn- eval-toplevel-1 - [ctx form] - # Repair point for the interpreted-fn ns swap: a body runs with current-ns - # rebound to its defining ns and restores it on normal return; an UNWINDING - # throw skips those restores (they're plain trailing calls — defer/try per - # call would cost a fiber per frame and blow the C stack on deep recursion). - # So save here, and on error put the entry ns back before re-raising — the - # ctx never leaks a callee's ns across top-level forms. - (def entry-ns (ctx-current-ns ctx)) - (defn- run [] - (defn try-compile [] (backend/compile-and-eval ctx form)) - (if (get (ctx :env) :compile?) - (if (array? form) - # A call/list: compile it unless its head is a stateful special form. - (let [hn (form-head-name form)] - (if (and hn (stateful-head? hn)) - (eval-form ctx @{} form) - (try-compile))) - # A bare symbol or vector literal compiles; anything else interprets. - (if (or (and (struct? form) (= :symbol (form :jolt/type))) (tuple? form)) - (try-compile) - (eval-form ctx @{} form))) - (eval-form ctx @{} form))) - (try - (run) - ([err fib] - (ctx-set-current-ns ctx entry-ns) - # Stash the full trace TEXT at this innermost boundary: janet's - # debug/stacktrace walks the propagation chain (fiber->child, no public - # accessor), so this is the only place the user's compiled frames - # (in _r$ns/fn--N ...) are reachable. Innermost capture wins; the CLI's - # report-error filters + demangles it. (jolt-2o7.1/2) - (when (nil? (get (ctx :env) :error-trace)) - (def buf @"") - (with-dyns [:err buf] (debug/stacktrace fib err "")) - (put (ctx :env) :error-trace (string buf))) - # propagate (not error): re-raising with `error` discards the failing - # fiber's stack - (propagate err fib)))) - -(defn eval-toplevel - "Evaluate one top-level form for ctx, honoring :compile?. Stateful forms always - interpret; otherwise the form runs through the self-hosted compile pipeline - (portable Clojure analyzer -> IR -> Janet back end), which falls back to the - interpreter for forms it can't compile. Only the compile step is guarded — - runtime errors in compiled code propagate (no double-eval, no hidden errors)." - [ctx form] - # Clojure's top-level `do` rule: children are compiled AND evaluated one at - # a time, so a child's runtime effects (defmulti's var intern, requires, …) - # are visible while the NEXT child compiles. Without the split, (do - # (defmulti area …) (area …)) can't analyze — `area` only exists once the - # defmulti has RUN, and unresolved symbols are analysis errors now - # (jolt-2o7.3). - (if (and (array? form) (= "do" (form-head-name form))) - (do - (var res nil) - (each child (array/slice form 1) (set res (eval-toplevel ctx child))) - res) - (eval-toplevel-1 ctx form))) - -(defn eval-forms-positioned - "Evaluate parsed [form line] pairs, recording WHERE an error happened: the - innermost failing form's {:file :line} goes to (env :error-pos) and each - file unwound through joins the (env :error-loading) chain — the CLI's - report-error prints 'at file:line' and 'while loading …' from these. - (jolt-2o7.4)" - [ctx pairs file] - (var res nil) - (each [form line] pairs - (try - (set res (eval-toplevel ctx form)) - ([err fib] - (def env (ctx :env)) - (when (nil? (get env :error-pos)) - (put env :error-pos {:file file :line line})) - (when (nil? (get env :error-loading)) (put env :error-loading @[])) - (def chain (get env :error-loading)) - (when (not= (last chain) file) (array/push chain file)) - (propagate err fib)))) - res) - -(defn load-ns - "Load a Clojure namespace from a .clj file. Per-form routing (compile-or- - interpret, stateful forms interpret) is shared with eval-one via eval-toplevel. - - (load-ns ctx filepath) → namespace symbol string" - [ctx filepath] - (def source (slurp filepath)) - (when (or (checker-enabled?) (get (ctx :env) :inline?)) - (track-positions! true) - (put (ctx :env) :tc-source source) - (put (ctx :env) :tc-file filepath)) - (def pairs (parse-all-positioned source filepath)) - (var ns-name nil) - (each [form _] pairs - # Extract ns name from the first ns form - (when (and (nil? ns-name) - (array? form) - (> (length form) 0) - (and (struct? (first form)) - (= :symbol ((first form) :jolt/type)) - (= "ns" ((first form) :name)))) - (let [name-form (in form 1)] - (set ns-name (if (struct? name-form) (name-form :name) (string name-form)))))) - - (when (nil? ns-name) - (error (string "No ns form found in " filepath))) - - (eval-forms-positioned ctx pairs filepath) - ns-name) diff --git a/src/jolt/main.janet b/src/jolt/main.janet deleted file mode 100644 index 9a826c5..0000000 --- a/src/jolt/main.janet +++ /dev/null @@ -1,826 +0,0 @@ -# Jolt REPL -# Read-eval-print loop for Clojure expressions. - -(use ./api) -(use ./types) -(use ./phm) -(use ./phs) -(use ./lazyseq) -(use ./pv) -(use ./plist) -(use ./config) -(use ./reader) -(import ./core :as jcore) -(import ./deps :as deps) -(import ./cgen_build :as cgen-build) - -(def jolt-version "0.1.0") - -# Compile by default: the shipped runtime runs each form through the self-hosted -# pipeline (portable Clojure analyzer -> IR -> Janet back end) to native bytecode -# (hybrid — forms the analyzer can't compile fall back to the interpreter, so the -# result always matches the interpreter; see backend.janet / loader/eval-toplevel). -# Set JOLT_INTERPRET=1 to force the tree-walking interpreter (debugging / A-B). -(def compile-default? (not (= "1" (os/getenv "JOLT_INTERPRET")))) -# A var, not a def: a -m run may replace it with a forked deps-image ctx that -# already has every dependency compiled (see run-main / the deps image cache). -(var ctx (init {:compile? compile-default?})) -(ctx-set-current-ns ctx "user") - -(defn read-line [prompt] - (prin prompt) - (flush) - (let [line (file/read stdin :line)] - (if line (string/trim line) nil))) - -# Forward declaration for mutual recursion -(var write-value nil) - -(defn- push-str [buf s] - (buffer/push-string buf s)) - -(defn- write-collection [v buf] - (cond - (pvec? v) - (do - (push-str buf "[") - (let [a (pv->array v) n (pv-count v)] - (var i 0) - (while (< i n) - (write-value (in a i) buf) - (when (< (+ i 1) n) (push-str buf " ")) - (++ i))) - (push-str buf "]")) - - (plist? v) - (do - (push-str buf "(") - (let [a (pl->array v) n (length a)] - (var i 0) - (while (< i n) - (write-value (in a i) buf) - (when (< (+ i 1) n) (push-str buf " ")) - (++ i))) - (push-str buf ")")) - - (tuple? v) - (do - (push-str buf "[") - (var i 0) - (let [n (length v)] - (while (< i n) - (write-value (in v i) buf) - (when (< (+ i 1) n) (push-str buf " ")) - (++ i))) - (push-str buf "]")) - - # LazySeq — realize the cell chain and print as a list. Capped to avoid - # hanging on infinite sequences; prints "..." when truncated. - (and (table? v) (= :jolt/lazy-seq (v :jolt/type))) - (do - (push-str buf "(") - (var cur v) - (var i 0) - (var go true) - (while (and go (< i 1000)) - (let [cell (realize-ls cur)] - (if (or (nil? cell) (= :jolt/pending cell) (= 0 (length cell))) - (set go false) - (do - (when (> i 0) (push-str buf " ")) - (write-value (in cell 0) buf) - (++ i) - (let [rt (in cell 1)] - (if (nil? rt) (set go false) (set cur (ls-rest-cached cur rt)))))))) - (when (and go (>= i 1000)) (push-str buf " ...")) - (push-str buf ")")) - - (array? v) - (do - # mutable mode: arrays are vectors -> [] ; immutable: arrays are lists -> () - (push-str buf (if mutable? "[" "(")) - (var i 0) - (let [n (length v)] - (while (< i n) - (write-value (in v i) buf) - (when (< (+ i 1) n) (push-str buf " ")) - (++ i))) - (push-str buf (if mutable? "]" ")"))) - - (and (table? v) (= :jolt/set (v :jolt/type))) - (do - (push-str buf "#{") - (var first? true) - (each k (phs-seq v) - (if first? (set first? false) (push-str buf " ")) - (write-value k buf)) - (push-str buf "}")) - - (and (table? v) (= :jolt/transient (v :jolt/type))) - (push-str buf (string "#")) - - (and (table? v) (= :jolt/chan (v :jolt/type))) - (push-str buf "#") - - (phm? v) - (do - (push-str buf "{") - (var first? true) - (each pair (phm-entries v) - (if first? (set first? false) (push-str buf ", ")) - (write-value (in pair 0) buf) (push-str buf " ") (write-value (in pair 1) buf)) - (push-str buf "}")) - - (and (table? v) (= :jolt/regex (v :jolt/type))) - (do (push-str buf "#\"") (push-str buf (v :source)) (push-str buf "\"")) - - # sorted colls: their comparator-ordered entries, materialized from the - # red-black tree via the value's own :entries op (jolt-0hbr), is all the - # printer reads. - (and (table? v) (= :jolt/sorted-map (v :jolt/type))) - (do - (push-str buf "{") - (var first? true) - (each e (let [ef (let [o (v :ops)] (and o (o :entries))) es (if ef (ef v) (v :entries))] (if (pvec? es) (pv->array es) es)) - (if first? (set first? false) (push-str buf ", ")) - (write-value (if (pvec? e) (pv-nth e 0) (in e 0)) buf) - (push-str buf " ") - (write-value (if (pvec? e) (pv-nth e 1) (in e 1)) buf)) - (push-str buf "}")) - - (and (table? v) (= :jolt/sorted-set (v :jolt/type))) - (do - (push-str buf "#{") - (var first? true) - (each x (let [ef (let [o (v :ops)] (and o (o :entries))) es (if ef (ef v) (v :entries))] (if (pvec? es) (pv->array es) es)) - (if first? (set first? false) (push-str buf " ")) - (write-value x buf)) - (push-str buf "}")) - - (and (table? v) (get v :jolt/deftype)) - (do - (push-str buf "{") - (var first? true) - (each [k val] (pairs v) - (when (and (not= k :jolt/deftype) (not= k :cnt) (not= k :buckets) - (not= k :_meta) (not= k :jolt/type) (not= k :phm)) - (if first? (set first? false) (push-str buf " ")) - (write-value k buf) - (push-str buf " ") - (write-value val buf))) - (push-str buf "}")) - - (struct? v) - (do - (push-str buf "{") - (var first? true) - (each [k val] (pairs v) - (if first? (set first? false) (push-str buf " ")) - (write-value k buf) - (push-str buf " ") - (write-value val buf)) - (push-str buf "}")) - - (table? v) - (do - (push-str buf "{") - (var first? true) - (each [k val] (pairs v) - (when (not= k :jolt/type) - (if first? (set first? false) (push-str buf " ")) - (write-value k buf) - (push-str buf " ") - (write-value val buf))) - (push-str buf "}")))) - -(set write-value (fn [v buf] - (cond - (nil? v) (push-str buf "nil") - (= true v) (push-str buf "true") - (= false v) (push-str buf "false") - (number? v) (push-str buf (string v)) - (string? v) (push-str buf v) - (keyword? v) (do (push-str buf ":") (push-str buf (string v))) - (and (struct? v) (= :jolt/char (get v :jolt/type))) - (do (push-str buf "\\") - (push-str buf (case (v :ch) - 10 "newline" 32 "space" 9 "tab" 13 "return" - 12 "formfeed" 8 "backspace" 0 "nul" - (string/from-bytes (v :ch))))) - (and (struct? v) (= :symbol (get v :jolt/type))) - (let [ns (get v :ns) name (get v :name)] - (if ns - (push-str buf (string ns "/" name)) - (push-str buf name))) - (and (table? v) (= :jolt/var (v :jolt/type))) - (push-str buf (string "#'" (ctx-current-ns ctx) "/" (var-name v))) - (or (tuple? v) (array? v) (struct? v) (table? v)) - (write-collection v buf) - true (push-str buf (string v))))) - -(defn print-value [v] - (def buf @"") - (write-value v buf) - (print (string buf))) - -(defn- err-message [err] - (cond - (string? err) err - (and (or (table? err) (struct? err)) (= :jolt/exception (get err :jolt/type))) - (err-message (get err :value)) - (and (or (table? err) (struct? err)) (= :jolt/ex-info (get err :jolt/type))) - (let [m (get err :message) d (get err :data)] - (if (and d (not (empty? d))) (string m " " (string/format "%q" d)) (string m))) - (string? err) err - (string/format "%q" err))) - -# --- error presentation (jolt-2o7.2, rephrase-inspired) ---------------------- -# Host messages rewritten into Clojure-shaped ones; stack frames filtered to -# the USER'S code (compiled jolt fns carry _r$ns/name--N janet names — round -# 2o7.1). JOLT_DEBUG=1 restores the raw janet trace for jolt development. - -(defn- demangle - "_r$app.deep/level3--105 -> app.deep/level3 (nil for non-jolt names)." - [nm] - (when (string/has-prefix? "_r$" nm) - (def s (string/slice nm 3)) - # the counter suffix is the LAST --N run - (var cut (length s)) - (var i (string/find "--" s)) - (while (not (nil? i)) - (set cut i) - (set i (string/find "--" s (+ i 1)))) - (string/slice s 0 cut))) - -(defn- fmt-val [x] - (cond - (string? x) (string `"` x `"`) - (nil? x) "nil" - (string x))) - -(def- op-words - {"+" "add" "-" "subtract" "*" "multiply" "/" "divide" - "<" "compare" ">" "compare" "<=" "compare" ">=" "compare"}) - -(defn- rewrite-message - "Host/janet error text -> a user-facing message. Unknown messages verbatim." - [msg] - (def msg (string msg)) - (cond - # janet polymorphic arithmetic. Binary: "could not find method :+ for 1 or - # :r+ for "a"". Unary (inc/dec/-): "could not find method :+ for "x"" — no - # "or :r" clause, so orpos is nil; handle both without crashing the reporter. - (string/has-prefix? "could not find method :" msg) - (let [rest* (string/slice msg (length "could not find method :")) - sp (string/find " " rest*) - op (string/slice rest* 0 sp) - tail (string/slice rest* (+ sp (length " for "))) - orpos (string/find " or :r" tail)] - (if (nil? orpos) - # unary form: one operand - (string "Cannot " (get op-words op op) " " tail - " — " op " expects numbers") - (let [a (string/slice tail 0 orpos) - forpos (string/find " for " tail (+ orpos 1)) - b (string/slice tail (+ forpos 5))] - (string "Cannot " (get op-words op op) " " a " and " b - " — " op " expects numbers")))) - # janet fixed-arity: called with 2 arguments, expected 1 - (and (string/has-prefix? " called with " msg)) - (let [nm-end (string/find ">" msg) - nm (string/slice msg (length " called with "))) - n-end (string/find " " tail) - n (string/slice tail 0 n-end) - exp (if-let [i (string/find "expected " tail)] - (string " (expected " (string/slice tail (+ i 9)) ")") "")] - (string "Wrong number of args (" n ") passed to: " pretty exp)) - # a typo'd symbol compiles to nil today (round 2o7.3 will fix resolution) - (= msg "Cannot call nil as a function") - (string msg " — often an undefined (misspelled?) symbol") - msg)) - -(defn- print-user-trace - "Filter the stashed janet trace down to frames a jolt user can act on: - compiled jolt fns (the _r$ns/name--N janet names, demangled) and frames - from non-jolt source files. Internal janet/jolt frames are dropped." - [trace] - (var shown 0) - (each line (string/split "\n" trace) - (def t (string/trim line)) - (when (string/has-prefix? "in " t) - (def rest* (string/slice t 3)) - (def sp (or (string/find " " rest*) (length rest*))) - (def nm (string/slice rest* 0 sp)) - (cond - (string/has-prefix? "_r$" nm) - (do (eprint " at " (demangle nm)) (++ shown)) - # a frame from a real source file outside jolt internals - (and (string/find "[" rest*) - (not (string/find "src/jolt/" rest*)) - (not (string/find "boot.janet" rest*)) - (not (string/find "[eval]" rest*))) - (do (eprint " " t) (++ shown)) - nil))) - shown) - -(defn- report-error [err fib] - (eprint "Error: " (rewrite-message (err-message err))) - (def env (ctx :env)) - (def stashed (get env :error-trace)) - (def pos (get env :error-pos)) - (def chain (get env :error-loading)) - (put env :error-trace nil) - (put env :error-pos nil) - (put env :error-loading nil) - # :1 is the synthetic require/apply string the CLI feeds itself (and - # any one-line -e) — no information there - (when (and pos (not (and (= (pos :file) "") (= (pos :line) 1)))) - (eprint " at " (pos :file) ":" (pos :line))) - (cond - (os/getenv "JOLT_DEBUG") - (if stashed (eprin stashed) (when fib (debug/stacktrace fib ""))) - stashed (print-user-trace stashed) - fib (when fib nil)) - # requires unwound through, innermost first; the failing file itself is - # already on the 'at' line - (when chain - (each f chain - (unless (or (= f "") (and pos (= f (pos :file)))) - (eprint " while loading " f))))) - -(defn- run-repl [] - (print "Jolt — Clojure on Janet") - (print "Type (exit) to quit.\n") - (var running true) - (var pending "") # accumulates a form split across multiple input lines - (while running - (let [prompt (if (= pending "") (string (ctx-current-ns ctx) "=> ") " #_=> ") - line (read-line prompt)] - (cond - (nil? line) (set running false) - (let [input (if (= pending "") line (string pending "\n" line)) - trimmed (string/trim input)] - (cond - (= trimmed "(exit)") (set running false) - (= trimmed "") (set pending "") - # Try to parse the accumulated input; if it's an incomplete form - # (unterminated list/vector/map/string), keep reading more lines. - (let [parsed (protect (parse-string input))] - (if (and (= (parsed 0) false) - (string/find "nterminated" (string (parsed 1)))) - (set pending input) - (do - (set pending "") - (try - (print-value (eval-string ctx input)) - ([err fib] (report-error err fib)))))))))))) - -(defn- set-command-line-args [argv] - # bind clojure.core/*command-line-args* to a vector of the remaining args - (ns-intern (ctx-find-ns ctx "clojure.core") "*command-line-args*" - (tuple/slice (tuple ;argv)))) - -(defn- run-file [path argv] - (set-command-line-args argv) - (ns-intern (ctx-find-ns ctx "clojure.core") "*file*" path) - (if (not (os/stat path)) - (do (eprint "Error: file not found: " path) (os/exit 1)) - (let [src (slurp path)] - (try - (load-string ctx src path) - ([err fib] (report-error err fib) (os/exit 1)))))) - -(defn- run-eval [expr argv] - (set-command-line-args argv) - (try - (let [v (load-string ctx expr)] - (when (not (nil? v)) (print-value v))) - ([err fib] (report-error err fib) (os/exit 1)))) - -(defn- ensure-nrepl-loaded [] - # jolt.nrepl is part of the baked-in stdlib, so require finds it anywhere. - (eval-string ctx "(require '[jolt.nrepl])")) - -(defn- run-nrepl [argv] - # addr is [host:]port; bare number is a port. Default 127.0.0.1:7888. - (def addr (get argv 0)) - (var host "127.0.0.1") - (var port 7888) - (when addr - (if-let [i (string/find ":" addr)] - (do (when (> i 0) (set host (string/slice addr 0 i))) - (set port (scan-number (string/slice addr (+ i 1))))) - (set port (scan-number addr)))) - (ensure-nrepl-loaded) - (eval-string ctx (string "(jolt.nrepl/start-server! {:host \"" host "\" :port " port "})")) - # Editors auto-discover the port from this file (nREPL convention). - (spit ".nrepl-port" (string port)) - # Remove .nrepl-port on exit — on a clean unwind (defer) and on Ctrl-C/SIGTERM - # (signal handlers). A hard SIGKILL can't be caught, so it may still be left. - (def cleanup (fn [&] (protect (os/rm ".nrepl-port")))) - (os/sigaction :int (fn [&] (cleanup) (os/exit 0)) true) - (os/sigaction :term (fn [&] (cleanup) (os/exit 0)) true) - (print "Jolt nREPL server started on " host ":" port) - (print "Wrote .nrepl-port — connect your editor; Ctrl-C to stop.") - (flush) - # Keep the main fiber alive so the event loop serves connections. - (defer (cleanup) - (forever (ev/sleep 60)))) - -(defn- print-version [] - (print "jolt v" jolt-version)) - -# --- Deps image cache: compile the dependencies ONCE ------------------------- -# The baked binary loads core in ~10ms (it's marshaled in), but a program still -# re-compiles ALL of its dependency namespaces (reitit, ring, …) from source on -# every run — seconds of analyzer->IR->emit that never change between runs. Like -# Clojure's AOT or Stalin's compile-once model, snapshot the ctx AFTER the -# require chain and reuse it: the first run compiles + caches, later runs fork -# the image (~10ms) and skip compilation entirely. The key includes the jolt -# version, entry ns, source roots, and the compile flags; the image carries a -# manifest of every loaded source file's mtime, so any source edit (app or dep) -# invalidates it. JOLT_NO_DEPS_CACHE=1 disables. -(defn- deps-image-path [ns-name] - (def dir (or (os/getenv "JOLT_IMAGE_CACHE_DIR") (os/getenv "TMPDIR") "/tmp")) - # Key on the jolt version + entry ns + every ctx-shaping env var (ctx-cache-key, - # jolt-q5ql): the run-mode flags this image bakes are all derived from those - # vars, so keying on the canonical list can't miss one the way the old - # hand-built positional key could. - (def key (ctx-cache-key [:jolt-version jolt-version :ns ns-name])) - (string dir "/jolt-deps-" (band (hash key) 0x7FFFFFFF) ".jimg")) - -(defn- manifest-of [files] - (def m @{}) - (each f files (when-let [st (os/stat f)] (put m f (st :modified)))) - m) - -(defn- manifest-current? [manifest] - (var ok true) - (eachp [f mt] manifest - (def st (os/stat f)) - (unless (and st (= (st :modified) mt)) (set ok false))) - ok) - -(defn- try-load-deps-image [path] - (unless (os/getenv "JOLT_NO_DEPS_CACHE") - # load-ctx-image forks + validates + rewires (shared with init-cached, jolt-q5ql); - # the deps-specific validity check is the source-mtime manifest. - (load-ctx-image path jcore/install-print-method-cb! - (fn [c] (let [m (get (c :env) :deps-manifest)] - (and m (manifest-current? m))))))) - -(defn- save-deps-image [c path] - (unless (os/getenv "JOLT_NO_DEPS_CACHE") - (put (c :env) :deps-manifest (manifest-of (or (get (c :env) :loaded-files) @[]))) - (save-ctx-image c path))) - -(defn- run-main [ns-name argv] - (when (nil? ns-name) (eprint "Error: -m/--main requires a namespace") (os/exit 1)) - (try - (do - (def path (deps-image-path ns-name)) - (if-let [cached (try-load-deps-image path)] - # cache hit: every dependency is already compiled in the image - (do (set ctx cached) (ctx-set-current-ns ctx "user")) - # cache miss: compile the requires, then snapshot for next time. Track the - # loaded files for the manifest. - (do - (put (ctx :env) :loaded-files @[]) - (load-string ctx (string "(require '[" ns-name "])")) - # whole-program (jolt-t34): every unit is loaded now — run the one - # closed-world fixpoint over all of them before -main. - (when (get (ctx :env) :whole-program?) - (when-let [ip (get (ctx :env) :infer-program!)] (protect (ip ctx))) - (put (ctx :env) :infer-program-done? true)) - (save-deps-image ctx path))) - # Bind *command-line-args* on the FINAL ctx, AFTER any cache swap: a cache - # hit replaces ctx with the saved image, which carries the args baked when - # it was saved — the current run's argv must win (jolt-4mui). - (set-command-line-args argv) - (load-string ctx (string "(apply " ns-name "/-main *command-line-args*)"))) - ([err fib] (report-error err fib) (os/exit 1)))) - -# --- uberscript dead-code elimination (jolt-atg) --------------------------- -# A bundle is closed-world: everything it needs is inlined and nothing is -# required afterward, so a user `defn` unreachable from the entry's reference -# graph can be dropped. Conservative + sound: only plain defn/defn- are -# prunable; a defn is kept if its (bare or ns-qualified) name appears in any -# kept form, the closure runs to a fixpoint, and any use of dynamic resolution -# disables pruning entirely. The drop is by exact source span, so formatting -# and reader macros in the surviving code are untouched. -(defn- dce-sym? [x] (and (struct? x) (= :symbol (get x :jolt/type)))) -(def- dce-bailout-syms - {"resolve" true "ns-resolve" true "requiring-resolve" true "find-var" true - "intern" true "eval" true "load-string" true}) -(defn- dce-collect-syms [form acc] - (cond - (dce-sym? form) (do (put acc (get form :name) true) - (when (get form :ns) - (put acc (string (get form :ns) "/" (get form :name)) true))) - (indexed? form) (each x form (dce-collect-syms x acc)) - (or (struct? form) (table? form)) (each k (keys form) - (dce-collect-syms k acc) - (dce-collect-syms (get form k) acc))) - acc) -(defn- dce-defn-name [form] - (when (and (indexed? form) (>= (length form) 2) (dce-sym? (get form 0)) - (let [nm (get (in form 0) :name)] (or (= nm "defn") (= nm "defn-"))) - (dce-sym? (get form 1))) - (get (in form 1) :name))) -(defn- dce-strip-spans [src dead] - (if (empty? dead) src - (do - (sort dead (fn [a b] (< (a 0) (b 0)))) - (def buf @"") - (var cur 0) - (each [s e] dead - (when (> s cur) (buffer/push-string buf (string/slice src cur s))) - (set cur (max cur e))) - (buffer/push-string buf (string/slice src cur)) - (string buf)))) - -(defn- run-uberscript [out main-ns] - # Bundle main-ns and everything it requires (from JOLT_PATH roots) into one - # .clj that runs on a plain jolt — no deps, no jpm. We require the entry and - # collect the load order the loader records (deps before dependents). - (when (or (nil? out) (nil? main-ns)) - (eprint "Usage: jolt uberscript OUT.clj -m NS") (os/exit 1)) - (put (ctx :env) :loaded-files @[]) - (try - (load-string ctx (string "(require '[" main-ns "])")) - ([err fib] (report-error err fib) (os/exit 1))) - (def seen @{}) - (def files @[]) - (each f (get (ctx :env) :loaded-files) - (unless (get seen f) (put seen f true) (array/push files f))) - # read every file's source and parse it into top-level forms with byte spans; - # if ANY file fails to parse, fall back to verbatim bundling (DCE off) so the - # uberscript stays exactly as robust as a plain concatenation. - (def srcs @{}) - (def file-forms @{}) - (def all-forms @[]) - (var dce-ok true) - (each f files - (def src (slurp f)) - (put srcs f src) - (def lst @[]) - (try - (each [form s e] (parse-all-spans src f) - (def entry @{:start s :end e :dname (dce-defn-name form) :form form}) - (array/push lst entry) - (array/push all-forms entry)) - ([_err _fib] (set dce-ok false))) - (put file-forms f lst)) - # disable DCE if the bundle resolves names dynamically (a defn could be - # reached by a string/symbol the reference scan can't see). - (when dce-ok - (def allsyms @{}) - (each e all-forms (dce-collect-syms (e :form) allsyms)) - (each nm (keys allsyms) (when (get dce-bailout-syms nm) (set dce-ok false)))) - # reachability: seed from the entry (-main) and every non-prunable form, then - # close over the bodies of defns that become live. - (def live @{}) - (when dce-ok - (def referenced @{"-main" true}) - (each e all-forms (unless (e :dname) (dce-collect-syms (e :form) referenced))) - (var changed true) - (while changed - (set changed false) - (each e all-forms - (when (and (e :dname) (not (get live e)) (get referenced (e :dname))) - (put live e true) - (dce-collect-syms (e :form) referenced) - (set changed true))))) - (var dropped 0) - (def buf @"") - (buffer/push-string buf (string ";; Generated by `jolt uberscript` — " (length files) " namespace(s)\n\n")) - (each f files - (buffer/push-string buf (string ";; --- " f " ---\n")) - (def src (get srcs f)) - (if-not dce-ok - (buffer/push-string buf src) - (do - (def dead @[]) - (each e (get file-forms f) - (when (and (e :dname) (not (get live e))) - (++ dropped) - (array/push dead [(e :start) (e :end)]))) - (buffer/push-string buf (dce-strip-spans src dead)))) - (buffer/push-string buf "\n")) - (buffer/push-string buf (string "\n(apply " main-ns "/-main *command-line-args*)\n")) - (spit out (string buf)) - (print "Wrote " out " (" (length files) " namespace(s)" - (if (and dce-ok (> dropped 0)) (string ", " dropped " dead fn(s) dropped") "") ")")) - -(defn- run-cgen-build [argv] - # jolt cgen-build -m NS -o OUT [--keep]: fuse the app's hot numeric-leaf fns - # (compiled to native code) + the app source into one static executable. - (var main-ns nil) - (var out nil) - (var keep false) - (var i 0) - (while (< i (length argv)) - (def a (argv i)) - (cond - (or (= a "-m") (= a "--main")) (do (set main-ns (get argv (+ i 1))) (+= i 2)) - (or (= a "-o") (= a "--out")) (do (set out (get argv (+ i 1))) (+= i 2)) - (= a "--keep") (do (set keep true) (++ i)) - (++ i))) - (when (or (nil? main-ns) (nil? out)) - (eprint "Usage: jolt cgen-build -m NS -o OUT [--keep]") - (os/exit 1)) - (try - (let [r (cgen-build/build-app {:main main-ns :out out :keep keep})] - (print "Wrote " (r :out) " (" (r :native-count) " native fn(s) linked)")) - ([err fib] (report-error err fib) (os/exit 1)))) - -(defn- print-help [] - (print "Jolt — a Clojure interpreter on Janet\n") - (print "Usage: jolt [opt] [args]\n") - (print " (no args), repl Start a REPL") - (print " FILE [args] Run a Clojure file (binds *command-line-args*, *file*)") - (print " - Run a program read from stdin") - (print " -e, --eval EXPR Evaluate EXPR and print the result") - (print " -f, --file FILE Run a Clojure file") - (print " -m, --main NS [args] Require NS and call its -main with the remaining args") - (print " nrepl-server [addr] Start an nREPL server (addr = [host:]port, default 7888)") - (print " (aliases: --nrepl-server, nrepl)") - (print " uberscript OUT -m NS Bundle NS + its required namespaces into one .clj") - (print " cgen-build -m NS -o OUT Build NS into a single static binary (hot fns") - (print " compiled to native code, no toolchain to run)") - (print " --version, version Print the Jolt version") - (print " -h, --help, help Show this help\n") - (print "Dependencies (deps.edn, git + :local deps — resolved into JOLT_PATH):") - (print " -M:a[:b] [args] Run the alias(es) :main-opts ++ args") - (print " -A:a[:b] CMD [args] Run CMD (repl/-m/nrepl-server/…) with the alias paths") - (print " run FILE [args] Run FILE with deps.edn resolved") - (print " path Print the resolved source roots (':'-joined)") - (print " tasks List :tasks from deps.edn") - (print " task NAME [args] Run a :tasks entry (shell string or :main-opts)") - (print " A deps.edn in the working dir is auto-resolved for repl/-m/-e/nrepl-server/FILE.\n") - (print "Running a program (a file, -m/-M) direct-links by default; type inference") - (print "and specialization are opt-in via JOLT_OPTIMIZE (the cost is paid once, then") - (print "cached). The repl, -e, and nrepl-server stay open so you can redefine vars.") - (print "Environment:") - (print " JOLT_OPTIMIZE=1 type-infer + specialize (whole-program over app nses)") - (print " JOLT_NO_DIRECT_LINK=1 keep a program run open/redefinable (no optimization)") - (print " JOLT_NO_WHOLE_PROGRAM=1 direct-link but skip the cross-namespace pass") - (print " JOLT_DIRECT_LINK=1 force direct-linking + optimization on (e.g. for -e)") - (print " JOLT_WHOLE_PROGRAM=1 force the whole-program pass on") - (print " JOLT_INTERPRET=1 run the tree-walking interpreter\n") - (print " JOLT_PATH=dir1:dir2 extra source roots (set automatically by deps resolution)")) - -(def- help-flags {"-h" true "--help" true "help" true "-?" true}) -(def- version-flags {"--version" true "version" true}) -(def- nrepl-flags {"nrepl-server" true "--nrepl-server" true "nrepl" true}) -(def- eval-flags {"-e" true "--eval" true}) -(def- file-flags {"-f" true "--file" true}) -(def- main-flags {"-m" true "--main" true}) - -# --- deps.edn integration (the old jolt-deps tool, folded in) ---------------- -# The runtime stays deps-agnostic: it reads source roots from JOLT_PATH (applied -# in `main`, below). This layer resolves a deps.edn into those roots IN-PROCESS, -# so a single `jolt` binary both resolves dependencies and runs code. ./deps -# loads jpm (git fetch + cache) lazily — only at an actual resolve — so a run -# with no deps.edn never pulls it in, and an app baked from its own entry (which -# imports jolt/api, not this CLI) never links the resolver at all. - -(defn- parse-alias-flag - ``"-A:dev:test" / "-M:dev" -> [:dev :test].`` - [arg] - (map keyword (filter |(not= "" $) (string/split ":" (string/slice arg 2))))) - -(defn- deps-roots [aliases] - (if (os/stat "deps.edn") (deps/resolve-deps-cached "deps.edn" nil aliases) @[])) - -(defn- set-deps-env! [aliases] - # Prepend the resolved roots to any existing JOLT_PATH; `main` (below) applies - # them to the ctx source-paths. JOLT_APP_PATHS scopes whole-program inference - # to the project's own namespaces — deps load-infer per-ns instead (jolt-87e). - (def rs (string/join (deps-roots aliases) ":")) - (def existing (os/getenv "JOLT_PATH")) - (os/setenv "JOLT_PATH" (if (and existing (> (length existing) 0)) (string rs ":" existing) rs)) - (when (os/stat "deps.edn") - (os/setenv "JOLT_APP_PATHS" (string/join (deps/project-source-roots "deps.edn" aliases) ":")))) - -(defn- resolve-deps-argv - ``Resolve deps.edn (when relevant) and de-sugar the deps subcommands into a - plain runtime argv that `main` then dispatches on. The pure deps queries - (path/tasks/task) print and exit. A runnable command resolves a deps.edn in - cwd when one is present — so `jolt repl` / `-m` / `nrepl-server` pick up the - project and its dependencies — and is a no-op (resolver untouched) with none.`` - [argv] - # leading -A:alias flags apply to whatever command follows - (var aliases nil) - (var rest argv) - (while (string/has-prefix? "-A" (or (get rest 0) "")) - (set aliases (array/concat (or aliases @[]) (parse-alias-flag (get rest 0)))) - (set rest (array/slice rest 1))) - (def cmd (get rest 0)) - (cond - # pure deps queries — produce output and exit, never start the runtime - (= cmd "path") - (do (print (string/join (deps-roots aliases) ":")) (os/exit 0)) - (= cmd "tasks") - (do (each row (deps/tasks "deps.edn") - (print (row 0) (if (row 1) (string "\t" (row 1)) ""))) - (os/exit 0)) - (= cmd "task") - (let [name (get rest 1) - spec (when name (deps/task-spec "deps.edn" name))] - (cond - (nil? name) (do (eprint "jolt: task needs a name") (os/exit 1)) - (nil? spec) (do (eprint "jolt: no such task: " name) (os/exit 1)) - (= :shell (spec :type)) - (os/exit (os/execute ["sh" "-c" (string/join [(spec :cmd) ;(array/slice rest 2)] " ")] :p)) - (do (set-deps-env! aliases) - (array/concat @[] (spec :argv) (array/slice rest 2))))) - # -M:aliases — resolve and run the alias's :main-opts ++ extra args - (and cmd (string/has-prefix? "-M" cmd)) - (let [als (array/concat (or aliases @[]) (parse-alias-flag cmd)) - mo (deps/alias-main-opts "deps.edn" als)] - (if mo - (do (set-deps-env! als) (array/concat @[] mo (array/slice rest 1))) - (do (eprint "jolt: no :main-opts in alias(es) " (string/format "%j" (map string als))) - (os/exit 1)))) - # explicit `run FILE` — resolve, then run the file - (= cmd "run") - (do (set-deps-env! aliases) (array/slice rest 1)) - # any runnable command: resolve a deps.edn if present (or if -A forced it); - # help/version never resolve, and with no deps.edn + no -A the resolver and - # jpm are never touched. - (and (not (help-flags cmd)) (not (version-flags cmd)) - (or aliases (os/stat "deps.edn"))) - (do (set-deps-env! aliases) rest) - # nothing deps-related — argv unchanged - true rest)) - -(defn main [&] - (def args (or (dyn :args) @[])) # @["jolt" arg1 arg2 ...] - # Resolve deps.edn + de-sugar deps subcommands (jolt-deps folded in): sets - # JOLT_PATH/JOLT_APP_PATHS in our env (read just below) and rewrites argv to a - # plain runtime command. A no-deps invocation passes through untouched. - (def argv (resolve-deps-argv (if (> (length args) 1) (array/slice args 1) @[]))) - (ctx-set-current-ns ctx "user") - # JOLT_PATH must be applied at runtime: this `ctx` is built into the image at - # build time, so its source-paths can't capture the runtime environment. - # resolve-deps-argv (above) sets it from the resolved deps.edn source roots. - (when-let [jp (os/getenv "JOLT_PATH")] - (each p (string/split ":" jp) - (when (> (length p) 0) (array/push (get (ctx :env) :source-paths) p)))) - # JOLT_APP_PATHS (jolt-87e), likewise applied at runtime: the project's own - # source roots, set by jolt-deps. Whole-program inference is scoped to - # namespaces under these (deps compile at default cost), so a dep-heavy app's - # optimize-mode startup doesn't re-infer every transitive dependency. Read here - # for the same baked-at-build-time reason as JOLT_PATH above. - (let [aps @[]] - (when-let [jap (os/getenv "JOLT_APP_PATHS")] - (each p (string/split ":" jap) (when (> (length p) 0) (array/push aps p)))) - (put (ctx :env) :app-source-paths aps)) - # JOLT_FEATURES, likewise, must be applied at runtime: reader-features-set! - # runs at module load, which for a baked binary is BUILD time — so a process - # that sets JOLT_FEATURES (e.g. to read a clj-targeted lib's :clj branches) - # would otherwise be ignored, and unmatched #?(...) forms silently splice to - # nothing. Re-read it here so the env wins in the running process. - (when-let [jf (os/getenv "JOLT_FEATURES")] - (reader-features-set! (filter |(> (length $) 0) (string/split "," jf)))) - # Linking default depends on the run MODE. Running a PROGRAM (a file, -f, -m/-M, - # stdin) is a closed world — all code is loaded, then it executes to completion - # — so it direct-links by default: user code gets inlining + shapes + the type - # inference's specialization (jolt-87f). INTERACTIVE modes (repl, -e, the nREPL - # server) stay indirect/open so redefinition works — direct-linking would seal - # callers against a redef. Explicit env always wins: JOLT_NO_DIRECT_LINK forces - # the open path even for a program run (runtime redefinition / hot-reload), - # JOLT_DIRECT_LINK forces it on even for -e. Core is already compiled into the - # image; this only governs user code compiled at runtime. - (def open-mode? - (or (empty? argv) - (help-flags (argv 0)) (version-flags (argv 0)) - (= (argv 0) "repl") (nrepl-flags (argv 0)) (eval-flags (argv 0)) - (= (argv 0) "uberscript"))) - (def main-entry? (and (not (empty? argv)) (main-flags (argv 0)))) - # Run-mode policy lives in config/resolve-run-mode now (jolt-q5ql) — unit- - # testable without the CLI, and the same canonical knob list backs the cache - # keys. Install the resolved knobs onto the runtime env (the baked ctx computed - # them at build time; a program run recomputes from the live env). - (let [mode (resolve-run-mode open-mode? main-entry?)] - (eachp [k v] mode (put (ctx :env) k v))) - (cond - (empty? argv) (run-repl) - (help-flags (argv 0)) (print-help) - (version-flags (argv 0)) (print-version) - (= (argv 0) "repl") (run-repl) - (nrepl-flags (argv 0)) (run-nrepl (array/slice argv 1)) - (eval-flags (argv 0)) (run-eval (get argv 1 "") (array/slice argv 2)) - (file-flags (argv 0)) (run-file (get argv 1) (array/slice argv 2)) - (main-flags (argv 0)) (run-main (get argv 1) (array/slice argv 2)) - (= (argv 0) "uberscript") - (let [out (get argv 1) - rest (array/slice argv 2) - mi (or (index-of "-m" rest) (index-of "--main" rest))] - (run-uberscript out (if mi (get rest (+ mi 1)) nil))) - (= (argv 0) "cgen-build") (run-cgen-build (array/slice argv 1)) - (= (argv 0) "-") (run-file "/dev/stdin" (array/slice argv 1)) - (run-file (argv 0) (array/slice argv 1)))) diff --git a/src/jolt/phm.janet b/src/jolt/phm.janet deleted file mode 100644 index bfbc609..0000000 --- a/src/jolt/phm.janet +++ /dev/null @@ -1,381 +0,0 @@ -# PersistentHashMap for Jolt — a HAMT (hash array mapped trie), the structure -# Clojure/ClojureScript/jank use. 32-way branching, 5 hash bits per level, with -# structural sharing: assoc/dissoc/get are O(log32 n) ~ effectively constant. -# Replaces the old flat copy-on-write bucket array, which was O(n) per assoc -# (O(n^2) to build — jolt-684u). Translated from the ClojureScript -# PersistentHashMap (cljs.core: BitmapIndexedNode / ArrayNode / HashCollisionNode). -# -# REP vs API: this file is ONLY the map representation (phm-* primitives). The -# Clojure-facing map ops (assoc/dissoc/get/conj/count/seq dispatch, nil-key, -# merge) live in core_coll.janet / core_types.janet, which recognize phm by its -# `:jolt/deftype` string and call these primitives. PersistentHashSet is layered -# on top in phs.janet. Transients are a separate mutable-table rep (core_types), -# so they don't touch this file. -# -# Node representation (Janet tuples, tagged at index 0; their arrays are built -# fresh on every modify and never mutated in place, so sharing is safe): -# [:bin bitmap arr] bitmap-indexed: arr is [k v k v ...]; a nil k means v is -# a sub-node (the slot recurses one level deeper). -# [:an cnt arr] array-node: arr is 32 slots of sub-node-or-nil. -# [:hcn hash cnt arr] hash-collision: arr is [k v k v ...] of same-hash keys. -# The map itself stays a table tagged :jolt/phm with :cnt (read directly by -# core), plus :root (the trie, nil when empty) and :has-nil/:nil-val (Clojure -# maps allow a nil key, which the trie can't store because a nil k marks a -# sub-node). -# -# Note on Janet `=`: it is STRUCTURAL on tuples, not identity, so cljs's -# `(identical? n node)` "nothing changed" early-outs are dropped here — we just -# rebuild the O(log32 n) path (an extra alloc only when overwriting an identical -# value). nil returns (a node that became empty) are kept; those are real nils. - -(def- DEFTYPE "jolt.lang.persistent-hash-map.PersistentHashMap") - -(defn phm? [x] - (and (table? x) (= DEFTYPE (x :jolt/deftype)))) - -# Keys are hashed and compared by VALUE. Scalars are value-hashable in Janet; -# collection keys (a phm/pvec/plist/vector) are Janet tables hashed by identity, -# so they're canonicalized to a value-hashable struct/tuple first. -# `canonicalize-key` is injected by core (which knows those types); phm stays -# dependency-free. Keys are STORED as-is, so retrieval/iteration return originals. -(var canonicalize-key nil) -(defn set-canonicalize-key! - "Install the value-canonicalizer for collection keys (called by core)." - [f] - (set canonicalize-key f)) -(defn- ck [k] - (if (and canonicalize-key (or (table? k) (struct? k) (array? k) (tuple? k))) - (canonicalize-key k) - k)) -(defn canon - "Public canonicalizer: maps a key to its value-hashable form (identity for - scalars). Used by callers that index the same canonicalized tables phm uses." - [k] (ck k)) -# Identity/scalar equality first (the common case), then value equality. -(defn- key= [a b] (or (= a b) (= (ck a) (ck b)))) -# Janet bit ops are 32-bit and split awkwardly: band/bor/bxor want SIGNED -# operands, brushift wants UNSIGNED — and `hash` is a signed 32-bit int. So we -# carry the hash as an UNSIGNED 32-bit value, extract the 5-bit level index with -# arithmetic (mask), and test/count bits with band against (1<= nkeys 16) - # expand to an array-node - (let [nodes (array/new-filled 32 nil) - jdx (mask h shift)] - (put nodes jdx (bin-assoc EMPTY-BIN (+ shift 5) h key val added)) - (var i 0) (var j 0) - (while (< i 32) - (unless (zero? (band bitmap (blshift 1 i))) - (let [ek (in arr (* 2 j)) ev (in arr (+ 1 (* 2 j)))] - (put nodes i (if (nil? ek) ev - (bin-assoc EMPTY-BIN (+ shift 5) (khash ek) ek ev added))) - (++ j))) - (++ i)) - [:an (+ nkeys 1) nodes]) - # insert (key val) into the bin arr at pair-index idx - (let [out (array)] - (array/concat out (array/slice arr 0 (* 2 idx))) - (array/push out key) (array/push out val) - (array/concat out (array/slice arr (* 2 idx))) - (put added 0 true) - [:bin (bor bitmap bit) out]))) - # slot occupied - (let [kon (in arr (* 2 idx)) von (in arr (+ 1 (* 2 idx)))] - (cond - (nil? kon) - [:bin bitmap (cset1 arr (+ 1 (* 2 idx)) (node-assoc von (+ shift 5) h key val added))] - (key= key kon) - [:bin bitmap (cset1 arr (+ 1 (* 2 idx)) val)] - (do (put added 0 true) - [:bin bitmap (cset2 arr (* 2 idx) nil (+ 1 (* 2 idx)) - (create-node (+ shift 5) kon von h key val))]))))) - -(defn- an-assoc [node shift h key val added] - (def cnt (in node 1)) (def arr (in node 2)) - (def idx (mask h shift)) (def sub (in arr idx)) - (if (nil? sub) - [:an (+ cnt 1) (cset1 arr idx (bin-assoc EMPTY-BIN (+ shift 5) h key val added))] - [:an cnt (cset1 arr idx (node-assoc sub (+ shift 5) h key val added))])) - -(defn- hcn-assoc [node shift h key val added] - (def chash (in node 1)) (def cnt (in node 2)) (def arr (in node 3)) - (if (= h chash) - (let [idx (hcn-find arr cnt key)] - (if (= idx -1) - (let [out (array ;arr)] (array/push out key) (array/push out val) - (put added 0 true) [:hcn chash (+ cnt 1) out]) - (if (= (in arr (+ 1 idx)) val) node - [:hcn chash cnt (cset1 arr (+ 1 idx) val)]))) - # different hash at this level: wrap in a bin node, then assoc - (bin-assoc [:bin (bitpos chash shift) (array nil node)] shift h key val added))) - -(set create-node (fn [shift k1 v1 k2h k2 v2] - (def k1h (khash k1)) - (if (= k1h k2h) - [:hcn k1h 2 (array k1 v1 k2 v2)] - (let [added @[false] - n1 (bin-assoc EMPTY-BIN shift k1h k1 v1 added)] - (bin-assoc n1 shift k2h k2 v2 added))))) - -(set node-assoc (fn [node shift h key val added] - (case (in node 0) - :bin (bin-assoc node shift h key val added) - :an (an-assoc node shift h key val added) - :hcn (hcn-assoc node shift h key val added)))) - -(defn- bin-lookup [node shift h key nf] - (def bitmap (in node 1)) (def arr (in node 2)) - (def m (mask h shift)) (def bit (blshift 1 m)) - (if (zero? (band bitmap bit)) nf - (let [idx (bidx bitmap m) kon (in arr (* 2 idx)) von (in arr (+ 1 (* 2 idx)))] - (cond - (nil? kon) (node-lookup von (+ shift 5) h key nf) - (key= key kon) von - nf)))) - -(defn- an-lookup [node shift h key nf] - (def sub (in (in node 2) (mask h shift))) - (if (nil? sub) nf (node-lookup sub (+ shift 5) h key nf))) - -(defn- hcn-lookup [node shift h key nf] - (def idx (hcn-find (in node 3) (in node 2) key)) - (if (< idx 0) nf (in (in node 3) (+ 1 idx)))) - -(set node-lookup (fn [node shift h key nf] - (case (in node 0) - :bin (bin-lookup node shift h key nf) - :an (an-lookup node shift h key nf) - :hcn (hcn-lookup node shift h key nf)))) - -(defn- bin-without [node shift h key] - (def bitmap (in node 1)) (def arr (in node 2)) - (def m (mask h shift)) (def bit (blshift 1 m)) - (if (zero? (band bitmap bit)) node - (let [idx (bidx bitmap m) kon (in arr (* 2 idx)) von (in arr (+ 1 (* 2 idx)))] - (cond - (nil? kon) - (let [nn (node-without von (+ shift 5) h key)] - (cond (not (nil? nn)) [:bin bitmap (cset1 arr (+ 1 (* 2 idx)) nn)] - (= bitmap bit) nil - [:bin (bxor bitmap bit) (remove-pair arr idx)])) - (key= key kon) - (if (= bitmap bit) nil [:bin (bxor bitmap bit) (remove-pair arr idx)]) - node)))) - -(defn- an-without [node shift h key] - (def cnt (in node 1)) (def arr (in node 2)) - (def idx (mask h shift)) (def sub (in arr idx)) - (if (nil? sub) node - (let [nn (node-without sub (+ shift 5) h key)] - (cond - (nil? nn) (if (<= cnt 8) (pack-array-node arr idx) [:an (- cnt 1) (cset1 arr idx nil)]) - [:an cnt (cset1 arr idx nn)])))) - -(defn- hcn-without [node shift h key] - (def chash (in node 1)) (def cnt (in node 2)) (def arr (in node 3)) - (def idx (hcn-find arr cnt key)) - (cond (= idx -1) node - (= cnt 1) nil - [:hcn chash (- cnt 1) (remove-pair arr (brshift idx 1))])) - -(set node-without (fn [node shift h key] - (case (in node 0) - :bin (bin-without node shift h key) - :an (an-without node shift h key) - :hcn (hcn-without node shift h key)))) - -# depth-first walk: call (f k v) for every entry (the nil key is handled at the -# map level, not in the trie). -(defn- node-each [node f] - (case (in node 0) - :bin (let [arr (in node 2) L (length arr)] - (var i 0) - (while (< i L) - (let [k (in arr i) v (in arr (+ i 1))] - (if (nil? k) (when v (node-each v f)) (f k v))) - (+= i 2))) - :an (let [arr (in node 2)] - (var i 0) (while (< i 32) (when (in arr i) (node-each (in arr i) f)) (++ i))) - :hcn (let [arr (in node 3) L (* 2 (in node 2))] - (var i 0) (while (< i L) (f (in arr i) (in arr (+ i 1))) (+= i 2))))) - -# --- map value + public API ------------------------------------------------- -(defn- mk [cnt root has-nil nil-val meta] - @{:jolt/type :jolt/phm :jolt/deftype DEFTYPE - :cnt cnt :root root :has-nil has-nil :nil-val nil-val :_meta meta}) - -(defn phm-get [m k &opt default] - (default default nil) - (if (nil? k) - (if (m :has-nil) (m :nil-val) default) - (let [root (m :root)] - (if root (node-lookup root 0 (khash k) k default) default)))) - -(def- NF (gensym)) -(defn phm-contains? [m k] - (if (nil? k) (truthy? (m :has-nil)) - (let [root (m :root)] - (if root (not= (node-lookup root 0 (khash k) k NF) NF) false)))) - -(defn phm-assoc [m k v] - (if (nil? k) - (mk (if (m :has-nil) (m :cnt) (+ (m :cnt) 1)) (m :root) true v (m :_meta)) - (let [added @[false] - root (or (m :root) EMPTY-BIN) - nroot (node-assoc root 0 (khash k) k v added)] - (mk (if (in added 0) (+ (m :cnt) 1) (m :cnt)) nroot (m :has-nil) (m :nil-val) (m :_meta))))) - -(defn phm-dissoc [m k] - (if (nil? k) - (if (m :has-nil) (mk (- (m :cnt) 1) (m :root) false nil (m :_meta)) m) - (let [root (m :root)] - (if (and root (phm-contains? m k)) - (mk (- (m :cnt) 1) (node-without root 0 (khash k) k) (m :has-nil) (m :nil-val) (m :_meta)) - m)))) - -(defn phm-entries [m] - (def out @[]) - (when (m :has-nil) (array/push out [nil (m :nil-val)])) - (when (m :root) (node-each (m :root) (fn [k v] (array/push out [k v])))) - out) - -(defn phm-to-struct [m] - # a Janet struct can't hold a nil key (matches Clojure struct/keys behavior); - # every other entry carries over. - (def t @{}) - (when (m :root) (node-each (m :root) (fn [k v] (put t k v)))) - (table/to-struct t)) - -(defn phm-count [m] (m :cnt)) - -(defn phm-has-nil? [m] (truthy? (m :has-nil))) - -# --- bulk bottom-up build (jolt-5vsp collections) --------------------------- -# Build the HAMT in one pass from a native array of entries, instead of n -# incremental phm-assoc calls (each of which rebuilt the O(log32 n) path with -# fresh arrays AND allocated a fresh map wrapper). The structure produced is -# IDENTICAL to the incremental one: the trie shape is a function of the key set -# (hash-partitioned, with the same bin<=16 / array-node>=17 promotion threshold -# at each level), so nth/lookup/assoc/without/each read it unchanged. Only a -# hash-collision node's internal order is insertion-dependent, and we preserve -# insertion order there too. Validated against phm-assoc across the size and -# branching boundaries (see the throwaway script in the PR). -# -# Entries are @[h key val] triples (h = khash key). build-node takes a non-empty -# group all destined for the same parent slot and returns its node. -(defn- all-same-hash? [entries] - (def h0 (in (in entries 0) 0)) - (var same true) (var i 1) (def L (length entries)) - (while (< i L) (when (not= (in (in entries i) 0) h0) (set same false) (break)) (++ i)) - same) - -(defn- build-node [entries shift] - (if (and (> (length entries) 1) (all-same-hash? entries)) - # all keys share a full 32-bit hash -> collision node (insertion order) - (let [arr (array)] - (each e entries (array/push arr (in e 1)) (array/push arr (in e 2))) - [:hcn (in (in entries 0) 0) (length entries) arr]) - # partition by the 5-bit mask at this level; iterate slots 0..31 ascending - # so the bin arr / array-node slots land in canonical (bidx) order. - (let [groups @{}] - (each e entries - (def m (mask (in e 0) shift)) - (if-let [g (in groups m)] (array/push g e) (put groups m @[e]))) - (def occupied (array)) - (var i 0) (while (< i 32) (when (in groups i) (array/push occupied i)) (++ i)) - (def s (length occupied)) - (if (>= s 17) - # array-node: every occupied slot is a sub-node (a lone key becomes its - # own single-key bin node at shift+5, matching the expand path). - (let [slots (array/new-filled 32 nil)] - (each m occupied (put slots m (build-node (in groups m) (+ shift 5)))) - [:an s slots]) - # bitmap-indexed node: lone key -> leaf pair, group -> nil + sub-node. - (let [arr (array)] - (var bitmap 0) - (each m occupied - (def g (in groups m)) - (set bitmap (bor bitmap (blshift 1 m))) - (if (= 1 (length g)) - (do (array/push arr (in (in g 0) 1)) (array/push arr (in (in g 0) 2))) - (do (array/push arr nil) (array/push arr (build-node g (+ shift 5)))))) - [:bin bitmap arr]))))) - -(defn phm-from-pairs [pairs &opt meta] - "Bulk-build a phm from an indexed collection of native [k v] pairs. Duplicate - keys follow assoc semantics (last value wins, first-seen key object kept). The - caller must pass native tuples/arrays (phm stays free of the value layer)." - (default meta nil) - (def entries @[]) - (def seen @{}) # canon-key -> index into entries (dedup) - (var has-nil false) (var nil-val nil) - (each p pairs - (def k (in p 0)) (def v (in p 1)) - (if (nil? k) - (do (set has-nil true) (set nil-val v)) - (let [c (ck k)] - (if-let [idx (in seen c)] - (put (in entries idx) 2 v) # last value wins - (do (put seen c (length entries)) - (array/push entries @[(khash k) k v])))))) - (def cnt (+ (length entries) (if has-nil 1 0))) - (def root (if (= 0 (length entries)) nil (build-node entries 0))) - (mk cnt root has-nil nil-val meta)) - -(defn make-phm [&opt kvs] - (default kvs nil) - (if (or (nil? kvs) (= 0 (length kvs))) - (mk 0 nil false nil nil) - # pair up the flat [k0 v0 k1 v1 ...] array and bulk-build - (let [pairs (array) n (length kvs)] - (var i 0) (while (< i n) (array/push pairs [(in kvs i) (in kvs (+ i 1))]) (+= i 2)) - (phm-from-pairs pairs)))) diff --git a/src/jolt/phs.janet b/src/jolt/phs.janet deleted file mode 100644 index c28c62a..0000000 --- a/src/jolt/phs.janet +++ /dev/null @@ -1,60 +0,0 @@ -# PersistentHashSet — a set backed by a PersistentHashMap (members are keys -# mapped to true). Extracted from phm.janet (jolt-bvek) so phm.janet is purely -# the hash map; the set is a thin layer over it. -# -# REP vs API: this file is ONLY the set representation (phs-* primitives). The -# Clojure-facing set ops (conj/disj/contains?/count/seq dispatch, set-as-fn -# membership) live in core_coll.janet / core_types.janet, branching on -# `:jolt/type :jolt/set`. - -(use ./phm) - -(defn set? - "Check if x is a PersistentHashSet." - [x] - (and (table? x) (= :jolt/set (x :jolt/type)))) - -(defn phs-from-seq [xs] - "Bulk-build a PersistentHashSet from an indexed collection of members. Members - back a phm as keys mapped to true, so the bulk HAMT builder (phm-from-pairs, - which dedups by canonical key) gives set semantics in one pass instead of an - immutable phm-assoc per element." - (def pairs @[]) - (each x xs (array/push pairs [x true])) - (def m (phm-from-pairs pairs)) - @{:jolt/type :jolt/set :phm m :cnt (phm-count m)}) - -(defn make-phs [& xs] - "Create a PersistentHashSet from items." - (phs-from-seq xs)) - -(defn phs-conj [s & xs] - (var m (s :phm)) - (each x xs (set m (phm-assoc m x true))) - @{:jolt/type :jolt/set :phm m :cnt (phm-count m)}) - -(defn phs-disj [s & xs] - (var m (s :phm)) - (each x xs (set m (phm-dissoc m x))) - @{:jolt/type :jolt/set :phm m :cnt (phm-count m)}) - -(defn phs-contains? [s x] - (phm-contains? (s :phm) x)) - -(defn phs-count [s] - (s :cnt)) - -(defn phs-empty? [s] - (= 0 (s :cnt))) - -(defn phs-seq [s] - # phm-to-struct drops a nil member (a Janet struct can't hold a nil key), so - # re-attach it from the phm's has-nil slot. Keep the struct-key order for the - # non-nil members so set printing stays stable. - (def m (s :phm)) - (def ks (keys (phm-to-struct m))) - (if (phm-has-nil? m) (tuple nil ;ks) (tuple ;ks))) - -(defn phs-get [s x &opt default] - (default default nil) - (if (phm-contains? (s :phm) x) x default)) diff --git a/src/jolt/plist.janet b/src/jolt/plist.janet deleted file mode 100644 index a32a284..0000000 --- a/src/jolt/plist.janet +++ /dev/null @@ -1,76 +0,0 @@ -# Persistent list — an immutable singly-linked cons cell, modeled on Clojure's -# PersistentList. The whole point is O(1) prepend (conj/cons): a new node simply -# points at the existing list as its tail, sharing all of it, so building a list -# with repeated conj is O(n) total instead of O(n²) array copies. -# -# A node is: -# @{:jolt/type :jolt/plist -# :first x head element -# :rest r tail: another plist, or a Janet array/tuple (a list that -# was conj'd onto), or nil for the empty tail -# :count n} element count, or nil when unknown (cons onto a lazy tail) -# -# `:rest` may be a plain array/tuple so `(conj some-list x)` needn't copy the -# original list — the node just references it. pl->array materializes the chain. -# -# REP vs API: this file is ONLY the cons-list representation (pl-* primitives). -# The Clojure-facing list/seq ops (conj/cons/first/rest/count/seq dispatch) live -# in core_coll.janet, which branches on `:jolt/type :jolt/plist`. - -(defn plist? [x] - (and (table? x) (= :jolt/plist (get x :jolt/type)))) - -(defn- counted - "Count of a tail value if known in O(1), else nil." - [r] - (cond - (nil? r) 0 - (plist? r) (get r :count) - (or (array? r) (tuple? r) (string? r) (buffer? r)) (length r) - nil)) - -(defn pl-cons - "Prepend x onto tail r (a plist / array / tuple / nil). O(1)." - [x r] - (def c (counted r)) - @{:jolt/type :jolt/plist :first x :rest r :count (if c (+ c 1) nil)}) - -(def EMPTY-PLIST @{:jolt/type :jolt/plist :first nil :rest nil :count 0}) - -(defn pl-empty? [p] (= 0 (get p :count))) -(defn pl-first [p] (get p :first)) - -(defn pl->array - "Materialize the cons chain to a fresh Janet array." - [p] - (def out @[]) - (var cur p) - (while (plist? cur) - (if (= 0 (get cur :count)) - (set cur nil) - (do (array/push out (get cur :first)) (set cur (get cur :rest))))) - # cur is now a non-plist tail (array/tuple) or nil - (when (and (not (nil? cur)) (or (array? cur) (tuple? cur))) - (each x cur (array/push out x))) - out) - -(defn pl-count [p] - (def c (get p :count)) - (if (nil? c) (length (pl->array p)) c)) - -(defn pl-rest - "The tail as a seqable (array). Returns an empty array for a one-element list." - [p] - (if (or (= 0 (get p :count)) (nil? (get p :rest))) - @[] - (get p :rest))) - -(defn pl-from-indexed - "Build a plist from a Janet array/tuple, preserving order. O(n)." - [xs] - (var p EMPTY-PLIST) - (var i (- (length xs) 1)) - (while (>= i 0) - (set p (pl-cons (in xs i) p)) - (-- i)) - p) diff --git a/src/jolt/png.janet b/src/jolt/png.janet deleted file mode 100644 index de45943..0000000 --- a/src/jolt/png.janet +++ /dev/null @@ -1,104 +0,0 @@ -# Minimal PNG encoder (the host side of `jolt.png`). 8-bit truecolour RGB -# (colour type 2), no interlace, filter 0 (None), and STORED (uncompressed) -# DEFLATE blocks — a valid zlib stream that needs no compressor. Files are larger -# than a compressed PNG but decode everywhere. -# -# Lives in Janet, not Clojure: jolt's per-op cost makes per-byte work (CRC32 over -# every byte) impractical in the overlay, so the whole encode runs here natively -# and jolt calls `write` once with a raw-RGB buffer. Exposed to jolt as -# `janet.png/...` via eval_base's module-load-env (see eval_base.janet). -# -# Janet's bit ops are 32-bit SIGNED (0xFFFFFFFF overflows), so the 32-bit -# unsigned arithmetic of CRC32/Adler32 is done with plain number ops (doubles -# hold 2^32 exactly) plus byte-level bxor, whose operands are always 0..255. - -(defn- u8 [v] (% v 256)) # low byte -(defn- shr [v n] (math/floor (/ v n))) # logical shift-right by a power of two - -# 32-bit xor via 4 byte-wise xors (each operand 0..255, safely in 32-bit range). -(defn- xor32 [a b] - (var r 0) - (var m 1) - (for i 0 4 - (set r (+ r (* (bxor (% (shr a m) 256) (% (shr b m) 256)) m))) - (set m (* m 256))) - r) - -(def- crc-table - (let [t (array/new-filled 256 0)] - (for n 0 256 - (var c n) - (for _ 0 8 - (set c (if (= 1 (% c 2)) (xor32 0xEDB88320 (shr c 2)) (shr c 2)))) - (put t n c)) - t)) - -(defn- crc32 [buf] - (var c 0xFFFFFFFF) - (def n (length buf)) - (for i 0 n - (set c (xor32 (get crc-table (bxor (% c 256) (get buf i))) (shr c 256)))) - (- 0xFFFFFFFF c)) # final xor with all-ones = complement - -(defn- adler32 [buf] - (var a 1) - (var b 0) - (def n (length buf)) - (for i 0 n - (set a (% (+ a (get buf i)) 65521)) - (set b (% (+ b a) 65521))) - (+ (* b 65536) a)) - -(defn- push-u32be [out v] - (buffer/push-byte out (% (shr v 16777216) 256) (% (shr v 65536) 256) - (% (shr v 256) 256) (% v 256))) - -(defn- push-chunk [out typ data] - (push-u32be out (length data)) - (def tagged (buffer typ data)) # CRC covers type + data - (buffer/push-string out tagged) - (push-u32be out (crc32 tagged))) - -# zlib stream of `raw` as stored DEFLATE blocks (<=65535 bytes each). -(defn- zlib-store [raw] - (def out (buffer/new (+ (length raw) 64))) - (buffer/push-byte out 0x78 0x01) # zlib header: CM=8 CINFO=7, FCHECK ok - (def n (length raw)) - (var pos 0) - (while (< pos n) - (def len (min 65535 (- n pos))) - (def final (if (>= (+ pos len) n) 1 0)) - (def nlen (- 65535 len)) # one's-complement of len in 16 bits - (buffer/push-byte out final (% len 256) (shr len 256) (% nlen 256) (shr nlen 256)) - (buffer/push-string out (buffer/slice raw pos (+ pos len))) - (set pos (+ pos len))) - (push-u32be out (adler32 raw)) - out) - -(defn encode - "Encode a w*h*3 raw-RGB buffer (row-major, top row first) as a PNG buffer." - [w h rgb] - (assert (= (length rgb) (* w h 3)) "png/encode: rgb length != w*h*3") - (def out (buffer/new (+ 64 (* w h 3)))) - (buffer/push-string out "\x89PNG\r\n\x1a\n") - (def ihdr (buffer/new 13)) - (push-u32be ihdr w) - (push-u32be ihdr h) - (buffer/push-byte ihdr 8 2 0 0 0) # bit depth 8, colour type 2 (RGB), … - (push-chunk out "IHDR" ihdr) - # scanlines, each prefixed with filter byte 0 (None) - (def stride (* w 3)) - (def raw (buffer/new (* h (+ 1 stride)))) - (for y 0 h - (buffer/push-byte raw 0) - (def off (* y stride)) - (buffer/push-string raw (buffer/slice rgb off (+ off stride)))) - (push-chunk out "IDAT" (zlib-store raw)) - (push-chunk out "IEND" (buffer/new 0)) - out) - -(defn write - "Encode and write a w*h*3 raw-RGB buffer to `path` as a PNG." - [path w h rgb] - (spit path (encode w h rgb)) - path) diff --git a/src/jolt/pv.janet b/src/jolt/pv.janet deleted file mode 100644 index e4f43d4..0000000 --- a/src/jolt/pv.janet +++ /dev/null @@ -1,189 +0,0 @@ -# Persistent vector — a 32-way branching trie with a tail buffer, modeled on -# Clojure's PersistentVector. Immutable: every update returns a new vector that -# structurally shares unchanged subtrees with the old one, so conj/assoc/pop are -# O(log32 n) and share memory instead of copying the whole vector. -# -# Layout: -# @{:jolt/type :jolt/pvec -# :cnt n number of elements -# :shift s bits to shift the index for the root level (5 * depth) -# :root node trie root: a tuple of up to 32 children -# :tail tail} a tuple of up to 32 trailing elements (append fast-path) -# -# Trie nodes are immutable tuples so unchanged subtrees are shared by identity. -# -# REP vs API: this file is ONLY the trie representation (pv-* primitives). The -# Clojure-facing vector ops (nth/conj/assoc/subvec, the count/seq/first/rest -# dispatch, and tuple↔pvec polymorphism) live in core_coll.janet / -# core_types.janet, which dispatch on `:jolt/type :jolt/pvec`. - -(def- bits 5) -(def- width 32) # 2^bits -(def- mask 31) # width - 1 - -(def empty-node []) - -(defn pvec? [x] - (and (table? x) (= :jolt/pvec (get x :jolt/type)))) - -(defn make-pv [cnt shift root tail] - @{:jolt/type :jolt/pvec :cnt cnt :shift shift :root root :tail tail}) - -(def EMPTY (make-pv 0 bits empty-node [])) - -(defn pv-count [pv] (get pv :cnt)) - -# Index of the first element held in the tail (everything before lives in the trie). -(defn- tail-offset [cnt] - (if (< cnt width) 0 (blshift (brshift (- cnt 1) bits) bits))) - -# Return the 32-element leaf array containing index i. -(defn- leaf-for [pv i] - (if (>= i (tail-offset (get pv :cnt))) - (get pv :tail) - (do - (var node (get pv :root)) - (var level (get pv :shift)) - (while (> level 0) - (set node (get node (band (brshift i level) mask))) - (set level (- level bits))) - node))) - -(defn pv-nth [pv i &opt dflt] - (if (and (>= i 0) (< i (get pv :cnt))) - (get (leaf-for pv i) (band i mask)) - dflt)) - -# --- conj ------------------------------------------------------------------- - -# Push the full tail down into the trie, returning a new root node array. -(defn- push-tail [level parent tail cnt] - (def sub-idx (band (brshift (- cnt 1) level) mask)) - (def child - (if (= level bits) - tail - (let [c (get parent sub-idx)] - (if c - (push-tail (- level bits) c tail cnt) - (push-tail (- level bits) empty-node tail cnt))))) - (def arr (array/slice parent)) - (put arr sub-idx child) - (tuple/slice arr)) - -(defn pv-conj [pv val] - (def cnt (get pv :cnt)) - (def tail (get pv :tail)) - (if (< (length tail) width) - # Room in the tail: just append to it. - (make-pv (+ cnt 1) (get pv :shift) - (get pv :root) - (tuple/slice (tuple ;tail val))) - # Tail is full: push it into the trie, start a fresh tail with val. - (let [shift (get pv :shift) - root (get pv :root)] - (if (> (brshift cnt bits) (blshift 1 shift)) - # Root overflow: grow the trie one level taller. - (let [new-root (tuple root (push-tail shift empty-node tail cnt))] - (make-pv (+ cnt 1) (+ shift bits) new-root [val])) - (make-pv (+ cnt 1) shift (push-tail shift root tail cnt) [val]))))) - -# --- assoc ------------------------------------------------------------------ - -(defn- assoc-in-node [level node i val] - (def arr (array/slice node)) - (if (= level 0) - (put arr (band i mask) val) - (let [sub-idx (band (brshift i level) mask)] - (put arr sub-idx (assoc-in-node (- level bits) (get node sub-idx) i val)))) - (tuple/slice arr)) - -(defn pv-assoc [pv i val] - (def cnt (get pv :cnt)) - (cond - (= i cnt) (pv-conj pv val) - (and (>= i 0) (< i cnt)) - (if (>= i (tail-offset cnt)) - (let [tail (array/slice (get pv :tail))] - (put tail (band i mask) val) - (make-pv cnt (get pv :shift) (get pv :root) (tuple/slice tail))) - (make-pv cnt (get pv :shift) - (assoc-in-node (get pv :shift) (get pv :root) i val) - (get pv :tail))) - (error (string "Index " i " out of bounds for vector of length " cnt)))) - -# --- pop -------------------------------------------------------------------- - -(defn- pop-tail [level node cnt] - (def sub-idx (band (brshift (- cnt 2) level) mask)) - (cond - (> level bits) - (let [child (pop-tail (- level bits) (get node sub-idx) cnt)] - (if (and (nil? child) (= sub-idx 0)) - nil - (let [arr (array/slice node)] (put arr sub-idx child) (tuple/slice arr)))) - (= sub-idx 0) nil - (let [arr (array/slice node)] (put arr sub-idx nil) (tuple/slice arr)))) - -(defn pv-pop [pv] - (def cnt (get pv :cnt)) - (cond - (= cnt 0) (error "Can't pop empty vector") - (= cnt 1) EMPTY - (> (- cnt (tail-offset cnt)) 1) - # More than one element in the tail: drop the last tail element. - (let [tail (get pv :tail)] - (make-pv (- cnt 1) (get pv :shift) (get pv :root) - (tuple/slice tail 0 (- (length tail) 1)))) - # Tail has one element: the new tail is the last leaf of the trie. - (let [shift (get pv :shift) - new-tail (leaf-for pv (- cnt 2)) - new-root-raw (pop-tail shift (get pv :root) cnt) - new-root (if (nil? new-root-raw) empty-node new-root-raw)] - (if (and (> shift bits) (nil? (get new-root 1))) - # Trie lost a level: promote the single remaining child to root. - (make-pv (- cnt 1) (- shift bits) (get new-root 0) new-tail) - (make-pv (- cnt 1) shift new-root new-tail))))) - -# --- conversions ------------------------------------------------------------ - -(defn pv->array [pv] - (def out @[]) - (def cnt (get pv :cnt)) - (var i 0) - (while (< i cnt) - (array/push out (pv-nth pv i)) - (++ i)) - out) - -(defn pv-from-indexed [xs] - # Build a pvec from any Janet-indexed collection (tuple/array) by constructing - # the trie BOTTOM-UP in one pass, instead of n incremental pv-conj calls (each - # of which allocated a pv wrapper and copied the tail). The structure produced - # is identical to the incremental one — tail-offset(n) = ((n-1)>>5)<<5 is - # exactly the trie/tail split, so leaf-for/nth/conj/assoc all read it the same. - # This is the bulk path behind vec/mapv/into-a-vector (jolt-5vsp collections). - (def n (length xs)) - (if (<= n width) - # everything fits in the tail (matches EMPTY's shift) - (make-pv n bits empty-node (tuple/slice xs)) - (let [tail-len (+ 1 (mod (- n 1) width)) - trie-count (- n tail-len) # = tail-offset(n), a multiple of width - tail (tuple/slice xs trie-count n)] - # value leaves: full 32-element tuples over [0, trie-count) - (def leaves @[]) - (var i 0) - (while (< i trie-count) - (array/push leaves (tuple/slice xs i (+ i width))) - (set i (+ i width))) - # group nodes 32-wide, bottom-up, until <=32 remain; that becomes the root - (var level leaves) - (var shift bits) - (while (> (length level) width) - (def parent @[]) - (var j 0) - (while (< j (length level)) - (array/push parent (tuple/slice level j (min (length level) (+ j width)))) - (set j (+ j width))) - (set level parent) - (set shift (+ shift bits))) - (make-pv n shift (tuple/slice level) tail)))) diff --git a/src/jolt/reader.janet b/src/jolt/reader.janet deleted file mode 100644 index bb26d1f..0000000 --- a/src/jolt/reader.janet +++ /dev/null @@ -1,831 +0,0 @@ -# Jolt Clojure Reader -# Recursive descent parser for Clojure source text. -# Output convention: -# Symbols foo, foo/bar → {:jolt/type :symbol :ns "foo" :name "bar"} -# Keywords :foo, :foo/bar → Janet keyword :foo, :foo/bar -# Lists (a b c) → Janet array @[a b c] -# Vectors [a b c] → Janet tuple [a b c] -# Maps {:a 1} → Janet struct {:a 1} -# Sets #{1 2} → tagged struct {:jolt/type :jolt/set :value [1 2]} - -(use ./types) -(import ./phm :as phm) - -# Forward declaration for mutual recursion -(var read-form nil) -(var read-meta nil) # forward decl: read-dispatch (#^) calls it before its defn below - -# Source-position tracking for the success checker (jolt-fqy). When enabled, the -# reader records each LIST form's absolute start offset (lists are the forms that -# become :invoke nodes — what the checker reports on). Off by default: a flag -# check per list is the only cost when the checker isn't running. Keyed by form -# IDENTITY (lists are fresh arrays, never interned), so a position survives -# macroexpansion exactly when the user's own sub-form is spliced through, and is -# absent for macro-synthesized structure — which is what we want (fall back to -# the call site). Not cleared between parses: nested parses (a require mid-load) -# would otherwise drop an outer file's positions; the table is bounded by forms -# compiled this process and only populated when the checker is on. -(def form-pos-table @{}) -(var track-positions false) -(var pos-base 0) # absolute offset of the slice read-form currently sees - -(defn track-positions! - "Enable/disable list-form position recording (jolt-fqy)." - [on] (set track-positions on)) - -(defn set-pos-base! - "Tell the reader the absolute offset of the slice it is about to read, so - recorded list positions are absolute (parse-all-positioned reads a shrinking - remainder)." - [b] (set pos-base b)) - -(defn form-pos - "Absolute start offset recorded for a list form, or nil." - [form] (get form-pos-table form)) - -(defn checker-enabled? - "True when JOLT_TYPE_CHECK selects a non-off level — the loaders use this to - decide whether to record form positions for the checker (jolt-fqy)." - [] - (def tc (os/getenv "JOLT_TYPE_CHECK")) - (if (and tc (not= tc "off") (not= tc "0")) true false)) - -(def whitespace-chars " \t\n\r,") - -(defn whitespace? [c] - (or (= c 32) # space - (= c 10) # \n - (= c 9) # \t - (= c 13) # \r - (= c 44))) # comma - -# Reader errors carry the raw byte OFFSET; the parse entry points (parse-string, -# parse-all-positioned) convert offset -> line:col against the full source and -# re-raise Clojure's 'Syntax error reading source at (file:line:col): msg' -# shape. Raising structured here keeps the 15 error sites one-liners. -# (jolt-2o7.5) -(defn- reader-error [msg pos] - (error {:jolt/type :jolt/reader-error :msg msg :pos pos})) - -(defn line-col - "1-based [line col] of byte offset in source." - [source offset] - (var line 1) - (var bol 0) - (def stop (min offset (length source))) - (loop [i :range [0 stop]] - (when (= (in source i) (chr "\n")) (++ line) (set bol (+ i 1)))) - [line (+ 1 (- stop bol))]) - -(defn format-reader-error - "Clojure-shaped syntax error message for a reader-error struct raised - against source; file may be nil (omitted)." - [e source file] - (def [l c] (line-col source (e :pos))) - (if file - (string "Syntax error reading source at (" file ":" l ":" c "): " (e :msg)) - (string "Syntax error reading source at (" l ":" c "): " (e :msg)))) - -(defn reader-error? [e] - (and (struct? e) (= :jolt/reader-error (e :jolt/type)))) - -(defn skip-whitespace [s pos] - (if (and (< pos (length s)) - (whitespace? (s pos))) - (skip-whitespace s (+ pos 1)) - pos)) - -(defn digit? [c] - (and (>= c 48) (<= c 57))) - -(defn hex-digit? [c] - (or (and (>= c 48) (<= c 57)) - (and (>= c 65) (<= c 70)) - (and (>= c 97) (<= c 102)))) - -(defn symbol-start? [c] - (or (and (>= c 65) (<= c 90)) # A-Z - (and (>= c 97) (<= c 122)) # a-z - (= c 42) # * - (= c 43) # + - (= c 33) # ! - (= c 95) # _ - (= c 45) # - - (= c 63) # ? - (= c 46) # . - (= c 60) # < - (= c 62) # > - (= c 61) # = - (= c 38) # & - (= c 124) # | - (= c 36) # $ - (= c 37) # % - (= c 47))) # / - -(defn symbol-char? [c] - (or (symbol-start? c) - (digit? c) - (= c 35) # # - (= c 39) # ' - (= c 58))) # : - -(defn read-symbol-name [s pos end] - (if (and (< end (length s)) - (symbol-char? (s end))) - (read-symbol-name s pos (+ end 1)) - end)) - -(defn make-symbol - "Create a Jolt symbol struct." - [name] - (let [slash (string/find "/" name)] - (if (and slash (> slash 0)) - {:jolt/type :symbol - :ns (string/slice name 0 slash) - :name (string/slice name (+ slash 1))} - {:jolt/type :symbol - :ns nil - :name name}))) - -(defn sym - "Convenience to create a symbol during testing." - [name] - (make-symbol name)) - -(defn read-symbol [s pos] - (let [end (read-symbol-name s pos pos)] - (if (= end pos) - (reader-error (string "Unrecognized character: " (string/from-bytes (s pos))) pos) - (let [name (string/slice s pos end)] - (if (= name "nil") [nil end] - (if (= name "true") [true end] - (if (= name "false") [false end] - [(make-symbol name) end]))))))) - -(defn read-keyword-name [s pos end] - (if (and (< end (length s)) - (symbol-char? (s end))) - (read-keyword-name s pos (+ end 1)) - end)) - -(defn read-keyword [s pos] - # pos is at the first colon - (if (and (< (+ pos 1) (length s)) (= (s (+ pos 1)) 58)) - # ::foo/bar — auto-resolved keyword - (let [start (+ pos 2) - end (read-keyword-name s start start) - name (string/slice s start end)] - [(keyword name) end]) - # :foo or :foo/bar - (let [start (+ pos 1) - end (read-keyword-name s start start) - name (string/slice s start end)] - [(keyword name) end]))) - -(defn escape-char [c] - (if (= c 110) "\n" - (if (= c 116) "\t" - (if (= c 114) "\r" - (if (= c 92) "\\" - (if (= c 34) "\"" - (string/from-bytes c))))))) - -(defn read-string-chars [s pos end chars] - (if (>= pos end) - (reader-error "Unterminated string" pos) - (let [c (s pos)] - (if (= c 92) # backslash - (let [next-pos (+ pos 1)] - (if (>= next-pos end) - (reader-error "Unterminated escape" pos) - (read-string-chars s (+ pos 2) end - (array/push chars (escape-char (s next-pos)))))) - (if (= c 34) # closing quote - [pos chars] - (read-string-chars s (+ pos 1) end - (array/push chars (string/from-bytes c)))))))) - -(defn read-string [s pos] - # pos is at opening double-quote - (let [end (length s) - [new-pos chars] (read-string-chars s (+ pos 1) end @[])] - [(string/join chars "") (+ new-pos 1)])) - -(defn read-hex-digits [s pos end] - (if (and (< end (length s)) (hex-digit? (s end))) - (read-hex-digits s pos (+ end 1)) - end)) - -(defn read-digits [s pos end] - (if (and (< end (length s)) (digit? (s end))) - (read-digits s pos (+ end 1)) - end)) - -(defn read-fractional [s pos end] - (if (and (< end (length s)) (digit? (s end))) - (read-fractional s pos (+ end 1)) - end)) - -# Value of an alphanumeric digit for radix parsing (0-9, a-z/A-Z = 10-35). -(defn- radix-digit-val [c] - (cond - (and (>= c 48) (<= c 57)) (- c 48) # 0-9 - (and (>= c 97) (<= c 122)) (+ 10 (- c 97)) # a-z - (and (>= c 65) (<= c 90)) (+ 10 (- c 65)) # A-Z - nil)) -(defn- read-alnum [s pos end] - (if (and (< end (length s)) (not (nil? (radix-digit-val (s end))))) - (read-alnum s pos (+ end 1)) - end)) -(defn- read-exponent - "If s[end] is e/E (optionally with sign) followed by digits, return the index - past the exponent; else end." - [s end] - (let [len (length s)] - (if (and (< end len) (or (= (s end) 101) (= (s end) 69))) # e / E - (let [p (if (and (< (+ end 1) len) (or (= (s (+ end 1)) 43) (= (s (+ end 1)) 45))) (+ end 2) (+ end 1)) - de (read-digits s p p)] - (if (> de p) de end)) - end))) - -# Jolt has no true bignum/ratio types (see README): an integer/float literal -# suffixed N (bigint) or M (bigdec) reads as the plain number, a ratio a/b reads -# as the double quotient, and radixed integers (2r101, 16rFF) are parsed by base. -(defn read-number [s pos] - (var start pos) # start is mutable for sign handling - (var neg false) - (def len (length s)) - # optional sign - (if (and (< pos len) (= (s pos) 45)) - (do (set start (+ pos 1)) (set neg true))) - - (let [pos start - hex? (and (< (+ pos 1) len) - (= (s pos) 48) (or (= (s (+ pos 1)) 120) (= (s (+ pos 1)) 88)))] # 0x / 0X - (if hex? - (let [hs (+ pos 2) he (read-hex-digits s hs hs)] - (if (= he hs) (reader-error "Expected hex digits" pos)) - (let [he2 (if (and (< he len) (= (s he) 78)) (+ he 1) he) # trailing N - val (scan-number (string "0x" (string/slice s hs he)))] - [(if neg (- val) val) he2])) - (let [iend (read-digits s pos pos)] - (if (= iend pos) (reader-error "Expected number" pos)) - (cond - # radix integer: r, e.g. 2r1010, 16rFF, 36rZ - (and (< iend len) (or (= (s iend) 114) (= (s iend) 82))) - (let [base (scan-number (string/slice s pos iend)) - ds (+ iend 1) - de (read-alnum s ds ds)] - (if (= de ds) (reader-error "Expected radix digits" ds)) - (var acc 0) - (var i ds) - (while (< i de) (set acc (+ (* acc base) (radix-digit-val (s i)))) (++ i)) - [(if neg (- acc) acc) de]) - # ratio: / (only when a digit follows the slash) - (and (< (+ iend 1) len) (= (s iend) 47) (digit? (s (+ iend 1)))) - (let [ds (+ iend 1) de (read-digits s ds ds) - numr (scan-number (string/slice s pos iend)) - den (scan-number (string/slice s ds de))] - [(if neg (- (/ numr den)) (/ numr den)) de]) - # fractional and/or exponent, optional trailing N/M - (let [frac-end (if (and (< iend len) (= (s iend) 46)) - (let [fs (+ iend 1) fe (read-fractional s fs fs)] - (if (= fe fs) (error "Expected digit after .")) fe) - iend) - exp-end (read-exponent s frac-end) - val (scan-number (string/slice s start exp-end)) - # consume a trailing N (bigint) or M (bigdec) suffix - fin (if (and (< exp-end len) (or (= (s exp-end) 78) (= (s exp-end) 77))) - (+ exp-end 1) exp-end)] - [(if neg (- val) val) fin])))))) - -# Read forms until `close` (a byte), returning [items end-pos]. Shared by the -# list/vector/set readers: skip #_ discards and splice #?@ items uniformly, so the -# skip/splice handling can't drift between them (it did once). The map reader -# keeps its own loop — its key/value pairing needs a different value-slot scan. -(defn read-delimited [s start-pos close err] - (defn read-items [s pos items] - (let [pos (skip-whitespace s pos)] - (if (>= pos (length s)) - (reader-error err pos)) - (if (= (s pos) close) - [items (+ pos 1)] - (let [[form new-pos] (read-form s pos)] - # skip #_ discarded forms - (if (and (struct? form) (= :jolt/skip (form :jolt/type))) - (read-items s new-pos items) - # splice #?@ items into the collection - (if (and (struct? form) (= :jolt/splice (form :jolt/type))) - (read-items s new-pos (array/concat items (form :items))) - (read-items s new-pos (array/push items form)))))))) - (read-items s start-pos @[])) - -(defn read-list [s pos] - # pos is at opening paren - (read-delimited s (+ pos 1) 41 "Unterminated list")) # ) - -(defn read-vector [s pos] - # pos is at opening bracket - (let [[items end] (read-delimited s (+ pos 1) 93 "Unterminated vector")] # ] - [(tuple/slice (tuple ;items)) end])) - -# A map-literal form. Janet structs drop nil keys/values, so when a key or value -# is nil (e.g. {:a nil}) build a phm — it preserves nil, matching Clojure. The -# common nil-free case stays a struct: fast, and what the downstream map-form -# handling (evaluator/analyzer) already expects. Collection keys are left to -# eval-time construction (build-map-literal/eval-form), which phm-ifies them. -(defn- reader-map [kvs] - (var has-nil false) (var i 0) - (while (< i (length kvs)) (when (nil? (in kvs i)) (set has-nil true) (break)) (++ i)) - # Source order rides along out-of-band (jolt-p3c): struct iteration is hash - # order, but Clojure evaluates literal entries left to right. A struct - # PROTOTYPE carries it without changing the form's map behavior (keys/kvs/ - # length ignore protos; jolt-equal? compares maps structurally); the phm rep - # (nil key/value present) gets a plain extra field. - (if has-nil - (let [m (phm/make-phm kvs)] - (put m :jolt/kv-order (tuple/slice kvs)) - m) - (struct/with-proto (struct :jolt/kv-order (tuple/slice kvs)) ;kvs))) - -(defn form-kv-order - "Source-ordered [k v k v ...] tuple of a map FORM (nil for maps built at - runtime, which carry no reader order)." - [form] - (cond - (struct? form) (get (struct/getproto form) :jolt/kv-order) - (table? form) (get form :jolt/kv-order))) - -(defn read-map [s pos] - # pos is at opening brace - (defn read-kvs [s pos kvs] - (let [pos (skip-whitespace s pos)] - (if (>= pos (length s)) - (reader-error "Unterminated map" pos)) - (if (= (s pos) 125) # } - [(reader-map kvs) (+ pos 1)] - (let [[key new-pos] (read-form s pos)] - (if (and (struct? key) (= :jolt/skip (key :jolt/type))) - (read-kvs s new-pos kvs) - (if (and (struct? key) (= :jolt/splice (key :jolt/type))) - (read-kvs s new-pos (array/concat kvs (key :items))) - (let [pos (skip-whitespace s new-pos) - # The VALUE slot must skip comments/#_ while KEEPING the - # pending key: dropping both (the old behavior) desynced - # the kv pairing — {:a ; comment\n 1} read 1 as the next - # KEY and the closing } landed in value position - # ("Unmatched closing brace", jolt-ou8 / Selmer deps.edn). - [val new-pos2] - (do - (var vp pos) - (var v nil) - (var looking true) - (while looking - (def [f np] (read-form s vp)) - (set vp np) - (if (and (struct? f) (= :jolt/skip (f :jolt/type))) - (set vp (skip-whitespace s np)) - (do (set v f) (set looking false)))) - [v vp])] - (if (and (struct? val) (= :jolt/splice (val :jolt/type))) - # Only push key if splice contributes items - (if (> (length (val :items)) 0) - (do (array/push kvs key) (read-kvs s new-pos2 (array/concat kvs (val :items)))) - (read-kvs s new-pos2 kvs)) - (read-kvs s new-pos2 (-> kvs (array/push key) (array/push val))))))))))) - (read-kvs s (+ pos 1) @[])) - -(defn read-set [s pos] - # pos is at #, next char is { - (let [[items end] (read-delimited s (+ pos 2) 125 "Unterminated set")] # } - [{:jolt/type :jolt/set :value (tuple/slice (tuple ;items))} end])) - -(defn read-char-name-end [s pos] - (if (and (< pos (length s)) (symbol-char? (s pos))) - (read-char-name-end s (+ pos 1)) - pos)) - -(defn read-char [s pos] - # pos is at backslash; produce a char value directly (self-evaluating) - (when (>= (+ pos 1) (length s)) - (error "unexpected end of input after \\")) - (let [end (read-char-name-end s (+ pos 1))] - (if (= end (+ pos 1)) - # The char right after \ isn't a symbol char (e.g. \{ \( \, \% \" ): it's a - # one-character literal of that character itself. - [(make-char (s (+ pos 1))) (+ pos 2)] - (let [char-name (string/slice s (+ pos 1) end)] - [(char-from-name char-name) end])))) - -(defn read-anon-fn [s pos] - # pos is at #, next char is ( - (let [[form new-pos] (read-form s (+ pos 1))] - # Positional index of a %-symbol name: % and %1 are both 1, %N is N, %& is the - # rest param (:rest); anything else is not a positional (nil). The fixed arity - # is the MAX index used (Clojure semantics: #(do %2 %&) -> [p1 p2 & rest], so - # unused lower positions still get a placeholder param and %& starts after %2). - (defn- pct-index [nm] - (cond - (= nm "%") 1 - (= nm "%&") :rest - (and (> (length nm) 1) (= "%" (string/slice nm 0 1))) - (let [n (scan-number (string/slice nm 1))] - (if (and n (= n (math/floor n)) (>= n 1)) n nil)) - nil)) - # Pass 1: max positional index + whether %& is used. - (var max-n 0) - (var has-rest false) - (defn- scan-pct [f] - (cond - (and (struct? f) (= :symbol (f :jolt/type))) - (let [i (pct-index (f :name))] - (cond (= i :rest) (set has-rest true) - (and i (> i max-n)) (set max-n i))) - (or (array? f) (tuple? f)) (each x f (scan-pct x)) - # set literal form — scan its elements (#(... #{%} ...)) - (and (struct? f) (= :jolt/set (f :jolt/type))) (each x (f :value) (scan-pct x)) - # map literal form — scan its keys AND values (#(... {:k %} ...)) - (not (nil? (form-kv-order f))) (each x (form-kv-order f) (scan-pct x)) - nil)) - (scan-pct form) - # One canonical gensym per slot 1..max-n (placeholders for unused), plus rest. - # Param names carry a trailing `#` (auto-gensym suffix, matching Clojure's - # `p1__N#`) so a #() written inside a syntax-quote survives: sq-symbol treats - # `#`-suffixed names as auto-gensyms (mapped consistently, left unqualified) - # rather than qualifying them to the current ns — a qualified symbol is not a - # valid fn param. Harmless outside a backtick (just a regular symbol name). - (def slot-syms @{}) - (var i 1) - (while (<= i max-n) (put slot-syms i (sym (string (gensym) "#"))) (++ i)) - (def rest-sym (if has-rest (sym (string (gensym) "#")) nil)) - # Pass 2: replace each %-symbol with its slot's gensym. - (defn- replace-pct [f] - (cond - (and (struct? f) (= :symbol (f :jolt/type))) - (let [idx (pct-index (f :name))] - (cond (= idx :rest) rest-sym - idx (get slot-syms idx) - f)) - (array? f) (array ;(map replace-pct f)) - (tuple? f) (tuple ;(map replace-pct f)) - (and (struct? f) (= :jolt/set (f :jolt/type))) - {:jolt/type :jolt/set :value (tuple ;(map replace-pct (f :value)))} - (not (nil? (form-kv-order f))) - (reader-map (array ;(map replace-pct (form-kv-order f)))) - f)) - (def replaced (replace-pct form)) - (def arg-names @[]) - (set i 1) - (while (<= i max-n) (array/push arg-names (get slot-syms i)) (++ i)) - (when has-rest - (array/push arg-names (sym "&")) - (array/push arg-names rest-sym)) - [@[(sym "fn*") (tuple ;arg-names) replaced] new-pos])) - -# The reader-conditional feature set (spec 02-reader S18): jolt is its own -# dialect, so the portable convention applies — the dialect key plus :default. -# Matching is by CLAUSE order (the first clause whose key is in the feature -# set wins), exactly like Clojure — NOT key-priority. JOLT_FEATURES overrides -# (comma-separated, e.g. "jolt,clj,default") for compat experiments and A/B -# measurement; :default is always honored. -# Mutable so a loading context can opt a clj-targeted foreign library into -# :clj compatibility (e.g. SCI) — see reader-features-set!. jolt itself and -# the conformance surface read under the portable set. -(var reader-features nil) - -(defn reader-features-set! - "Replace the active reader-conditional feature set (a list of keyword-name - strings or keywords). :default is always honored. Returns the previous set - so callers can restore." - [names] - (def prev reader-features) - (def t @{}) - (each n names (put t (if (keyword? n) n (keyword n)) true)) - (put t :default true) - (set reader-features t) - prev) - -(reader-features-set! - (let [env (os/getenv "JOLT_FEATURES")] - (if env (filter |(> (length $) 0) (string/split "," env)) - ["jolt" "default"]))) - -(defn read-reader-conditional [s pos] - # pos is at #, next char is ? or ?@ - (def splice? (and (< (+ pos 2) (length s)) (= (s (+ pos 2)) 64))) # @ = 64 - (def form-start (if splice? (+ pos 3) (+ pos 2))) - (let [[form new-pos] (read-form s form-start)] - (if (array? form) - (do - # First clause (in clause order) whose feature key is in the set. - # `matched` is tracked separately: a matched clause may be nil. - (var result nil) - (var matched false) - (var i 0) - (while (and (not matched) (< i (length form))) - (when (get reader-features (in form i)) - (set result (in form (+ i 1))) - (set matched true)) - (+= i 2)) - (if splice? - # #?@ splicing: resolve :clj branch, wrap for splice - (let [items (if (nil? result) - @[] - (if (or (array? result) (tuple? result)) - result - @[result]))] - [{:jolt/type :jolt/splice :items items} new-pos]) - # #? non-splicing: skip nil results (from :cljs branches on CLJ) - (if (nil? result) - [{:jolt/type :jolt/skip} new-pos] - [result new-pos]))) - [{:jolt/type :jolt/reader-conditional :clauses form} new-pos]))) - -(defn read-var-quote [s pos] - # pos is at #, next char is ' - (let [[form new-pos] (read-form s (+ pos 2))] - [(array (sym "var") form) new-pos])) - -(defn read-regex [s pos] - # pos is at #, next char is " - # Read until unescaped closing " - (var i (+ pos 2)) - (var done nil) - (while (and (< i (length s)) (not done)) - (if (= (s i) 92) # backslash — skip next char - (+= i 2) - (if (= (s i) 34) # closing quote - (set done [(struct ;[:jolt/type :jolt/tagged :tag :regex :form (string/slice s (+ pos 2) i)]) - (+ i 1)]) - (++ i)))) - (if done done (reader-error "Unterminated regex literal" pos))) - -(defn read-dispatch [s pos] - # pos is at # - (if (>= (+ pos 1) (length s)) - (error "Unexpected end after #")) - (let [c (s (+ pos 1))] - (cond - (= c 123) (read-set s pos) # #{ - (= c 40) (read-anon-fn s pos) # #( - (= c 63) (read-reader-conditional s pos) # #? - (= c 95) (let [[_ new-pos] (read-form s (+ pos 2))] # #_ - [{:jolt/type :jolt/skip} new-pos]) - (= c 39) (read-var-quote s pos) # #' - (= c 94) (read-meta s (+ pos 1)) # #^ — deprecated metadata reader macro (= ^) - (= c 34) (read-regex s pos) # #"regex - (= c 35) # ## symbolic value: ##Inf ##-Inf ##NaN - (let [end (read-symbol-name s (+ pos 2) (+ pos 2)) - name (string/slice s (+ pos 2) end)] - (cond - (= name "Inf") [math/inf end] - (= name "-Inf") [(- math/inf) end] - (= name "NaN") [math/nan end] - (reader-error (string "Invalid symbolic value: ##" name) pos))) - # unknown dispatch — tagged literal - (let [end (read-symbol-name s pos pos) - tag (string/slice s pos end) - [form new-pos] (read-form s end)] - [{:jolt/type :jolt/tagged :tag (keyword tag) :form form} new-pos])))) - -(defn- self-evaluating-literal? - "True for forms syntax-quote passes through unchanged: strings, numbers, - booleans, nil, keywords, and character literals. NOT symbols (they qualify) - or collections (they template)." - [form] - (or (nil? form) (= true form) (= false form) (number? form) - (string? form) (buffer? form) (keyword? form) - (and (struct? form) (= :jolt/char (form :jolt/type))))) - -(defn read-quote [s new-pos token-sym] - (let [[form final-pos] (read-form s new-pos)] - # Spec 02-reader S25: syntax-quote of a self-evaluating literal is the - # literal, collapsed at READ time (matching Clojure's reader) — so nested - # backticks over literals are inert: ```"meow" reads as "meow". - (if (and (= "syntax-quote" (token-sym :name)) (self-evaluating-literal? form)) - [form final-pos] - [(array token-sym form) final-pos]))) - -(defn- meta-form->map - "Normalize a metadata reader form (Clojure semantics): a symbol or string is a - :tag, a keyword is {kw true}. Returns a metadata table, or nil if it isn't one - of those simple shapes (e.g. a map literal — handled via with-meta instead)." - [meta-form] - (cond - (keyword? meta-form) {meta-form true} - # A symbol tag keeps its namespace qualifier (^t/Ray -> "t/Ray", not "Ray") so - # an aliased/qualified record hint resolves through the ns's aliases the same - # way a bare referred one does; dropping it silently mis-hinted across - # namespaces. Bare symbols (^Ray, ^String) are unchanged. - (and (struct? meta-form) (= :symbol (meta-form :jolt/type))) - {:tag (if (meta-form :ns) - (string (meta-form :ns) "/" (meta-form :name)) - (meta-form :name))} - (string? meta-form) {:tag meta-form} - nil)) - -(set read-meta (fn read-meta [s pos] - # pos is at ^ - (let [[meta-form new-pos] (read-form s (+ pos 1)) - [form new-pos2] (read-form s new-pos) - m (meta-form->map meta-form)] - (if (and m (struct? form) (= :symbol (form :jolt/type))) - # Attach the metadata to the symbol itself and keep it a bare symbol, so - # type hints (^String x) and ^:dynamic etc. are transparent in every - # position (params, lets, bodies) — the evaluator reads :name and ignores - # :meta. This is what makes type hints "parse and otherwise do nothing". - [(struct ;(kvs form) :meta (merge (or (form :meta) {}) m)) new-pos2] - # Non-symbol targets (collections etc.) keep a runtime with-meta form. Use the - # NORMALIZED metadata map (:kw -> {:kw true}, tag -> {:tag …}); a map-literal - # meta-form (m is nil) is already a map, so pass it through. - [(array (sym "with-meta") form (if m m meta-form)) new-pos2])))) - -(defn read-until-newline [s pos] - (if (or (>= pos (length s)) (= (s pos) 10)) - pos - (read-until-newline s (+ pos 1)))) - -(set read-form (fn [s pos] - (let [pos (skip-whitespace s pos)] - (if (>= pos (length s)) - [nil pos] - (let [c (s pos)] - (cond - # comment - (= c 59) - (let [line-end (read-until-newline s pos)] - [{:jolt/type :jolt/skip} line-end]) - - # dispatch - (= c 35) - (read-dispatch s pos) - - # string - (= c 34) - (read-string s pos) - - # list - (= c 40) - (let [r (read-list s pos)] - (when track-positions (put form-pos-table (in r 0) (+ pos-base pos))) - r) - - # unmatched closing delimiters - (= c 41) - (reader-error "Unmatched delimiter: )" pos) - - (= c 93) - (reader-error "Unmatched delimiter: ]" pos) - - (= c 125) - (reader-error "Unmatched delimiter: }" pos) - - # vector - (= c 91) - (read-vector s pos) - - # map - (= c 123) - (read-map s pos) - - # keyword - (= c 58) - (read-keyword s pos) - - # quote - (= c 39) - (read-quote s (+ pos 1) (sym "quote")) - - # syntax-quote / backtick - (= c 96) - (read-quote s (+ pos 1) (sym "syntax-quote")) - - # unquote ~ - (= c 126) - (if (and (< (+ pos 1) (length s)) (= (s (+ pos 1)) 64)) - (read-quote s (+ pos 2) (sym "unquote-splicing")) - (read-quote s (+ pos 1) (sym "unquote"))) - - # deref — @x is (clojure.core/deref x), QUALIFIED like Clojure, so it - # still derefs even where a ns shadows `deref` (malli excludes and - # redefines clojure.core/deref for its own schema-deref). - (= c 64) - (read-quote s (+ pos 1) (sym "clojure.core/deref")) - - # metadata - (= c 94) - (read-meta s pos) - - # character - (= c 92) - (read-char s pos) - - # number or symbol - (if (or (digit? c) - (and (= c 45) (< (+ pos 1) (length s)) (digit? (s (+ pos 1)))) - (and (= c 43) (< (+ pos 1) (length s)) (digit? (s (+ pos 1))))) - (read-number s pos) - (read-symbol s pos)))))))) - -(defn parse-string - "Parse a Clojure source string and return the first form." - [s] - (try - (let [[form pos] (read-form s 0)] - (if (and (struct? form) (= :jolt/skip (form :jolt/type))) - (parse-string (string/slice s pos)) - form)) - ([err fib] - (if (reader-error? err) - (error (format-reader-error err s nil)) - (propagate err fib))))) - -(defn parse-next - "Parse the first form from a string. Returns [form remaining-string]." - [s] - (defn- parse-next-loop [pos] - (let [[form new-pos] (read-form s pos)] - (if (and (struct? form) (= :jolt/skip (form :jolt/type))) - (parse-next-loop new-pos) - [form (string/slice s new-pos)]))) - (parse-next-loop 0)) - -(defn parse-all-positioned - "Parse every top-level form of source, returning an array of [form line] - where line is the 1-based source line the form starts on. parse-next eats - leading trivia itself, so the form's start line is the running newline - count plus the newlines in the trivia (whitespace, commas, ; comments) - ahead of it. (jolt-2o7.4)" - [source &opt file] - (def out @[]) - (var s source) - (var line 1) - (while (> (length (string/trim s)) 0) - # newlines in the leading trivia belong BEFORE the form's line - (var i 0) - (def n (length s)) - (var scanning true) - (while (and scanning (< i n)) - (def c (in s i)) - (cond - (= c (chr "\n")) (do (++ line) (++ i)) - (or (= c (chr " ")) (= c (chr "\t")) (= c (chr "\r")) (= c (chr ","))) (++ i) - (= c (chr ";")) (while (and (< i n) (not= (in s i) (chr "\n"))) (++ i)) - (set scanning false))) - # list-form positions recorded during this parse-next are relative to s; - # tell the reader the slice base so they land absolute (jolt-fqy) - (when track-positions (set-pos-base! (- (length source) (length s)))) - (def [form rest*] - (try (parse-next s) - ([err fib] - (if (reader-error? err) - # err's :pos is relative to the remaining slice — rebase onto the - # full source so line:col are absolute (jolt-2o7.5) - (error (format-reader-error - {:jolt/type :jolt/reader-error :msg (err :msg) - :pos (+ (- (length source) (length s)) (err :pos))} - source file)) - (propagate err fib))))) - (def consumed (- (length s) (length rest*))) - (def form-line line) - # count newlines inside the consumed chunk past the trivia - (loop [j :range [i consumed]] - (when (= (in s j) (chr "\n")) (++ line))) - (set s rest*) - (when (not (nil? form)) (array/push out [form form-line]))) - out) - -(defn parse-all-spans - "Parse every top-level form of source, returning an array of - [form abs-start abs-end] where abs-start is the byte offset of the form's - first non-trivia char and abs-end is just past it (leading whitespace/comment - trivia is excluded). Lets a caller reconstruct source by slicing verbatim — - used by `jolt uberscript`'s dead-code elimination to drop a defn's exact byte - span without re-printing (so formatting and reader macros survive)." - [source &opt file] - (def out @[]) - (var s source) - (while (> (length (string/trim s)) 0) - (def base (- (length source) (length s))) - (var i 0) - (def n (length s)) - (var scanning true) - (while (and scanning (< i n)) - (def c (in s i)) - (cond - (or (= c (chr "\n")) (= c (chr " ")) (= c (chr "\t")) (= c (chr "\r")) (= c (chr ","))) (++ i) - (= c (chr ";")) (while (and (< i n) (not= (in s i) (chr "\n"))) (++ i)) - (set scanning false))) - (def [form rest*] - (try (parse-next s) - ([err fib] - (if (reader-error? err) - (error (format-reader-error - {:jolt/type :jolt/reader-error :msg (err :msg) - :pos (+ base (err :pos))} - source file)) - (propagate err fib))))) - (def consumed (- (length s) (length rest*))) - (set s rest*) - (when (not (nil? form)) (array/push out [form (+ base i) (+ base consumed)]))) - out) diff --git a/src/jolt/regex.janet b/src/jolt/regex.janet deleted file mode 100644 index d0e12cf..0000000 --- a/src/jolt/regex.janet +++ /dev/null @@ -1,499 +0,0 @@ -# Regex support for Jolt, compiled to Janet's PEG engine. -# -# Path A: a real regex parser -> AST -> PEG grammar with continuation passing -# and position-based group captures. This gives genuine backtracking (greedy and -# lazy) that threads through capturing groups, plus capturing groups returned in -# Clojure's [whole g1 g2 ...] order, lookahead, anchors, classes, flags. -# -# Supported: literals, `.`, char classes `[...]`/`[^...]` (ranges, POSIX, -# `\d \w \s` etc.), quantifiers `* + ? {n} {n,} {n,m}` (greedy + lazy `?`), -# groups `(...)` (numbered), non-capturing `(?:...)`, lookahead `(?=...)`/`(?!...)`, -# alternation `|`, anchors `^ $ \b \B`, escapes, inline flag `(?i)`, and -# single-digit backreferences `\1`..`\9` (a backreferenced group matches -# possessively — no backtracking back into it; rare in practice). -# Not supported: lookbehind, named groups (rare; documented). - -(defn- chr [s] (get s 0)) -(defn regex? [x] (and (table? x) (= :jolt/regex (x :jolt/type)))) - -# ============================================================ -# Parser: regex source -> AST -# ============================================================ -# AST nodes (structs): {:op ...} -# :char {:b byte :ci bool} :any {:dotall bool} -# :class {:peg :neg bool} :pred {:peg } -# :seq {:items [...]} :alt {:items [...]} -# :star/:plus/:quest {:item ast :greedy bool} -# :rep {:item ast :min n :max m-or-nil :greedy bool} -# :group {:n num :item ast} :ncgroup {:item ast} -# :look {:neg bool :item ast} -# :anchor {:kind :start/:end/:wordb/:nwordb} - -(defn- lower-b [b] (if (and (>= b 65) (<= b 90)) (+ b 32) b)) -(defn- upper-b [b] (if (and (>= b 97) (<= b 122)) (- b 32) b)) - -(defn- pred-frag [c] - (case c - (chr "d") '(range "09") - (chr "D") '(if-not (range "09") 1) - (chr "w") '(choice (range "az" "AZ" "09") (set "_")) - (chr "W") '(if-not (choice (range "az" "AZ" "09") (set "_")) 1) - (chr "s") '(set " \t\n\r\f\v") - (chr "S") '(if-not (set " \t\n\r\f\v") 1) - nil)) - -# Unicode property classes \p{...} (jolt-xlp), mapped onto the byte PEGs: -# ASCII exactly; any high byte (>= 0x80, i.e. inside a UTF-8 sequence) counts -# as a LETTER byte — so ^\p{L}+$ accepts UTF-8 words, while \p{N}/\p{Z} -# stay ASCII-only. Lu/Ll are ASCII (case is byte-based throughout this -# engine). Unknown property names error at compile. -(defn- prop-frag [name] - (case name - "L" '(choice (range "az" "AZ") (range "\x80\xFF")) - "Lu" '(range "AZ") - "Ll" '(range "az") - "N" '(range "09") - "Nd" '(range "09") - "Z" '(set " ") - "Zs" '(set " ") - "P" '(set "!\"#%&'()*,-./:;?@[\\]_{}") - "Ps" '(set "([{") - "Pe" '(set ")]}") - "Alpha" '(choice (range "az" "AZ") (range "\x80\xFF")) - "Digit" '(range "09") - nil)) - -# At s[i] = backslash: if this is \p{Name} / \P{Name}, return [peg-frag end-i] -# (end-i past the closing brace), else nil. -(defn- parse-prop [s i] - (def pc (get s (+ i 1))) - (when (and (or (= pc (chr "p")) (= pc (chr "P"))) - (= (get s (+ i 2)) (chr "{"))) - (def close (string/find "}" s (+ i 3))) - (unless close (error "regex: unterminated \\p{...}")) - (def nm (string/slice s (+ i 3) close)) - (def frag (prop-frag nm)) - (unless frag (error (string "regex: unsupported property class \\p{" nm "}"))) - [(if (= pc (chr "P")) ~(if-not ,frag 1) frag) (+ close 1)])) - -(defn- esc-byte [c] - (case c - (chr "n") 10 (chr "t") 9 (chr "r") 13 (chr "f") 12 (chr "v") 11 (chr "0") 0 - c)) - -# Parse a [...] character class body, returns a PEG fragment + negation flag. -(defn- parse-class [s start ci] - (var i start) - (def neg (and (< i (length s)) (= (s i) (chr "^")))) - (when neg (++ i)) - (def alts @[]) - (while (and (< i (length s)) (not= (s i) (chr "]"))) - (cond - # POSIX class [:alpha:] etc. - (and (= (s i) (chr "[")) (< (+ i 1) (length s)) (= (s (+ i 1)) (chr ":"))) - (let [close (string/find ":]" s i) - name (string/slice s (+ i 2) close)] - (array/push alts (case name - "alpha" '(range "az" "AZ") - "digit" '(range "09") - "alnum" '(range "az" "AZ" "09") - "space" '(set " \t\n\r\f\v") - "upper" '(range "AZ") - "lower" '(range "az") - '(set ""))) - (set i (+ close 2))) - # escape inside class — \p{...} first (multi-char), then 2-char escapes - (= (s i) (chr "\\")) - (if-let [pr (parse-prop s i)] - (do (array/push alts (pr 0)) (set i (pr 1))) - (let [c (s (+ i 1)) p (pred-frag c)] - (if p (array/push alts p) - (array/push alts ~(set ,(string/from-bytes (esc-byte c))))) - (set i (+ i 2)))) - # range a-z - (and (< (+ i 2) (length s)) (= (s (+ i 1)) (chr "-")) (not= (s (+ i 2)) (chr "]"))) - (do - (if ci - (array/push alts ~(range ,(string/from-bytes (lower-b (s i)) (lower-b (s (+ i 2))) - (upper-b (s i)) (upper-b (s (+ i 2)))))) - (array/push alts ~(range ,(string/from-bytes (s i) (s (+ i 2)))))) - (set i (+ i 3))) - # single char - (do - (if ci - (array/push alts ~(set ,(string/from-bytes (lower-b (s i)) (upper-b (s i))))) - (array/push alts ~(set ,(string/from-bytes (s i))))) - (++ i)))) - (def frag (if (= 1 (length alts)) (alts 0) ~(choice ,;alts))) - [(if neg ~(if-not ,frag 1) frag) (+ i 1)]) # i is at ], skip it - -(var parse-alt nil) - -(defn- parse-atom [st] - # returns ast; advances (st :pos) - (def s (st :s)) - (def c (s (st :pos))) - (def ci (st :ci)) - (cond - (= c (chr "(")) - (let [nx (if (< (+ (st :pos) 1) (length s)) (s (+ (st :pos) 1)) 0)] - (if (= nx (chr "?")) - (let [k (s (+ (st :pos) 2))] - (cond - (= k (chr ":")) (do (+= (st :pos) 3) - (let [inner (parse-alt st)] (+= (st :pos) 1) {:op :ncgroup :item inner})) - (= k (chr "=")) (do (+= (st :pos) 3) - (let [inner (parse-alt st)] (+= (st :pos) 1) {:op :look :neg false :item inner})) - (= k (chr "!")) (do (+= (st :pos) 3) - (let [inner (parse-alt st)] (+= (st :pos) 1) {:op :look :neg true :item inner})) - # inline flags (?i) / (?m) / (?im:...) etc. - (do - (var j (+ (st :pos) 2)) - (var seti false) - (var setm false) - (while (and (< j (length s)) (not= (s j) (chr ")")) (not= (s j) (chr ":"))) - (when (= (s j) (chr "i")) (set seti true)) - (when (= (s j) (chr "m")) (set setm true)) - (++ j)) - (if (= (s j) (chr ":")) - (do (set (st :pos) (+ j 1)) - (def savedci (st :ci)) - (def savedml (st :ml)) - (when seti (set (st :ci) true)) - (when setm (set (st :ml) true)) - (def inner (parse-alt st)) - (set (st :ci) savedci) - (set (st :ml) savedml) - (+= (st :pos) 1) - {:op :ncgroup :item inner}) - (do (set (st :pos) (+ j 1)) # (?i) / (?m) — flag for rest of pattern - (when seti (set (st :ci) true)) - (when setm (set (st :ml) true)) - {:op :seq :items @[]}))))) - # capturing group - (let [n (++ (st :ngroup))] - (+= (st :pos) 1) - (let [inner (parse-alt st)] - (+= (st :pos) 1) # skip ) - {:op :group :n n :item inner})))) - (= c (chr "[")) - (let [[frag np] (parse-class s (+ (st :pos) 1) ci)] - (set (st :pos) np) - {:op :class :peg frag}) - (= c (chr ".")) - (do (++ (st :pos)) {:op :any :dotall (st :dotall)}) - (= c (chr "\\")) - (if-let [pr (parse-prop s (st :pos))] - (do (set (st :pos) (pr 1)) {:op :pred :peg (pr 0)}) - (let [nc (s (+ (st :pos) 1)) p (pred-frag nc)] - (+= (st :pos) 2) - (cond - p {:op :pred :peg p} - (= nc (chr "b")) {:op :anchor :kind :wordb} - (= nc (chr "B")) {:op :anchor :kind :nwordb} - # \1..\9 backreference (single digit) — record the referenced group so - # the emitter knows to tag-capture its text - (and (>= nc (chr "1")) (<= nc (chr "9"))) - (let [n (- nc (chr "0"))] (put (st :refs) n true) {:op :backref :n n}) - {:op :char :b (esc-byte nc) :ci ci}))) - (= c (chr "^")) (do (++ (st :pos)) {:op :anchor :kind :start}) - (= c (chr "$")) (do (++ (st :pos)) {:op :anchor :kind :end}) - (do (++ (st :pos)) {:op :char :b c :ci ci}))) - -(defn- parse-quant [st] - (def atom (parse-atom st)) - (def s (st :s)) - (if (>= (st :pos) (length s)) - atom - (let [q (s (st :pos))] - # called after advancing past the quantifier char: a trailing `?` -> lazy - (defn lazy? [] - (if (and (< (st :pos) (length s)) (= (s (st :pos)) (chr "?"))) - (do (++ (st :pos)) false) # lazy -> greedy=false - true)) - (cond - (= q (chr "*")) (do (++ (st :pos)) {:op :star :item atom :greedy (lazy?)}) - (= q (chr "+")) (do (++ (st :pos)) {:op :plus :item atom :greedy (lazy?)}) - (= q (chr "?")) (do (++ (st :pos)) {:op :quest :item atom :greedy (lazy?)}) - (= q (chr "{")) - (let [close (string/find "}" s (st :pos)) - spec (string/slice s (+ (st :pos) 1) close) - comma (string/find "," spec)] - (set (st :pos) (+ close 1)) - (def greedy (lazy?)) - (if comma - (let [lo (scan-number (string/slice spec 0 comma)) - hs (string/slice spec (+ comma 1)) - hi (if (= 0 (length hs)) nil (scan-number hs))] - {:op :rep :item atom :min lo :max hi :greedy greedy}) - {:op :rep :item atom :min (scan-number spec) :max (scan-number spec) :greedy greedy})) - atom)))) - -(defn- parse-seq [st] - (def s (st :s)) - (def items @[]) - (while (and (< (st :pos) (length s)) - (not= (s (st :pos)) (chr "|")) - (not= (s (st :pos)) (chr ")"))) - (array/push items (parse-quant st))) - (if (= 1 (length items)) (items 0) {:op :seq :items items})) - -(set parse-alt (fn [st] - (def branches @[(parse-seq st)]) - (def s (st :s)) - (while (and (< (st :pos) (length s)) (= (s (st :pos)) (chr "|"))) - (++ (st :pos)) - (array/push branches (parse-seq st))) - (if (= 1 (length branches)) (branches 0) {:op :alt :items branches}))) - -(defn- parse [source] - (def st @{:s source :pos 0 :ngroup 0 :ci false :ml false :dotall false :refs @{}}) - (def ast (parse-alt st)) - [ast (st :ngroup) (st :ml) (st :refs)]) - -# ============================================================ -# Emit: AST -> PEG grammar (continuation passing) -# ============================================================ - -(def- word-frag '(choice (range "az" "AZ" "09") (set "_"))) - -(defn- char-peg [b ci] - (if (and ci (not= (lower-b b) (upper-b b))) - ~(set ,(string/from-bytes (lower-b b) (upper-b b))) - ~(set ,(string/from-bytes b)))) - -(defn- make-emitter [grammar ml refs] - (var ctr 0) - (defn fresh [] (++ ctr) (keyword (string "r" ctr))) - (var emit nil) - (set emit (fn [ast k] - (case (ast :op) - :char ~(sequence ,(char-peg (ast :b) (ast :ci)) ,k) - :any ~(sequence ,(if (ast :dotall) 1 ~(if-not "\n" 1)) ,k) - :class ~(sequence ,(ast :peg) ,k) - :pred ~(sequence ,(ast :peg) ,k) - :seq (do (var acc k) (var i (dec (length (ast :items)))) - (while (>= i 0) (set acc (emit (in (ast :items) i) acc)) (-- i)) acc) - :alt (let [kr (fresh)] - (put grammar kr k) - ~(choice ,;(map (fn [a] (emit a (keyword kr))) (ast :items)))) - :star (let [r (fresh)] - (put grammar r (if (ast :greedy) - ~(choice ,(emit (ast :item) (keyword r)) ,k) - ~(choice ,k ,(emit (ast :item) (keyword r))))) - (keyword r)) - :plus (let [r (fresh)] - (put grammar r (if (ast :greedy) - ~(choice ,(emit (ast :item) (keyword r)) ,k) - ~(choice ,k ,(emit (ast :item) (keyword r))))) - (emit (ast :item) (keyword r))) - :quest (if (ast :greedy) - ~(choice ,(emit (ast :item) k) ,k) - ~(choice ,k ,(emit (ast :item) k))) - :rep (let [lo (ast :min) hi (ast :max) item (ast :item) greedy (ast :greedy)] - # desugar: lo required, then (hi-lo) optional, or star if hi is nil - (var tail (if (nil? hi) - (let [r (fresh)] - (put grammar r (if greedy - ~(choice ,(emit item (keyword r)) ,k) - ~(choice ,k ,(emit item (keyword r))))) - (keyword r)) - # Each optional level is its OWN grammar rule that - # references the previous level by name. Inlining instead - # (choice (emit item acc) acc) duplicates `acc` per level, - # so {0,n} built a structure the PEG compiler expanded to - # 2^n nodes and hung (jolt-3xur). Naming keeps it O(n). - (do (def kr (fresh)) (put grammar kr k) - (var acc (keyword kr)) (var c (- hi lo)) - (while (> c 0) - (let [r (fresh)] - (put grammar r (if greedy ~(choice ,(emit item acc) ,acc) - ~(choice ,acc ,(emit item acc)))) - (set acc (keyword r))) - (-- c)) - acc))) - (var acc tail) (var c lo) - (while (> c 0) (set acc (emit item acc)) (-- c)) - acc) - :group (let [n (ast :n)] - (if (and refs (refs n)) - # backreferenced group: also capture its text under tag :gN so a - # later \N can (backmatch). The item runs with just the end-marker - # as its continuation, so it matches POSSESSIVELY — backtracking - # INTO a backreferenced group isn't supported (rare; the usual - # (x)...\1 patterns don't need it). - (let [tag (keyword (string "g" n))] - ~(sequence (/ (position) ,(fn [p] [n :s p])) - (<- ,(emit (ast :item) ~(/ (position) ,(fn [p] [n :e p]))) ,tag) - ,k)) - ~(sequence (/ (position) ,(fn [p] [n :s p])) - ,(emit (ast :item) - ~(sequence (/ (position) ,(fn [p] [n :e p])) ,k))))) - :backref ~(sequence (backmatch ,(keyword (string "g" (ast :n)))) ,k) - :ncgroup (emit (ast :item) k) - :look (if (ast :neg) - ~(sequence (not ,(emit (ast :item) 0)) ,k) - ~(sequence (not (not ,(emit (ast :item) 0))) ,k)) - :anchor (case (ast :kind) - :start (if ml - ~(sequence (choice (not (look -1 1)) (look -1 "\n")) ,k) - ~(sequence (not (look -1 1)) ,k)) - :end (if ml - ~(sequence (choice (not 1) (not (not "\n"))) ,k) - ~(sequence (not 1) ,k)) - :wordb ~(sequence (choice (sequence (look -1 ,word-frag) (not ,word-frag)) - (sequence (not (look -1 ,word-frag)) (not (not ,word-frag)))) - ,k) - :nwordb ~(sequence (choice (sequence (look -1 ,word-frag) (not (not ,word-frag))) - (sequence (not (look -1 ,word-frag)) (not ,word-frag))) - ,k) - ~(sequence 0 ,k)) - (error (string "regex emit: unhandled op " (ast :op)))))) - emit) - -(defn compile-regex [source] - (def [ast ngroups ml refs] (parse source)) - (def grammar @{}) - (def emit (make-emitter grammar ml refs)) - # group 0 = whole match: mark start, body, mark end - (def body (emit ast ~(sequence (/ (position) ,(fn [p] [0 :e p])) 0))) - (put grammar :main ~(sequence (/ (position) ,(fn [p] [0 :s p])) ,body)) - (def gstruct (table/to-struct grammar)) - # anchored variant for re-matches: whole input must be consumed - (def anchored (table/to-struct (merge grammar {:main ~(sequence ,(grammar :main) -1)}))) - @{:jolt/type :jolt/regex - :source source - :ngroups ngroups - :peg (peg/compile gstruct) - :anchored (peg/compile anchored)}) - -(defn re-pattern [source] - (if (regex? source) source (compile-regex source))) - -# ============================================================ -# Matching -# ============================================================ - -(defn- marks->groups [marks s ngroups] - # marks: array of [n :s pos] / [n :e pos]; build [g0 g1 ... gN], slicing input - (def starts (array/new-filled (+ ngroups 1))) - (def ends (array/new-filled (+ ngroups 1))) - (each m marks - # backreferenced groups also leave a tagged TEXT capture (a string) on the - # stack — skip those; only the [n :s/:e pos] position tuples carry group spans - (when (indexed? m) - (let [n (m 0)] - (if (= (m 1) :s) (put starts n (m 2)) (put ends n (m 2)))))) - (def groups (array/new-filled (+ ngroups 1))) - (var n 0) - (while (<= n ngroups) - (if (and (not (nil? (in starts n))) (not (nil? (in ends n)))) - (put groups n (string/slice s (in starts n) (in ends n))) - (put groups n nil)) - (++ n)) - groups) - -(defn- match-at [re s start] - # returns groups array or nil - (def marks (peg/match (re :peg) s start)) - (if marks (marks->groups marks s (re :ngroups)) nil)) - -(defn- groups->result [groups ngroups] - # 0 groups -> whole-match string; else tuple [whole g1 ...] - (if (= ngroups 0) (in groups 0) (tuple/slice groups))) - -(defn re-find [re s] - (def re (re-pattern re)) - (var result nil) (var pos 0) - (while (and (nil? result) (<= pos (length s))) - (def g (match-at re s pos)) - (if g (set result (groups->result g (re :ngroups))) (++ pos))) - result) - -(defn re-matches [re s] - (def re (re-pattern re)) - (def marks (peg/match (re :anchored) s 0)) - (if marks (groups->result (marks->groups marks s (re :ngroups)) (re :ngroups)) nil)) - -(defn re-seq [re s] - (def re (re-pattern re)) - (def out @[]) (var pos 0) - (while (<= pos (length s)) - (def g (match-at re s pos)) - (if g - (let [whole (in g 0)] - (array/push out (groups->result g (re :ngroups))) - (set pos (+ pos (max 1 (length whole))))) - (++ pos))) - # Clojure's re-seq is nil (not an empty seq) when there are no matches, so - # `(if-let [m (re-seq ...)] ...)` works — an empty seq would be truthy. - (if (= 0 (length out)) nil out)) - -(defn re-split [re s &opt limit] - # limit (Java Pattern.split n>0): at most `limit` parts — stop after limit-1 - # splits and keep the rest of the string as the final unsplit part. nil/<=0 - # splits at every match. - (def re (re-pattern re)) - (def lim (if (and limit (> limit 0)) limit nil)) - (def out @[]) (var pos 0) (var last 0) - (while (and (<= pos (length s)) (or (nil? lim) (< (length out) (dec lim)))) - (def g (match-at re s pos)) - (if (and g (> (length (in g 0)) 0)) - (do (array/push out (string/slice s last pos)) - (set pos (+ pos (length (in g 0)))) - (set last pos)) - (++ pos))) - (array/push out (string/slice s last)) - out) - -(defn- expand-replacement [repl groups] - # $0 / $1 ... substitution in replacement string - (def buf @"") (var i 0) - (while (< i (length repl)) - (let [c (repl i)] - (if (and (= c (chr "$")) (< (+ i 1) (length repl)) (>= (repl (+ i 1)) 48) (<= (repl (+ i 1)) 57)) - (let [n (- (repl (+ i 1)) 48)] - (when (and (< n (length groups)) (in groups n)) (buffer/push-string buf (in groups n))) - (set i (+ i 2))) - (do (buffer/push-string buf (string/from-bytes c)) (++ i))))) - (string buf)) - -(defn- replacement-for - "One match's replacement text. A string replacement gets $N expansion; a FN - replacement (Clojure: fn of the match — string, or [whole g1 ...] when the - pattern has groups) is called and its result used literally." - [replacement g ngroups] - (cond - (string? replacement) (expand-replacement replacement g) - (or (function? replacement) (cfunction? replacement)) - (string (replacement (groups->result g ngroups))) - (string replacement))) - -(defn re-replace-all [re s replacement] - (def re (re-pattern re)) - (def buf @"") (var pos 0) (var last 0) - (while (<= pos (length s)) - (def g (match-at re s pos)) - (if (and g (> (length (in g 0)) 0)) - (do (buffer/push-string buf (string/slice s last pos)) - (buffer/push-string buf (replacement-for replacement g (re :ngroups))) - (set pos (+ pos (length (in g 0)))) - (set last pos)) - (++ pos))) - (buffer/push-string buf (string/slice s last)) - (string buf)) - -(defn re-replace-first [re s replacement] - (def re (re-pattern re)) - (var pos 0) (var done nil) - (while (and (nil? done) (<= pos (length s))) - (def g (match-at re s pos)) - (if (and g (> (length (in g 0)) 0)) - (set done [pos g]) - (++ pos))) - (if done - (let [[p g] done] - (string (string/slice s 0 p) - (replacement-for replacement g (re :ngroups)) - (string/slice s (+ p (length (in g 0)))))) - s)) diff --git a/src/jolt/stdlib_embed.janet b/src/jolt/stdlib_embed.janet deleted file mode 100644 index 6dd5eb6..0000000 --- a/src/jolt/stdlib_embed.janet +++ /dev/null @@ -1,35 +0,0 @@ -# Bakes the Clojure stdlib (.clj/.cljc under src/jolt/clojure and src/jolt/jolt) -# into the image at build time, so the runtime can load clojure.string, jolt.http, -# jolt.nrepl, etc. from any directory — not just when run from the repo. -# -# `sources` is built at module-load time. During `jpm build` that's the build -# (cwd = repo), so the map is captured into the image and frozen; in the shipped -# binary the files are never read from disk. Running from source rebuilds it. - -(defn- relpath->ns [rel] - # string/replace-all takes the string LAST, so thread with ->> - (->> rel (string/replace-all "/" ".") (string/replace-all "_" "-"))) - -(defn- strip-ext [name] - (cond - (string/has-suffix? ".cljc" name) (string/slice name 0 (- (length name) 5)) - (string/has-suffix? ".clj" name) (string/slice name 0 (- (length name) 4)) - name)) - -(defn- collect [root prefix acc] - (when (os/stat root) - (each e (os/dir root) - (def p (string root "/" e)) - (cond - (= :directory (os/stat p :mode)) (collect p (string prefix e "/") acc) - (or (string/has-suffix? ".clj" e) (string/has-suffix? ".cljc" e)) - (put acc (relpath->ns (string prefix (strip-ext e))) (slurp p))))) - acc) - -(def sources - (let [acc @{}] - (collect "src/jolt/clojure" "clojure/" acc) - (collect "src/jolt/jolt" "jolt/" acc) - # Portable Clojure core (analyzer/IR/…): jolt-core/jolt/foo.clj -> jolt.foo - (collect "jolt-core" "" acc) - acc)) diff --git a/src/jolt/types.janet b/src/jolt/types.janet deleted file mode 100644 index 094a4d2..0000000 --- a/src/jolt/types.janet +++ /dev/null @@ -1,11 +0,0 @@ -# Jolt value layer (types) -# -# AGGREGATOR (jolt-bvek phase 5a): the value/var/ns/ctx/protocol concerns now -# live in sibling modules, loaded here in dependency order and re-exported -# (:export true) so every consumer keeps its single `(use ./types)`. - -(import ./types_symbols :prefix "" :export true) -(import ./types_var :prefix "" :export true) -(import ./types_ns :prefix "" :export true) -(import ./types_ctx :prefix "" :export true) -(import ./types_protocols :prefix "" :export true) diff --git a/src/jolt/types_ctx.janet b/src/jolt/types_ctx.janet deleted file mode 100644 index 4a5c9a7..0000000 --- a/src/jolt/types_ctx.janet +++ /dev/null @@ -1,241 +0,0 @@ -# Jolt value layer — Context (+ inst/uuid values) -# Extracted from types.janet (jolt-bvek phase 5a split). - -(use ./types_symbols) -(use ./types_var) -(use ./types_ns) -# ============================================================ -# Context -# ============================================================ - -(defn ctx-find-ns - "Find or create a namespace in the context by name symbol." - [ctx ns-sym] - (let [env (ctx :env) - namespaces (env :namespaces)] - (or (get namespaces ns-sym) - (let [ns (make-ns ns-sym)] - (put namespaces ns-sym ns) - ns)))) - -# Instant value: an immutable tagged struct keyed by epoch milliseconds, so -# equality and map-key hashing are by INSTANT (offset-normalized): two #inst -# literals with different offsets denoting the same moment are =. -(defn make-inst [ms] - {:jolt/type :jolt/inst :ms ms}) - -(defn parse-inst - "Parse an RFC3339 timestamp with Clojure's partial defaults - (yyyy[-MM[-dd[Thh[:mm[:ss[.fff]]]]]][Z|+hh:mm|-hh:mm]) to an inst value. - Errors on a malformed timestamp." - [ts] - (def pat (peg/compile - ~(sequence - (capture (repeat 4 :d)) # year - (opt (sequence "-" (capture (repeat 2 :d)))) # month - (opt (sequence "-" (capture (repeat 2 :d)))) # day - (opt (sequence "T" (capture (repeat 2 :d)) # hour - (opt (sequence ":" (capture (repeat 2 :d)) # min - (opt (sequence ":" (capture (repeat 2 :d)) # sec - (opt (sequence "." (capture (some :d)))))))))) # frac - (opt (choice (capture "Z") - (sequence (capture (set "+-")) (capture (repeat 2 :d)) - ":" (capture (repeat 2 :d))))) - -1))) - (def m (peg/match pat ts)) - (when (nil? m) (error (string "Unrecognized #inst timestamp: " ts))) - # captures arrive positionally; classify by shape: digits runs + offset parts. - (var year nil) (var month 1) (var day 1) - (var hh 0) (var mm 0) (var ss 0) (var frac "0") - (var off-sign nil) (var off-h 0) (var off-m 0) - (var i 0) - (def fields @[:year :month :day :hh :mm :ss]) - (var fi 0) - (while (< i (length m)) - (def part (in m i)) - (cond - (= part "Z") nil - (or (= part "+") (= part "-")) - (do (set off-sign part) - (set off-h (scan-number (in m (+ i 1)))) - (set off-m (scan-number (in m (+ i 2)))) - (+= i 2)) - # fractional seconds arrive right after :ss was filled - (and (>= fi 6)) - (set frac part) - (do - (def v (scan-number part)) - (case (in fields fi) - :year (set year v) :month (set month v) :day (set day v) - :hh (set hh v) :mm (set mm v) :ss (set ss v)) - (++ fi))) - (++ i)) - (when (nil? year) (error (string "Unrecognized #inst timestamp: " ts))) - (def base-s (os/mktime {:year year :month (- month 1) :month-day (- day 1) - :hours hh :minutes mm :seconds ss})) - # fractional part -> milliseconds (truncate beyond 3 digits) - (def frac3 (string/slice (string frac "000") 0 3)) - (def ms-frac (scan-number frac3)) - (def off-s (* (if (= off-sign "-") -1 1) (+ (* off-h 3600) (* off-m 60)))) - (make-inst (- (+ (* base-s 1000) ms-frac) (* off-s 1000)))) - -(defn inst->rfc3339 - "Canonical print form: yyyy-MM-ddThh:mm:ss.fff-00:00 (UTC, like Clojure)." - [inst] - (def ms (inst :ms)) - (def s (math/floor (/ ms 1000))) - (def frac (- ms (* s 1000))) - (def d (os/date s)) - (string/format "%04d-%02d-%02dT%02d:%02d:%02d.%03d-00:00" - (d :year) (+ 1 (d :month)) (+ 1 (d :month-day)) - (d :hours) (d :minutes) (d :seconds) frac)) - -# UUID value: an immutable tagged struct. Lowercased at construction so -# equality and map-key hashing are case-insensitive by value (struct equality), -# matching Clojure (java.util.UUID equality / cljs UUID). -(defn make-uuid [s] - {:jolt/type :jolt/uuid :str (string/ascii-lower s)}) - -(defn make-ctx - "Create a new evaluation context. - (make-ctx) — empty context with 'user namespace - (make-ctx opts) — context with initial namespaces from opts - - opts may contain: - :namespaces — struct of {ns-symbol → {sym → value, ...}, ...}" - [&opt opts] - (default opts nil) - (let [compile? (if opts (get opts :compile?) false) - # Direct-linking (call-site/unit property, like Clojure). :aot-core? - # (default true; JOLT_AOT_CORE=0 disables) compiles the core tiers + - # compiler with direct-linking on. :direct-linking? is the per-unit flag - # the back end reads while emitting; it defaults to the user-code setting - # (off unless opted in) and load-core-overlay! flips it on around core. - aot-core? (let [o (if opts (get opts :aot-core?) nil)] - (if (nil? o) (not (= "0" (os/getenv "JOLT_AOT_CORE"))) o)) - # Macro expanders compile in EVERY mode (macros are ordinary compiled - # fns, as in Clojure) — including interpret mode, where evaluation stays - # interpreted but expansion runs native. :compile-macros? false (or - # JOLT_INTERPRET_MACROS=1) opts back into the fully-interpreted oracle. - compile-macros? (let [o (if opts (get opts :compile-macros?) nil)] - (if (nil? o) - (not (= "1" (os/getenv "JOLT_INTERPRET_MACROS"))) - o)) - env @{:namespaces @{} - :class->opts @{} - :current-ns "user" - :compile? compile? - :aot-core? aot-core? - :compile-macros? compile-macros? - # User-code direct-linking default (off unless opted in), the - # apples-to-apples analog of jank's -Odirect-call / Clojure's - # :direct-linking. JOLT_DIRECT_LINK=1 turns it on for user units; - # this is also the gate the inline pass reads (a call is only - # inline-safe when the callee won't be redefined). load-core-overlay! - # still flips core to :aot-core? around the tiers and restores this. - :direct-linking? (let [o (if opts (get opts :direct-linking?) nil)] - (if (nil? o) (= "1" (os/getenv "JOLT_DIRECT_LINK")) o)) - # Inline + scalar-replacement passes (jolt-87f). OFF for all of init - # (core load + self-hosted compiler recompile), so core/bootstrap - # compile exactly as before; api/init flips it on to the user - # direct-linking setting AFTER init, so only opted-in user code - # inlines. The inline pass also reads this (via host/inline-enabled?). - :inline? false - # Ordered roots searched (after the stdlib) to resolve a namespace - # to a .clj/.cljc file. jolt-core holds the portable Clojure layer - # (analyzer/IR/core); deps.edn resolution appends dep src dirs. - :source-paths @["jolt-core" "src/jolt"] - :type-registry @{} - :data-readers (let [dr @{}] - (put dr (keyword "#inst") (fn [s] (parse-inst s))) - (put dr (keyword "#uuid") (fn [s] (make-uuid s))) - dr)} - # create the user namespace via a partial context - _ (ctx-find-ns {:env env} "user")] - # initialize from opts - (when opts - (when-let [ns-opts (get opts :namespaces)] - (loop [[ns-sym mappings] :pairs ns-opts] - (let [ns (ctx-find-ns {:env env} ns-sym)] - (loop [[sym val] :pairs mappings] - (ns-intern ns sym val)))))) - {:jolt/type :jolt/context - :env env})) - -(defn ctx? - "Check if x is a Jolt Context." - [x] - (and (struct? x) (= :jolt/context (x :jolt/type)))) - -(defn ctx-env - "Return the env atom from the context." - [ctx] - (ctx :env)) - -(defn ctx-current-ns - "Get the current namespace symbol." - [ctx] - (get (ctx :env) :current-ns)) - -(defn ctx-set-current-ns - "Set the current namespace symbol. Also keeps the *ns* dynamic var's root in - sync (the var table is cached on the env by install-stateful-fns! — one table - put on this hot path, no ns lookup chain)." - [ctx ns-sym] - (put (ctx :env) :current-ns ns-sym) - (when-let [v (get (ctx :env) :ns-var)] - (put v :root (ctx-find-ns ctx ns-sym)))) - -(defn all-ns - "Return a list of all namespaces in the context." - [ctx] - (let [namespaces (get (ctx :env) :namespaces) - result @[]] - (loop [[_ ns] :pairs namespaces] - (array/push result ns)) - result)) - -(defn remove-ns - "Remove a namespace from the context by name string." - [ctx ns-name] - (put (get (ctx :env) :namespaces) ns-name nil) nil) - -(defn create-ns - "Create a new namespace." - [ctx ns-name] - (ctx-find-ns ctx ns-name)) - -(defn the-ns - "Return the current namespace object." - [ctx] - (ctx-find-ns ctx (ctx-current-ns ctx))) - -(defn ns-interns - "Return the map of all interned vars in the current namespace." - [ctx] - (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] - (ns :mappings))) - -(defn ns-aliases - "Return the alias map of the current namespace." - [ctx] - (let [ns (ctx-find-ns ctx (ctx-current-ns ctx))] - (ns :aliases))) - -(defn find-var - "Resolve a symbol to a var in the current context. - Looks in current namespace first, then clojure.core." - [ctx sym-s] - (let [name (sym-s :name) - ns-sym (sym-s :ns)] - (if ns-sym - (let [ns (ctx-find-ns ctx ns-sym)] - (ns-find ns name)) - (let [current-ns (ctx-find-ns ctx (ctx-current-ns ctx)) - v (ns-find current-ns name)] - (if v v - (let [core-ns (ctx-find-ns ctx "clojure.core")] - (ns-find core-ns name))))))) - - -# ============================================================ diff --git a/src/jolt/types_ns.janet b/src/jolt/types_ns.janet deleted file mode 100644 index d484811..0000000 --- a/src/jolt/types_ns.janet +++ /dev/null @@ -1,100 +0,0 @@ -# Jolt value layer — Namespace -# Extracted from types.janet (jolt-bvek phase 5a split). - -(use ./types_symbols) -(use ./types_var) -# ============================================================ -# Namespace -# ============================================================ - -(defn make-ns - "Create a new namespace. - (make-ns name) — empty namespace - name is a symbol struct {:jolt/type :symbol ...}" - [name] - (struct - :jolt/type :jolt/namespace - :name name - :mappings @{} - :imports @{} - :aliases @{})) - -(defn ns? - "Check if x is a Jolt Namespace." - [x] - (and (or (struct? x) (table? x)) (= :jolt/namespace (x :jolt/type)))) - -(defn ns-name - "Return the name symbol of a namespace." - [ns] - (ns :name)) - -(defn ns-map - "Return the mappings table (symbol → var) for a namespace." - [ns] - (ns :mappings)) - -(defn ns-intern - "Find or create a var named by sym in namespace ns, setting root binding to val if given. - (ns-intern ns sym) — find or create unbound var - (ns-intern ns sym val) — find or create with root binding" - [ns sym &opt val] - (default val nil) - (let [mappings (ns :mappings) - existing (get mappings sym)] - (if existing - (do - (when (not (nil? val)) - (bind-root existing val)) - existing) - # Store the namespace *name*, not the ns table: a back-pointer to the ns - # would make the var cyclic (ns -> mappings -> var -> ns), and the compiler - # embeds var cells as constants, which can't be cyclic. - (let [v (make-var sym val {:ns (get ns :name) :name sym})] - (put mappings sym v) - v)))) - -(defn ns-find - "Find a var by symbol in the namespace. Returns nil if not found." - [ns sym] - (get (ns :mappings) sym)) - -(defn ns-unmap - "Remove a mapping by symbol from the namespace." - [ns sym] - (put (ns :mappings) sym nil)) - -(defn ns-resolve - "Resolve a symbol in a namespace. Looks in own mappings first, - then aliases. Returns the var or nil." - [ns sym] - (or (ns-find ns sym) - (let [qualified? (sym? sym)] - (when qualified? - # qualified symbol: look up via alias (string-keyed store) - (let [alias-ns (get (ns :aliases) (sym :ns))] - (when alias-ns - (ns-find alias-ns (sym :name)))))))) - -(defn ns-import - "Add an import to the namespace. class-name is local symbol, fq-class-name is the full qualified name." - [ns class-name fq-class-name] - (put (ns :imports) class-name fq-class-name)) - -(defn ns-import-lookup - "Look up an import in the namespace. Returns the full qualified name or nil." - [ns class-name] - (get (ns :imports) class-name)) - -(defn ns-add-alias - "Add an alias: alias-name (string) -> target ns NAME (string). The ONE alias - store (jolt-ark): resolution and ns-aliases both read it; :imports is class - imports only." - [ns alias-name target-ns-name] - (put (ns :aliases) alias-name target-ns-name)) - -(defn ns-alias-lookup - "The target ns NAME for alias-name, or nil." - [ns alias-name] - (get (ns :aliases) alias-name)) - diff --git a/src/jolt/types_protocols.janet b/src/jolt/types_protocols.janet deleted file mode 100644 index c692644..0000000 --- a/src/jolt/types_protocols.janet +++ /dev/null @@ -1,156 +0,0 @@ -# Jolt value layer — protocol/type registry + shape-records -# Extracted from types.janet (jolt-bvek phase 5a split). - -(use ./types_symbols) -(use ./types_var) -(use ./types_ns) -(use ./types_ctx) -# Protocol type registry -# ============================================================ - -(defn register-protocol-method - "Register a protocol method implementation for a type." - [ctx type-tag protocol-name method-name fn] - (let [env (ctx :env) - registry (get env :type-registry) - type-impls (or (get registry type-tag) - (do (put registry type-tag @{}) (get registry type-tag))) - proto-impls (or (get type-impls protocol-name) - (do (put type-impls protocol-name @{}) (get type-impls protocol-name)))] - (put proto-impls method-name fn) - # Bump the registry generation so any dispatch cache keyed on it invalidates. - (put env :type-registry-gen (+ 1 (or (get env :type-registry-gen) 0))))) - -(defn find-protocol-method - "Find a protocol method implementation for a type." - [ctx type-tag protocol-name method-name] - (let [registry (get (ctx :env) :type-registry) - type-impls (get registry type-tag)] - (when type-impls - (let [proto-impls (get type-impls protocol-name)] - (when proto-impls - (get proto-impls method-name)))))) - -(defn find-method-any-protocol - "Find a method implementation for a type, searching every protocol it - implements (dot calls name the method but not the protocol)." - [ctx type-tag method-name] - (let [type-impls (get (get (ctx :env) :type-registry) type-tag)] - (when type-impls - (var r nil) - (eachp [_ proto-impls] type-impls - (when (nil? r) (set r (get proto-impls method-name)))) - r))) - -(defn type-satisfies? - "Check if a type satisfies a protocol." - [ctx type-tag protocol-name] - (let [registry (get (ctx :env) :type-registry) - type-impls (get registry type-tag)] - (if (and type-impls (get type-impls protocol-name)) true false))) - -# --- shape records (hidden classes, jolt-t34) ------------------------------- -# A "shape record" is a cheap fixed-layout representation for a map literal -# whose keys are a known compile-time set (e.g. a vec3 {:r :g :b}). It is a -# Janet tuple [SHAPE v0 v1 ...] where SHAPE is an interned descriptor struct -# {:jolt/shape KEYS :idx {k->pos}}. Construction is a tuple (≈2x cheaper than a -# struct), const-keyword lookup compiles to an index, and general map ops below -# recognize it via shape-rec? and treat it as a map — so it is transparent -# wherever it flows. Created only by the backend when JOLT_SHAPE is on and the -# inference proves the shape; the runtime support here is always present so a -# shape value is handled correctly regardless. -(def- shape-cache @{}) # canonical-keys-tuple -> interned shape descriptor -# Canonical key order, OWNED BY THE RUNTIME (jolt-t34): every site that builds or -# reads a shape (shape-for, emit-map, emit-kw-lookup, build-map-literal) derives -# the layout from this one function, so they always agree regardless of what -# order the inference passed the keys in. Sorted by the keys' jdn print form — -# deterministic and total across keywords/strings/numbers/bools. -(defn shape-sort [ks] - (sort (array ;ks) (fn [a b] (< (string/format "%j" a) (string/format "%j" b))))) -(defn shape-for - "Interned shape descriptor for a key set. Keys are canonicalized internally, - so callers need not pre-sort and any permutation yields the same descriptor." - [keyv] - (def sk (tuple ;(shape-sort keyv))) - (or (get shape-cache sk) - (let [idx @{}] - (var i 0) (each k sk (put idx k i) (++ i)) - (def desc (struct :jolt/shape sk :idx (table/to-struct idx))) - (put shape-cache sk desc) - desc))) -(defn shape-rec? [x] - (and (tuple? x) (> (length x) 0) - (struct? (in x 0)) (not (nil? (in (in x 0) :jolt/shape))))) -(defn shape-keys [rec] ((in rec 0) :jolt/shape)) -(defn shape-get [rec k default] - (def desc (in rec 0)) - (def pos (get (desc :idx) k)) - (cond - (not (nil? pos)) (in rec (+ pos 1)) - # records respond to the virtual :jolt/deftype key with their type tag, so - # every existing (get obj :jolt/deftype) dispatch site keeps working - (and (= k :jolt/deftype) (desc :type)) (desc :type) - default)) -(defn shape-assoc [rec k v] - # assoc on a known key keeps the layout. A new key: a record keeps its type - # and grows a slot (Clojure records stay records when extended); a plain - # shape-rec falls back to a struct. - (def desc (in rec 0)) - (def pos (get (desc :idx) k)) - (cond - (not (nil? pos)) (let [a (array ;rec)] (put a (+ pos 1) v) (tuple ;a)) - (desc :type) - (let [new-keys (array ;(desc :jolt/shape) k) idx @{}] - (var i 0) (each kk new-keys (put idx kk i) (++ i)) - (def ndesc (struct :jolt/shape (tuple ;new-keys) :idx (table/to-struct idx) :type (desc :type))) - (def out @[ndesc]) - (each kk (desc :jolt/shape) (array/push out (shape-get rec kk nil))) - (array/push out v) - (tuple ;out)) - (let [t @{}] (each kk (desc :jolt/shape) (put t kk (shape-get rec kk nil))) (put t k v) (table/to-struct t)))) -(defn shape-count [rec] (- (length rec) 1)) -(defn shape-contains? [rec k] (not (nil? (get ((in rec 0) :idx) k)))) -# a struct snapshot of a shape-rec — the reusable bridge for ops that already -# handle structs (dissoc, vals, seq, equality, print, ...) without per-op code -(defn shape->struct [rec] - (def desc (in rec 0)) (def t @{}) - (each kk (desc :jolt/shape) (put t kk (in rec (+ 1 (get (desc :idx) kk))))) - (table/to-struct t)) - -# --- records as shapes (jolt-t34 R3) ---------------------------------------- -# A user record (deftype/defrecord) is a shape-rec whose descriptor ALSO carries -# :type (the type tag). Field layout is the DECLARED field order (not sorted), -# so the positional ->Name constructor maps args to slots directly. The -# descriptor is interned per type tag, so all instances of a type share it. -# record-tag unifies the type accessor over both the new shape-rec records and -# the table form still used for reified protocol objects. -(def- record-desc-cache @{}) -(defn record-desc [type-tag field-keys] - "Build a record descriptor (interned in declared field order) for the given - key set. Not cached — used for records extended past their declared fields." - (let [idx @{}] - (var i 0) (each k field-keys (put idx k i) (++ i)) - (struct :jolt/shape (tuple ;field-keys) :idx (table/to-struct idx) :type type-tag))) -# Interned per (type-tag, field-keys): keying on the tag alone would hand back a -# STALE descriptor after a record is redefined with different fields (a REPL -# redefine, or two same-named records in different test cases) — the new instance -# would carry the old layout. Old instances keep their own descriptor and stay -# valid; new ones get the new layout. (jolt-t34) -(defn record-shape-for [type-tag field-keys] - (def ck (tuple type-tag (tuple ;field-keys))) - (or (get record-desc-cache ck) - (let [desc (record-desc type-tag field-keys)] - (put record-desc-cache ck desc) - desc))) -(defn make-record [type-tag field-keys args] - (def out @[(record-shape-for type-tag field-keys)]) - (var i 0) (each k field-keys (array/push out (in args i)) (++ i)) - (tuple ;out)) -(defn record-tag - "The deftype/record type tag of x, or nil. Covers shape-rec records (descriptor - :type) and the table form (reified objects, :jolt/deftype)." - [x] - (cond - (and (tuple? x) (> (length x) 0) (struct? (in x 0))) (get (in x 0) :type) - (and (table? x) (get x :jolt/deftype)) (get x :jolt/deftype))) - diff --git a/src/jolt/types_symbols.janet b/src/jolt/types_symbols.janet deleted file mode 100644 index 487a9ae..0000000 --- a/src/jolt/types_symbols.janet +++ /dev/null @@ -1,41 +0,0 @@ -# Jolt value layer — characters + symbol helpers -# Extracted from types.janet (jolt-bvek phase 5a split). - -# Jolt Types -# Core types for the Clojure-on-Janet interpreter. -# -# Types: -# JoltVar — mutable container with metadata (like Clojure Var) -# JoltNamespace — namespace with symbol→var mappings and imports -# JoltContext — evaluation context (env atom, namespaces) -# -# Symbols are represented as {:jolt/type :symbol :ns :name } -# as produced by the reader. - -# Characters are {:jolt/type :jolt/char :ch }, distinct from strings. -(defn make-char [code] {:jolt/type :jolt/char :ch code}) - -(def- char-named @{"newline" 10 "space" 32 "tab" 9 "return" 13 - "formfeed" 12 "backspace" 8 "newpage" 12 "nul" 0}) - -(defn char-from-name - "Resolve a reader char-literal name (\\a, \\newline, \\uNNNN, \\oNNN) to a char value." - [name] - (cond - (= 1 (length name)) (make-char (in name 0)) - (get char-named name) (make-char (get char-named name)) - (and (> (length name) 1) (= (in name 0) (get "u" 0))) - (make-char (scan-number (string "16r" (string/slice name 1)))) - (and (> (length name) 1) (= (in name 0) (get "o" 0))) - (make-char (scan-number (string "8r" (string/slice name 1)))) - (error (string "Unsupported character: \\" name)))) - -# ============================================================ -# Symbol helpers -# ============================================================ - -(defn sym? - "Check if x is a Jolt symbol struct." - [x] - (and (struct? x) (= :symbol (x :jolt/type)))) - diff --git a/src/jolt/types_var.janet b/src/jolt/types_var.janet deleted file mode 100644 index f19f9f8..0000000 --- a/src/jolt/types_var.janet +++ /dev/null @@ -1,179 +0,0 @@ -# Jolt value layer — Var -# Extracted from types.janet (jolt-bvek phase 5a split). - -(use ./types_symbols) -# ============================================================ -# Var -# ============================================================ - -# Dynamic-var binding stack. Stored fiber-locally (via Janet's dyn), so that -# concurrent go blocks — each a Janet fiber — don't interleave each other's -# dynamic bindings, and a go block conveys the bindings in effect when it was -# spawned (see snapshot-bindings/install-bindings). Each fiber lazily gets its -# own array on first use. -(defn cur-binding-stack [] - (or (dyn :jolt/binding-stack) - (let [s @[]] (setdyn :jolt/binding-stack s) s))) - -(defn push-thread-bindings - "Push a frame of dynamic var bindings. Takes a struct of var→value." - [bindings] - (array/push (cur-binding-stack) bindings)) - -(defn pop-thread-bindings - "Pop the most recent frame of dynamic var bindings." - [] - (array/pop (cur-binding-stack))) - -(defn snapshot-bindings - "Shallow copy of the current binding stack (frames are immutable value maps). - Captured by a go block at spawn time for binding conveyance." - [] - (array/slice (cur-binding-stack))) - -(defn install-bindings - "Install a snapshot as this fiber's binding stack (a fresh copy, so the - fiber's own push/pop/var-set don't mutate the snapshot's frames array)." - [snap] - (setdyn :jolt/binding-stack (array/slice snap))) - -(defn make-var - "Create a new Jolt Var. - (make-var name) — unbound var - (make-var name init-val) — var with root binding - (make-var name init-val meta) — var with root and metadata - - name is a symbol struct {:jolt/type :symbol ...}" - [name &opt init-val meta] - (default init-val nil) - (default meta nil) - (let [m (if meta meta {:name name}) - result @{:jolt/type :jolt/var - :name name - :root init-val - :meta m - # Generation: bumped on every root change (redefinition). Call - # sites / dispatch caches keyed on this can detect a redef and - # invalidate; direct-linked (sealed) sites can detect staleness. - :gen 0 - :dynamic (if meta (get meta :dynamic) false) - :macro (if meta (get meta :macro) false) - :ns (if meta (get meta :ns) nil)}] - result)) - -(defn var? - "Check if x is a Jolt Var." - [x] - (and (table? x) (= :jolt/var (x :jolt/type)))) - -(defn var-dynamic? - "Check if var is marked :dynamic." - [v] - (v :dynamic)) - -(defn var-macro? - "Check if var is marked :macro." - [v] - (v :macro)) - -(defn var-name - "Return the symbol name of the var." - [v] - (v :name)) - -(defn var-meta - "Return the metadata of the var." - [v] - (v :meta)) - -(defn var-ns - "Return the namespace of the var." - [v] - (v :ns)) - -(defn var-get - "Deref the var. If the var is dynamic and has a thread-local binding, return that. - Otherwise return the root binding." - [v] - # Fast path: no dynamic bindings are active (the common case — the stack is - # only non-empty inside a `binding` block), so the value is just the root. This - # is the hot path for every global deref; skip building the walk otherwise. - (def bs (cur-binding-stack)) - (if (= 0 (length bs)) - (v :root) - # walk binding stack top-down for this var - (do - (var result nil) - (var i (dec (length bs))) - (while (>= i 0) - (let [frame (in bs i) - val (get frame v)] - (if (not (nil? val)) - (do - (set result (if (var? val) (var-get val) val)) - (set i -1)) - (-- i)))) - (if (not (nil? result)) result (v :root))))) - -(defn var-set - "Set a var's value. If the var has a thread-local binding on the stack, update - the innermost frame that binds it (matching Clojure, where var-set targets the - current binding); otherwise set the root." - [v val] - (def bs (cur-binding-stack)) - (var i (dec (length bs))) - (var done false) - (while (and (not done) (>= i 0)) - (let [frame (in bs i)] - (if (not (nil? (get frame v))) - (do (put bs i (merge frame {v val})) (set done true)) - (-- i)))) - (unless done (do (put v :root val) (put v :gen (+ 1 (or (v :gen) 0))))) - val) - -(defn alter-var-root - "Atomically alter the root binding of v by applying f to current value plus args." - [v f & args] - (let [new-val (f (v :root) ;args)] - (put v :root new-val) - (put v :gen (+ 1 (or (v :gen) 0))) - new-val)) - -(defn alter-meta! - "Atomically update a var's metadata via (apply f args)." - [v f & args] - (let [new-meta (apply f (var-meta v) args)] - (put v :meta new-meta) - new-meta)) - -(defn reset-meta! - "Reset a var's metadata to the given value." - [v meta] - (put v :meta meta) - meta) - - -(defn with-meta - "Return a new var with updated metadata. The original var is unchanged." - [v meta] - # build new meta as a table first (to allow adding keys), then convert - (let [new-meta-table (merge @{} (v :meta) meta) - # convert to struct by extracting all keys - new-meta (table/to-struct new-meta-table)] - @{:jolt/type :jolt/var - :name (v :name) - :root (v :root) - :meta new-meta - :gen (or (v :gen) 0) - :dynamic (v :dynamic) - :macro (v :macro) - :ns (v :ns)})) - -(defn bind-root - "Set the root binding and bump the var's generation (the redefinition - chokepoint: def, ns-intern-with-val, and the root-set paths all route here)." - [v val] - (put v :root val) - (put v :gen (+ 1 (or (v :gen) 0))) - val) - diff --git a/test/bench/core-bench.janet b/test/bench/core-bench.janet deleted file mode 100644 index cc95a60..0000000 --- a/test/bench/core-bench.janet +++ /dev/null @@ -1,50 +0,0 @@ -# Performance baseline for the clojure.core migration (jolt-1j0). -# -# Times representative core operations end-to-end (compile path) so a phase that -# moves fns from native Janet to the self-hosted Clojure overlay can be checked -# for regressions. Same programs before/after a phase -> relative delta is the -# migration's perf impact. Run: JOLT_BENCH=1 janet test/bench/core-bench.janet -# (skipped under `jpm test` — it asserts nothing; see main). -# -# Each program carries its own internal iteration so the measured work dominates -# parse/compile overhead. Reports the min of N runs (least noisy). - -(import ../../src/jolt/api :as api) - -(def runs 5) - -(def benches - [[:fib "(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 28)"] - [:seq-pipe "(loop [i 0 a 0] (if (< i 300) (recur (inc i) (+ a (reduce + 0 (map inc (filter even? (range 200)))))) a))"] - [:reduce "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (reduce + 0 (range 500)))) a))"] - [:into-vec "(loop [i 0 a 0] (if (< i 1000) (recur (inc i) (+ a (count (into [] (map inc (range 100)))))) a))"] - [:map-build "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (count (reduce (fn [m k] (assoc m k k)) {} (range 50))))) a))"] - [:map-read "(let [m (zipmap (range 100) (range 100))] (loop [i 0 a 0] (if (< i 5000) (recur (inc i) (+ a (get m (mod i 100) 0))) a)))"] - [:str-join "(loop [i 0 a 0] (if (< i 1000) (recur (inc i) (+ a (count (apply str (map str (range 100)))))) a))"] - [:hof "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (reduce + 0 (map (comp inc inc) (range 200))))) a))"]]) - -(defn time-bench [ctx src] - (var best math/inf) - (for _ 0 runs - (def t0 (os/clock)) - (api/load-string ctx src) - (def dt (* 1000 (- (os/clock) t0))) - (when (< dt best) (set best dt))) - best) - -(defn main [&] - # `jpm test` recurses test/ and would run this every gate, but it's a manual - # perf tool that asserts nothing (just reports timings) — so skip it unless - # opted in with JOLT_BENCH=1. Keeps ~35s of unasserted benchmark work out of - # the correctness gate (same pattern as suite-worker's no-arg no-op). - (unless (os/getenv "JOLT_BENCH") - (print "core-bench: SKIP (set JOLT_BENCH=1 to run)") - (os/exit 0)) - (def ctx (api/init {:compile? true})) - (print "bench (compile mode), min of " runs " runs, ms:") - (var total 0) - (each [name src] benches - (def ms (time-bench ctx src)) - (+= total ms) - (printf " %-10s %8.2f ms" name ms)) - (printf " %-10s %8.2f ms" "TOTAL" total)) diff --git a/test/chez/README.md b/test/chez/README.md new file mode 100644 index 0000000..46a8a23 --- /dev/null +++ b/test/chez/README.md @@ -0,0 +1,41 @@ +# Chez test harness + +The correctness gate for jolt. Pure Chez (+ Clojure for the JVM oracle). +Correctness is judged against the JVM-sourced conformance spec; the spec itself +lives in `test/conformance/` (see its `SPEC.md`). Run the whole gate with `make +test` from the repo root. + +## The spec corpus + +`corpus.edn` is the contract: ~2920 rows `{:suite :label :expected :actual}`, with +`:expected` sourced from reference JVM Clojure by `test/conformance/regen-corpus.clj`. +It is frozen (the canonical source) — add or change cases here, then re-source the +answers with `regen-corpus.clj` and re-certify with `test/conformance/certify.clj`. + +## The gate runners (`host/chez/`) + +- `run-corpus.ss` — runs every corpus case through the spine (read → analyze → IR → + emit → eval, all on Chez), comparing each result by value-equality against the JVM + `:expected`. A `known-fail` allowlist covers cases jolt can't match because Chez has + no JVM host (Java classes, arrays, `BigDecimal`, opaque host-object printers, …); + the gate fails only on a NEW divergence or if the pass count drops below the floor. + + chez --script host/chez/run-corpus.ss + JOLT_CORPUS_LIMIT=200 … # every-Nth stride, fast iteration + JOLT_CHEZ_ZJ_FLOOR=N … # override the floor (default 2678) + +- `run-unit.ss` — host-specific unit cases (`test/chez/unit.edn`) that aren't in the + JVM-portable corpus: dot-forms, java statics, io, reader, walk, vars/namespaces, + refs. Each `:expr` is evaluated in-process and its printed value compared to a baked + `:expected` (`:throws` asserts a raise). + +- `selfcheck.sh` — self-host fixpoint: `bootstrap.ss` rebuild byte-equals the + checked-in seed (`host/chez/seed/`). +- `smoke.sh` — real `bin/joltc -e` CLI smoke. + +## Other Chez tests + +- `values-test.ss` — the value model (nil/truthiness/collections). `make values`. +- `bench-chez.ss` — compute bench through the pipeline (opt-in; not in the gate). + +All runners assume `chez` on PATH. diff --git a/test/chez/bench-chez.ss b/test/chez/bench-chez.ss new file mode 100644 index 0000000..488dc05 --- /dev/null +++ b/test/chez/bench-chez.ss @@ -0,0 +1,42 @@ +;; bench-chez.ss (jolt-cf1q.5) — Phase 4 perf probe for the zero-Janet Chez path. +;; +;; Mirrors test/bench/core-bench.janet's programs and methodology (load the runtime +;; ONCE, then time compile+run of each program, min of N) so the Chez compute path +;; (analyze->Scheme->Chez eval) is comparable to the Janet compile path. Run: +;; chez --script test/chez/bench-chez.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 runs 5) +(define benches + (list + (cons "fib" "(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 28)") + (cons "seq-pipe" "(loop [i 0 a 0] (if (< i 300) (recur (inc i) (+ a (reduce + 0 (map inc (filter even? (range 200)))))) a))") + (cons "reduce" "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (reduce + 0 (range 500)))) a))") + (cons "into-vec" "(loop [i 0 a 0] (if (< i 1000) (recur (inc i) (+ a (count (into [] (map inc (range 100)))))) a))") + (cons "map-build" "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (count (reduce (fn [m k] (assoc m k k)) {} (range 50))))) a))") + (cons "map-read" "(let [m (zipmap (range 100) (range 100))] (loop [i 0 a 0] (if (< i 5000) (recur (inc i) (+ a (get m (mod i 100) 0))) a)))") + (cons "str-join" "(loop [i 0 a 0] (if (< i 1000) (recur (inc i) (+ a (count (apply str (map str (range 100)))))) a))") + (cons "hof" "(loop [i 0 a 0] (if (< i 2000) (recur (inc i) (+ a (reduce + 0 (map (comp inc inc) (range 200))))) a))"))) + +(define (now-ms) + (let ((t (current-time 'time-monotonic))) + (+ (* 1000.0 (time-second t)) (/ (time-nanosecond t) 1000000.0)))) + +(for-each + (lambda (b) + (let ((name (car b)) (src (string-append "(do " (cdr b) ")"))) + (let loop ((i 0) (best +inf.0)) + (if (>= i runs) + (printf "~a\t~a ms\n" name (/ (round (* 100 best)) 100.0)) + (let ((t0 (now-ms))) + (jolt-compile-eval src "user") + (loop (+ i 1) (min best (- (now-ms) t0)))))))) + benches) diff --git a/test/chez/corpus.edn b/test/chez/corpus.edn new file mode 100644 index 0000000..59f878e --- /dev/null +++ b/test/chez/corpus.edn @@ -0,0 +1,2904 @@ +[ + {:suite "interop-fixes / deprecated #^ metadata reader" :label "#^ type hint on a param" :expected "\"x\"" :actual "(do (defn f1 [#^String s] s) (f1 \"x\"))"} + {:suite "interop-fixes / deprecated #^ metadata reader" :label "#^\"[B\" array hint" :expected "[1 2]" :actual "(do (defn f2 [#^\"[B\" b] b) (f2 [1 2]))"} + {:suite "interop-fixes / deprecated #^ metadata reader" :label "#^ is equivalent to ^" :expected "true" :actual "(= (meta (with-meta [] {:tag (quote String)})) {:tag (quote String)})"} + {:suite "interop-fixes / (str pattern) yields raw source" :label "str of a regex" :expected "\"abc\"" :actual "(str #\"abc\")"} + {:suite "interop-fixes / (str pattern) yields raw source" :label "compose patterns via str" :expected "true" :actual "(boolean (re-matches (re-pattern (str #\"<\" \"(.*)\" \">\")) \"\"))"} + {:suite "interop-fixes / into onto a map" :label "merges map items" :expected "true" :actual "(= {:a 1 :b 2} (into {} [{:a 1} {:b 2}]))"} + {:suite "interop-fixes / into onto a map" :label "accepts [k v] pairs" :expected "true" :actual "(= {:a 1} (into {} [[:a 1]]))"} + {:suite "interop-fixes / into onto a map" :label "map item onto empty {}" :expected "true" :actual "(= {:x 1} (into {} (list {:x 1})))"} + {:suite "interop-fixes / into onto a map" :label "conj a map onto {}" :expected "true" :actual "(= {:a 1} (conj {} {:a 1}))"} + {:suite "interop-fixes / a var is callable as its value" :label "call a var directly" :expected "42" :actual "(do (def vf (fn [x] (inc x))) ((var vf) 41))"} + {:suite "interop-fixes / a var is callable as its value" :label "var bound as a client fn" :expected "\"ok\"" :actual "(do (def base (fn [_] \"ok\")) (def mw (fn [client] (fn [req] (client req)))) ((mw (var base)) {}))"} + {:suite "control / conditionals" :label "if true" :expected "1" :actual "(if true 1 2)"} + {:suite "control / conditionals" :label "if false" :expected "2" :actual "(if false 1 2)"} + {:suite "control / conditionals" :label "if nil is false" :expected "2" :actual "(if nil 1 2)"} + {:suite "control / conditionals" :label "if no else" :expected "nil" :actual "(if false 1)"} + {:suite "control / conditionals" :label "when true" :expected "3" :actual "(when true 1 2 3)"} + {:suite "control / conditionals" :label "when false" :expected "nil" :actual "(when false 1)"} + {:suite "control / conditionals" :label "when-not" :expected "1" :actual "(when-not false 1)"} + {:suite "control / conditionals" :label "cond" :expected ":b" :actual "(cond false :a true :b :else :c)"} + {:suite "control / conditionals" :label "cond :else" :expected ":c" :actual "(cond false :a false :b :else :c)"} + {:suite "control / conditionals" :label "cond no match" :expected "nil" :actual "(cond false :a)"} + {:suite "control / conditionals" :label "condp" :expected "\"two\"" :actual "(condp = 2 1 \"one\" 2 \"two\" \"other\")"} + {:suite "control / conditionals" :label "case" :expected ":b" :actual "(case 2 1 :a 2 :b :default)"} + {:suite "control / conditionals" :label "case default" :expected ":d" :actual "(case 9 1 :a 2 :b :d)"} + {:suite "control / conditionals" :label "case multi" :expected ":ab" :actual "(case 2 (1 2) :ab 3 :c)"} + {:suite "control / conditionals" :label "case symbol const" :expected ":s" :actual "(case 'foo foo :s :default)"} + {:suite "control / conditionals" :label "case vector const" :expected ":v" :actual "(case [1 2] [1 2] :v :default)"} + {:suite "control / conditionals" :label "case map const" :expected ":m" :actual "(case {:a 1} {:a 1} :m :default)"} + {:suite "control / conditionals" :label "case list const" :expected ":l" :actual "(case '(a b) (quote (a b)) :l :default)"} + {:suite "control / conditionals" :label "case keyword" :expected ":k" :actual "(case :x :x :k :default)"} + {:suite "control / logic" :label "and all true" :expected "3" :actual "(and 1 2 3)"} + {:suite "control / logic" :label "and short circuits" :expected "nil" :actual "(and 1 nil 3)"} + {:suite "control / logic" :label "and empty" :expected "true" :actual "(and)"} + {:suite "control / logic" :label "or first truthy" :expected "1" :actual "(or nil 1 2)"} + {:suite "control / logic" :label "or all false" :expected "false" :actual "(or nil false)"} + {:suite "control / logic" :label "or empty" :expected "nil" :actual "(or)"} + {:suite "control / logic" :label "not" :expected "false" :actual "(not true)"} + {:suite "control / let & loop" :label "let" :expected "3" :actual "(let [a 1 b 2] (+ a b))"} + {:suite "control / let & loop" :label "let sequential" :expected "3" :actual "(let [a 1 b (+ a 2)] b)"} + {:suite "control / let & loop" :label "let shadowing" :expected "2" :actual "(let [a 1] (let [a 2] a))"} + {:suite "control / let & loop" :label "letfn mutual" :expected "true" :actual "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 10))"} + {:suite "control / let & loop" :label "loop/recur" :expected "15" :actual "(loop [i 1 acc 0] (if (> i 5) acc (recur (inc i) (+ acc i))))"} + {:suite "control / let & loop" :label "when-let" :expected "2" :actual "(when-let [x 1] (inc x))"} + {:suite "control / let & loop" :label "when-let nil" :expected "nil" :actual "(when-let [x nil] (inc x))"} + {:suite "control / let & loop" :label "if-let" :expected "2" :actual "(if-let [x 1] (inc x) :none)"} + {:suite "control / let & loop" :label "if-let else" :expected ":none" :actual "(if-let [x nil] (inc x) :none)"} + {:suite "control / let & loop" :label "if-some zero" :expected "1" :actual "(if-some [x 0] (inc x) :none)"} + {:suite "control / let & loop" :label "when-some nil" :expected "nil" :actual "(when-some [x nil] x)"} + {:suite "control / conditional-binding scope" :label "if-let else sees outer" :expected "5" :actual "(let [x 5] (if-let [x nil] :then x))"} + {:suite "control / conditional-binding scope" :label "if-let then binds" :expected "7" :actual "(let [x 5] (if-let [x 7] x :else))"} + {:suite "control / conditional-binding scope" :label "if-some else sees outer" :expected "5" :actual "(let [x 5] (if-some [x nil] :then x))"} + {:suite "control / conditional-binding scope" :label "if-some binds false" :expected "false" :actual "(if-some [x false] x :else)"} + {:suite "control / conditional-binding scope" :label "when-let else via or" :expected "5" :actual "(let [x 5] (or (when-let [x nil] x) x))"} + {:suite "control / conditional-binding scope" :label "when-let multi-form body" :expected "14" :actual "(when-let [x 7] (inc x) (* x 2))"} + {:suite "control / conditional-binding scope" :label "if-let in fn param" :expected "9" :actual "((fn [xs] (if-let [xs nil] :then xs)) 9)"} + {:suite "control / conditional-binding scope" :label "when-some binds zero" :expected "1" :actual "(when-some [x 0] (inc x))"} + {:suite "control / conditional-binding scope" :label "if-let evals test once" :expected "1" :actual "(let [c (atom 0)] (if-let [v (do (swap! c inc) :v)] @c :none))"} + {:suite "control / loop lowering (jolt-v28u)" :label "closure captures per-iter binding" :expected "[0 1 2]" :actual "(mapv (fn [g] (g)) (loop [i 0 fs []] (if (< i 3) (recur (inc i) (conj fs (fn [] i))) fs)))"} + {:suite "control / loop lowering (jolt-v28u)" :label "fib via loop" :expected "55" :actual "(loop [a 0 b 1 i 0] (if (= i 10) a (recur b (+ a b) (inc i))))"} + {:suite "control / loop lowering (jolt-v28u)" :label "recur args no clobber" :expected "[2 1]" :actual "(loop [a 1 b 2 n 0] (if (= n 1) [a b] (recur b a (inc n))))"} + {:suite "control / loop lowering (jolt-v28u)" :label "nested loops" :expected "9" :actual "(loop [i 0 s 0] (if (= i 3) s (recur (inc i) (loop [j 0 t s] (if (= j 3) t (recur (inc j) (inc t)))))))"} + {:suite "control / loop lowering (jolt-v28u)" :label "loop sequential init" :expected "12" :actual "(loop [a 1 b (+ a 10)] (+ a b))"} + {:suite "control / loop lowering (jolt-v28u)" :label "recur through let" :expected "6" :actual "(loop [i 0 acc 0] (let [x (* i 2)] (if (< i 3) (recur (inc i) (+ acc x)) acc)))"} + {:suite "control / loop lowering (jolt-v28u)" :label "fn-arity recur intact" :expected "15" :actual "((fn f [n acc] (if (zero? n) acc (recur (dec n) (+ acc n)))) 5 0)"} + {:suite "control / iteration" :label "dotimes side-effect" :expected "5" :actual "(let [a (atom 0)] (dotimes [i 5] (swap! a inc)) @a)"} + {:suite "control / iteration" :label "while" :expected "5" :actual "(let [a (atom 0)] (while (< @a 5) (swap! a inc)) @a)"} + {:suite "control / iteration" :label "for" :expected "[0 1 2]" :actual "(for [x (range 3)] x)"} + {:suite "control / iteration" :label "for nested" :expected "[[0 :a] [0 :b] [1 :a] [1 :b]]" :actual "(for [x (range 2) y [:a :b]] [x y])"} + {:suite "control / iteration" :label "for :when" :expected "[0 2 4]" :actual "(for [x (range 6) :when (even? x)] x)"} + {:suite "control / iteration" :label "for :while" :expected "[0 1 2]" :actual "(for [x (range 10) :while (< x 3)] x)"} + {:suite "control / iteration" :label "for :let" :expected "[0 1 4]" :actual "(for [x (range 3) :let [sq (* x x)]] sq)"} + {:suite "control / iteration" :label "for :let+:when" :expected "[4 6 8]" :actual "(for [x (range 5) :let [y (* x 2)] :when (> y 3)] y)"} + {:suite "control / iteration" :label "for multi :when" :expected "[[1 :a] [1 :b]]" :actual "(for [x [0 1] :when (odd? x) y [:a :b]] [x y])"} + {:suite "control / iteration" :label "for destructure" :expected "[3 7]" :actual "(for [[a b] [[1 2] [3 4]]] (+ a b))"} + {:suite "control / iteration" :label "doseq side-effect" :expected "6" :actual "(let [a (atom 0)] (doseq [x [1 2 3]] (swap! a (fn [v] (+ v x)))) @a)"} + {:suite "control / iteration" :label "doseq nested" :expected "4" :actual "(let [c (atom 0)] (doseq [x [1 2] y [10 20]] (swap! c inc)) @c)"} + {:suite "control / iteration" :label "doseq :when" :expected "[1 3]" :actual "(let [a (atom [])] (doseq [x [1 2 3] :when (odd? x)] (swap! a conj x)) @a)"} + {:suite "control / iteration" :label "doseq :while" :expected "6" :actual "(let [a (atom 0)] (doseq [x (range 10) :while (< x 4)] (swap! a + x)) @a)"} + {:suite "control / iteration" :label "doseq :let" :expected "[0 1 4]" :actual "(let [a (atom [])] (doseq [x (range 3) :let [sq (* x x)]] (swap! a conj sq)) @a)"} + {:suite "control / iteration" :label "doseq returns nil" :expected "nil" :actual "(doseq [x [1 2 3]] x)"} + {:suite "control / threading" :label "->" :expected "6" :actual "(-> 1 inc (+ 4))"} + {:suite "control / threading" :label "-> with forms" :expected "[1 2 3]" :actual "(-> [] (conj 1) (conj 2) (conj 3))"} + {:suite "control / threading" :label "->>" :expected "9" :actual "(->> [1 2 3] (map inc) (reduce +))"} + {:suite "control / threading" :label "as->" :expected "2" :actual "(as-> [0 1] x (map inc x) (reverse x) (first x))"} + {:suite "control / threading" :label "some->" :expected "2" :actual "(some-> 1 inc)"} + {:suite "control / threading" :label "some-> nil stops" :expected "nil" :actual "(some-> nil inc)"} + {:suite "control / threading" :label "some->>" :expected "[2 3]" :actual "(some->> [1 2] (map inc))"} + {:suite "control / threading" :label "cond->" :expected "2" :actual "(cond-> 1 true inc false inc)"} + {:suite "control / threading" :label "cond->>" :expected "[1 2]" :actual "(cond->> [2] true (cons 1))"} + {:suite "control / threading" :label "doto returns subject" :expected "5" :actual "(let [a (doto (atom 0) (reset! 5))] @a)"} + {:suite "deftype / custom toString" :label ".toString uses the method" :expected "\"hi\"" :actual "(do (deftype Foo [s] Object (toString [_] s)) (.toString (->Foo \"hi\")))"} + {:suite "deftype / custom toString" :label "str uses the method" :expected "\"hi\"" :actual "(do (deftype Foo [s] Object (toString [_] s)) (str (->Foo \"hi\")))"} + {:suite "deftype / custom toString" :label "str concatenation uses it" :expected "\"\"" :actual "(do (deftype Foo [s] Object (toString [_] s)) (str \"<\" (->Foo \"hi\") \">\"))"} + {:suite "deftype / custom toString" :label "computed toString" :expected "\"v=7\"" :actual "(do (deftype Boxed [v] Object (toString [_] (str \"v=\" v))) (str (->Boxed 7)))"} + {:suite "deftype / custom toString" :label "defrecord without toString keeps repr" :expected "true" :actual "(do (defrecord Bar [x]) (boolean (re-find #\"Bar\" (str (->Bar 1)))))"} + {:suite "deftype / custom toString" :label "pr-str of a defrecord is the repr" :expected "true" :actual "(do (defrecord Baz [x]) (boolean (re-find #\"\\{\" (pr-str (->Baz 1)))))"} + {:suite "destructure / sequential" :label "basic vector" :expected "3" :actual "(let [[a b] [1 2]] (+ a b))"} + {:suite "destructure / sequential" :label "skip with _" :expected "3" :actual "(let [[_ b] [1 2]] (+ b 1))"} + {:suite "destructure / sequential" :label "rest with &" :expected "[3 4]" :actual "(let [[a & more] [1 3 4]] more)"} + {:suite "destructure / sequential" :label ":as whole" :expected "[1 2]" :actual "(let [[a :as v] [1 2]] v)"} + {:suite "destructure / sequential" :label "nested" :expected "3" :actual "(let [[[a b]] [[1 2]]] (+ a b))"} + {:suite "destructure / sequential" :label "fewer values nil" :expected "nil" :actual "(let [[a b c] [1 2]] c)"} + {:suite "destructure / sequential" :label "over a list" :expected "1" :actual "(let [[a] (list 1 2)] a)"} + {:suite "destructure / sequential" :label "over a seq" :expected "2" :actual "(let [[a b] (rest [9 1 2])] b)"} + {:suite "destructure / sequential" :label "string chars" :expected "\\a" :actual "(let [[a] (seq \"ab\")] a)"} + {:suite "destructure / associative" :label "keys" :expected "3" :actual "(let [{:keys [a b]} {:a 1 :b 2}] (+ a b))"} + {:suite "destructure / associative" :label ":as map" :expected "{:a 1}" :actual "(let [{:as m} {:a 1}] m)"} + {:suite "destructure / associative" :label ":or default" :expected "9" :actual "(let [{:keys [a] :or {a 9}} {}] a)"} + {:suite "destructure / associative" :label ":or present" :expected "1" :actual "(let [{:keys [a] :or {a 9}} {:a 1}] a)"} + {:suite "destructure / associative" :label "explicit binding" :expected "1" :actual "(let [{x :a} {:a 1}] x)"} + {:suite "destructure / associative" :label "nested map" :expected "2" :actual "(let [{{b :b} :a} {:a {:b 2}}] b)"} + {:suite "destructure / associative" :label "keys + as" :expected "[1 {:a 1}]" :actual "(let [{:keys [a] :as m} {:a 1}] [a m])"} + {:suite "destructure / associative" :label "map in vector" :expected "1" :actual "(let [[{:keys [a]}] [{:a 1}]] a)"} + {:suite "destructure / in forms" :label "fn params" :expected "3" :actual "((fn [[a b]] (+ a b)) [1 2])"} + {:suite "destructure / in forms" :label "fn map param" :expected "1" :actual "((fn [{:keys [a]}] a) {:a 1})"} + {:suite "destructure / in forms" :label "defn destructure" :expected "3" :actual "(do (defn f [[a b]] (+ a b)) (f [1 2]))"} + {:suite "destructure / in forms" :label "loop destructure" :expected "3" :actual "(loop [[a b] [1 2]] (+ a b))"} + {:suite "destructure / in forms" :label "doseq destructure" :expected "12" :actual "(let [s (atom 0)] (doseq [[k v] {:a 4 :b 8}] (swap! s (fn [x] (+ x v)))) @s)"} + {:suite "destructure / in forms" :label "for destructure" :expected "[3 7]" :actual "(for [[a b] [[1 2] [3 4]]] (+ a b))"} + {:suite "destructure / in forms" :label "& rest in fn" :expected "[2 3]" :actual "((fn [a & more] more) 1 2 3)"} + {:suite "destructure / associative extras" :label ":strs" :expected "7" :actual "(let [{:strs [a]} {\"a\" 7}] a)"} + {:suite "destructure / associative extras" :label ":syms" :expected "8" :actual "(let [{:syms [a]} {(quote a) 8}] a)"} + {:suite "destructure / associative extras" :label "namespaced :keys" :expected "3" :actual "(let [{:keys [x/y]} {:x/y 3}] y)"} + {:suite "destructure / associative extras" :label "namespaced :syms" :expected "4" :actual "(let [{:syms [p/q]} {(quote p/q) 4}] q)"} + {:suite "destructure / associative extras" :label "keyword :keys" :expected "3" :actual "(let [{:keys [:a :b]} {:a 1 :b 2}] (+ a b))"} + {:suite "destructure / associative extras" :label "keyword :keys ns" :expected "3" :actual "(let [{:keys [:x/y]} {:x/y 3}] y)"} + {:suite "destructure / keyword args (& {:keys})" :label "fn kwargs" :expected "[1 2]" :actual "(do (defn f [& {:keys [a b]}] [a b]) (f :a 1 :b 2))"} + {:suite "destructure / keyword args (& {:keys})" :label "fn kwargs + fixed" :expected "[0 5]" :actual "(do (defn g [x & {:keys [a]}] [x a]) (g 0 :a 5))"} + {:suite "destructure / keyword args (& {:keys})" :label "fn kwargs :or" :expected "9" :actual "(do (defn h [& {:keys [a] :or {a 9}}] a) (h))"} + {:suite "destructure / keyword args (& {:keys})" :label "fn kwargs trailing map" :expected "7" :actual "(do (defn k [& {:keys [a]}] a) (k {:a 7}))"} + {:suite "destructure / fn params & loop" :label "fn vector param" :expected "7" :actual "((fn [[a b]] (+ a b)) [3 4])"} + {:suite "destructure / fn params & loop" :label "fn map param" :expected "30" :actual "((fn [{:keys [x y]}] (* x y)) {:x 5 :y 6})"} + {:suite "destructure / fn params & loop" :label "fn :or param" :expected "7" :actual "((fn [{:keys [x] :or {x 7}}] x) {})"} + {:suite "destructure / fn params & loop" :label "fn multi-arity destr" :expected "15" :actual "((fn ([[a]] a) ([[a] b] (+ a b))) [10] 5)"} + {:suite "destructure / fn params & loop" :label "loop vector binding" :expected "[4 2]" :actual "(loop [[a b] [1 2] n 0] (if (< n 3) (recur [(inc a) b] (inc n)) [a b]))"} + {:suite "destructure / fn params & loop" :label "loop map binding" :expected "4" :actual "(loop [{:keys [v]} {:v 1} n 0] (if (< n 2) (recur {:v (* v 2)} (inc n)) v))"} + {:suite "destructure / fn params & loop" :label "loop init sees destr" :expected "[1 2 3]" :actual "(loop [[a b] [1 2] c (+ a b)] [a b c])"} + {:suite "destructure / primitives reject patterns (jolt-f79)" :label "fn* fixed pattern" :expected :throws :actual "((fn* [[a b]] a) [1 2])"} + {:suite "destructure / primitives reject patterns (jolt-f79)" :label "fn* rest pattern" :expected :throws :actual "((fn* [a & [b]] b) 1 2 3)"} + {:suite "destructure / primitives reject patterns (jolt-f79)" :label "let* pattern" :expected :throws :actual "(let* [[a b] [1 2]] a)"} + {:suite "destructure / primitives reject patterns (jolt-f79)" :label "loop* pattern" :expected :throws :actual "(loop* [[a b] [1 2]] a)"} + {:suite "destructure / primitives reject patterns (jolt-f79)" :label "fn desugars" :expected "[1 2]" :actual "((fn [[a b]] [a b]) [1 2])"} + {:suite "destructure / primitives reject patterns (jolt-f79)" :label "let desugars" :expected "[1 2]" :actual "(let [[a b] [1 2]] [a b])"} + {:suite "destructure / macro params" :label "macro & [a & more :as all]" :expected "[1 [2 3] [1 2 3]]" :actual "(do (defmacro m [& [a & more :as all]] (list (quote quote) [a (vec more) (vec all)])) (m 1 2 3))"} + {:suite "destructure / macro params" :label "macro fixed destructure" :expected "[2 1]" :actual "(do (defmacro mm [[a b]] (list (quote quote) [b a])) (mm [1 2]))"} + {:suite "destructure / macro params" :label "macro & {:keys}" :expected "5" :actual "(do (defmacro mk [& {:keys [x]}] (list (quote quote) x)) (mk :x 5))"} + {:suite "exceptions / try-catch" :label "catch :default" :expected ":caught" :actual "(try (throw (ex-info \"boom\" {})) (catch :default e :caught))"} + {:suite "exceptions / try-catch" :label "catch by class" :expected ":caught" :actual "(try (throw (ex-info \"boom\" {})) (catch Exception e :caught))"} + {:suite "exceptions / try-catch" :label "catch binds error" :expected "\"boom\"" :actual "(try (throw (ex-info \"boom\" {})) (catch :default e (ex-message e)))"} + {:suite "exceptions / try-catch" :label "no throw -> body" :expected "1" :actual "(try 1 (catch :default e :caught))"} + {:suite "exceptions / try-catch" :label "finally runs on ok" :expected "2" :actual "(let [a (atom 0)] (try 2 (finally (reset! a 9))) )"} + {:suite "exceptions / try-catch" :label "finally runs on throw" :expected "9" :actual "(let [a (atom 0)] (try (throw (ex-info \"x\" {})) (catch :default e nil) (finally (reset! a 9))) @a)"} + {:suite "exceptions / try-catch" :label "catch value of body" :expected "5" :actual "(try (+ 2 3) (catch :default e 0))"} + {:suite "exceptions / try-catch" :label "malformed catch: non-symbol binding" :expected :throws :actual "(try 1 (catch e (* e 10)))"} + {:suite "exceptions / try-catch" :label "malformed catch: literal binding" :expected :throws :actual "(try 1 (catch e 5))"} + {:suite "exceptions / try-catch" :label "malformed catch: too short" :expected :throws :actual "(try 1 (catch Exception))"} + {:suite "exceptions / assert" :label "assert true -> ok" :expected ":ok" :actual "(do (assert true) :ok)"} + {:suite "exceptions / assert" :label "assert expr -> ok" :expected ":ok" :actual "(do (assert (= 1 1)) :ok)"} + {:suite "exceptions / assert" :label "assert false throws" :expected :throws :actual "(assert false)"} + {:suite "exceptions / assert" :label "assert nil throws" :expected :throws :actual "(assert nil)"} + {:suite "exceptions / ex-info" :label "ex-message" :expected "\"oops\"" :actual "(ex-message (ex-info \"oops\" {}))"} + {:suite "exceptions / ex-info" :label "ex-data" :expected "{:k 1}" :actual "(ex-data (ex-info \"oops\" {:k 1}))"} + {:suite "exceptions / ex-info" :label "ex-data via catch" :expected "{:code 42}" :actual "(try (throw (ex-info \"e\" {:code 42})) (catch :default e (ex-data e)))"} + {:suite "exceptions / ex-info" :label "ex-cause" :expected "true" :actual "(let [c (ex-info \"root\" {})] (= c (ex-cause (ex-info \"outer\" {} c))))"} + {:suite "exceptions / ex-info" :label "propagates to outer" :expected "\"inner\"" :actual "(try (try (throw (ex-info \"inner\" {})) (finally nil)) (catch :default e (ex-message e)))"} + {:suite "exceptions / ex-info" :label "catch binds thrown value" :expected "42" :actual "(try (throw 42) (catch :default e e))"} + {:suite "exceptions / ex-info" :label "rethrow preserves ex" :expected "\"inner\"" :actual "(try (try (throw (ex-info \"inner\" {})) (catch :default e (throw e))) (catch :default e (ex-message e)))"} + {:suite "exceptions / ex-info" :label "ex-data on non-ex" :expected "nil" :actual "(ex-data 42)"} + {:suite "exceptions / ex-info" :label "ex-cause on non-ex" :expected "nil" :actual "(ex-cause {:k 1})"} + {:suite "exceptions / ex-info" :label "ex-message of string" :expected "nil" :actual "(ex-message \"hi\")"} + {:suite "forms / case" :label "bool" :expected ":yes" :actual "(case true true :yes false :no :default)"} + {:suite "forms / case" :label "keyword match" :expected ":b" :actual "(case :a :x :wrong :a :b :default)"} + {:suite "forms / case" :label "number match" :expected ":two" :actual "(case 2 1 :one 2 :two :default)"} + {:suite "forms / case" :label "string match" :expected ":hit" :actual "(case \"x\" \"y\" :miss \"x\" :hit :default)"} + {:suite "forms / case" :label "nil match" :expected ":nada" :actual "(case nil nil :nada :default)"} + {:suite "forms / case" :label "default" :expected ":def" :actual "(case 99 1 :one 2 :two :def)"} + {:suite "forms / case" :label "list of consts" :expected ":vowel" :actual "(case \\a (\\a \\e \\i \\o \\u) :vowel :consonant)"} + {:suite "forms / case" :label "no match no default" :expected :throws :actual "(case 5 1 :one)"} + {:suite "forms / case" :label "duplicate keys" :expected :throws :actual "(case 1 1 :one 1 :dup :default)"} + {:suite "forms / case" :label "duplicate in or-group" :expected :throws :actual "(case 2 (1 2) :a (2 3) :b :default)"} + {:suite "forms / fn" :label "named fn nil" :expected "nil" :actual "((fn* foo-bar []))"} + {:suite "forms / fn" :label "immediate call" :expected "1" :actual "((fn* [] 1))"} + {:suite "forms / fn" :label "args" :expected "[:a :b]" :actual "((fn* [a b] [a b]) :a :b)"} + {:suite "forms / fn" :label "multi-arity 0" :expected "0" :actual "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add))"} + {:suite "forms / fn" :label "multi-arity 1" :expected "-500" :actual "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add -500))"} + {:suite "forms / fn" :label "multi-arity 2" :expected "-450" :actual "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add -500 50))"} + {:suite "forms / fn" :label "variadic rest" :expected "[3 4]" :actual "(do (def v (fn* ([a b & args] args) ([] 0))) (v 1 2 3 4))"} + {:suite "forms / fn" :label "variadic empty" :expected "0" :actual "(do (def v (fn* ([a b & args] args) ([] 0))) (v))"} + {:suite "forms / fn" :label "variadic collect" :expected "[{} nil :m]" :actual "((fn* [a b & args] args) 'w 't {} nil :m)"} + {:suite "forms / fn" :label "closure capture" :expected "8" :actual "(do (def adder (fn* [n] (fn* [x] (+ x n)))) ((adder 5) 3))"} + {:suite "forms / fn" :label "recur countdown" :expected "0" :actual "(do (def cd (fn* [n] (if (< 0 n) (recur (+ n -1)) n))) (cd 10))"} + {:suite "forms / fn" :label "named self-recur" :expected "120" :actual "(do (def f (fn* fact [n] (if (= n 0) 1 (* n (fact (dec n)))))) (f 5))"} + {:suite "forms / fn" :label "no param vector" :expected :throws :actual "(fn* foo)"} + {:suite "forms / fn" :label "non-symbol param" :expected :throws :actual "(fn* [1] 1)"} + {:suite "forms / let" :label "literal" :expected "1" :actual "(let* [a 1] a)"} + {:suite "forms / let" :label "multiple" :expected "[1 2]" :actual "(let* [a 1 b 2] [a b])"} + {:suite "forms / let" :label "previous ref" :expected ":bee" :actual "(let* [a 1 b (if (= 1 a) :bee :uh-oh)] b)"} + {:suite "forms / let" :label "nested let" :expected "3" :actual "(let* [a 5 b (let* [c -2] (+ a c))] b)"} + {:suite "forms / let" :label "fn value bound" :expected "\":foo\"" :actual "(let* [kw->str (fn* [kw] (str kw))] (kw->str :foo))"} + {:suite "forms / let" :label "shadowing" :expected "2" :actual "(let* [a 1 a 2] a)"} + {:suite "forms / letfn" :label "mutual top" :expected "[1 2]" :actual "(letfn [(a [] 1) (b [] 2)] [(a) (b)])"} + {:suite "forms / letfn" :label "mutual recursion" :expected ":done" :actual "(letfn [(ev? [n] (if (= 0 n) :done (od? (dec n)))) (od? [n] (ev? n))] (ev? 4))"} + {:suite "forms / letfn" :label "nested letfn" :expected "3" :actual "(letfn [(a [] 5) (b [] (letfn [(c [] -2)] (+ (a) (c))))] (b))"} + {:suite "forms / loop" :label "sum" :expected "55" :actual "(loop* [sum 0 cnt 10] (if (= cnt 0) sum (recur (+ cnt sum) (dec cnt))))"} + {:suite "forms / loop" :label "multi binding" :expected "[4 2]" :actual "(loop* [a 1 b 2 n 0] (if (< n 3) (recur (inc a) b (inc n)) [a b]))"} + {:suite "forms / loop" :label "init sees prior" :expected "[1 2 3]" :actual "(loop* [a 1 b (+ a 1) c (+ b 1)] [a b c])"} + {:suite "forms / try" :label "immediate throw caught" :expected ":caught" :actual "(try (throw :boom) (catch :default e :caught))"} + {:suite "forms / try" :label "first throw wins" :expected "\"a\"" :actual "(try (throw (ex-info \"a\" {})) (throw (ex-info \"b\" {})) (catch :default e (ex-message e)))"} + {:suite "forms / try" :label "catch ex-data" :expected "7" :actual "(try (throw (ex-info \"e\" {:v 7})) (catch :default e (:v (ex-data e))))"} + {:suite "forms / try" :label "finally runs" :expected "9" :actual "(let [a (atom 0)] (try 1 (finally (reset! a 9))) @a)"} + {:suite "forms / try" :label "body value w/ finally" :expected "1" :actual "(try 1 (finally 2))"} + {:suite "forms / try" :label "catch value w/ finally" :expected ":h" :actual "(try (throw (ex-info \"x\" {})) (catch :default e :h) (finally :ignored))"} + {:suite "forms / try" :label "no throw skips catch" :expected "5" :actual "(try 5 (catch :default e :nope))"} + {:suite "forms / if-do-def-call" :label "if truthy vec" :expected ":fine" :actual "(if [:ok] :fine :no)"} + {:suite "forms / if-do-def-call" :label "if truthy str" :expected ":fine" :actual "(if \"good?\" :fine :no)"} + {:suite "forms / if-do-def-call" :label "if nil = false" :expected ":else" :actual "(if nil :then :else)"} + {:suite "forms / if-do-def-call" :label "if no else" :expected "nil" :actual "(if false 1)"} + {:suite "forms / if-do-def-call" :label "do nested" :expected "1" :actual "(do (do (do (do 1))))"} + {:suite "forms / if-do-def-call" :label "do returns last" :expected "3" :actual "(do 1 2 3)"} + {:suite "forms / if-do-def-call" :label "def + deref var" :expected "true" :actual "(var? (def one 1))"} + {:suite "forms / if-do-def-call" :label "def no init interns var" :expected "true" :actual "(var? (def no-init))"} + {:suite "forms / if-do-def-call" :label "def no init keeps existing root" :expected "7" :actual "(do (def kept 7) (def kept) kept)"} + {:suite "forms / if-do-def-call" :label "declare interns var" :expected "true" :actual "(do (declare fwd-declared) (var? (var fwd-declared)))"} + {:suite "forms / if-do-def-call" :label "def redefine" :expected "100" :actual "(do (def one 1) (def one 100) one)"} + {:suite "forms / if-do-def-call" :label "def in fn mutates" :expected "[:default :meow]" :actual "(do (def a :default) (def set-a (fn* [v] (def a v))) (let* [before a] (set-a :meow) [before a]))"} + {:suite "forms / if-do-def-call" :label "call literal fn" :expected "1" :actual "((fn* [] 1))"} + {:suite "forms / if-do-def-call" :label "call nested" :expected "6" :actual "(+ ((fn* [] 1)) ((fn* [] 2)) ((fn* [] 3)))"} + {:suite "forms / if-do-def-call" :label "call nil" :expected :throws :actual "(nil)"} + {:suite "forms / if arity (X1)" :label "bare if throws" :expected :throws :actual "(if)"} + {:suite "forms / if arity (X1)" :label "one-arg if throws" :expected :throws :actual "(if true)"} + {:suite "forms / if arity (X1)" :label "four-arg if throws" :expected :throws :actual "(if true 1 2 3)"} + {:suite "forms / if arity (X1)" :label "two-arg if ok" :expected "nil" :actual "(if false 1)"} + {:suite "forms / if arity (X1)" :label "three-arg if ok" :expected "2" :actual "(if false 1 2)"} + {:suite "functions / definition" :label "fn literal" :expected "3" :actual "((fn [a b] (+ a b)) 1 2)"} + {:suite "functions / definition" :label "fn shorthand" :expected "3" :actual "(#(+ %1 %2) 1 2)"} + {:suite "functions / definition" :label "fn shorthand %" :expected "2" :actual "(#(inc %) 1)"} + {:suite "functions / definition" :label "defn" :expected "5" :actual "(do (defn f [x] (+ x 2)) (f 3))"} + {:suite "functions / definition" :label "multi-arity" :expected "[1 5]" :actual "(do (defn f ([x] x) ([x y] (+ x y))) [(f 1) (f 2 3)])"} + {:suite "functions / definition" :label "variadic" :expected "[1 2 3]" :actual "(do (defn f [& xs] xs) (f 1 2 3))"} + {:suite "functions / definition" :label "variadic with fixed" :expected "[1 [2 3]]" :actual "(do (defn f [a & xs] [a xs]) (f 1 2 3))"} + {:suite "functions / definition" :label "closure captures" :expected "8" :actual "(do (defn adder [n] (fn [x] (+ x n))) ((adder 5) 3))"} + {:suite "functions / definition" :label "recursion" :expected "120" :actual "(do (defn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) (fact 5))"} + {:suite "functions / definition" :label "named fn self-ref" :expected "120" :actual "((fn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) 5)"} + {:suite "functions / definition" :label "param named `in`" :expected "1" :actual "((fn [in] (first in)) [1 2 3])"} + {:suite "functions / definition" :label "param `in` via core fn" :expected "3" :actual "((fn [in] (count in)) [1 2 3])"} + {:suite "functions / definition" :label "local `in` in let body" :expected "2" :actual "(let [in [2 3]] (first in))"} + {:suite "functions / application" :label "apply" :expected "6" :actual "(apply + [1 2 3])"} + {:suite "functions / application" :label "apply with leading" :expected "10" :actual "(apply + 1 2 [3 4])"} + {:suite "functions / application" :label "apply keyword" :expected "1" :actual "(apply :a [{:a 1}])"} + {:suite "functions / application" :label "partial" :expected "7" :actual "((partial + 5) 2)"} + {:suite "functions / application" :label "partial multi" :expected "10" :actual "((partial + 1 2) 3 4)"} + {:suite "functions / application" :label "comp" :expected "4" :actual "((comp inc inc) 2)"} + {:suite "functions / application" :label "comp order" :expected "5" :actual "((comp inc (fn [x] (* x 2))) 2)"} + {:suite "functions / application" :label "comp identity" :expected "3" :actual "((comp) 3)"} + {:suite "functions / application" :label "complement" :expected "true" :actual "((complement even?) 3)"} + {:suite "functions / application" :label "constantly" :expected "5" :actual "((constantly 5) 1 2 3)"} + {:suite "functions / application" :label "identity" :expected "7" :actual "(identity 7)"} + {:suite "functions / combinators" :label "juxt" :expected "[1 3]" :actual "((juxt first last) [1 2 3])"} + {:suite "functions / combinators" :label "fnil" :expected "1" :actual "((fnil inc 0) nil)"} + {:suite "functions / combinators" :label "fnil passes value" :expected "6" :actual "((fnil inc 0) 5)"} + {:suite "functions / combinators" :label "every-pred true" :expected "true" :actual "((every-pred pos? even?) 4)"} + {:suite "functions / combinators" :label "every-pred false" :expected "false" :actual "((every-pred pos? even?) 3)"} + {:suite "functions / combinators" :label "some-fn" :expected "true" :actual "((some-fn even? neg?) 3 4)"} + {:suite "functions / combinators" :label "memoize" :expected "2" :actual "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) x))) (f 1) (f 1) (f 2) @c)"} + {:suite "functions / combinators" :label "trampoline" :expected "10" :actual "(trampoline (fn f [n acc] (if (zero? n) acc (fn [] (f (dec n) (+ acc 2))))) 5 0)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "complement true" :expected "true" :actual "((complement pos?) -1)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "complement false" :expected "false" :actual "((complement pos?) 1)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "complement multi" :expected "true" :actual "((complement <) 3 2)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil patches nil" :expected "1" :actual "((fnil inc 0) nil)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil passes non-nil" :expected "6" :actual "((fnil inc 0) 5)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil two defaults" :expected "8" :actual "((fnil + 1 2) nil nil 5)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil only first 3" :expected "[:a :b :c nil]" :actual "((fnil vector :a :b :c) nil nil nil nil)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "fnil in update" :expected "{:k 1}" :actual "(update {} :k (fnil inc 0))"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "clojure-version" :expected "true" :actual "(string? (clojure-version))"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "bigdec" :expected "3M" :actual "(bigdec 3)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "numerator throws" :expected :throws :actual "(numerator 1)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "denominator throws" :expected :throws :actual "(denominator 1)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "supers empty set" :expected "#{}" :actual "(supers 1)"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "munge dashes" :expected "\"a_b\"" :actual "(munge \"a-b\")"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "munge symbol" :expected "(quote x_y)" :actual "(munge (quote x-y))"} + {:suite "clojure.core / leaf batch (complement fnil munge etc.)" :label "test no-test" :expected ":no-test" :actual "(test (quote foo))"} + {:suite "clojure.core / leaf batch 2" :label "key" :expected "1" :actual "(key (first {1 :a}))"} + {:suite "clojure.core / leaf batch 2" :label "val" :expected ":a" :actual "(val (first {1 :a}))"} + {:suite "clojure.core / leaf batch 2" :label "key non-entry throws" :expected :throws :actual "(key 5)"} + {:suite "clojure.core / leaf batch 2" :label "find hit" :expected "[:a 1]" :actual "(find {:a 1} :a)"} + {:suite "clojure.core / leaf batch 2" :label "find miss" :expected "nil" :actual "(find {:a 1} :b)"} + {:suite "clojure.core / leaf batch 2" :label "find nil value" :expected "[:a nil]" :actual "(find {:a nil} :a)"} + {:suite "clojure.core / leaf batch 2" :label "find on vector" :expected "[0 :x]" :actual "(find [:x :y] 0)"} + {:suite "clojure.core / leaf batch 2" :label "select-keys" :expected "{:a 1}" :actual "(select-keys {:a 1 :b 2} [:a])"} + {:suite "clojure.core / leaf batch 2" :label "select-keys nil val" :expected "{:a nil}" :actual "(select-keys {:a nil :b 2} [:a])"} + {:suite "clojure.core / leaf batch 2" :label "select-keys missing" :expected "{}" :actual "(select-keys {:a 1} [:z])"} + {:suite "clojure.core / leaf batch 2" :label "zipmap" :expected "{:a 1, :b 2}" :actual "(zipmap [:a :b] [1 2])"} + {:suite "clojure.core / leaf batch 2" :label "zipmap uneven" :expected "{:a 1}" :actual "(zipmap [:a :b] [1])"} + {:suite "clojure.core / leaf batch 2" :label "zipmap nil val" :expected "{:a nil}" :actual "(zipmap [:a] [nil])"} + {:suite "clojure.core / leaf batch 2" :label "merge" :expected "{:a 1, :b 2}" :actual "(merge {:a 1} {:b 2})"} + {:suite "clojure.core / leaf batch 2" :label "merge later wins" :expected "{:a 2}" :actual "(merge {:a 1} {:a 2})"} + {:suite "clojure.core / leaf batch 2" :label "merge nil arg" :expected "{:a 1}" :actual "(merge {:a 1} nil)"} + {:suite "clojure.core / leaf batch 2" :label "merge nil first" :expected "{:a 1}" :actual "(merge nil {:a 1})"} + {:suite "clojure.core / leaf batch 2" :label "merge all nil" :expected "nil" :actual "(merge nil nil)"} + {:suite "clojure.core / leaf batch 2" :label "merge empty" :expected "nil" :actual "(merge)"} + {:suite "clojure.core / leaf batch 2" :label "merge entry pair" :expected "{:a 1, :b 2}" :actual "(merge {:a 1} [:b 2])"} + {:suite "clojure.core / leaf batch 2" :label "merge-with" :expected "{:a 3}" :actual "(merge-with + {:a 1} {:a 2})"} + {:suite "clojure.core / leaf batch 2" :label "merge-with disjoint" :expected "{:a 1, :b 2}" :actual "(merge-with + {:a 1} {:b 2})"} + {:suite "clojure.core / leaf batch 2" :label "merge-with nil-val present" :expected "{:a 1}" :actual "(merge-with (fn [a b] (or a b)) {:a nil} {:a 1})"} + {:suite "clojure.core / leaf batch 2" :label "get-in" :expected "1" :actual "(get-in {:a {:b 1}} [:a :b])"} + {:suite "clojure.core / leaf batch 2" :label "get-in missing" :expected ":nf" :actual "(get-in {:a 1} [:z :y] :nf)"} + {:suite "clojure.core / leaf batch 2" :label "get-in nil value present" :expected "nil" :actual "(get-in {:a {:b nil}} [:a :b] :nf)"} + {:suite "clojure.core / leaf batch 2" :label "get-in empty path" :expected "{:a 1}" :actual "(get-in {:a 1} [])"} + {:suite "clojure.core / leaf batch 2" :label "memoize" :expected "2" :actual "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) x))) (f 1) (f 1) (f 2) (deref c))"} + {:suite "clojure.core / leaf batch 2" :label "memoize caches nil" :expected "1" :actual "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) nil))) (f 1) (f 1) (deref c))"} + {:suite "clojure.core / leaf batch 2" :label "partial" :expected "6" :actual "((partial + 1 2) 3)"} + {:suite "clojure.core / leaf batch 2" :label "partial no extra" :expected "3" :actual "((partial + 1 2))"} + {:suite "clojure.core / leaf batch 2" :label "partial many fixed" :expected "15" :actual "((partial + 1 2 3 4) 5)"} + {:suite "clojure.core / leaf batch 2" :label "trampoline" :expected "10" :actual "(trampoline (fn f [n acc] (if (zero? n) acc (fn [] (f (dec n) (+ acc 2))))) 5 0)"} + {:suite "clojure.core / leaf batch 2" :label "some? true" :expected "true" :actual "(some? 0)"} + {:suite "clojure.core / leaf batch 2" :label "some? false" :expected "false" :actual "(some? nil)"} + {:suite "clojure.core / leaf batch 2" :label "true?/false?" :expected "[true false false]" :actual "[(true? true) (true? 1) (false? nil)]"} + {:suite "clojure.core / leaf batch 2" :label "max" :expected "3" :actual "(max 1 3 2)"} + {:suite "clojure.core / leaf batch 2" :label "min" :expected "1" :actual "(min 3 1 2)"} + {:suite "clojure.core / leaf batch 2" :label "max single" :expected "5" :actual "(max 5)"} + {:suite "clojure.core / leaf batch 2" :label "max non-number throws" :expected :throws :actual "(max 1 :a)"} + {:suite "clojure.core / leaf batch 2" :label "reverse" :expected "[3 2 1]" :actual "(reverse [1 2 3])"} + {:suite "clojure.core / leaf batch 2" :label "reverse empty" :expected "[]" :actual "(reverse nil)"} + {:suite "clojure.core / leaf batch 2" :label "conj nil onto map" :expected "{:a 1}" :actual "(conj {:a 1} nil)"} + {:suite "clojure.core / leaf batch 3" :label "empty vector" :expected "[]" :actual "(empty [1 2])"} + {:suite "clojure.core / leaf batch 3" :label "empty list" :expected "[]" :actual "(empty (list 1))"} + {:suite "clojure.core / leaf batch 3" :label "empty map" :expected "{}" :actual "(empty {:a 1})"} + {:suite "clojure.core / leaf batch 3" :label "empty set" :expected "#{}" :actual "(empty #{1})"} + {:suite "clojure.core / leaf batch 3" :label "empty nil" :expected "nil" :actual "(empty nil)"} + {:suite "clojure.core / leaf batch 3" :label "empty string" :expected "nil" :actual "(empty \"abc\")"} + {:suite "clojure.core / leaf batch 3" :label "empty lazy is ()" :expected "[]" :actual "(empty (map inc [1 2]))"} + {:suite "clojure.core / leaf batch 3" :label "empty sorted keeps cmp" :expected "[3 1]" :actual "(vec (seq (into (empty (sorted-set-by > 1 2)) [1 3])))"} + {:suite "clojure.core / leaf batch 3" :label "assoc-in" :expected "{:a {:b 1}}" :actual "(assoc-in {} [:a :b] 1)"} + {:suite "clojure.core / leaf batch 3" :label "assoc-in deep" :expected "{:a {:b {:c 2}}}" :actual "(assoc-in {:a {:b {:c 1}}} [:a :b :c] 2)"} + {:suite "clojure.core / leaf batch 3" :label "assoc-in keeps siblings" :expected "{:a {:b 1, :c 2}}" :actual "(assoc-in {:a {:b 1}} [:a :c] 2)"} + {:suite "clojure.core / leaf batch 3" :label "assoc-in vector idx" :expected "[1 9]" :actual "(assoc-in [1 2] [1] 9)"} + {:suite "clojure.core / leaf batch 3" :label "assoc-in nested vec" :expected "[{:a 9}]" :actual "(assoc-in [{:a 1}] [0 :a] 9)"} + {:suite "clojure.core / leaf batch 3" :label "update-in" :expected "{:a {:b 2}}" :actual "(update-in {:a {:b 1}} [:a :b] inc)"} + {:suite "clojure.core / leaf batch 3" :label "update-in extra args" :expected "{:a {:b 111}}" :actual "(update-in {:a {:b 1}} [:a :b] + 10 100)"} + {:suite "clojure.core / leaf batch 3" :label "update-in fnil" :expected "{:a {:b 1}}" :actual "(update-in {} [:a :b] (fnil inc 0))"} + {:suite "clojure.core / leaf batch 3" :label "update-in single key" :expected "{:a 2}" :actual "(update-in {:a 1} [:a] inc)"} + {:suite "clojure.core / leaf batch 3" :label "interpose" :expected "[1 :s 2 :s 3]" :actual "(interpose :s [1 2 3])"} + {:suite "clojure.core / leaf batch 3" :label "interpose empty" :expected "[]" :actual "(interpose :s [])"} + {:suite "clojure.core / leaf batch 3" :label "interpose one" :expected "[1]" :actual "(interpose :s [1])"} + {:suite "clojure.core / leaf batch 3" :label "interpose is lazy" :expected "[0 :s 1]" :actual "(take 3 (interpose :s (range)))"} + {:suite "clojure.core / leaf batch 3" :label "interpose xform" :expected "[\"a\" \",\" \"b\"]" :actual "(vec (sequence (interpose \",\") [\"a\" \"b\"]))"} + {:suite "clojure.core / leaf batch 3" :label "take-nth" :expected "[1 3 5]" :actual "(take-nth 2 [1 2 3 4 5 6])"} + {:suite "clojure.core / leaf batch 3" :label "take-nth lazy" :expected "[0 3 6]" :actual "(take 3 (take-nth 3 (range)))"} + {:suite "clojure.core / leaf batch 3" :label "take-nth xform" :expected "[1 3 5]" :actual "(vec (sequence (take-nth 2) [1 2 3 4 5 6]))"} + {:suite "clojure.core / leaf batch 3" :label "take-nth into" :expected "[1 4]" :actual "(into [] (take-nth 3) [1 2 3 4 5])"} + {:suite "clojure.core / leaf batch 4" :label "sort-by keyfn" :expected "[[1 :b] [2 :a]]" :actual "(sort-by first [[2 :a] [1 :b]])"} + {:suite "clojure.core / leaf batch 4" :label "sort-by string keys" :expected "[\"a\" \"bb\" \"ccc\"]" :actual "(sort-by count [\"ccc\" \"a\" \"bb\"])"} + {:suite "clojure.core / leaf batch 4" :label "sort-by comparator" :expected "[3 2 1]" :actual "(sort-by identity > [1 3 2])"} + {:suite "clojure.core / leaf batch 4" :label "sort-by 3way cmp" :expected "[3 2 1]" :actual "(sort-by identity (fn [a b] (- b a)) [1 3 2])"} + {:suite "clojure.core / leaf batch 4" :label "sort-by mixed nil" :expected "[nil 1 2]" :actual "(sort-by identity [2 nil 1])"} + {:suite "clojure.core / leaf batch 4" :label "sort-by empty" :expected "[]" :actual "(sort-by first [])"} + {:suite "clojure.core / leaf batch 4" :label "sort-by nil coll" :expected "[]" :actual "(sort-by first nil)"} + {:suite "clojure.core / leaf batch 4" :label "rand-int range" :expected "true" :actual "(every? (fn [_] (let [r (rand-int 5)] (and (int? r) (<= 0 r 4)))) (range 50))"} + {:suite "clojure.core / leaf batch 4" :label "rand-int zero" :expected "0" :actual "(rand-int 1)"} + {:suite "clojure.core / leaf batch 4" :label "shuffle is permutation" :expected "true" :actual "(= (sort (shuffle [5 3 1 4 2])) [1 2 3 4 5])"} + {:suite "clojure.core / leaf batch 4" :label "shuffle returns vector" :expected "true" :actual "(vector? (shuffle [1 2 3]))"} + {:suite "clojure.core / leaf batch 4" :label "shuffle empty" :expected "[]" :actual "(shuffle [])"} + {:suite "clojure.core / leaf batch 4" :label "shuffle non-coll throws" :expected :throws :actual "(shuffle 5)"} + {:suite "clojure.core / leaf batch 4" :label "random-uuid is uuid" :expected "true" :actual "(uuid? (random-uuid))"} + {:suite "clojure.core / leaf batch 4" :label "random-uuid v4 shape" :expected "true" :actual "(boolean (re-matches #\"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\" (str (random-uuid))))"} + {:suite "clojure.core / leaf batch 4" :label "random-uuid distinct" :expected "true" :actual "(not= (random-uuid) (random-uuid))"} + {:suite "clojure.core / leaf batch 4" :label "char-escape newline" :expected "\"\\\\n\"" :actual "(char-escape-string \\newline)"} + {:suite "clojure.core / leaf batch 4" :label "char-escape quote" :expected "true" :actual "(= 2 (count (char-escape-string \\\")))"} + {:suite "clojure.core / leaf batch 4" :label "char-escape none" :expected "nil" :actual "(char-escape-string \\a)"} + {:suite "clojure.core / leaf batch 4" :label "char-name space" :expected "\"space\"" :actual "(char-name-string \\space)"} + {:suite "clojure.core / leaf batch 4" :label "char-name newline" :expected "\"newline\"" :actual "(char-name-string \\newline)"} + {:suite "clojure.core / leaf batch 4" :label "char-name none" :expected "nil" :actual "(char-name-string \\a)"} + {:suite "functions / recur into variadic arity" :label "counts rest via recur" :expected "3" :actual "((fn cnt [acc & xs] (if (seq xs) (recur (inc acc) (rest xs)) acc)) 0 :a :b :c)"} + {:suite "functions / recur into variadic arity" :label "zero-fixed variadic" :expected "4" :actual "((fn f [& xs] (if (< (count xs) 4) (recur (cons :x xs)) (count xs))) :a)"} + {:suite "functions / recur into variadic arity" :label "rest empties to nil" :expected "[:done]" :actual "((fn f [& xs] (if xs (recur (next xs)) (list :done))) 1 2)"} + {:suite "functions / recur into variadic arity" :label "multi-arity variadic recur" :expected "6" :actual "((fn ma ([a] a) ([a & xs] (if (seq xs) (recur (+ a (first xs)) (rest xs)) a))) 1 2 3)"} + {:suite "functions / recur into variadic arity" :label "recur passes nil rest" :expected ":empty" :actual "((fn f [acc & xs] (if (seq xs) (recur acc (rest xs)) :empty)) 0 1)"} + {:suite "functions / recur into variadic arity" :label "fixed-arity recur untouched" :expected "10" :actual "((fn f [n acc] (if (pos? n) (recur (dec n) (+ acc 2)) acc)) 5 0)"} + {:suite "functions / empty rest arg is nil" :label "no args" :expected ":nil" :actual "((fn [& r] (if r :truthy :nil)))"} + {:suite "functions / empty rest arg is nil" :label "after fixed" :expected ":nil" :actual "((fn [a & r] (if r :truthy :nil)) 1)"} + {:suite "functions / empty rest arg is nil" :label "via apply" :expected ":nil" :actual "(apply (fn [& r] (if r :truthy :nil)) [])"} + {:suite "functions / empty rest arg is nil" :label "defn no args" :expected ":nil" :actual "(do (defn er-f [& r] (if r :truthy :nil)) (er-f))"} + {:suite "functions / empty rest arg is nil" :label "non-empty unchanged" :expected "[1 2]" :actual "((fn [& r] r) 1 2)"} + {:suite "functions / empty rest arg is nil" :label "one extra" :expected "[2]" :actual "((fn [a & r] r) 1 2)"} + {:suite "functions / empty rest arg is nil" :label "rest destructure with no args" :expected ":nil" :actual "((fn [& [a]] (if a :truthy :nil)))"} + {:suite "functions / arity enforcement" :label "fixed extra args" :expected :throws :actual "((fn [x] x) 1 2)"} + {:suite "functions / arity enforcement" :label "fixed missing args" :expected :throws :actual "((fn [x y] x) 1)"} + {:suite "functions / arity enforcement" :label "fixed zero of one" :expected :throws :actual "((fn [x] x))"} + {:suite "functions / arity enforcement" :label "named defn extra" :expected :throws :actual "(do (defn af1 [x] x) (af1 1 2))"} + {:suite "functions / arity enforcement" :label "overlay fn extra" :expected :throws :actual "(identity 1 2)"} + {:suite "functions / arity enforcement" :label "through apply" :expected :throws :actual "(apply (fn [x] x) [1 2])"} + {:suite "functions / arity enforcement" :label "through update" :expected :throws :actual "(update {:k 1} :k identity 1 2 3 4)"} + {:suite "functions / arity enforcement" :label "variadic below min" :expected :throws :actual "((fn [x & r] x))"} + {:suite "functions / arity enforcement" :label "variadic at min" :expected "nil" :actual "((fn [x & r] r) 1)"} + {:suite "functions / arity enforcement" :label "variadic above min" :expected "[2 3]" :actual "((fn [x & r] r) 1 2 3)"} + {:suite "functions / arity enforcement" :label "multi-arity no match" :expected :throws :actual "((fn ([x] x) ([x y] y)) 1 2 3)"} + {:suite "functions / arity enforcement" :label "multi-arity variadic below min" :expected :throws :actual "((fn ([x] x) ([x y & r] r)))"} + {:suite "functions / arity enforcement" :label "destructured param counts as one" :expected "3" :actual "((fn [[a b] c] c) [1 2] 3)"} + {:suite "functions / arity enforcement" :label "destructured extra throws" :expected :throws :actual "((fn [[a b]] a) [1 2] [3 4])"} + {:suite "functions / arity enforcement" :label "hof exact arity ok" :expected "[2 4]" :actual "(mapv (fn [x] (* 2 x)) [1 2])"} + {:suite "functions / arity enforcement" :label "zero-arity fn ok" :expected "7" :actual "((fn [] 7))"} + {:suite "clojure.core / futures — deref" :label "future + deref" :expected "3" :actual "(deref (future (+ 1 2)))"} + {:suite "clojure.core / futures — deref" :label "@ reader macro derefs" :expected "42" :actual "@(future (* 6 7))"} + {:suite "clojure.core / futures — deref" :label "future returns collection" :expected "[2 3 4]" :actual "(deref (future (mapv inc [1 2 3])))"} + {:suite "clojure.core / futures — deref" :label "future returns a map" :expected "{:a 1}" :actual "(deref (future {:a 1}))"} + {:suite "clojure.core / futures — deref" :label "deref is cached/idempotent" :expected "[2 2]" :actual "(let [f (future (+ 1 1))] [(deref f) (deref f)])"} + {:suite "clojure.core / futures — deref" :label "timed deref of ready future" :expected "42" :actual "(let [f (future 42)] (deref f) (deref f 1000 :nope))"} + {:suite "clojure.core / futures — deref" :label "body error re-raised on deref" :expected :throws :actual "(deref (future (throw \"boom\")))"} + {:suite "clojure.core / futures — deref" :label "timed deref times out" :expected ":timed-out" :actual "(deref (future (do (Thread/sleep 300) :late)) 10 :timed-out)"} + {:suite "clojure.core / futures — deref" :label "Thread/sleep in body" :expected ":slept" :actual "(deref (future (do (Thread/sleep 5) :slept)))"} + {:suite "clojure.core / futures — deref" :label "timed-out future still completes" :expected ":late" :actual "(let [f (future (do (Thread/sleep 30) :late))] (deref f 5 :early) (deref f))"} + {:suite "clojure.core / futures — predicates" :label "future? true" :expected "true" :actual "(future? (future 1))"} + {:suite "clojure.core / futures — predicates" :label "future? false" :expected "false" :actual "(future? 42)"} + {:suite "clojure.core / futures — predicates" :label "future-done? after deref" :expected "true" :actual "(let [f (future 1)] (deref f) (future-done? f))"} + {:suite "clojure.core / futures — predicates" :label "realized? after deref" :expected "true" :actual "(let [f (future 1)] (deref f) (realized? f))"} + {:suite "clojure.core / futures — predicates" :label "cancel an in-flight future returns true" :expected "true" :actual "(let [f (future 1)] (future-cancel f))"} + {:suite "clojure.core / futures — predicates" :label "future-cancelled? after cancel" :expected "true" :actual "(let [f (future 1)] (future-cancel f) (future-cancelled? f))"} + {:suite "clojure.core / futures — predicates" :label "future-done? after cancel" :expected "true" :actual "(let [f (future 1)] (future-cancel f) (future-done? f))"} + {:suite "clojure.core / futures — predicates" :label "cancel an already-completed future returns false" :expected "false" :actual "(let [f (future 1)] (deref f) (future-cancel f))"} + {:suite "clojure.core / futures — predicates" :label "future-cancelled? fresh is false" :expected "false" :actual "(future-cancelled? (future 1))"} + {:suite "clojure.core / futures — snapshot (copy) semantics" :label "captured atom is snapshotted, not shared" :expected "1" :actual "(let [a (atom 0)] (deref (future (swap! a inc))) @a)"} + {:suite "clojure.core / futures — snapshot (copy) semantics" :label "future sees its own mutation" :expected "1" :actual "(let [a (atom 0)] (deref (future (swap! a inc))))"} + {:suite "clojure.core / pmap family" :label "pmap values in order" :expected "[2 3 4]" :actual "(vec (pmap inc [1 2 3]))"} + {:suite "clojure.core / pmap family" :label "pmap multi-coll" :expected "[5 7 9]" :actual "(vec (pmap + [1 2 3] [4 5 6]))"} + {:suite "clojure.core / pmap family" :label "pmap empty" :expected "[]" :actual "(pmap inc [])"} + {:suite "clojure.core / pmap family" :label "pmap is parallel" :expected "true" :actual "(do (deref (future :warmup)) (let [t0 (System/currentTimeMillis)] (dorun (pmap (fn [_] (Thread/sleep 200)) [1 2 3 4])) (< (- (System/currentTimeMillis) t0) 700)))"} + {:suite "clojure.core / pmap family" :label "pcalls" :expected "[1 2]" :actual "(vec (pcalls (fn [] 1) (fn [] 2)))"} + {:suite "clojure.core / pmap family" :label "pvalues" :expected "[3 7]" :actual "(vec (pvalues (+ 1 2) (+ 3 4)))"} + {:suite "clojure.core / pmap family" :label "snapshot semantics" :expected "2" :actual "(let [a (atom 0)] (dorun (pmap (fn [_] (swap! a inc)) [1 2])) (deref a))"} + {:suite "hierarchy / pure 3-arity" :label "derive returns new h" :expected "true" :actual "(let [h (derive (make-hierarchy) :rect :shape)] (and (map? h) (isa? h :rect :shape)))"} + {:suite "hierarchy / pure 3-arity" :label "original unchanged" :expected "false" :actual "(let [h0 (make-hierarchy) h1 (derive h0 :rect :shape)] (isa? h0 :rect :shape))"} + {:suite "hierarchy / pure 3-arity" :label "isa? self" :expected "true" :actual "(isa? (make-hierarchy) :a :a)"} + {:suite "hierarchy / pure 3-arity" :label "isa? transitive" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (isa? h :square :shape))"} + {:suite "hierarchy / pure 3-arity" :label "multi-parent" :expected "[true true]" :actual "(let [h (-> (make-hierarchy) (derive :sq :rect) (derive :sq :rhombus))] [(isa? h :sq :rect) (isa? h :sq :rhombus)])"} + {:suite "hierarchy / pure 3-arity" :label "parents set" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :sq :rect) (derive :sq :rhombus))] (= #{:rect :rhombus} (parents h :sq)))"} + {:suite "hierarchy / pure 3-arity" :label "ancestors transitive" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (= #{:rect :shape} (ancestors h :square)))"} + {:suite "hierarchy / pure 3-arity" :label "descendants transitive" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (= #{:rect :square} (descendants h :shape)))"} + {:suite "hierarchy / pure 3-arity" :label "underive removes" :expected "false" :actual "(let [h (-> (make-hierarchy) (derive :a :b) (underive :a :b))] (isa? h :a :b))"} + {:suite "hierarchy / pure 3-arity" :label "vector isa?" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :rect :shape))] (isa? h [:rect :rect] [:shape :shape]))"} + {:suite "hierarchy / pure 3-arity" :label "vector isa? length" :expected "false" :actual "(isa? (make-hierarchy) [:a] [:a :a])"} + {:suite "hierarchy / pure 3-arity" :label "cyclic derive throws" :expected :throws :actual "(-> (make-hierarchy) (derive :a :b) (derive :b :a))"} + {:suite "hierarchy / pure 3-arity" :label "duplicate derive ok" :expected "true" :actual "(let [h (-> (make-hierarchy) (derive :a :b) (derive :a :b))] (isa? h :a :b))"} + {:suite "hierarchy / pure 3-arity" :label "parents nil when none" :expected "nil" :actual "(parents (make-hierarchy) :x)"} + {:suite "hierarchy / global + multimethod dispatch" :label "global derive + isa?" :expected "true" :actual "(do (derive :gsq :grect) (isa? :gsq :grect))"} + {:suite "hierarchy / global + multimethod dispatch" :label "global ancestors" :expected "true" :actual "(do (derive :ga :gb) (derive :gb :gc) (contains? (ancestors :ga) :gc))"} + {:suite "hierarchy / global + multimethod dispatch" :label "global underive" :expected "false" :actual "(do (derive :gu :gv) (underive :gu :gv) (isa? :gu :gv))"} + {:suite "hierarchy / global + multimethod dispatch" :label "dispatch via hierarchy" :expected ":is-shape" :actual "(do (derive :hsq :hshape) (defmulti hmm identity) (defmethod hmm :hshape [_] :is-shape) (hmm :hsq))"} + {:suite "hierarchy / global + multimethod dispatch" :label "dispatch custom hierarchy" :expected ":parent" :actual "(do (def hh (atom (derive (make-hierarchy) :c :p))) (defmulti cmm identity :hierarchy hh) (defmethod cmm :p [_] :parent) (cmm :c))"} + {:suite "hierarchy / global + multimethod dispatch" :label "dispatch exact beats isa" :expected ":exact" :actual "(do (derive :de1 :de2) (defmulti emm identity) (defmethod emm :de2 [_] :parent) (defmethod emm :de1 [_] :exact) (emm :de1))"} + {:suite "interop / dot forms" :label "method call" :expected "\"v=41\"" :actual "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)"} + {:suite "interop / dot forms" :label "method with args" :expected "\"Hello Alice\"" :actual "(. {:greet (fn [self n] (str \"Hello \" n))} greet \"Alice\")"} + {:suite "interop / dot forms" :label "field access .-" :expected "41" :actual "(.-value {:value 41})"} + {:suite "interop / dot forms" :label "dot field keyword" :expected "41" :actual "(. {:value 41} :value)"} + {:suite "interop / dot dispatch arms" :label "zero-arg coll-interop .count" :expected "3" :actual "(.count [1 2 3])"} + {:suite "interop / dot dispatch arms" :label "zero-arg coll-interop .seq" :expected "[1 2]" :actual "(.seq [1 2])"} + {:suite "interop / dot dispatch arms" :label "explicit dot zero-arg interop" :expected "3" :actual "(. [1 2 3] count)"} + {:suite "interop / dot dispatch arms" :label "with-arg coll-interop .nth" :expected "2" :actual "(.nth [1 2 3] 1)"} + {:suite "interop / dot dispatch arms" :label "record zero-arg method" :expected "10" :actual "(do (defprotocol Pd (gm [this])) (defrecord Rd [x] Pd (gm [this] (* 2 x))) (.gm (->Rd 5)))"} + {:suite "interop / dot dispatch arms" :label "record method with args" :expected "15" :actual "(do (defprotocol Pa (am [this y])) (defrecord Ra [x] Pa (am [this y] (+ x y))) (.am (->Ra 5) 10))"} + {:suite "interop / dot dispatch arms" :label "deftype method with args" :expected "7" :actual "(do (defprotocol Pq (qq [this y])) (deftype Tq [x] Pq (qq [this y] (+ x y))) (.qq (Tq. 3) 4))"} + {:suite "interop / dot dispatch arms" :label "record -field is field access" :expected "7" :actual "(do (defrecord Rf [x]) (.-x (->Rf 7)))"} + {:suite "interop / dot dispatch arms" :label "object-method with args .equals" :expected "true" :actual "(.equals \"a\" \"a\")"} + {:suite "interop / arrays (aget/aset/alength)" :label "alength" :expected "3" :actual "(alength (object-array [1 2 3]))"} + {:suite "interop / arrays (aget/aset/alength)" :label "aget" :expected "20" :actual "(aget (object-array [10 20 30]) 1)"} + {:suite "interop / arrays (aget/aset/alength)" :label "aset returns val" :expected "9" :actual "(aset (object-array [1 2 3]) 1 9)"} + {:suite "interop / arrays (aget/aset/alength)" :label "aset mutates" :expected "[7 2 3]" :actual "(let [a (object-array [1 2 3])] (aset a 0 7) (vec a))"} + {:suite "interop / arrays (aget/aset/alength)" :label "aget 2d" :expected "4" :actual "(aget (to-array-2d [[1 2] [3 4]]) 1 1)"} + {:suite "interop / String methods" :label ".toLowerCase" :expected "\"hi\"" :actual "(.toLowerCase \"HI\")"} + {:suite "interop / String methods" :label ".toUpperCase" :expected "\"HI\"" :actual "(.toUpperCase \"hi\")"} + {:suite "interop / String methods" :label "dot-form" :expected "\"hi\"" :actual "(. \"HI\" toLowerCase)"} + {:suite "interop / String methods" :label ".trim" :expected "\"x\"" :actual "(.trim \" x \")"} + {:suite "interop / String methods" :label ".length" :expected "3" :actual "(.length \"abc\")"} + {:suite "interop / String methods" :label ".isEmpty" :expected "[true false]" :actual "[(.isEmpty \"\") (.isEmpty \"a\")]"} + {:suite "interop / String methods" :label ".indexOf hit" :expected "1" :actual "(.indexOf \"abc\" \"b\")"} + {:suite "interop / String methods" :label ".indexOf miss is -1" :expected "-1" :actual "(.indexOf \"abc\" \"z\")"} + {:suite "interop / String methods" :label ".lastIndexOf" :expected "3" :actual "(.lastIndexOf \"abab\" \"b\")"} + {:suite "interop / String methods" :label ".substring" :expected "\"bc\"" :actual "(.substring \"abc\" 1)"} + {:suite "interop / String methods" :label ".substring end" :expected "\"b\"" :actual "(.substring \"abc\" 1 2)"} + {:suite "interop / String methods" :label ".startsWith" :expected "true" :actual "(.startsWith \"abc\" \"ab\")"} + {:suite "interop / String methods" :label ".endsWith" :expected "true" :actual "(.endsWith \"abc\" \"bc\")"} + {:suite "interop / String methods" :label ".contains" :expected "true" :actual "(.contains \"abc\" \"b\")"} + {:suite "interop / String methods" :label ".replace" :expected "\"axc\"" :actual "(.replace \"abc\" \"b\" \"x\")"} + {:suite "interop / String methods" :label ".charAt" :expected "\\b" :actual "(.charAt \"abc\" 1)"} + {:suite "interop / String methods" :label ".equalsIgnoreCase" :expected "true" :actual "(.equalsIgnoreCase \"AbC\" \"aBc\")"} + {:suite "interop / String methods" :label "Long/MAX_VALUE" :expected "true" :actual "(pos? Long/MAX_VALUE)"} + {:suite "interop / String methods" :label "String/valueOf num" :expected "\"42\"" :actual "(String/valueOf 42)"} + {:suite "interop / String methods" :label "String/valueOf str" :expected "\"hi\"" :actual "(String/valueOf \"hi\")"} + {:suite "interop / String methods" :label "String/valueOf kw" :expected "\":k\"" :actual "(String/valueOf :k)"} + {:suite "interop / String methods" :label "String/valueOf nil" :expected "\"null\"" :actual "(String/valueOf nil)"} + {:suite "interop / String methods" :label "instance? CharSequence" :expected "true" :actual "(instance? CharSequence \"aaa\")"} + {:suite "interop / String methods" :label "instance? CharSequence non-str" :expected "false" :actual "(instance? CharSequence 42)"} + {:suite "interop / String methods" :label "unsupported method throws" :expected :throws :actual "(.frobnicate \"abc\")"} + {:suite "interop / java.time shims" :label "ofPattern formats #inst" :expected "true" :actual "(string? (.format (DateTimeFormatter/ofPattern \"yyyy-MM-dd\") #inst \"2020-03-05T13:45:30Z\"))"} + {:suite "interop / java.time shims" :label "pattern shape" :expected "true" :actual "(boolean (re-matches #\"\\d{4}-\\d{2}-\\d{2}\" (.format (DateTimeFormatter/ofPattern \"yyyy-MM-dd\") #inst \"2020-03-05T13:45:30Z\")))"} + {:suite "interop / java.time shims" :label "month name + ampm" :expected "true" :actual "(boolean (re-matches #\"[A-Z][a-z]{2} \\d{1,2}, 2020 \\d{1,2}:\\d{2} [AP]M\" (.format (DateTimeFormatter/ofPattern \"MMM d, yyyy h:mm a\") #inst \"2020-03-05T13:45:30Z\")))"} + {:suite "interop / java.time shims" :label "quoted literal" :expected "true" :actual "(boolean (re-matches #\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\" (.format DateTimeFormatter/ISO_LOCAL_DATE_TIME #inst \"2020-03-05T13:45:30Z\")))"} + {:suite "interop / java.time shims" :label "localized style" :expected "true" :actual "(string? (.format (DateTimeFormatter/ofLocalizedDate FormatStyle/MEDIUM) #inst \"2020-03-05T13:45:30Z\"))"} + {:suite "interop / java.time shims" :label "withLocale chain" :expected "true" :actual "(string? (.format (.withLocale (DateTimeFormatter/ofPattern \"yyyy\") (java.util.Locale. \"en\")) #inst \"2020-01-01T00:00:00Z\"))"} + {:suite "interop / java.time shims" :label "fix-date chain" :expected "true" :actual "(instance? LocalDateTime (-> #inst \"2020-03-05T13:45:30Z\" (.toInstant) (.atZone (ZoneId/systemDefault)) (.toLocalDateTime)))"} + {:suite "interop / java.time shims" :label "inst is java.util.Date" :expected "true" :actual "(instance? java.util.Date #inst \"2020-01-01T00:00:00Z\")"} + {:suite "interop / java.time shims" :label "Instant instance" :expected "true" :actual "(instance? java.time.Instant (Instant/ofEpochMilli 0))"} + {:suite "interop / java.time shims" :label "getTime epoch ms" :expected "0" :actual "(.getTime #inst \"1970-01-01T00:00:00Z\")"} + {:suite "interop / java.time shims" :label "toEpochMilli round trip" :expected "1234" :actual "(.toEpochMilli (Instant/ofEpochMilli 1234))"} + {:suite "interop / java.time shims" :label "Instant/now is current" :expected "true" :actual "(> (.toEpochMilli (Instant/now)) 1500000000000)"} + {:suite "interop / java.time shims" :label "sql types are not" :expected "false" :actual "(instance? java.sql.Timestamp #inst \"2020-01-01T00:00:00Z\")"} + {:suite "interop / StringReader & StringBuilder" :label "StringReader read" :expected "[97 98 -1]" :actual "(let [r (java.io.StringReader. \"ab\")] [(.read r) (.read r) (.read r)])"} + {:suite "interop / StringReader & StringBuilder" :label "mark/reset" :expected "[97 97]" :actual "(let [r (StringReader. \"ab\")] (.mark r 1) [(.read r) (do (.reset r) (.read r))])"} + {:suite "interop / StringReader & StringBuilder" :label "StringBuilder append" :expected "\"ab1\"" :actual "(.toString (-> (StringBuilder.) (.append \"a\") (.append \\b) (.append 1)))"} + {:suite "interop / StringReader & StringBuilder" :label "capacity arg is not content" :expected "\"x\"" :actual "(.toString (.append (StringBuilder. 16) \"x\"))"} + {:suite "interop / StringReader & StringBuilder" :label "setLength truncates" :expected "\"ab\"" :actual "(let [sb (StringBuilder.)] (.append sb \"abcd\") (.setLength sb 2) (.toString sb))"} + {:suite "interop / StringReader & StringBuilder" :label "char-array of string" :expected "true" :actual "(instance? (Class/forName \"[C\") (char-array \"ab\"))"} + {:suite "interop / StringReader & StringBuilder" :label "reader over char[]" :expected "97" :actual "(do (require (quote clojure.java.io)) (.read (clojure.java.io/reader (char-array \"abc\"))))"} + {:suite "interop / StringReader & StringBuilder" :label "with-open closes shim" :expected "97" :actual "(with-open [r (StringReader. \"a\")] (.read r))"} + {:suite "interop / StringReader & StringBuilder" :label "File.toURL methods read it back" :expected "\"file:/tmp/x\"" :actual "(do (require (quote clojure.java.io)) (.toString (.toURL (clojure.java.io/file \"/tmp/x\"))))"} + {:suite "interop / StringReader & StringBuilder" :label "vector :import shares deftype ctor" :expected "\"hi!\"" :actual "(do (ns spec.nodea) (defprotocol SpecP (spec-pm [this])) (deftype SpecTN [t] SpecP (spec-pm [this] (str t \"!\"))) (ns spec.nodeb (:import [spec.nodea SpecTN])) (.spec-pm (SpecTN. \"hi\")))"} + {:suite "interop / PushbackReader & parse statics" :label "PushbackReader read" :expected "[97 98]" :actual "(let [r (java.io.PushbackReader. (java.io.StringReader. \"ab\"))] [(.read r) (.read r)])"} + {:suite "interop / PushbackReader & parse statics" :label "unread pushes back" :expected "[97 97 98]" :actual "(let [r (PushbackReader. (StringReader. \"ab\")) a (.read r)] (.unread r a) [a (.read r) (.read r)])"} + {:suite "interop / PushbackReader & parse statics" :label "unread accepts a char" :expected "[120 97]" :actual "(let [r (PushbackReader. (StringReader. \"a\"))] (.unread r \\x) [(.read r) (.read r)])"} + {:suite "interop / PushbackReader & parse statics" :label "edn/read from reader" :expected "5432" :actual "(do (require (quote clojure.edn)) (clojure.edn/read (java.io.PushbackReader. (java.io.StringReader. \"{:db {:port 5432}}\\nrest\"))) (get-in (clojure.edn/read-string \"{:db {:port 5432}}\") [:db :port]))"} + {:suite "interop / PushbackReader & parse statics" :label "edn/read multi-line" :expected "true" :actual "(do (require (quote clojure.edn)) (= {:a 1 :b 2} (clojure.edn/read (PushbackReader. (StringReader. \"{:a 1\\n :b 2}\")))))"} + {:suite "interop / PushbackReader & parse statics" :label "Long/parseLong" :expected "42" :actual "(Long/parseLong \"42\")"} + {:suite "interop / PushbackReader & parse statics" :label "parseLong rejects non-numeric" :expected :throws :actual "(Long/parseLong \"4x\")"} + {:suite "interop / PushbackReader & parse statics" :label "BigInteger." :expected "123" :actual "(BigInteger. \"123\")"} + {:suite "interop / PushbackReader & parse statics" :label "Boolean/parseBoolean" :expected "[true false false]" :actual "[(Boolean/parseBoolean \"true\") (Boolean/parseBoolean \"false\") (Boolean/parseBoolean \"yes\")]"} + {:suite "interop / PushbackReader & parse statics" :label "System/getenv is a map" :expected "true" :actual "(string? (get (System/getenv) \"HOME\"))"} + {:suite "interop / PushbackReader & parse statics" :label "System/exit resolves" :expected "true" :actual "(fn? System/exit)"} + {:suite "interop / PushbackReader & parse statics" :label "getenv entries destructure (non-empty)" :expected "true" :actual "(let [es (map (fn [[k v]] [k v]) (System/getenv))] (and (pos? (count es)) (every? vector? es)))"} + {:suite "interop / PushbackReader & parse statics" :label "seq over a raw host table" :expected "true" :actual "(pos? (count (seq (System/getenv))))"} + {:suite "interop / PushbackReader & parse statics" :label "into {} from host table" :expected "true" :actual "(string? (get (into {} (map (fn [[k v]] [k v]) (System/getenv))) \"HOME\"))"} + {:suite "interop / PushbackReader & parse statics" :label "System/getProperties" :expected "true" :actual "(string? (get (System/getProperties) \"os.name\"))"} + {:suite "host-interop / ring-codec surface" :label "URLEncoder www form" :expected "\"a+b%3Dc\"" :actual "(URLEncoder/encode \"a b=c\")"} + {:suite "host-interop / ring-codec surface" :label "URLDecoder www form" :expected "\"a b=c\"" :actual "(URLDecoder/decode \"a+b%3Dc\" (Charset/forName \"UTF-8\"))"} + {:suite "host-interop / ring-codec surface" :label "url round trip" :expected "\"x &=%?\"" :actual "(URLDecoder/decode (URLEncoder/encode \"x &=%?\"))"} + {:suite "host-interop / ring-codec surface" :label "Base64 encode" :expected "\"aGVsbG8=\"" :actual "(String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))"} + {:suite "host-interop / ring-codec surface" :label "Base64 round trip" :expected "\"hello\"" :actual "(String. (.decode (Base64/getDecoder) (String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))))"} + {:suite "host-interop / ring-codec surface" :label "Integer radix + byteValue" :expected "-1" :actual "(.byteValue (Integer/valueOf \"ff\" 16))"} + {:suite "host-interop / ring-codec surface" :label "Integer parseInt" :expected "255" :actual "(Integer/parseInt \"ff\" 16)"} + {:suite "host-interop / ring-codec surface" :label "StringTokenizer" :expected "[\"a=1\" \"b=2\"]" :actual "(let [t (StringTokenizer. \"a=1&b=2\" \"&\")] [(.nextToken t) (.nextToken t)])"} + {:suite "host-interop / ring-codec surface" :label "MapEntry key/val" :expected "[:a 1]" :actual "(let [e (MapEntry. :a 1)] [(key e) (val e)])"} + {:suite "host-interop / ring-codec surface" :label "String ctor from bytes" :expected "\"hi\"" :actual "(String. (.getBytes \"hi\"))"} + {:suite "host-interop / ring-codec surface" :label "extend-protocol Map" :expected ":map" :actual "(do (defprotocol Pe (pe [x])) (extend-protocol Pe Map (pe [m] :map) Object (pe [o] :obj)) (pe {:a 1}))"} + {:suite "host-interop / ring-codec surface" :label "extend-protocol nil" :expected ":nil" :actual "(do (defprotocol Pn (pn [x])) (extend-protocol Pn nil (pn [n] :nil) Object (pn [o] :obj)) (pn nil))"} + {:suite "host-interop / ring-codec surface" :label "extend-protocol Map covers sorted" :expected ":map" :actual "(do (defprotocol Ps (ps [x])) (extend-protocol Ps Map (ps [m] :map) Object (ps [o] :obj)) (ps (sorted-map 1 2)))"} + {:suite "host-interop / ring-codec surface" :label "reduce over reified IReduceInit" :expected "42" :actual "(reduce + 0 (reify clojure.lang.IReduceInit (reduce [_ f init] (f (f init 40) 2))))"} + {:suite "host-interop / class tokens & readers" :label "class name evaluates to canonical string" :expected "java.lang.String" :actual "String"} + {:suite "host-interop / class tokens & readers" :label "dispatch-only class name" :expected "\"java.io.InputStream\"" :actual "InputStream"} + {:suite "host-interop / class tokens & readers" :label "(class x) matches the token" :expected "true" :actual "(= String (class \"abc\"))"} + {:suite "host-interop / class tokens & readers" :label "defmulti on class dispatches" :expected ":str" :actual "(do (defmulti cm (fn [x] (class x))) (defmethod cm String [x] :str) (cm \"a\"))"} + {:suite "host-interop / class tokens & readers" :label "defmethod on nil dispatch value" :expected ":nil" :actual "(do (defmulti cn (fn [x] (class x))) (defmethod cn nil [x] :nil) (defmethod cn String [x] :str) (cn nil))"} + {:suite "host-interop / class tokens & readers" :label "ctor sugar still constructs" :expected "\"x\"" :actual "(.toString (StringBuilder. \"x\"))"} + {:suite "host-interop / class tokens & readers" :label "return-hinted defn parses" :expected "7" :actual "(do (defn- hb ^bytes [b] b) (hb 7))"} + {:suite "host-interop / class tokens & readers" :label "hinted multi-arity parses" :expected ":two" :actual "((fn ([x] :one) (^String [x y] :two)) 1 2)"} + {:suite "host-interop / class tokens & readers" :label "slurp drains a StringReader" :expected "\"a=1\"" :actual "(slurp (StringReader. \"a=1\"))"} + {:suite "host-interop / class tokens & readers" :label "slurp accepts :encoding opts" :expected "\"b\"" :actual "(slurp (StringReader. \"b\") :encoding \"UTF-8\")"} + {:suite "host-interop / class tokens & readers" :label "replace with fn replacement is literal" :expected "\"$0\"" :actual "(do (require (quote [clojure.string :as s9])) (s9/replace \"x\" #\".\" (fn [m] \"$0\")))"} + {:suite "host-interop / class tokens & readers" :label "replace fn gets group vector" :expected "\"v=k\"" :actual "(do (require (quote [clojure.string :as s9])) (s9/replace \"k=v\" #\"(\\w+)=(\\w+)\" (fn [[_ k v]] (str v \"=\" k))))"} + {:suite "host-interop / class tokens & readers" :label "indexOf int needle is a char code" :expected "1" :actual "(.indexOf \"a=b\" 61)"} + {:suite "host-interop / exception + HashMap shims" :label "getMessage on a thrown string" :expected "\"class java.lang.String cannot be cast to class java.lang.Throwable (java.lang.String and java.lang.Throwable are in module java.base of loader 'bootstrap')\"" :actual "(try (throw \"boom\") (catch Throwable e (.getMessage e)))"} + {:suite "host-interop / exception + HashMap shims" :label "getMessage on ex-info" :expected "\"bad\"" :actual "(try (throw (ex-info \"bad\" {})) (catch Throwable e (.getMessage e)))"} + {:suite "host-interop / exception + HashMap shims" :label "HashMap get" :expected "2" :actual "(let [m (HashMap. {:a 1 :b 2})] (.get m :b))"} + {:suite "host-interop / exception + HashMap shims" :label "HashMap put + size" :expected "2" :actual "(let [m (HashMap. {})] (.put m :x 1) (.put m :y 2) (.size m))"} + {:suite "host-interop / reader-feature toggle" :label "features default to jolt+default" :expected "true" :actual "(contains? (set (__reader-features)) \"jolt\")"} + {:suite "host-interop / reader-feature toggle" :label "set + read back" :expected "true" :actual "(do (def prev (__reader-features)) (__reader-features-set! [\"clj\" \"jolt\" \"default\"]) (def r (contains? (set (__reader-features)) \"clj\")) (__reader-features-set! prev) r)"} + {:suite "host-interop / reader-feature toggle" :label "restore returns to default" :expected "false" :actual "(do (def prev (__reader-features)) (__reader-features-set! [\"clj\"]) (__reader-features-set! prev) (contains? (set (__reader-features)) \"clj\"))"} + {:suite "host-interop / migratus class shims" :label "Exception. message" :expected "\"boom\"" :actual "(try (throw (Exception. \"boom\")) (catch Throwable e (.getMessage e)))"} + {:suite "host-interop / migratus class shims" :label "IllegalArgumentException." :expected "\"bad\"" :actual "(try (throw (IllegalArgumentException. \"bad\")) (catch Exception e (.getMessage e)))"} + {:suite "host-interop / migratus class shims" :label "InterruptedException." :expected "\"stop\"" :actual "(try (throw (InterruptedException. \"stop\")) (catch Throwable e (.getMessage e)))"} + {:suite "host-interop / migratus class shims" :label "Character/isUpperCase" :expected "true" :actual "(Character/isUpperCase \\A)"} + {:suite "host-interop / migratus class shims" :label "Character/isLowerCase" :expected "true" :actual "(Character/isLowerCase \\a)"} + {:suite "host-interop / migratus class shims" :label "Character/isUpperCase neg" :expected "false" :actual "(Character/isUpperCase \\a)"} + {:suite "host-interop / migratus class shims" :label "Thread/interrupted" :expected "false" :actual "(Thread/interrupted)"} + {:suite "host-interop / migratus class shims" :label "Long/valueOf" :expected "42" :actual "(Long/valueOf \"42\")"} + {:suite "host-interop / migratus class shims" :label "Timestamp is millis" :expected "1000" :actual "(.getTime (java.util.Date. (java.sql.Timestamp. 1000)))"} + {:suite "host-interop / migratus class shims" :label "SimpleDateFormat UTC" :expected "\"19700101000000\"" :actual "(let [f (doto (java.text.SimpleDateFormat. \"yyyyMMddHHmmss\") (.setTimeZone (java.util.TimeZone/getTimeZone \"UTC\")))] (.format f (java.util.Date. 0)))"} + {:suite "host-interop / java.io.File" :label "instance? File" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (instance? java.io.File (io/file \"/a/b\")))"} + {:suite "host-interop / java.io.File" :label "str is the path" :expected "\"/a/b\"" :actual "(do (require '[clojure.java.io :as io]) (str (io/file \"/a/b\")))"} + {:suite "host-interop / java.io.File" :label "getName" :expected "\"c.txt\"" :actual "(do (require '[clojure.java.io :as io]) (.getName (io/file \"/a/b/c.txt\")))"} + {:suite "host-interop / java.io.File" :label "getPath joins" :expected "\"/a/b\"" :actual "(do (require '[clojure.java.io :as io]) (.getPath (io/file \"/a\" \"b\")))"} + {:suite "host-interop / java.io.File" :label "isDirectory of repo dir" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (.isDirectory (io/file \"docs\")))"} + {:suite "host-interop / java.io.File" :label "isFile of repo file" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (.isFile (io/file \"README.md\")))"} + {:suite "host-interop / java.io.File" :label "exists is false off-disk" :expected "false" :actual "(do (require '[clojure.java.io :as io]) (.exists (io/file \"/no/such/path/xyz\")))"} + {:suite "host-interop / java.io.File" :label "file-seq yields File values" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (every? (fn [f] (instance? java.io.File f)) (file-seq (io/file \"docs\"))))"} + {:suite "host-interop / java.io.File" :label "file-seq finds files" :expected "true" :actual "(do (require '[clojure.java.io :as io]) (pos? (count (filter (fn [f] (.isFile f)) (file-seq (io/file \"docs\"))))))"} + {:suite "host-interop / logging host shims" :label "LockingTransaction/isRunning" :expected "false" :actual "(clojure.lang.LockingTransaction/isRunning)"} + {:suite "host-interop / logging host shims" :label "pprint writes value" :expected "\"[1 2 3]\\n\"" :actual "(do (require '[clojure.pprint :as pp]) (with-out-str (pp/pprint [1 2 3])))"} + {:suite "host-interop / logging host shims" :label "with-pprint-dispatch runs body" :expected "42" :actual "(do (require '[clojure.pprint :as pp]) (pp/with-pprint-dispatch pp/code-dispatch 42))"} + {:suite "host-interop / macro dispatch & short-circuit patterns" :label "conditional-eval suppresses" :expected "0" :actual "(do (def ^:dynamic *enabled* false) (defmacro when-on [& body] `(when *enabled* ~@body)) (let [a (atom 0)] (when-on (reset! a 9)) @a))"} + {:suite "host-interop / macro dispatch & short-circuit patterns" :label "conditional-eval fires" :expected "9" :actual "(do (def ^:dynamic *enabled* true) (defmacro when-on [& body] `(when *enabled* ~@body)) (let [a (atom 0)] (when-on (reset! a 9)) @a))"} + {:suite "host-interop / macro dispatch & short-circuit patterns" :label "spy-like eval+print+return" :expected "3" :actual "(do (defmacro spylog [expr] `(let [v# ~expr] (println v#) v#)) (spylog (+ 1 2)))"} + {:suite "host-interop / macro dispatch & short-circuit patterns" :label "multi-arity 4 dispatch" :expected "[:single :double :triple :quad]" :actual "(do (defmacro ml ([a] :single) ([a b] :double) ([a b c] :triple) ([a b c d] :quad)) [(ml 1) (ml 1 2) (ml 1 2 3) (ml 1 2 3 4)])"} + {:suite "inst / reading & identity" :label "reads to inst" :expected "true" :actual "(inst? #inst \"2020-01-01T00:00:00Z\")"} + {:suite "inst / reading & identity" :label "inst? false on string" :expected "false" :actual "(inst? \"2020-01-01\")"} + {:suite "inst / reading & identity" :label "epoch zero" :expected "0" :actual "(inst-ms #inst \"1970-01-01T00:00:00Z\")"} + {:suite "inst / reading & identity" :label "one second" :expected "1000" :actual "(inst-ms #inst \"1970-01-01T00:00:01Z\")"} + {:suite "inst / reading & identity" :label "millis" :expected "123" :actual "(inst-ms #inst \"1970-01-01T00:00:00.123Z\")"} + {:suite "inst / reading & identity" :label "a real date" :expected "1577836800000" :actual "(inst-ms #inst \"2020-01-01T00:00:00Z\")"} + {:suite "inst / reading & identity" :label "inst-ms throws on non-inst" :expected :throws :actual "(inst-ms 42)"} + {:suite "inst / partial timestamps & offsets" :label "year only" :expected "true" :actual "(= #inst \"2020\" #inst \"2020-01-01T00:00:00.000Z\")"} + {:suite "inst / partial timestamps & offsets" :label "year-month" :expected "true" :actual "(= #inst \"2020-03\" #inst \"2020-03-01T00:00:00Z\")"} + {:suite "inst / partial timestamps & offsets" :label "date only" :expected "true" :actual "(= #inst \"2020-03-15\" #inst \"2020-03-15T00:00:00Z\")"} + {:suite "inst / partial timestamps & offsets" :label "positive offset" :expected "true" :actual "(= #inst \"2020-01-01T01:00:00+01:00\" #inst \"2020-01-01T00:00:00Z\")"} + {:suite "inst / partial timestamps & offsets" :label "negative offset" :expected "true" :actual "(= #inst \"2019-12-31T23:00:00-01:00\" #inst \"2020-01-01T00:00:00Z\")"} + {:suite "inst / partial timestamps & offsets" :label "-00:00 offset" :expected "true" :actual "(= #inst \"2020-01-01T00:00:00-00:00\" #inst \"2020-01-01T00:00:00Z\")"} + {:suite "inst / partial timestamps & offsets" :label "bad timestamp throws" :expected :throws :actual "#inst \"garbage\""} + {:suite "inst / value semantics & printing" :label "equal by instant" :expected "true" :actual "(= #inst \"2020-01-01T00:00:00Z\" #inst \"2020-01-01T00:00:00.000Z\")"} + {:suite "inst / value semantics & printing" :label "unequal instants" :expected "false" :actual "(= #inst \"2020-01-01T00:00:00Z\" #inst \"2020-01-01T00:00:01Z\")"} + {:suite "inst / value semantics & printing" :label "works as map key" :expected ":v" :actual "(get {#inst \"2020-01-01T00:00:00Z\" :v} #inst \"2020-01-01T00:00:00.000Z\")"} + {:suite "inst / value semantics & printing" :label "pr-str round-trips" :expected "\"#inst \\\"2020-01-01T00:00:00.000-00:00\\\"\"" :actual "(pr-str #inst \"2020-01-01T00:00:00Z\")"} + {:suite "io / with-out-str captures" :label "println" :expected "\"hi\\n\"" :actual "(with-out-str (println \"hi\"))"} + {:suite "io / with-out-str captures" :label "print spaces" :expected "\"a b\"" :actual "(with-out-str (print \"a\" \"b\"))"} + {:suite "io / with-out-str captures" :label "prn quotes" :expected "\"[1 2]\\n\"" :actual "(with-out-str (prn [1 2]))"} + {:suite "io / with-out-str captures" :label "pr no newline" :expected "\"5\"" :actual "(with-out-str (pr 5))"} + {:suite "io / with-out-str captures" :label "multiple writes" :expected "\"12\"" :actual "(with-out-str (print 1) (print 2))"} + {:suite "io / with-out-str captures" :label "no output" :expected "\"\"" :actual "(with-out-str 42)"} + {:suite "io / with-out-str captures" :label "println no args" :expected "\"\\n\"" :actual "(with-out-str (println))"} + {:suite "io / *-str builders" :label "print-str" :expected "\"a b\"" :actual "(print-str \"a\" \"b\")"} + {:suite "io / *-str builders" :label "println-str" :expected "\"x\\n\"" :actual "(println-str \"x\")"} + {:suite "io / *-str builders" :label "prn-str" :expected "\"[1 2]\\n\"" :actual "(prn-str [1 2])"} + {:suite "io / *-str builders" :label "pr-str quotes" :expected "\"\\\"s\\\"\"" :actual "(pr-str \"s\")"} + {:suite "io / *-str builders" :label "pr-str keyword" :expected "\":a\"" :actual "(pr-str :a)"} + {:suite "io / str & format" :label "str concat" :expected "\"1:ab\"" :actual "(str 1 :a \"b\")"} + {:suite "io / str & format" :label "str nil" :expected "\"\"" :actual "(str nil)"} + {:suite "io / str & format" :label "str of coll" :expected "\"[1 2]\"" :actual "(str [1 2])"} + {:suite "io / str & format" :label "format d/s" :expected "\"5-x\"" :actual "(format \"%d-%s\" 5 \"x\")"} + {:suite "io / str & format" :label "format float" :expected "\"3.14\"" :actual "(format \"%.2f\" 3.14159)"} + {:suite "io / *in* + with-in-str + read-line" :label "read-line one line" :expected "\"hello\"" :actual "(with-in-str \"hello\" (read-line))"} + {:suite "io / *in* + with-in-str + read-line" :label "read-line strips nl" :expected "\"a\"" :actual "(with-in-str \"a\\nb\" (read-line))"} + {:suite "io / *in* + with-in-str + read-line" :label "read-line sequential" :expected "[\"a\" \"b\"]" :actual "(with-in-str \"a\\nb\" [(read-line) (read-line)])"} + {:suite "io / *in* + with-in-str + read-line" :label "read-line EOF nil" :expected "nil" :actual "(with-in-str \"\" (read-line))"} + {:suite "io / *in* + with-in-str + read-line" :label "read-line after last" :expected "[\"x\" nil]" :actual "(with-in-str \"x\" [(read-line) (read-line)])"} + {:suite "io / *in* + with-in-str + read-line" :label "empty line" :expected "[\"\" \"y\"]" :actual "(with-in-str \"\\ny\" [(read-line) (read-line)])"} + {:suite "io / *in* + with-in-str + read-line" :label "*in* is bound" :expected "false" :actual "(with-in-str \"\" (map? *in*))"} + {:suite "io / read" :label "read a form" :expected "42" :actual "(with-in-str \"42\" (read))"} + {:suite "io / read" :label "read a list form" :expected "(quote (+ 1 2))" :actual "(with-in-str \"(+ 1 2)\" (read))"} + {:suite "io / read" :label "read two forms" :expected "[1 2]" :actual "(with-in-str \"1 2\" [(read) (read)])"} + {:suite "io / read" :label "read then read-line" :expected "[1 \" rest\"]" :actual "(with-in-str \"1 rest\\nnext\" [(read) (read-line)])"} + {:suite "io / read" :label "read vector" :expected "[1 2]" :actual "(with-in-str \"[1 2]\" (read))"} + {:suite "io / read" :label "read nil literal" :expected "nil" :actual "(with-in-str \"nil\" (read))"} + {:suite "io / read" :label "read EOF throws" :expected :throws :actual "(with-in-str \"\" (read))"} + {:suite "io / read" :label "read EOF value" :expected ":done" :actual "(with-in-str \"\" (read *in* false :done))"} + {:suite "io / read" :label "read eval data" :expected "3" :actual "(with-in-str \"(+ 1 2)\" (eval (read)))"} + {:suite "io / line-seq" :label "line-seq" :expected "[\"a\" \"b\" \"c\"]" :actual "(with-in-str \"a\\nb\\nc\" (vec (line-seq *in*)))"} + {:suite "io / line-seq" :label "line-seq empty" :expected "nil" :actual "(with-in-str \"\" (seq (line-seq *in*)))"} + {:suite "io / line-seq" :label "line-seq is lazy seq" :expected "true" :actual "(with-in-str \"a\\nb\" (seq? (line-seq *in*)))"} + {:suite "io / line-seq" :label "line-seq count" :expected "3" :actual "(with-in-str \"1\\n2\\n3\" (count (line-seq *in*)))"} + {:suite "io / print family (overlay)" :label "pr-str multi-arg spacing" :expected "\"\\\"a\\\" [1 2] :k\"" :actual "(pr-str \"a\" [1 2] :k)"} + {:suite "io / print family (overlay)" :label "pr-str zero args" :expected "\"\"" :actual "(pr-str)"} + {:suite "io / print family (overlay)" :label "pr-str escapes" :expected "\"\\\"a\\\\\\\"b\\\"\"" :actual "(pr-str \"a\\\"b\")"} + {:suite "io / print family (overlay)" :label "print is unreadable" :expected "\"a b\"" :actual "(with-out-str (print \"a\" \"b\"))"} + {:suite "io / print family (overlay)" :label "println appends newline" :expected "\"x 1\\n\"" :actual "(with-out-str (println \"x\" 1))"} + {:suite "io / print family (overlay)" :label "prn is readable + newline" :expected "\"[1 \\\"s\\\"]\\n\"" :actual "(with-out-str (prn [1 \"s\"]))"} + {:suite "io / print family (overlay)" :label "pr writes no newline" :expected "\"\\\\a\"" :actual "(with-out-str (pr \\a))"} + {:suite "io / print family (overlay)" :label "print nil arg" :expected "\"nil\"" :actual "(with-out-str (print nil))"} + {:suite "io / print family (overlay)" :label "prn keyword" :expected "\":k\\n\"" :actual "(with-out-str (prn :k))"} + {:suite "io / print-method multimethod" :label "records print canonically" :expected "\"#user.Pt{:x 1, :y 2}\"" :actual "(do (defrecord Pt [x y]) (pr-str (->Pt 1 2)))"} + {:suite "io / print-method multimethod" :label "records nested in colls" :expected "\"[#user.Pt{:x 1, :y 2}]\"" :actual "(do (defrecord Pt [x y]) (pr-str [(->Pt 1 2)]))"} + {:suite "io / print-method multimethod" :label "defmethod overrides a record, top level" :expected "\"#user.Pt{:x 3, :y 4}\"" :actual "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (pr-str (->Pt 3 4)))"} + {:suite "io / print-method multimethod" :label "defmethod fires nested in a map" :expected "\"{:p #user.Pt{:x 5, :y 6}}\"" :actual "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (pr-str {:p (->Pt 5 6)}))"} + {:suite "io / print-method multimethod" :label "defmethod fires through prn" :expected "\"[#user.Pt{:x 1, :y 2}]\\n\"" :actual "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (with-out-str (prn [(->Pt 1 2)])))"} + {:suite "io / print-method multimethod" :label "direct call uses :default" :expected "\"42\"" :actual "(let [w (StringWriter.)] (print-method 42 w) (.toString w))"} + {:suite "io / print-method multimethod" :label "direct builtin override" :expected "\"#42#\"" :actual "(do (defmethod print-method :number [n w] (.write w (str \"#\" n \"#\"))) (let [w (StringWriter.)] (print-method 42 w) (.toString w)))"} + {:suite "io / print-method multimethod" :label "print-dup routes to print-method" :expected "\"[1 2]\"" :actual "(let [w (StringWriter.)] (print-dup [1 2] w) (.toString w))"} + {:suite "io / print-method multimethod" :label "StringWriter accumulates" :expected "\"ab\"" :actual "(let [w (StringWriter.)] (.write w \"a\") (.append w \\b) (.toString w))"} + {:suite "io / print-method multimethod" :label "methods table inspectable" :expected "true" :actual "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] r) (contains? (methods print-method) (quote user.Pt)))"} + {:suite "io / cold tagged types via print-method" :label "uuid" :expected "\"#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"\"" :actual "(pr-str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"} + {:suite "io / cold tagged types via print-method" :label "uuid nested" :expected "\"[#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"]\"" :actual "(pr-str [(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")])"} + {:suite "io / cold tagged types via print-method" :label "regex" :expected "\"#\\\"a+b\\\"\"" :actual "(pr-str #\"a+b\")"} + {:suite "io / cold tagged types via print-method" :label "transient vector" :expected "\"#object[clojure.lang.PersistentVector$TransientVector 0xa4ac20b \\\"clojure.lang.PersistentVector$TransientVector@a4ac20b\\\"]\"" :actual "(pr-str (transient [1]))"} + {:suite "io / cold tagged types via print-method" :label "transient map" :expected "\"#object[clojure.lang.PersistentArrayMap$TransientArrayMap 0x79939c8 \\\"clojure.lang.PersistentArrayMap$TransientArrayMap@79939c8\\\"]\"" :actual "(pr-str (transient {:a 1}))"} + {:suite "io / cold tagged types via print-method" :label "atom override fires nested" :expected "\"{:a #object[clojure.lang.Atom 0x2bb39d6c {:status :ready, :val 7}]}\"" :actual "(do (defmethod print-method :jolt/atom [a w] (.write w (str \"#atom[\" (deref a) \"]\"))) (pr-str {:a (atom 7)}))"} + {:suite "io / cold tagged types via print-method" :label "uuid through str unchanged" :expected "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" :actual "(str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"} + {:suite "ISeq call forms (jolt-2rx)" :label "eval a cons'd call" :expected "3" :actual "(eval (cons (quote +) (quote (1 2))))"} + {:suite "ISeq call forms (jolt-2rx)" :label "eval a list-built call" :expected "6" :actual "(eval (list (quote +) 1 2 3))"} + {:suite "ISeq call forms (jolt-2rx)" :label "eval a concat'd call" :expected "10" :actual "(eval (concat (list (quote +)) (list 1 2 3 4)))"} + {:suite "ISeq call forms (jolt-2rx)" :label "nested cons'd subform" :expected "7" :actual "(eval (list (quote +) 3 (cons (quote +) (quote (1 3)))))"} + {:suite "ISeq call forms (jolt-2rx)" :label "empty list self-evals" :expected "[]" :actual "(eval (list))"} + {:suite "ISeq call forms (jolt-2rx)" :label "macro output via cons" :expected "3" :actual "(do (defmacro mc [] (cons (quote +) (quote (1 2)))) (mc))"} + {:suite "ISeq call forms (jolt-2rx)" :label "macro output via concat" :expected "6" :actual "(do (defmacro mk [] (concat (list (quote +)) (list 1 2 3))) (mk))"} + {:suite "ISeq call forms (jolt-2rx)" :label "vector value self-evals" :expected "[1 2 3]" :actual "(eval (vec [1 2 3]))"} + {:suite "ISeq call forms (jolt-2rx)" :label "quoted list of data" :expected "[1 2 3]" :actual "(quote (1 2 3))"} + {:suite "lazy / construction & laziness" :label "lazy-seq value" :expected "[1 2 3]" :actual "(take 3 (lazy-seq (cons 1 (lazy-seq (cons 2 (lazy-seq (cons 3 nil)))))))"} + {:suite "lazy / construction & laziness" :label "not eagerly evaluated" :expected "0" :actual "(let [c (atom 0)] (lazy-seq (swap! c inc) nil) @c)"} + {:suite "lazy / construction & laziness" :label "realized on demand" :expected "1" :actual "(let [c (atom 0) s (lazy-seq (swap! c inc) [1])] (first s) @c)"} + {:suite "lazy / construction & laziness" :label "lazy-cat" :expected "[0 1 2 3]" :actual "(lazy-cat [0 1] [2 3])"} + {:suite "lazy / construction & laziness" :label "doall forces" :expected "[2 3 4]" :actual "(doall (map inc [1 2 3]))"} + {:suite "lazy / construction & laziness" :label "dorun returns nil" :expected "nil" :actual "(dorun (map inc [1 2 3]))"} + {:suite "lazy / infinite" :label "take from repeat" :expected "[7 7 7]" :actual "(take 3 (repeat 7))"} + {:suite "lazy / infinite" :label "take from iterate" :expected "[1 2 4 8]" :actual "(take 4 (iterate (fn [x] (* 2 x)) 1))"} + {:suite "lazy / infinite" :label "take from cycle" :expected "[1 2 1 2]" :actual "(take 4 (cycle [1 2]))"} + {:suite "lazy / infinite" :label "take from range" :expected "[0 1 2]" :actual "(take 3 (range))"} + {:suite "lazy / infinite" :label "drop then take" :expected "[5 6 7]" :actual "(take 3 (drop 5 (range)))"} + {:suite "lazy / infinite" :label "filter infinite" :expected "[0 2 4]" :actual "(take 3 (filter even? (range)))"} + {:suite "lazy / infinite" :label "map infinite" :expected "[0 1 4]" :actual "(take 3 (map (fn [x] (* x x)) (range)))"} + {:suite "lazy / infinite" :label "nth of infinite" :expected "100" :actual "(nth (range) 100)"} + {:suite "lazy / self-referential" :label "self-ref ones" :expected "[1 1 1 1 1]" :actual "(do (def ones (lazy-seq (cons 1 ones))) (take 5 ones))"} + {:suite "lazy / self-referential" :label "self-ref nats" :expected "[0 1 2 3 4]" :actual "(do (def nats (lazy-cat [0] (map inc nats))) (take 5 nats))"} + {:suite "lazy / self-referential" :label "self-ref fib" :expected "[0 1 1 2 3 5 8 13 21 34]" :actual "(do (def fib (lazy-cat [0 1] (map + (rest fib) fib))) (take 10 fib))"} + {:suite "lazy / realized?" :label "unrealized" :expected "false" :actual "(realized? (lazy-seq (cons 1 nil)))"} + {:suite "lazy / realized?" :label "realized after" :expected "true" :actual "(let [s (lazy-seq (cons 1 nil))] (first s) (realized? s))"} + {:suite "lazy / realized?" :label "body runs once" :expected "1" :actual "(let [c (atom 0) s (lazy-seq (do (swap! c inc) [1 2 3]))] (seq s) (seq s) @c)"} + {:suite "lazy-seq / realization is shared across walks" :label "effects run once across three walks" :expected "3" :actual "(let [a (atom 0) s (map (fn [x] (swap! a inc) x) [1 2 3])] (doall s) (dorun s) (vec s) (deref a))"} + {:suite "lazy-seq / realization is shared across walks" :label "values stable across walks" :expected "true" :actual "(let [s (map inc [1 2 3])] (= (vec s) (vec s) [2 3 4]))"} + {:suite "lazy-seq / realization is shared across walks" :label "filter effects once" :expected "4" :actual "(let [a (atom 0) s (filter (fn [x] (swap! a inc) (odd? x)) [1 2 3 4])] (dorun s) (count s) (deref a))"} + {:suite "list / construct & predicate" :label "list" :expected "[1 2 3]" :actual "(list 1 2 3)"} + {:suite "list / construct & predicate" :label "empty list" :expected "[]" :actual "(list)"} + {:suite "list / construct & predicate" :label "quoted list" :expected "[1 2 3]" :actual "(quote (1 2 3))"} + {:suite "list / construct & predicate" :label "list? true" :expected "true" :actual "(list? (list 1 2))"} + {:suite "list / construct & predicate" :label "list? on conj result" :expected "true" :actual "(list? (conj (list 1) 0))"} + {:suite "list / construct & predicate" :label "count" :expected "3" :actual "(count (list 1 2 3))"} + {:suite "list / construct & predicate" :label "empty? true" :expected "true" :actual "(empty? (list))"} + {:suite "list / construct & predicate" :label "list = vector elts" :expected "true" :actual "(= (list 1 2 3) [1 2 3])"} + {:suite "list / access & update" :label "first" :expected "1" :actual "(first (list 1 2 3))"} + {:suite "list / access & update" :label "rest" :expected "[2 3]" :actual "(rest (list 1 2 3))"} + {:suite "list / access & update" :label "peek is first" :expected "1" :actual "(peek (list 1 2 3))"} + {:suite "list / access & update" :label "pop drops first" :expected "[2 3]" :actual "(pop (list 1 2 3))"} + {:suite "list / access & update" :label "conj prepends" :expected "[0 1 2]" :actual "(conj (list 1 2) 0)"} + {:suite "list / access & update" :label "conj many prepends" :expected "[4 3 1 2]" :actual "(conj (list 1 2) 3 4)"} + {:suite "list / access & update" :label "cons prepends" :expected "[0 1 2]" :actual "(cons 0 (list 1 2))"} + {:suite "list / access & update" :label "nth" :expected "20" :actual "(nth (list 10 20 30) 1)"} + {:suite "list / immutability & performance" :label "conj does not mutate" :expected "true" :actual "(let [l (list 1 2 3) m (conj l 0)] (and (= l [1 2 3]) (= m [0 1 2 3])))"} + {:suite "list / immutability & performance" :label "reduce conj builds" :expected "[2 1 0]" :actual "(reduce conj (list) (range 3))"} + {:suite "list / immutability & performance" :label "O(1) conj at scale" :expected "200000" :actual "(count (reduce conj (list) (range 200000)))"} + {:suite "list / immutability & performance" :label "scale head correct" :expected "199999" :actual "(first (reduce conj (list) (range 200000)))"} + {:suite "macros / quoting" :label "quote symbol" :expected "(quote a)" :actual "(quote a)"} + {:suite "macros / quoting" :label "quote list" :expected "[1 2 3]" :actual "(quote (1 2 3))"} + {:suite "macros / quoting" :label "quote nested" :expected "[1 [2 3]]" :actual "(quote (1 (2 3)))"} + {:suite "macros / quoting" :label "quote sugar" :expected "'a" :actual "'a"} + {:suite "macros / quoting" :label "syntax-quote literal" :expected "[1 2]" :actual "`[1 2]"} + {:suite "macros / quoting" :label "unquote" :expected "[1 2 3]" :actual "(let [x 2] `[1 ~x 3])"} + {:suite "macros / quoting" :label "unquote-splicing" :expected "[1 2 3 4]" :actual "(let [xs [2 3]] `[1 ~@xs 4])"} + {:suite "macros / quoting" :label "unquote in list" :expected "[3]" :actual "(let [x 3] `(~x))"} + {:suite "macros / quoting" :label "syntax-quote symbol qualifies" :expected "true" :actual "(symbol? `foo)"} + {:suite "macros / defmacro" :label "simple macro" :expected "3" :actual "(do (defmacro m [a b] `(+ ~a ~b)) (m 1 2))"} + {:suite "macros / defmacro" :label "macro unless" :expected "1" :actual "(do (defmacro unless [c body] `(if ~c nil ~body)) (unless false 1))"} + {:suite "macros / defmacro" :label "macro with body splice" :expected "6" :actual "(do (defmacro msum [& xs] `(+ ~@xs)) (msum 1 2 3))"} + {:suite "macros / defmacro" :label "macroexpand-1" :expected "false" :actual "(do (defmacro m [x] `(inc ~x)) (list? (macroexpand-1 '(m 5))))"} + {:suite "macros / defmacro" :label "gensym unique" :expected "false" :actual "(= (gensym) (gensym))"} + {:suite "macros / defmacro" :label "gensym# in template" :expected "true" :actual "(do (defmacro m [] `(let [x# 1] x#)) (= 1 (m)))"} + {:suite "macros / defmacro" :label "#() inside syntax-quote" :expected "[2 4 6]" :actual "(do (defmacro m [] `(mapv #(* % 2) [1 2 3])) (m))"} + {:suite "macros / defmacro" :label "#() + auto-gensym share in template" :expected "\"ab\"" :actual "(do (defmacro m [] `(let [sb# (StringBuilder.)] (mapv #(.append sb# %) [\"a\" \"b\"]) (.toString sb#))) (m))"} + {:suite "macros / core-overlay" :label "if-not true branch" :expected ":then" :actual "(if-not false :then :else)"} + {:suite "macros / core-overlay" :label "if-not else branch" :expected ":else" :actual "(if-not true :then :else)"} + {:suite "macros / core-overlay" :label "if-not no else" :expected "nil" :actual "(if-not true :then)"} + {:suite "macros / core-overlay" :label "if-not no else hit" :expected ":then" :actual "(if-not false :then)"} + {:suite "macros / core-overlay" :label "comment -> nil" :expected "nil" :actual "(comment a b c)"} + {:suite "macros / core-overlay" :label "comment in do" :expected "42" :actual "(do (comment ignored) 42)"} + {:suite "macros / core-overlay" :label "if-let then" :expected "6" :actual "(if-let [x 5] (inc x) :none)"} + {:suite "macros / core-overlay" :label "if-let else" :expected ":none" :actual "(if-let [x nil] (inc x) :none)"} + {:suite "macros / core-overlay" :label "if-let else scope" :expected "9" :actual "(let [x 9] (if-let [x nil] :t x))"} + {:suite "macros / core-overlay" :label "if-some zero" :expected "1" :actual "(if-some [x 0] (inc x) :none)"} + {:suite "macros / core-overlay" :label "if-some nil" :expected ":none" :actual "(if-some [x nil] x :none)"} + {:suite "macros / core-overlay" :label "when-some multi" :expected "14" :actual "(when-some [x 7] (inc x) (* x 2))"} + {:suite "macros / core-overlay" :label "when-some nil" :expected "nil" :actual "(when-some [x nil] x)"} + {:suite "macros / core-overlay" :label "while loop" :expected "3" :actual "(let [a (atom 0)] (while (< @a 3) (swap! a inc)) @a)"} + {:suite "macros / core-overlay" :label "dotimes sum" :expected "10" :actual "(let [a (atom 0)] (dotimes [i 5] (swap! a + i)) @a)"} + {:suite "macros / core-overlay" :label "as-> threads" :expected "12" :actual "(as-> 5 x (+ x 1) (* x 2))"} + {:suite "macros / core-overlay" :label "as-> no forms" :expected "5" :actual "(as-> 5 x)"} + {:suite "macros / core-overlay" :label "some-> through" :expected "6" :actual "(some-> {:a {:b 5}} :a :b inc)"} + {:suite "macros / core-overlay" :label "some-> short-circuit" :expected "nil" :actual "(some-> {:a nil} :a :b)"} + {:suite "macros / core-overlay" :label "some->> through" :expected "9" :actual "(some->> [1 2 3] (map inc) (reduce +))"} + {:suite "macros / core-overlay" :label "some->> nil" :expected "nil" :actual "(some->> nil (map inc))"} + {:suite "macros / core-overlay" :label "doto returns obj" :expected "[1 2]" :actual "(deref (doto (atom []) (swap! conj 1) (swap! conj 2)))"} + {:suite "macros / core-overlay" :label "when-first" :expected "20" :actual "(when-first [x [10 20 30]] (* x 2))"} + {:suite "macros / core-overlay" :label "when-first empty" :expected "nil" :actual "(when-first [x []] :body)"} + {:suite "macros / core-overlay" :label "when-first nil coll" :expected "nil" :actual "(when-first [x nil] :body)"} + {:suite "macros / core-overlay" :label "when-first range" :expected "0" :actual "(when-first [x (range 5)] x)"} + {:suite "macros / core-overlay" :label "cond->> threads" :expected "12" :actual "(cond->> 5 true (+ 1) false (* 100) true (* 2))"} + {:suite "macros / core-overlay" :label "cond->> skip" :expected "10" :actual "(cond->> 10 false (+ 1))"} + {:suite "macros / core-overlay" :label "assert pass" :expected ":ok" :actual "(do (assert (= 1 1)) :ok)"} + {:suite "macros / core-overlay" :label "assert throws" :expected ":threw" :actual "(try (assert (= 1 2)) (catch :default e :threw))"} + {:suite "macros / core-overlay" :label "assert message" :expected "\"nope\"" :actual "(try (assert false \"nope\") (catch :default e (ex-message e)))"} + {:suite "macros / core-overlay" :label "delay value" :expected "42" :actual "(deref (delay 42))"} + {:suite "macros / core-overlay" :label "delay forces once" :expected "1" :actual "(let [c (atom 0) d (delay (swap! c inc))] @d @d @c)"} + {:suite "macros / core-overlay" :label "future deref" :expected "9" :actual "(deref (future (* 3 3)))"} + {:suite "macros / core-overlay" :label "letfn simple" :expected "25" :actual "(letfn [(sq [x] (* x x))] (sq 5))"} + {:suite "macros / core-overlay" :label "letfn mutual" :expected "true" :actual "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 8))"} + {:suite "macros / core-overlay" :label "condp match" :expected ":two" :actual "(condp = 2 1 :one 2 :two 3 :three)"} + {:suite "macros / core-overlay" :label "condp default" :expected ":else" :actual "(condp = 9 1 :one 2 :two :else)"} + {:suite "macros / core-overlay" :label "condp :>> form" :expected "\"got 2\"" :actual "(condp some [1 2 3] #{0 9} :>> (fn [x] (str \"got \" x)) #{2 6} :>> (fn [x] (str \"got \" x)))"} + {:suite "macros / core-overlay" :label "condp no match" :expected ":threw" :actual "(try (condp = 9 1 :one) (catch :default e :threw))"} + {:suite "macros / core-overlay" :label "binding rebinds" :expected "99" :actual "(do (def ^:dynamic *bx* 10) (binding [*bx* 99] *bx*))"} + {:suite "macros / core-overlay" :label "binding restores" :expected "10" :actual "(do (def ^:dynamic *by* 10) (binding [*by* 99] *by*) *by*)"} + {:suite "macros / core-overlay" :label "binding seen by fn" :expected "7" :actual "(do (def ^:dynamic *bz* 0) (defn rdz [] *bz*) (binding [*bz* 7] (rdz)))"} + {:suite "macros / time, with-redefs, macroexpand" :label "time returns value" :expected "3" :actual "(time (+ 1 2))"} + {:suite "macros / time, with-redefs, macroexpand" :label "with-redefs rebinds" :expected "42" :actual "(do (defn wr-f [] 1) (with-redefs [wr-f (fn [] 42)] (wr-f)))"} + {:suite "macros / time, with-redefs, macroexpand" :label "with-redefs restores" :expected "1" :actual "(do (defn wr-g [] 1) (with-redefs [wr-g (fn [] 42)]) (wr-g))"} + {:suite "macros / time, with-redefs, macroexpand" :label "with-redefs restores on throw" :expected "1" :actual "(do (defn wr-h [] 1) (try (with-redefs [wr-h (fn [] 42)] (throw (ex-info \"x\" {}))) (catch :default e nil)) (wr-h))"} + {:suite "macros / time, with-redefs, macroexpand" :label "with-redefs-fn" :expected "42" :actual "(do (defn wr-i [] 1) (with-redefs-fn {(var wr-i) (fn [] 42)} (fn [] (wr-i))))"} + {:suite "macros / time, with-redefs, macroexpand" :label "macroexpand full" :expected "true" :actual "(let [e (macroexpand (quote (when-not false 1)))] (= (quote if) (first e)))"} + {:suite "macros / time, with-redefs, macroexpand" :label "macroexpand non-macro" :expected "[1 2]" :actual "(macroexpand (quote [1 2]))"} + {:suite "macros / defmacro arity-clause & name metadata" :label "arity-clause form" :expected "10" :actual "(do (defmacro tw ([x] (list (quote *) x 2))) (tw 5))"} + {:suite "macros / defmacro arity-clause & name metadata" :label "docstring + arity" :expected "15" :actual "(do (defmacro th \"triple\" ([x] (list (quote *) x 3))) (th 5))"} + {:suite "macros / defmacro arity-clause & name metadata" :label "^{:map} name meta" :expected "7" :actual "(do (defmacro ^{:private true} pm [] 7) (pm))"} + {:suite "macros / defmacro arity-clause & name metadata" :label "multi-form body" :expected "6" :actual "(do (defmacro mb ([a b] (list (quote +) a b))) (mb 2 4))"} + {:suite "macros / defmacro multi-arity & attr-map" :label "multi-arity 1" :expected "6" :actual "(do (defmacro ma ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b))) (ma 5))"} + {:suite "macros / defmacro multi-arity & attr-map" :label "multi-arity 2" :expected "5" :actual "(do (defmacro ma ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b))) (ma 2 3))"} + {:suite "macros / defmacro multi-arity & attr-map" :label "arity delegates" :expected "[:d nil 9]" :actual "(do (defmacro lg ([m] `(lg :d nil ~m)) ([l t m] (list (quote vector) l t m))) (lg 9))"} + {:suite "macros / defmacro multi-arity & attr-map" :label "doc + attr-map + params" :expected "10" :actual "(do (defmacro am \"doc\" {:arglists (quote ([x]))} [x] (list (quote inc) x)) (am 9))"} + {:suite "macros / defmacro multi-arity & attr-map" :label "doc + attr-map + variadic" :expected "6" :actual "(do (defmacro vg \"d\" {:arglists (quote ([& a]))} [& xs] `(+ ~@xs)) (vg 1 2 3))"} + {:suite "maps / keyword invoke" :label "hit" :expected "1" :actual "(:a {:a 1 :b 2})"} + {:suite "maps / keyword invoke" :label "miss" :expected "nil" :actual "(:z {:a 1})"} + {:suite "maps / keyword invoke" :label "miss with default" :expected ":d" :actual "(:z {:a 1} :d)"} + {:suite "maps / keyword invoke" :label "hit with default" :expected "1" :actual "(:a {:a 1} :d)"} + {:suite "maps / keyword invoke" :label "on nil" :expected "nil" :actual "(:a nil)"} + {:suite "maps / keyword invoke" :label "on nil with default" :expected ":d" :actual "(:a nil :d)"} + {:suite "maps / keyword invoke" :label "nil value is present" :expected "nil" :actual "(:a {:a nil} :d)"} + {:suite "maps / keyword invoke" :label "false value is present" :expected "false" :actual "(:a {:a false} :d)"} + {:suite "maps / keyword invoke" :label "on a vector" :expected "nil" :actual "(:a [1 2 3])"} + {:suite "maps / keyword invoke" :label "on a number" :expected "nil" :actual "(:a 42)"} + {:suite "maps / keyword invoke" :label "on a sorted map" :expected "2" :actual "(:b (sorted-map :a 1 :b 2))"} + {:suite "maps / keyword invoke" :label "on assoc result" :expected "3" :actual "(:c (assoc {:a 1} :c 3))"} + {:suite "maps / keyword invoke" :label "on a record field" :expected "5" :actual "(do (defrecord KFP [x]) (:x (->KFP 5)))"} + {:suite "maps / keyword invoke" :label "qualified keyword" :expected "1" :actual "(:n/a {:n/a 1})"} + {:suite "maps / keyword invoke" :label "nested in expr" :expected "6" :actual "(+ (:a {:a 1}) (:b {:b 2}) (:c {:c 3}))"} + {:suite "maps / keyword invoke" :label "evaluates map expr once" :expected "[2 1]" :actual "(do (def cnt (atom 0)) (let [v (:a (do (swap! cnt inc) {:a 2}))] [v @cnt]))"} + {:suite "maps / literal construction" :label "basic" :expected "{:a 1, :b 2}" :actual "{:a 1 :b 2}"} + {:suite "maps / literal construction" :label "empty" :expected "{}" :actual "{}"} + {:suite "maps / literal construction" :label "computed values" :expected "{:a 3}" :actual "{:a (+ 1 2)}"} + {:suite "maps / literal construction" :label "nil value kept" :expected "true" :actual "(contains? {:a nil} :a)"} + {:suite "maps / literal construction" :label "nil value lookup" :expected "nil" :actual "(get {:a nil} :a :d)"} + {:suite "maps / literal construction" :label "string key" :expected "1" :actual "(get {\"k\" 1} \"k\")"} + {:suite "maps / literal construction" :label "number key" :expected ":one" :actual "(get {1 :one} 1)"} + {:suite "maps / literal construction" :label "collection key" :expected ":v" :actual "(get {[1 2] :v} [1 2])"} + {:suite "maps / literal construction" :label "collection value-equal key" :expected ":v" :actual "(get {[1 2] :v} (vector 1 2))"} + {:suite "maps / literal construction" :label "computed key" :expected "1" :actual "(get {(keyword \"a\") 1} :a)"} + {:suite "maps / literal construction" :label "values evaluate in source order" :expected "[1 2 3]" :actual "(do (def log (atom [])) {:a (swap! log conj 1) :b (swap! log conj 2) :c (swap! log conj 3)} (deref log))"} + {:suite "maps / literal construction" :label "keys evaluate before their values, pairwise" :expected "[:k1 :v1 :k2 :v2]" :actual "(do (def log (atom [])) {(do (swap! log conj :k1) :a) (do (swap! log conj :v1) 1) (do (swap! log conj :k2) :b) (do (swap! log conj :v2) 2)} (deref log))"} + {:suite "maps / literal construction" :label "source order with a nil value (phm form)" :expected "[1 2 3]" :actual "(do (def log (atom [])) {:a (do (swap! log conj 1) nil) :b (swap! log conj 2) :c (swap! log conj 3)} (deref log))"} + {:suite "maps / literal construction" :label "source order through syntax-quote" :expected "[2 1]" :actual "(do (def log (atom [])) (defmacro m-p3c [] `{:a ~(list 'swap! 'log 'conj 1) :b ~(list 'swap! 'log 'conj 2)}) (m-p3c) (deref log))"} + {:suite "maps / literal construction" :label "count" :expected "3" :actual "(count {:a 1 :b 2 :c 3})"} + {:suite "maps / literal construction" :label "equality with phm" :expected "true" :actual "(= {:a 1 :b 2} (assoc {:a 1} :b 2))"} + {:suite "maps / literal construction" :label "keys work after assoc" :expected "2" :actual "(:b (assoc {:a 1 :b 2} :c 3))"} + {:suite "maps / literal construction" :label "literal in fn body" :expected "12" :actual "(do (defn mfp-mk [x] {:v (* x 2)}) (:v (mfp-mk 6)))"} + {:suite "clojure.math (jolt-h79)" :label "sqrt" :expected "true" :actual "(< 1.4142 (clojure.math/sqrt 2) 1.4143)"} + {:suite "clojure.math (jolt-h79)" :label "pow" :expected "1024" :actual "(long (clojure.math/pow 2 10))"} + {:suite "clojure.math (jolt-h79)" :label "tan of 0" :expected "0" :actual "(long (clojure.math/tan 0))"} + {:suite "clojure.math (jolt-h79)" :label "round" :expected "3" :actual "(clojure.math/round 2.6)"} + {:suite "clojure.math (jolt-h79)" :label "floor" :expected "2.0" :actual "(clojure.math/floor 2.9)"} + {:suite "clojure.math (jolt-h79)" :label "signum" :expected "-1.0" :actual "(clojure.math/signum -7.2)"} + {:suite "clojure.math (jolt-h79)" :label "to-radians" :expected "true" :actual "(< 3.14 (clojure.math/to-radians 180) 3.15)"} + {:suite "clojure.math (jolt-h79)" :label "PI" :expected "true" :actual "(< 3.14 clojure.math/PI 3.15)"} + {:suite "clojure.math (jolt-h79)" :label "require + alias" :expected "5" :actual "(do (require '[clojure.math :as m]) (long (m/hypot 3 4)))"} + {:suite "clojure.math (jolt-h79)" :label "as a value" :expected "[1 2]" :actual "(mapv (comp long clojure.math/sqrt) [1 4])"} + {:suite "calls / locals named like janet macros" :label "local fn named repeat" :expected "[1 1]" :actual "(let [repeat (fn [x] [x x])] (repeat 1))"} + {:suite "calls / locals named like janet macros" :label "local fn named seq" :expected ":end" :actual "((fn seq [n] (if (pos? n) (seq (dec n)) :end)) 2)"} + {:suite "calls / locals named like janet macros" :label "local fn named loop2" :expected "[2 1]" :actual "(let [with (fn [a b] [b a])] (with 1 2))"} + {:suite "calls / locals named like janet macros" :label "overlay repeat self-call (regression)" :expected "[0 0 0]" :actual "(take 3 (repeat 0))"} + {:suite "calls / locals named like janet macros" :label "closure param called" :expected "42" :actual "((fn [f] (f 41)) inc)"} + {:suite "calls / locals named like janet macros" :label "param holding a keyword (IFn leftover)" :expected "1" :actual "((fn [f] (f {:a 1})) :a)"} + {:suite "map / construct & predicate" :label "literal" :expected "{:a 1}" :actual "{:a 1}"} + {:suite "map / construct & predicate" :label "hash-map" :expected "{:b 2, :a 1}" :actual "(hash-map :a 1 :b 2)"} + {:suite "map / construct & predicate" :label "empty" :expected "{}" :actual "{}"} + {:suite "map / construct & predicate" :label "map? true" :expected "true" :actual "(map? {:a 1})"} + {:suite "map / construct & predicate" :label "map? false on vector" :expected "false" :actual "(map? [1 2])"} + {:suite "map / construct & predicate" :label "count" :expected "2" :actual "(count {:a 1 :b 2})"} + {:suite "map / construct & predicate" :label "empty? true" :expected "true" :actual "(empty? {})"} + {:suite "map / construct & predicate" :label "equality order-indep" :expected "true" :actual "(= {:a 1 :b 2} {:b 2 :a 1})"} + {:suite "map / access" :label "get" :expected "1" :actual "(get {:a 1} :a)"} + {:suite "map / access" :label "get missing nil" :expected "nil" :actual "(get {:a 1} :z)"} + {:suite "map / access" :label "get default" :expected ":x" :actual "(get {:a 1} :z :x)"} + {:suite "map / access" :label "keyword as fn" :expected "1" :actual "(:a {:a 1})"} + {:suite "map / access" :label "keyword fn default" :expected ":x" :actual "(:z {:a 1} :x)"} + {:suite "map / access" :label "map as fn" :expected "1" :actual "({:a 1} :a)"} + {:suite "map / access" :label "get-in" :expected "2" :actual "(get-in {:a {:b 2}} [:a :b])"} + {:suite "map / access" :label "get-in missing" :expected "nil" :actual "(get-in {:a {}} [:a :b])"} + {:suite "map / access" :label "contains? key" :expected "true" :actual "(contains? {:a 1} :a)"} + {:suite "map / access" :label "contains? missing" :expected "false" :actual "(contains? {:a 1} :z)"} + {:suite "map / access" :label "find returns entry" :expected "[:a 1]" :actual "(find {:a 1} :a)"} + {:suite "map / access" :label "keys" :expected "true" :actual "(= #{:a :b} (set (keys {:a 1 :b 2})))"} + {:suite "map / access" :label "vals" :expected "true" :actual "(= #{1 2} (set (vals {:a 1 :b 2})))"} + {:suite "map / update" :label "assoc adds" :expected "{:a 1, :b 2}" :actual "(assoc {:a 1} :b 2)"} + {:suite "map / update" :label "assoc overwrites" :expected "{:a 9}" :actual "(assoc {:a 1} :a 9)"} + {:suite "map / update" :label "assoc many" :expected "{:a 1, :b 2}" :actual "(assoc {} :a 1 :b 2)"} + {:suite "map / update" :label "dissoc" :expected "{:a 1}" :actual "(dissoc {:a 1 :b 2} :b)"} + {:suite "map / update" :label "dissoc many" :expected "{:a 1}" :actual "(dissoc {:a 1 :b 2 :c 3} :b :c)"} + {:suite "map / update" :label "merge" :expected "{:a 1, :b 2}" :actual "(merge {:a 1} {:b 2})"} + {:suite "map / update" :label "merge overwrites" :expected "{:a 2}" :actual "(merge {:a 1} {:a 2})"} + {:suite "map / update" :label "merge lattermost wins" :expected "{:a 3}" :actual "(merge {:a 1} {:a 2} {:a 3})"} + {:suite "map / update" :label "merge no args -> nil" :expected "nil" :actual "(merge)"} + {:suite "map / update" :label "merge all nil -> nil" :expected "nil" :actual "(merge nil nil)"} + {:suite "map / update" :label "merge nil arg no-op" :expected "{:a 1}" :actual "(merge {:a 1} nil)"} + {:suite "map / update" :label "merge nil then map" :expected "{:a 1}" :actual "(merge nil {:a 1})"} + {:suite "map / update" :label "merge empty + nil" :expected "{}" :actual "(merge {} nil)"} + {:suite "map / update" :label "merge map-entry (conj)" :expected "{:a 1}" :actual "(merge {} (first {:a 1}))"} + {:suite "map / update" :label "merge [k v] vector" :expected "{:foo 1}" :actual "(merge {} [:foo 1])"} + {:suite "map / update" :label "merge collection key" :expected "true" :actual "(= {[2 3] :foo} (merge {[2 3] :foo} nil {}))"} + {:suite "map / update" :label "merge-with" :expected "{:a 3}" :actual "(merge-with + {:a 1} {:a 2})"} + {:suite "map / update" :label "update" :expected "{:a 2}" :actual "(update {:a 1} :a inc)"} + {:suite "map / update" :label "update missing w/ fnil" :expected "{:a 1}" :actual "(update {} :a (fnil inc 0))"} + {:suite "map / update" :label "update-in" :expected "{:a {:b 2}}" :actual "(update-in {:a {:b 1}} [:a :b] inc)"} + {:suite "map / update" :label "assoc-in" :expected "{:a {:b 1}}" :actual "(assoc-in {} [:a :b] 1)"} + {:suite "map / update" :label "select-keys" :expected "{:a 1}" :actual "(select-keys {:a 1 :b 2} [:a])"} + {:suite "map / update" :label "into onto map" :expected "{:a 1, :b 2}" :actual "(into {:a 1} [[:b 2]])"} + {:suite "map / update" :label "zipmap" :expected "{:a 1, :b 2}" :actual "(zipmap [:a :b] [1 2])"} + {:suite "map / iteration & entries" :label "map over entries" :expected "true" :actual "(= #{1 2} (set (map val {:a 1 :b 2})))"} + {:suite "map / iteration & entries" :label "map keys" :expected "true" :actual "(= #{:a :b} (set (map key {:a 1 :b 2})))"} + {:suite "map / iteration & entries" :label "reduce over entries" :expected "6" :actual "(reduce (fn [a e] (+ a (val e))) 0 {:a 1 :b 2 :c 3})"} + {:suite "map / iteration & entries" :label "reduce-kv" :expected "6" :actual "(reduce-kv (fn [a k v] (+ a v)) 0 {:a 1 :b 2 :c 3})"} + {:suite "map / iteration & entries" :label "destructure entry" :expected "true" :actual "(= [[:a 2]] (into [] (map (fn [[k v]] [k (inc v)]) {:a 1})))"} + {:suite "map / iteration & entries" :label "first of map is entry" :expected "true" :actual "(let [e (first {:a 1})] (and (= (key e) :a) (= (val e) 1)))"} + {:suite "map / iteration & entries" :label "map-entry?" :expected "true" :actual "(map-entry? (first {:a 1}))"} + {:suite "map / iteration & entries" :label "count of nil map" :expected "0" :actual "(count nil)"} + {:suite "map / iteration & entries" :label "get from nil" :expected "nil" :actual "(get nil :a)"} + {:suite "map / iteration & entries" :label "immutability" :expected "true" :actual "(let [m {:a 1} n (assoc m :b 2)] (and (= m {:a 1}) (= n {:a 1 :b 2})))"} + {:suite "map / collection keys (by value)" :label "vector key literal" :expected ":v" :actual "(get {[1 2] :v} [1 2])"} + {:suite "map / collection keys (by value)" :label "map key literal" :expected ":v" :actual "(get {(hash-map :a 1) :v} {:a 1})"} + {:suite "map / collection keys (by value)" :label "assoc vector key" :expected ":v" :actual "(get (assoc {} [1 2] :v) [1 2])"} + {:suite "map / collection keys (by value)" :label "key across repr" :expected ":v" :actual "(get (assoc {} (vec [1 2]) :v) [1 2])"} + {:suite "map / collection keys (by value)" :label "frequencies of maps" :expected "2" :actual "(get (frequencies [{:a 1} (hash-map :a 1)]) {:a 1})"} + {:suite "map / collection keys (by value)" :label "group-by collection key" :expected "1" :actual "(count (group-by identity [{:a 1} (hash-map :a 1)]))"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "set key w/ nil distinct" :expected "2" :actual "(count {#{nil 1} :a, #{1} :b})"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "set key w/ nil neg lookup" :expected "nil" :actual "(get {#{nil 1} :a} #{1})"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "set key w/ nil pos lookup" :expected ":a" :actual "(get {#{nil 1} :a} #{nil 1})"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "set key just nil distinct" :expected "false" :actual "(= {#{nil} :x} {#{} :x})"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "map nil-value key distinct" :expected "2" :actual "(count {{:a nil} 1, {} 2})"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "map nil-value key neg" :expected "nil" :actual "(get {{:a nil} 1} {})"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "map nil-value key pos" :expected "1" :actual "(get {{:a nil} 1} {:a nil})"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "map nil-key key distinct" :expected "2" :actual "(count {{nil :a} 1, {} 2})"} + {:suite "map / nil inside a collection key (jolt-zcm9)" :label "map nil-key key pos" :expected "1" :actual "(get {{nil :a} 1} {nil :a})"} + {:suite "map / strictness (throws like Clojure)" :label "assoc vec out of bounds" :expected :throws :actual "(assoc [0 1 2] 4 4)"} + {:suite "map / strictness (throws like Clojure)" :label "assoc vec negative" :expected :throws :actual "(assoc [] -1 0)"} + {:suite "map / strictness (throws like Clojure)" :label "assoc vec at count ok" :expected "[1 2 3]" :actual "(assoc [1 2] 2 3)"} + {:suite "map / strictness (throws like Clojure)" :label "dissoc on number" :expected :throws :actual "(dissoc 42 :a)"} + {:suite "map / strictness (throws like Clojure)" :label "dissoc on vector" :expected :throws :actual "(dissoc [1 2] 0)"} + {:suite "map / strictness (throws like Clojure)" :label "dissoc on set" :expected :throws :actual "(dissoc #{:a} :a)"} + {:suite "map / strictness (throws like Clojure)" :label "dissoc nil ok" :expected "nil" :actual "(dissoc nil :a)"} + {:suite "map / strictness (throws like Clojure)" :label "count on number" :expected :throws :actual "(count 1)"} + {:suite "map / strictness (throws like Clojure)" :label "count on keyword" :expected :throws :actual "(count :a)"} + {:suite "map / strictness (throws like Clojure)" :label "count string ok" :expected "3" :actual "(count \"abc\")"} + {:suite "map / strictness (throws like Clojure)" :label "numerator throws" :expected :throws :actual "(numerator 1)"} + {:suite "map / strictness (throws like Clojure)" :label "denominator throws" :expected :throws :actual "(denominator 2)"} + {:suite "map / strictness (throws like Clojure)" :label "subvec out of range" :expected :throws :actual "(subvec [0 1 2 3] 1 5)"} + {:suite "map / strictness (throws like Clojure)" :label "subvec start>end" :expected :throws :actual "(subvec [0 1 2 3] 3 2)"} + {:suite "map / strictness (throws like Clojure)" :label "subvec ok" :expected "[1 2]" :actual "(subvec [0 1 2 3] 1 3)"} + {:suite "map / strictness (throws like Clojure)" :label "min-key empty" :expected :throws :actual "(apply min-key identity [])"} + {:suite "map / strictness (throws like Clojure)" :label "merge empty vector" :expected :throws :actual "(merge {} [])"} + {:suite "map / strictness (throws like Clojure)" :label "merge 1-elem vector" :expected :throws :actual "(merge {} [:foo])"} + {:suite "map / strictness (throws like Clojure)" :label "merge atomic arg" :expected :throws :actual "(merge {} :foo)"} + {:suite "map / strictness (throws like Clojure)" :label "merge [k v] ok" :expected "{:foo 1}" :actual "(merge {} [:foo 1])"} + {:suite "map / strictness (throws like Clojure)" :label "merge maps ok" :expected "{:a 1, :b 2}" :actual "(merge {:a 1} {:b 2})"} + {:suite "map / map-entry & key ordering" :label "key of entry" :expected ":a" :actual "(key (first {:a 1}))"} + {:suite "map / map-entry & key ordering" :label "val of entry" :expected "1" :actual "(val (first {:a 1}))"} + {:suite "map / map-entry & key ordering" :label "key rejects vector" :expected :throws :actual "(key [:a 1])"} + {:suite "map / map-entry & key ordering" :label "val rejects vector" :expected :throws :actual "(val [:a 1])"} + {:suite "map / map-entry & key ordering" :label "map-entry? entry" :expected "true" :actual "(map-entry? (first {:a 1}))"} + {:suite "map / map-entry & key ordering" :label "map-entry? vector" :expected "false" :actual "(map-entry? [:a 1])"} + {:suite "map / map-entry & key ordering" :label "min-key NaN first" :expected "1" :actual "(min-key identity ##NaN 1)"} + {:suite "map / map-entry & key ordering" :label "min-key NaN last" :expected "true" :actual "(NaN? (min-key identity 1 ##NaN))"} + {:suite "map / map-entry & key ordering" :label "min-key NaN three" :expected "true" :actual "(infinite? (min-key identity ##NaN ##-Inf 1))"} + {:suite "map / map-entry & key ordering" :label "min-key keys nonnum" :expected :throws :actual "(min-key identity \"x\" \"y\")"} + {:suite "map / map-entry & key ordering" :label "max-key picks max" :expected "[1 2 3]" :actual "(max-key count [1] [1 2 3] [1 2])"} + {:suite "map / map-entry & key ordering" :label "subvec float trunc" :expected "[0]" :actual "(subvec [0 1 2] 0.5 1.33)"} + {:suite "map / map-entry & key ordering" :label "subvec NaN start" :expected "[0 1 2]" :actual "(subvec [0 1 2] ##NaN 3)"} + {:suite "map / map-entry & key ordering" :label "subvec NaN end" :expected "[]" :actual "(subvec [0 1 2] 0 ##NaN)"} + {:suite "map / nil values preserved" :label "literal contains" :expected "true" :actual "(contains? {:b nil} :b)"} + {:suite "map / nil values preserved" :label "literal not= empty" :expected "false" :actual "(= {:b nil} {})"} + {:suite "map / nil values preserved" :label "literal get nil" :expected "nil" :actual "(get {:b nil} :b :x)"} + {:suite "map / nil values preserved" :label "literal keys incl nil" :expected "true" :actual "(= #{:a :b} (set (keys {:a nil :b 1})))"} + {:suite "map / nil values preserved" :label "literal count" :expected "2" :actual "(count {:a nil :b 1})"} + {:suite "map / nil values preserved" :label "literal vals incl nil" :expected "2" :actual "(count (vals {:a nil :b 1}))"} + {:suite "map / nil values preserved" :label "eval values w/ nil" :expected "3" :actual "(:a {:a (+ 1 2) :b nil})"} + {:suite "map / nil values preserved" :label "nil key present" :expected "true" :actual "(contains? {nil :v} nil)"} + {:suite "map / nil values preserved" :label "assoc nil present" :expected "true" :actual "(contains? (assoc {:a 1} :b nil) :b)"} + {:suite "map / nil values preserved" :label "assoc nil get" :expected "nil" :actual "(get (assoc {:a 1} :b nil) :b :x)"} + {:suite "map / nil values preserved" :label "assoc overwrite nil" :expected "nil" :actual "(get (assoc {:a 1} :a nil) :a :x)"} + {:suite "map / nil values preserved" :label "hash-map nil" :expected "true" :actual "(contains? (hash-map :b nil) :b)"} + {:suite "map / nil values preserved" :label "merge new nil" :expected "true" :actual "(contains? (merge {:a 1} {:b nil}) :b)"} + {:suite "map / nil values preserved" :label "merge overwrite nil" :expected "nil" :actual "(get (merge {:a 1} {:a nil}) :a :x)"} + {:suite "map / nil values preserved" :label "merge-with present nil" :expected "true" :actual "(= [nil 1] (get (merge-with (fn [a b] [a b]) {:a nil} {:a 1}) :a))"} + {:suite "map / nil values preserved" :label "into nil val" :expected "true" :actual "(contains? (into {} [[:a nil]]) :a)"} + {:suite "map / nil values preserved" :label "conj map nil" :expected "true" :actual "(contains? (conj {:x 1} {:a nil}) :a)"} + {:suite "map / nil values preserved" :label "zipmap nil" :expected "true" :actual "(contains? (zipmap [:a] [nil]) :a)"} + {:suite "map / nil values preserved" :label "select-keys nil" :expected "true" :actual "(contains? (select-keys {:a nil} [:a]) :a)"} + {:suite "map / nil values preserved" :label "get-in present nil" :expected "nil" :actual "(get-in {:a nil} [:a] :x)"} + {:suite "map / nil values preserved" :label "get-in through nil" :expected ":x" :actual "(get-in {:a nil} [:a :b] :x)"} + {:suite "map / nil values preserved" :label "dissoc keeps nil" :expected "true" :actual "(contains? (dissoc {:a nil :b 1} :b) :a)"} + {:suite "map / nil values preserved" :label "reduce-kv sees nil" :expected "true" :actual "(= #{:a :b} (reduce-kv (fn [acc k v] (conj acc k)) #{} {:a nil :b 2}))"} + {:suite "map / nil values preserved" :label "nil-free stays fast" :expected "true" :actual "(= {:a 1 :b 2} {:b 2 :a 1})"} + {:suite "map / update-keys & update-vals (1.11)" :label "update-keys" :expected "{\"a\" 1, \"b\" 2}" :actual "(update-keys {:a 1 :b 2} name)"} + {:suite "map / update-keys & update-vals (1.11)" :label "update-keys empty" :expected "{}" :actual "(update-keys {} inc)"} + {:suite "map / update-keys & update-vals (1.11)" :label "update-keys nil" :expected "{}" :actual "(update-keys nil str)"} + {:suite "map / update-keys & update-vals (1.11)" :label "update-keys collide last wins" :expected "1" :actual "(count (update-keys {:a 1 :b 2} (fn [_] :k)))"} + {:suite "map / update-keys & update-vals (1.11)" :label "update-vals" :expected "{:a 2, :b 3}" :actual "(update-vals {:a 1 :b 2} inc)"} + {:suite "map / update-keys & update-vals (1.11)" :label "update-vals empty" :expected "{}" :actual "(update-vals {} inc)"} + {:suite "map / update-keys & update-vals (1.11)" :label "update-vals nil" :expected "{}" :actual "(update-vals nil inc)"} + {:suite "map / update-keys & update-vals (1.11)" :label "update-vals keeps keys" :expected "[:a :b]" :actual "(sort (keys (update-vals {:a 1 :b 2} inc)))"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "keys" :expected "[:a]" :actual "(keys {:a 1})"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "keys empty map" :expected "nil" :actual "(keys {})"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "keys nil" :expected "nil" :actual "(keys nil)"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "vals" :expected "[1]" :actual "(vals {:a 1})"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "vals empty" :expected "nil" :actual "(vals {})"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "keys sorted order" :expected "[1 2 3]" :actual "(vec (keys (sorted-map 2 :b 1 :a 3 :c)))"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "vals sorted order" :expected "[:a :b :c]" :actual "(vec (vals (sorted-map 2 :b 1 :a 3 :c)))"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "keys/vals zip" :expected "{:a 1, :b 2}" :actual "(zipmap (keys {:a 1 :b 2}) (vals {:a 1 :b 2}))"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? map" :expected "true" :actual "(empty? {})"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? vec" :expected "[true false]" :actual "[(empty? []) (empty? [1])]"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? list" :expected "[true false]" :actual "[(empty? ()) (empty? (list 1))]"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? string" :expected "[true false]" :actual "[(empty? \"\") (empty? \"a\")]"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? nil" :expected "true" :actual "(empty? nil)"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? set" :expected "[true false]" :actual "[(empty? #{}) (empty? #{1})]"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? lazy" :expected "[true false]" :actual "[(empty? (filter pos? [-1])) (empty? (map inc [1]))]"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? lazy nil elem" :expected "false" :actual "(empty? (cons nil nil))"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? sorted" :expected "[true false]" :actual "[(empty? (sorted-map)) (empty? (sorted-set 1))]"} + {:suite "maps / keys-vals-empty? as overlay fns" :label "empty? number throws" :expected :throws :actual "(empty? 5)"} + {:suite "map / assoc on nil" :label "assoc nil is a map" :expected "{:a 1}" :actual "(assoc nil :a 1)"} + {:suite "map / assoc on nil" :label "count of assoc nil" :expected "1" :actual "(count (assoc nil :a 1))"} + {:suite "map / assoc on nil" :label "assoc-in nested countable" :expected "1" :actual "(count (:a (assoc-in {} [:a :b] 1)))"} + {:suite "map / assoc on nil" :label "assoc-in deep get" :expected "9" :actual "(get-in (assoc-in {} [:a :b :c] 9) [:a :b :c])"} + {:suite "map / assoc on nil" :label "seq over assoc-nil map" :expected ":a" :actual "(ffirst (seq (assoc nil :a 1)))"} + {:suite "map / assoc on nil" :label "keys of assoc-nil map" :expected "[:a]" :actual "(vec (keys (assoc nil :a 1)))"} + {:suite "map / bulk build boundaries" :label "into = incr at 17" :expected "true" :actual "(= (into {} (map (fn [i] [i (* i 2)]) (range 17))) (reduce (fn [m p] (assoc m (first p) (second p))) {} (map (fn [i] [i (* i 2)]) (range 17))))"} + {:suite "map / bulk build boundaries" :label "into = incr at 1000" :expected "true" :actual "(= (into {} (map (fn [i] [i (* i 2)]) (range 1000))) (reduce (fn [m p] (assoc m (first p) (second p))) {} (map (fn [i] [i (* i 2)]) (range 1000))))"} + {:suite "map / bulk build boundaries" :label "into count 1000" :expected "1000" :actual "(count (into {} (map (fn [i] [i i]) (range 1000))))"} + {:suite "map / bulk build boundaries" :label "into reads back" :expected "999" :actual "(get (into {} (map (fn [i] [i (* i 3)]) (range 1000))) 333)"} + {:suite "map / bulk build boundaries" :label "into onto non-empty" :expected "9" :actual "(get (into {:a 1} [[:a 9] [:b 2]]) :a)"} + {:suite "map / bulk build boundaries" :label "into dup last wins" :expected "9" :actual "(get (into {} [[:k 1] [:k 9]]) :k)"} + {:suite "map / bulk build boundaries" :label "into nil key" :expected ":x" :actual "(get (into {} [[nil :x] [:a 1]]) nil)"} + {:suite "map / bulk build boundaries" :label "assoc after bulk" :expected "7" :actual "(get (assoc (into {} (map (fn [i] [i i]) (range 100))) :new 7) :new)"} + {:suite "map / bulk build boundaries" :label "dissoc after bulk" :expected "nil" :actual "(get (dissoc (into {} (map (fn [i] [i i]) (range 100))) 50) 50)"} + {:suite "map / bulk build boundaries" :label "frequencies count" :expected "3" :actual "(get (frequencies [1 2 2 1 2 1]) 1)"} + {:suite "map / bulk build boundaries" :label "frequencies coll-key" :expected "2" :actual "(get (frequencies [[1 2] [1 2] [3 4]]) [1 2])"} + {:suite "map / bulk build boundaries" :label "frequencies nil key" :expected "2" :actual "(get (frequencies [nil nil 1]) nil)"} + {:suite "map / bulk build boundaries" :label "group-by nil key" :expected "[nil nil]" :actual "(get (group-by identity [nil nil 1]) nil)"} + {:suite "map / bulk build boundaries" :label "group-by nil count" :expected "2" :actual "(count (group-by identity [nil nil 1]))"} + {:suite "map / bulk build boundaries" :label "transient nil key" :expected ":x" :actual "(let [t (transient {})] (assoc! t nil :x) (get (persistent! t) nil))"} + {:suite "map / bulk build boundaries" :label "transient nil get" :expected "true" :actual "(let [t (transient {})] (assoc! t nil :x) (contains? t nil))"} + {:suite "map / bulk build boundaries" :label "transient nil dissoc" :expected ":gone" :actual "(let [t (transient {})] (assoc! t nil :x) (dissoc! t nil) (get (persistent! t) nil :gone))"} + {:suite "map / bulk build boundaries" :label "group-by bucket" :expected "[1 3 5]" :actual "(get (group-by odd? (range 1 6)) true)"} + {:suite "map / bulk build boundaries" :label "group-by big bucket" :expected "true" :actual "(= (group-by even? (range 200)) {true (vec (filter even? (range 200))) false (vec (filter odd? (range 200)))})"} + {:suite "map / bulk build boundaries" :label "group-by order" :expected "[0 3 6 9]" :actual "(get (group-by (fn [x] (mod x 3)) (range 10)) 0)"} + {:suite "map / bulk build boundaries" :label "hash-map bulk = incr" :expected "true" :actual "(= (apply hash-map (mapcat (fn [i] [i i]) (range 50))) (reduce (fn [m i] (assoc m i i)) {} (range 50)))"} + {:suite "metadata / with-meta & meta" :label "meta of bare value" :expected "nil" :actual "(meta [1 2 3])"} + {:suite "metadata / with-meta & meta" :label "with-meta then meta" :expected "{:a 1}" :actual "(meta (with-meta [1 2 3] {:a 1}))"} + {:suite "metadata / with-meta & meta" :label "with-meta preserves value" :expected "true" :actual "(= [1 2 3] (with-meta [1 2 3] {:a 1}))"} + {:suite "metadata / with-meta & meta" :label "with-meta on map" :expected "{:doc \"x\"}" :actual "(meta (with-meta {:k 1} {:doc \"x\"}))"} + {:suite "metadata / with-meta & meta" :label "vary-meta" :expected "{:a 2}" :actual "(meta (vary-meta (with-meta [1] {:a 1}) update :a inc))"} + {:suite "metadata / with-meta & meta" :label "vary-meta extra args" :expected "{:a 1, :b 2}" :actual "(meta (vary-meta (with-meta [1] {:a 1}) assoc :b 2))"} + {:suite "metadata / with-meta & meta" :label "meta reader ^" :expected "{:tag :int}" :actual "(meta ^{:tag :int} [1 2])"} + {:suite "metadata / with-meta & meta" :label "with-meta on fn ok" :expected "true" :actual "(fn? (with-meta inc {:a 1}))"} + {:suite "metadata / with-meta & meta" :label "with-meta nil clears" :expected "nil" :actual "(meta (with-meta [1 2 3] nil))"} + {:suite "metadata / type hints" :label "type hint on param" :expected "\"hi\"" :actual "(do (defn f [^String s] s) (f \"hi\"))"} + {:suite "metadata / type hints" :label "type hint, extra params" :expected "[1 2]" :actual "(do (defn g [^String x y] [x y]) (g 1 2))"} + {:suite "metadata / type hints" :label "type hint in let" :expected "6" :actual "(let [^long x 5] (inc x))"} + {:suite "metadata / type hints" :label "type hint in body" :expected "2" :actual "(let [s \"ab\"] (count ^String s))"} + {:suite "metadata / type hints" :label "type hint in destructure" :expected "3" :actual "(let [{:keys [^long a]} {:a 3}] a)"} + {:suite "metadata / type hints" :label "symbol hint -> :tag" :expected "\"String\"" :actual "(:tag (meta (read-string \"^String x\")))"} + {:suite "metadata / type hints" :label "keyword hint -> true" :expected "true" :actual "(:foo (meta (read-string \"^:foo x\")))"} + {:suite "metadata / def metadata" :label "^:dynamic var binds" :expected "9" :actual "(do (def ^:dynamic *d* 1) (binding [*d* 9] *d*))"} + {:suite "metadata / def metadata" :label "^:private on var" :expected "true" :actual "(do (def ^:private pv 1) (:private (meta (var pv))))"} + {:suite "metadata / def metadata" :label "^Type tag on var" :expected "java.lang.String" :actual "(do (def ^String tv \"a\") (:tag (meta (var tv))))"} + {:suite "metadata / def metadata" :label "^{:doc} on var" :expected "\"hi\"" :actual "(do (def ^{:doc \"hi\"} dv 1) (:doc (meta (var dv))))"} + {:suite "metadata / def metadata" :label "(def name doc val) doc" :expected "\"d\"" :actual "(do (def dd \"d\" 5) (:doc (meta (var dd))))"} + {:suite "core / find-keyword + inst-ms*" :label "find-keyword" :expected ":a" :actual "(find-keyword \"a\")"} + {:suite "core / find-keyword + inst-ms*" :label "find-keyword 2-arity" :expected ":n/a" :actual "(find-keyword \"n\" \"a\")"} + {:suite "core / find-keyword + inst-ms*" :label "find-keyword = keyword" :expected "true" :actual "(= (find-keyword \"x\") :x)"} + {:suite "core / find-keyword + inst-ms*" :label "inst-ms*" :expected "true" :actual "(= (inst-ms* #inst \"2020-01-01T00:00:00Z\") (inst-ms #inst \"2020-01-01T00:00:00Z\"))"} + {:suite "core / find-keyword + inst-ms*" :label "inst-ms* value" :expected "0" :actual "(inst-ms* #inst \"1970-01-01T00:00:00Z\")"} + {:suite "core / with-local-vars" :label "var-get initial" :expected "1" :actual "(with-local-vars [x 1] (var-get x))"} + {:suite "core / with-local-vars" :label "var-set" :expected "2" :actual "(with-local-vars [x 1] (var-set x 2) (var-get x))"} + {:suite "core / with-local-vars" :label "two vars" :expected "[1 2]" :actual "(with-local-vars [a 1 b 2] [(var-get a) (var-get b)])"} + {:suite "core / with-local-vars" :label "vars are values" :expected "5" :actual "(with-local-vars [x 0] (let [bump (fn [v] (var-set v (+ 5 (var-get v))))] (bump x) (var-get x)))"} + {:suite "core / with-local-vars" :label "init sees outer" :expected "3" :actual "(let [y 3] (with-local-vars [x y] (var-get x)))"} + {:suite "core / with-local-vars" :label "body result" :expected ":done" :actual "(with-local-vars [x 1] :done)"} + {:suite "core / with-open" :label "body result" :expected ":r" :actual "(let [log (atom [])] (with-open [c {:close (fn [] (swap! log conj :closed))}] :r))"} + {:suite "core / with-open" :label "close runs" :expected "[:closed]" :actual "(let [log (atom [])] (with-open [c {:close (fn [] (swap! log conj :closed))}] :r) (deref log))"} + {:suite "core / with-open" :label "close on throw" :expected "[]" :actual "(let [log (atom [])] (try (with-open [c {:close (fn [] (swap! log conj :closed))}] (throw (ex-info \"boom\" {}))) (catch Exception e nil)) (deref log))"} + {:suite "core / with-open" :label "nested close order" :expected "[:inner :outer]" :actual "(let [log (atom [])] (with-open [a {:close (fn [] (swap! log conj :outer))} b {:close (fn [] (swap! log conj :inner))}] :r) (deref log))"} + {:suite "core / with-open" :label "zero bindings" :expected ":r" :actual "(with-open [] :r)"} + {:suite "core / with-open" :label "binding visible" :expected "5" :actual "(with-open [c {:close (fn [] nil) :v 5}] (:v c))"} + {:suite "core / with-precision" :label "body evaluates" :expected "3.14" :actual "(with-precision 3 3.14)"} + {:suite "core / with-precision" :label "multiple body forms" :expected "2" :actual "(with-precision 10 1 2)"} + {:suite "core / with-precision" :label "rounding arg accepted" :expected "1.5" :actual "(with-precision 4 :rounding :half-up 1.5)"} + {:suite "core / with-precision" :label "arithmetic" :expected "2" :actual "(with-precision 5 (+ 1 1))"} + {:suite "core / read+string" :label "form and text" :expected "true" :actual "(let [[v s] (with-in-str \"42 rest\" (read+string))] (and (= v 42) (string? s)))"} + {:suite "core / read+string" :label "form value" :expected "(quote (+ 1 2))" :actual "(first (with-in-str \"(+ 1 2)\" (read+string)))"} + {:suite "core / read+string" :label "text covers the form" :expected "true" :actual "(let [[v s] (with-in-str \" [1 2] tail\" (read+string))] (and (= v [1 2]) (> (count s) 3)))"} + {:suite "core / read+string" :label "advances the stream" :expected "[1 2]" :actual "(with-in-str \"1 2\" [(first (read+string)) (first (read+string))])"} + {:suite "core / read+string" :label "EOF throws" :expected :throws :actual "(with-in-str \"\" (read+string))"} + {:suite "core / read+string" :label "eof-value arity" :expected ":done" :actual "(first (with-in-str \"\" (read+string *in* false :done)))"} + {:suite "core / extenders" :label "lists extended type" :expected "[]" :actual "(do (defprotocol Px (pm [x])) (defrecord Rx [] Px (pm [x] 1)) (mapv str (extenders Px)))"} + {:suite "core / extenders" :label "nil when none" :expected "nil" :actual "(do (defprotocol Py (pn [x])) (extenders Py))"} + {:suite "core / extenders" :label "seq of tags" :expected "nil" :actual "(do (defprotocol Pz (pz [x])) (defrecord Rz [] Pz (pz [x] 1)) (and (seq (extenders Pz)) (= 1 (count (extenders Pz)))))"} + {:suite "multimethods / dispatch" :label "dispatch on value" :expected "\"two\"" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (f 2))"} + {:suite "multimethods / dispatch" :label "dispatch on keyword fn" :expected "\"circle\"" :actual "(do (defmulti area :shape) (defmethod area :circle [_] \"circle\") (area {:shape :circle}))"} + {:suite "multimethods / dispatch" :label ":default method" :expected "\"other\"" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f :default [_] \"other\") (f 99))"} + {:suite "multimethods / dispatch" :label "no match throws" :expected :throws :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (f 99))"} + {:suite "multimethods / dispatch" :label "multiple args" :expected "5" :actual "(do (defmulti g (fn [a b] a)) (defmethod g :add [_ b] b) (g :add 5))"} + {:suite "multimethods / dispatch" :label "get-method" :expected "\"one\"" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") ((get-method f 1) 1))"} + {:suite "multimethods / dispatch" :label "remove-method" :expected :throws :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (remove-method f 1) (f 1))"} + {:suite "multimethods / dispatch" :label "methods" :expected "\"one\"" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") ((get (methods f) 1) 1))"} + {:suite "multimethods / dispatch" :label "methods count" :expected "2" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (count (methods f)))"} + {:suite "multimethods / dispatch" :label "remove-all-methods" :expected :throws :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (remove-all-methods f) (f 1))"} + {:suite "multimethods / dispatch" :label "remove-all-methods empties the table" :expected "0" :actual "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (remove-all-methods f) (count (methods f)))"} + {:suite "multimethods / hierarchies" :label "derive + isa?" :expected "true" :actual "(do (derive ::child ::parent) (isa? ::child ::parent))"} + {:suite "multimethods / hierarchies" :label "isa? reflexive" :expected "true" :actual "(isa? ::x ::x)"} + {:suite "multimethods / hierarchies" :label "isa? unrelated" :expected "false" :actual "(do (derive ::a ::b) (isa? ::a ::c))"} + {:suite "multimethods / hierarchies" :label "parents" :expected "true" :actual "(do (derive ::c ::p) (contains? (parents ::c) ::p))"} + {:suite "multimethods / hierarchies" :label "ancestors" :expected "true" :actual "(do (derive ::c ::p) (derive ::p ::g) (contains? (ancestors ::c) ::g))"} + {:suite "multimethods / hierarchies" :label "descendants" :expected "true" :actual "(do (derive ::c ::p) (contains? (descendants ::p) ::c))"} + {:suite "multimethods / hierarchies" :label "dispatch via hierarchy" :expected "\"animal\"" :actual "(do (derive ::dog ::animal) (defmulti speak identity) (defmethod speak ::animal [_] \"animal\") (speak ::dog))"} + {:suite "multimethods / hierarchies" :label "custom :default key" :expected ":unknown" :actual "(do (defmulti classify :type :default :other) (defmethod classify :a [_] :alpha) (defmethod classify :other [_] :unknown) (classify {:type :zzz}))"} + {:suite "multimethods / hierarchies" :label "explicit :hierarchy" :expected "\"a\"" :actual "(do (def h (derive (make-hierarchy) ::dog ::animal)) (defmulti snd identity :hierarchy h) (defmethod snd ::animal [_] \"a\") (snd ::dog))"} + {:suite "multimethods / prefer-method" :label "preference picks the winner" :expected ":rect" :actual "(do (derive :p/sq :p/rect) (derive :p/sq :p/shape) (defmulti pm1 identity) (defmethod pm1 :p/rect [x] :rect) (defmethod pm1 :p/shape [x] :shape) (prefer-method pm1 :p/rect :p/shape) (pm1 :p/sq))"} + {:suite "multimethods / prefer-method" :label "reverse preference" :expected ":shape" :actual "(do (derive :q/sq :q/rect) (derive :q/sq :q/shape) (defmulti pm2 identity) (defmethod pm2 :q/rect [x] :rect) (defmethod pm2 :q/shape [x] :shape) (prefer-method pm2 :q/shape :q/rect) (pm2 :q/sq))"} + {:suite "multimethods / prefer-method" :label "ambiguity throws" :expected :throws :actual "(do (derive :r/sq :r/rect) (derive :r/sq :r/shape) (defmulti pm3 identity) (defmethod pm3 :r/rect [x] :rect) (defmethod pm3 :r/shape [x] :shape) (pm3 :r/sq))"} + {:suite "multimethods / prefer-method" :label "isa dominance needs no preference" :expected ":child" :actual "(do (derive :s/c :s/p) (defmulti pm4 identity) (defmethod pm4 :s/c [x] :child) (defmethod pm4 :s/p [x] :parent) (pm4 :s/c))"} + {:suite "multimethods / prefer-method" :label "prefers map shape" :expected "true" :actual "(do (defmulti pm5 identity) (defmethod pm5 :a [x] 1) (defmethod pm5 :b [x] 2) (prefer-method pm5 :a :b) (contains? (get (prefers pm5) :a) :b))"} + {:suite "multimethods / prefer-method" :label "exact match needs no preference" :expected ":exact" :actual "(do (derive :t/sq :t/rect) (defmulti pm6 identity) (defmethod pm6 :t/sq [x] :exact) (defmethod pm6 :t/rect [x] :parent) (pm6 :t/sq))"} + {:suite "multimethods / docstring & value-based table ops" :label "defmulti docstring" :expected "\"A\"" :actual "(do (defmulti gd \"the dispatcher\" identity) (defmethod gd :a [_] \"A\") (gd :a))"} + {:suite "multimethods / docstring & value-based table ops" :label "defmulti doc+default" :expected "\"d\"" :actual "(do (defmulti gx \"doc\" identity) (defmethod gx :default [_] \"d\") (gx :anything))"} + {:suite "multimethods / docstring & value-based table ops" :label "methods on value" :expected "2" :actual "(do (defmulti gm identity) (defmethod gm 1 [_] :one) (defmethod gm 2 [_] :two) (count (methods gm)))"} + {:suite "multimethods / docstring & value-based table ops" :label "get-method on value" :expected "true" :actual "(do (defmulti gg identity) (defmethod gg :a [_] :x) (fn? (get-method gg :a)))"} + {:suite "namespaces / def & vars" :label "def + deref" :expected "5" :actual "(do (def x 5) x)"} + {:suite "namespaces / def & vars" :label "def returns var" :expected "true" :actual "(var? (def y 1))"} + {:suite "namespaces / def & vars" :label "declare then def" :expected "2" :actual "(do (declare z) (def z 2) z)"} + {:suite "namespaces / def & vars" :label "var special form" :expected "true" :actual "(var? (var +))"} + {:suite "namespaces / def & vars" :label "var sugar #'" :expected "true" :actual "(var? #'+)"} + {:suite "namespaces / def & vars" :label "var-get" :expected "5" :actual "(do (def w 5) (var-get #'w))"} + {:suite "namespaces / def & vars" :label "defn defines fn" :expected "3" :actual "(do (defn f [x] (inc x)) (f 2))"} + {:suite "namespaces / def & vars" :label "def with docstring" :expected "7" :actual "(do (def d \"a doc\" 7) d)"} + {:suite "namespaces / def & vars" :label "dynamic var binding" :expected "2" :actual "(do (def ^:dynamic *x* 1) (binding [*x* 2] *x*))"} + {:suite "namespaces / def & vars" :label "binding restores" :expected "1" :actual "(do (def ^:dynamic *y* 1) (binding [*y* 9] nil) *y*)"} + {:suite "namespaces / def & vars" :label "var-set in binding" :expected "5" :actual "(do (def ^:dynamic *z* 1) (binding [*z* 0] (var-set (var *z*) 5) *z*))"} + {:suite "namespaces / ns operations" :label "in-ns switches" :expected "true" :actual "(do (in-ns 'my.ns) (symbol? 'x))"} + {:suite "namespaces / ns operations" :label "ns form + alias" :expected "\"HI\"" :actual "(do (ns my.app (:require [clojure.string :as s])) (s/upper-case \"hi\"))"} + {:suite "namespaces / ns operations" :label "ns :use refers all" :expected "9" :actual "(do (ns src.lib) (def helper 9) (ns dst.app (:use [src.lib])) helper)"} + {:suite "namespaces / ns operations" :label "standalone use" :expected "7" :actual "(do (ns src.l2) (def k 7) (in-ns 'dst.a2) (use '[src.l2]) k)"} + {:suite "namespaces / ns operations" :label "ns-name" :expected "true" :actual "(do (require (quote [clojure.string])) (= 'clojure.string (ns-name (find-ns 'clojure.string))))"} + {:suite "namespaces / ns operations" :label "find-ns existing" :expected "true" :actual "(some? (find-ns 'clojure.core))"} + {:suite "namespaces / ns operations" :label "find-ns missing" :expected "nil" :actual "(find-ns 'does.not.exist)"} + {:suite "namespaces / ns operations" :label "resolve var" :expected "true" :actual "(var? (resolve '+))"} + {:suite "namespaces / ns operations" :label "resolve missing" :expected "nil" :actual "(resolve 'totally-undefined-xyz)"} + {:suite "namespaces / require & refer" :label "require :as" :expected "\"AB\"" :actual "(do (require '[clojure.string :as s]) (s/upper-case \"ab\"))"} + {:suite "namespaces / require & refer" :label "require :refer" :expected "true" :actual "(do (require '[clojure.string :refer [blank?]]) (blank? \"\"))"} + {:suite "namespaces / require & refer" :label "require :as + :refer" :expected "true" :actual "(do (require '[clojure.string :as s :refer [blank?]]) (and (blank? \"\") (= \"X\" (s/upper-case \"x\"))))"} + {:suite "namespaces / require & refer" :label "require clojure.set" :expected "#{1 3 2}" :actual "(do (require '[clojure.set :as set]) (set/union #{1 2} #{3}))"} + {:suite "namespaces / require & refer" :label "require clojure.walk" :expected "{:a 2}" :actual "(do (require '[clojure.walk :as w]) (w/postwalk (fn [x] (if (number? x) (inc x) x)) {:a 1}))"} + {:suite "namespaces / require & refer" :label "walk keywordize-keys" :expected "{:a 1}" :actual "(do (require '[clojure.walk :as w]) (w/keywordize-keys {\"a\" 1}))"} + {:suite "namespaces / require & refer" :label "walk stringify-keys" :expected "true" :actual "(do (require '[clojure.walk :as w]) (= {\"a\" 1} (w/stringify-keys {:a 1})))"} + {:suite "namespaces / require & refer" :label "require missing lib throws" :expected :throws :actual "(require '[no.such.lib])"} + {:suite "namespaces / require & refer" :label "use missing lib throws" :expected :throws :actual "(use 'no.such.lib)"} + {:suite "namespaces / require & refer" :label "require of in-session ns ok" :expected "1" :actual "(do (ns made.here) (def x 1) (require '[made.here]) made.here/x)"} + {:suite "namespaces / alias, ns-unalias, ns-publics" :label "alias + use" :expected "\"1,2\"" :actual "(do (require (quote clojure.string)) (alias (quote st) (quote clojure.string)) (st/join \",\" [1 2]))"} + {:suite "namespaces / alias, ns-unalias, ns-publics" :label "ns-unalias removes" :expected "true" :actual "(do (require (quote clojure.string)) (alias (quote st2) (quote clojure.string)) (ns-unalias (quote user) (quote st2)) (nil? (get (ns-aliases (quote user)) (quote st2))))"} + {:suite "namespaces / alias, ns-unalias, ns-publics" :label "ns-publics has var" :expected "true" :actual "(do (def npv 1) (some? (get (ns-publics (quote user)) (quote npv))))"} + {:suite "namespaces / alias, ns-unalias, ns-publics" :label "newline returns nil" :expected "nil" :actual "(newline)"} + {:suite "namespaces / error inside a fn must not leak its defining ns" :label "alias survives a throwing stdlib call" :expected "\"A\"" :actual "(do (require (quote [clojure.string :as s9])) (try (s9/join nil nil nil) (catch Exception e nil)) (s9/upper-case \"a\"))"} + {:suite "namespaces / error inside a fn must not leak its defining ns" :label "*ns* restored after throw" :expected "\"user\"" :actual "(do (require (quote [clojure.walk :as w9])) (try (w9/postwalk nil nil nil) (catch Exception e nil)) (str *ns*))"} + {:suite "namespaces / unified alias store" :label "require :as registers the alias" :expected "1" :actual "(do (require (quote [clojure.string :as st1])) (count (filter (fn [[a n]] (= (str a) \"st1\")) (ns-aliases))))"} + {:suite "namespaces / unified alias store" :label "aliased call resolves" :expected "\"A\"" :actual "(do (require (quote [clojure.string :as st2])) (st2/upper-case \"a\"))"} + {:suite "namespaces / unified alias store" :label "alias fn registers + resolves" :expected "\"B\"" :actual "(do (require (quote [clojure.string])) (alias (quote st3) (quote clojure.string)) (st3/upper-case \"b\"))"} + {:suite "namespaces / unified alias store" :label "alias fn visible to ns-aliases" :expected "true" :actual "(do (require (quote [clojure.string])) (alias (quote st4) (quote clojure.string)) (pos? (count (filter (fn [[a n]] (= (str a) \"st4\")) (ns-aliases)))))"} + {:suite "namespaces / unified alias store" :label "ns-unalias removes both views" :expected "[0 false]" :actual "(do (require (quote [clojure.string :as st5])) (ns-unalias (quote user) (quote st5)) [(count (filter (fn [[a n]] (= (str a) \"st5\")) (ns-aliases))) (boolean (resolve (quote st5/upper-case)))])"} + {:suite "namespaces / unified alias store" :label "ns-resolve through alias" :expected "true" :actual "(do (require (quote [clojure.string :as st6])) (var? (ns-resolve (quote user) (quote st6/upper-case))))"} + {:suite "namespaces / unified alias store" :label "empty ns-aliases is a map" :expected "true" :actual "(map? (ns-aliases (quote clojure.core)))"} + {:suite "*ns* / identity & printing" :label "str of *ns*" :expected "\"user\"" :actual "(str *ns*)"} + {:suite "*ns* / identity & printing" :label "ns-name of *ns*" :expected "(quote user)" :actual "(ns-name *ns*)"} + {:suite "*ns* / identity & printing" :label "*ns* is find-ns" :expected "true" :actual "(= (ns-name *ns*) (ns-name (find-ns (quote user))))"} + {:suite "*ns* / identity & printing" :label "*ns* not a map" :expected "false" :actual "(map? *ns*)"} + {:suite "*ns* / identity & printing" :label "tracks in-ns" :expected "\"jolt.test-ns-a\"" :actual "(do (in-ns (quote jolt.test-ns-a)) (str *ns*))"} + {:suite "*ns* / identity & printing" :label "in-ns returns ns" :expected "\"jolt.test-ns-b\"" :actual "(str (in-ns (quote jolt.test-ns-b)))"} + {:suite "*ns* / identity & printing" :label "usable with ns fns" :expected "true" :actual "(do (require (quote clojure.string)) (alias (quote nsv) (quote clojure.string)) (some? (get (ns-aliases *ns*) (quote nsv))))"} + {:suite "*ns* / identity & printing" :label "ns-unalias via *ns*" :expected "true" :actual "(do (require (quote clojure.string)) (alias (quote nsw) (quote clojure.string)) (ns-unalias *ns* (quote nsw)) (nil? (get (ns-aliases *ns*) (quote nsw))))"} + {:suite "numbers / arithmetic" :label "add" :expected "6" :actual "(+ 1 2 3)"} + {:suite "numbers / arithmetic" :label "add zero args" :expected "0" :actual "(+)"} + {:suite "numbers / arithmetic" :label "subtract" :expected "5" :actual "(- 10 3 2)"} + {:suite "numbers / arithmetic" :label "negate" :expected "-5" :actual "(- 5)"} + {:suite "numbers / arithmetic" :label "multiply" :expected "24" :actual "(* 2 3 4)"} + {:suite "numbers / arithmetic" :label "multiply zero args" :expected "1" :actual "(*)"} + {:suite "numbers / arithmetic" :label "divide" :expected "2" :actual "(/ 10 5)"} + {:suite "numbers / arithmetic" :label "divide to fraction" :expected "1/2" :actual "(/ 1 2)"} + {:suite "numbers / arithmetic" :label "inc" :expected "6" :actual "(inc 5)"} + {:suite "numbers / arithmetic" :label "dec" :expected "4" :actual "(dec 5)"} + {:suite "numbers / arithmetic" :label "quot" :expected "3" :actual "(quot 10 3)"} + {:suite "numbers / arithmetic" :label "rem" :expected "1" :actual "(rem 10 3)"} + {:suite "numbers / arithmetic" :label "mod" :expected "2" :actual "(mod -1 3)"} + {:suite "numbers / arithmetic" :label "rem negative" :expected "-1" :actual "(rem -1 3)"} + {:suite "numbers / arithmetic" :label "max" :expected "9" :actual "(max 3 9 1)"} + {:suite "numbers / arithmetic" :label "min" :expected "1" :actual "(min 3 9 1)"} + {:suite "numbers / arithmetic" :label "abs" :expected "5" :actual "(abs -5)"} + {:suite "numbers / arithmetic" :label "promoting + alias" :expected "3" :actual "(+' 1 2)"} + {:suite "numbers / arithmetic" :label "inc' alias" :expected "6" :actual "(inc' 5)"} + {:suite "numbers / comparison" :label "less than" :expected "true" :actual "(< 1 2 3)"} + {:suite "numbers / comparison" :label "less than false" :expected "false" :actual "(< 1 3 2)"} + {:suite "numbers / comparison" :label "greater than" :expected "true" :actual "(> 3 2 1)"} + {:suite "numbers / comparison" :label "<=" :expected "true" :actual "(<= 1 1 2)"} + {:suite "numbers / comparison" :label ">=" :expected "true" :actual "(>= 3 3 2)"} + {:suite "numbers / comparison" :label "= numbers" :expected "true" :actual "(= 2 2)"} + {:suite "numbers / comparison" :label "= different" :expected "false" :actual "(= 2 3)"} + {:suite "numbers / comparison" :label "== numeric" :expected "true" :actual "(== 2 2)"} + {:suite "numbers / comparison" :label "not=" :expected "true" :actual "(not= 1 2)"} + {:suite "numbers / comparison" :label "compare less" :expected "-1" :actual "(compare 1 2)"} + {:suite "numbers / comparison" :label "compare equal" :expected "0" :actual "(compare 1 1)"} + {:suite "numbers / comparison" :label "compare greater" :expected "1" :actual "(compare 2 1)"} + {:suite "numbers / predicates" :label "zero?" :expected "true" :actual "(zero? 0)"} + {:suite "numbers / predicates" :label "pos?" :expected "true" :actual "(pos? 5)"} + {:suite "numbers / predicates" :label "neg?" :expected "true" :actual "(neg? -5)"} + {:suite "numbers / predicates" :label "even?" :expected "true" :actual "(even? 4)"} + {:suite "numbers / predicates" :label "odd?" :expected "true" :actual "(odd? 3)"} + {:suite "numbers / predicates" :label "number?" :expected "true" :actual "(number? 5)"} + {:suite "numbers / predicates" :label "number? false" :expected "false" :actual "(number? :a)"} + {:suite "numbers / predicates" :label "int?" :expected "true" :actual "(int? 5)"} + {:suite "numbers / predicates" :label "pos-int?" :expected "true" :actual "(pos-int? 5)"} + {:suite "numbers / predicates" :label "neg-int?" :expected "true" :actual "(neg-int? -5)"} + {:suite "numbers / predicates" :label "nat-int? zero" :expected "true" :actual "(nat-int? 0)"} + {:suite "numbers / predicates" :label "nat-int? neg" :expected "false" :actual "(nat-int? -1)"} + {:suite "numbers / predicates" :label "ratio? false" :expected "false" :actual "(ratio? 5)"} + {:suite "numbers / floats & symbolic values" :label "read ##Inf" :expected "true" :actual "(= ##Inf (/ 1.0 0.0))"} + {:suite "numbers / floats & symbolic values" :label "read ##-Inf" :expected "true" :actual "(< ##-Inf 0)"} + {:suite "numbers / floats & symbolic values" :label "##NaN not= itself" :expected "true" :actual "(not (== ##NaN ##NaN))"} + {:suite "numbers / floats & symbolic values" :label "float? fractional" :expected "true" :actual "(float? 1.5)"} + {:suite "numbers / floats & symbolic values" :label "double? fractional" :expected "true" :actual "(double? 0.25)"} + {:suite "numbers / floats & symbolic values" :label "float? integer" :expected "false" :actual "(float? 3)"} + {:suite "numbers / floats & symbolic values" :label "float? ##Inf" :expected "true" :actual "(float? ##Inf)"} + {:suite "numbers / floats & symbolic values" :label "double? ##NaN" :expected "true" :actual "(double? ##NaN)"} + {:suite "numbers / floats & symbolic values" :label "infinite? ##Inf" :expected "true" :actual "(infinite? ##Inf)"} + {:suite "numbers / floats & symbolic values" :label "infinite? ##-Inf" :expected "true" :actual "(infinite? ##-Inf)"} + {:suite "numbers / floats & symbolic values" :label "infinite? finite" :expected "false" :actual "(infinite? 1.5)"} + {:suite "numbers / floats & symbolic values" :label "NaN? ##NaN" :expected "true" :actual "(NaN? ##NaN)"} + {:suite "numbers / floats & symbolic values" :label "NaN? number" :expected "false" :actual "(NaN? 1.0)"} + {:suite "numbers / floats & symbolic values" :label "int? ##Inf false" :expected "false" :actual "(int? ##Inf)"} + {:suite "numbers / floats & symbolic values" :label "pos-int? ##Inf" :expected "false" :actual "(pos-int? ##Inf)"} + {:suite "numbers / literal syntax" :label "bigint suffix N" :expected "42N" :actual "42N"} + {:suite "numbers / literal syntax" :label "bigint zero" :expected "0N" :actual "0N"} + {:suite "numbers / literal syntax" :label "bigdec suffix M" :expected "1.5M" :actual "1.5M"} + {:suite "numbers / literal syntax" :label "bigdec int M" :expected "0.0M" :actual "0.0M"} + {:suite "numbers / literal syntax" :label "ratio -> double" :expected "1/2" :actual "1/2"} + {:suite "numbers / literal syntax" :label "ratio 3/4" :expected "3/4" :actual "3/4"} + {:suite "numbers / literal syntax" :label "neg ratio" :expected "-1/2" :actual "-1/2"} + {:suite "numbers / literal syntax" :label "radix binary" :expected "10" :actual "2r1010"} + {:suite "numbers / literal syntax" :label "radix hex-ish" :expected "255" :actual "16rFF"} + {:suite "numbers / literal syntax" :label "radix base36" :expected "35" :actual "36rZ"} + {:suite "numbers / literal syntax" :label "hex" :expected "255" :actual "0xFF"} + {:suite "numbers / literal syntax" :label "exponent" :expected "1000.0" :actual "1e3"} + {:suite "numbers / literal syntax" :label "exponent neg" :expected "0.015" :actual "1.5e-2"} + {:suite "numbers / strictness (throws like Clojure)" :label "odd? nil" :expected :throws :actual "(odd? nil)"} + {:suite "numbers / strictness (throws like Clojure)" :label "odd? fractional" :expected :throws :actual "(odd? 1.5)"} + {:suite "numbers / strictness (throws like Clojure)" :label "even? inf" :expected :throws :actual "(even? ##Inf)"} + {:suite "numbers / strictness (throws like Clojure)" :label "zero? nil" :expected :throws :actual "(zero? nil)"} + {:suite "numbers / strictness (throws like Clojure)" :label "pos? false" :expected :throws :actual "(pos? false)"} + {:suite "numbers / strictness (throws like Clojure)" :label "neg? keyword" :expected :throws :actual "(neg? :a)"} + {:suite "numbers / strictness (throws like Clojure)" :label "< nil" :expected :throws :actual "(< nil 1)"} + {:suite "numbers / strictness (throws like Clojure)" :label "> with nil" :expected :throws :actual "(> 1 nil)"} + {:suite "numbers / strictness (throws like Clojure)" :label "max non-number" :expected :throws :actual "(max 1 nil)"} + {:suite "numbers / strictness (throws like Clojure)" :label "quot by zero" :expected :throws :actual "(quot 10 0)"} + {:suite "numbers / strictness (throws like Clojure)" :label "quot inf" :expected :throws :actual "(quot ##Inf 1)"} + {:suite "numbers / strictness (throws like Clojure)" :label "< arity-1 any" :expected "true" :actual "(< :anything)"} + {:suite "numbers / strictness (throws like Clojure)" :label "odd? ok" :expected "true" :actual "(odd? 3)"} + {:suite "numbers / strictness (throws like Clojure)" :label "< ok" :expected "true" :actual "(< 1 2 3)"} + {:suite "numbers / strictness (throws like Clojure)" :label "quot ok" :expected "3" :actual "(quot 10 3)"} + {:suite "numbers / printing of inf & nan" :label "str Infinity" :expected "\"Infinity\"" :actual "(str ##Inf)"} + {:suite "numbers / printing of inf & nan" :label "str -Infinity" :expected "\"-Infinity\"" :actual "(str ##-Inf)"} + {:suite "numbers / printing of inf & nan" :label "str NaN" :expected "\"NaN\"" :actual "(str ##NaN)"} + {:suite "numbers / printing of inf & nan" :label "pr-str Infinity" :expected "\"##Inf\"" :actual "(pr-str ##Inf)"} + {:suite "numbers / printing of inf & nan" :label "inf inside coll" :expected "\"[##Inf]\"" :actual "(str [##Inf])"} + {:suite "numbers / bit-ops & math" :label "bit-and" :expected "4" :actual "(bit-and 12 6)"} + {:suite "numbers / bit-ops & math" :label "bit-or" :expected "14" :actual "(bit-or 12 6)"} + {:suite "numbers / bit-ops & math" :label "bit-xor" :expected "10" :actual "(bit-xor 12 6)"} + {:suite "numbers / bit-ops & math" :label "bit-shift-left" :expected "8" :actual "(bit-shift-left 1 3)"} + {:suite "numbers / bit-ops & math" :label "bit-shift-right" :expected "2" :actual "(bit-shift-right 8 2)"} + {:suite "numbers / bit-ops & math" :label "bit-set" :expected "8" :actual "(bit-set 0 3)"} + {:suite "numbers / bit-ops & math" :label "bit-clear" :expected "13" :actual "(bit-clear 15 1)"} + {:suite "numbers / bit-ops & math" :label "bit-test true" :expected "true" :actual "(bit-test 4 2)"} + {:suite "numbers / bit-ops & math" :label "bigint 64-bit" :expected "\"9000000000\"" :actual "(str (bigint 9000000000))"} + {:suite "numbers / random (invariants — non-deterministic)" :label "rand-int in range" :expected "true" :actual "(let [r (rand-int 5)] (and (integer? r) (>= r 0) (< r 5)))"} + {:suite "numbers / random (invariants — non-deterministic)" :label "rand-int zero" :expected "0" :actual "(rand-int 1)"} + {:suite "numbers / random (invariants — non-deterministic)" :label "rand in [0,1)" :expected "true" :actual "(let [r (rand)] (and (>= r 0) (< r 1)))"} + {:suite "numbers / random (invariants — non-deterministic)" :label "rand n in [0,n)" :expected "true" :actual "(let [r (rand 10)] (and (>= r 0) (< r 10)))"} + {:suite "numbers / random (invariants — non-deterministic)" :label "rand-nth member" :expected "true" :actual "(contains? #{:a :b :c} (rand-nth [:a :b :c]))"} + {:suite "numbers / random (invariants — non-deterministic)" :label "rand-nth single" :expected ":x" :actual "(rand-nth [:x])"} + {:suite "numbers / parse fns (1.11)" :label "parse-long" :expected "42" :actual "(parse-long \"42\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-long negative" :expected "-7" :actual "(parse-long \"-7\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-long plus" :expected "7" :actual "(parse-long \"+7\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-long float nil" :expected "nil" :actual "(parse-long \"1.5\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-long hex nil" :expected "nil" :actual "(parse-long \"0x10\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-long empty nil" :expected "nil" :actual "(parse-long \"\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-long junk nil" :expected "nil" :actual "(parse-long \"12ab\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-long throws" :expected :throws :actual "(parse-long 42)"} + {:suite "numbers / parse fns (1.11)" :label "parse-double" :expected "1.5" :actual "(parse-double \"1.5\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-double int" :expected "4.0" :actual "(parse-double \"4\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-double sci" :expected "1500.0" :actual "(parse-double \"1.5e3\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-double neg" :expected "-0.5" :actual "(parse-double \"-0.5\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-double junk" :expected "nil" :actual "(parse-double \"abc\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-double trail" :expected "nil" :actual "(parse-double \"1.5x\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-double throws" :expected :throws :actual "(parse-double :k)"} + {:suite "numbers / parse fns (1.11)" :label "parse-boolean true" :expected "true" :actual "(parse-boolean \"true\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-boolean false" :expected "false" :actual "(parse-boolean \"false\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-boolean case" :expected "nil" :actual "(parse-boolean \"True\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-boolean junk" :expected "nil" :actual "(parse-boolean \"yes\")"} + {:suite "numbers / parse fns (1.11)" :label "parse-boolean throws" :expected :throws :actual "(parse-boolean true)"} + {:suite "numbers / promoting & unchecked aliases" :label "+'" :expected "3" :actual "(+' 1 2)"} + {:suite "numbers / promoting & unchecked aliases" :label "-'" :expected "3" :actual "(-' 5 2)"} + {:suite "numbers / promoting & unchecked aliases" :label "*'" :expected "12" :actual "(*' 3 4)"} + {:suite "numbers / promoting & unchecked aliases" :label "inc'" :expected "6" :actual "(inc' 5)"} + {:suite "numbers / promoting & unchecked aliases" :label "dec'" :expected "4" :actual "(dec' 5)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-add" :expected "5" :actual "(unchecked-add 2 3)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-add-int" :expected "5" :actual "(unchecked-add-int 2 3)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-subtract" :expected "3" :actual "(unchecked-subtract 5 2)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-subtract-int" :expected "3" :actual "(unchecked-subtract-int 5 2)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-multiply" :expected "12" :actual "(unchecked-multiply 3 4)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-multiply-int" :expected "12" :actual "(unchecked-multiply-int 3 4)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-negate" :expected "-5" :actual "(unchecked-negate 5)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-negate-int" :expected "-5" :actual "(unchecked-negate-int 5)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-inc" :expected "2" :actual "(unchecked-inc 1)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-inc-int" :expected "2" :actual "(unchecked-inc-int 1)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-dec" :expected "0" :actual "(unchecked-dec 1)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-dec-int" :expected "0" :actual "(unchecked-dec-int 1)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-divide-int" :expected "3" :actual "(unchecked-divide-int 7 2)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-divide-int negative truncates toward zero" :expected "-3" :actual "(unchecked-divide-int -7 2)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-divide-int by zero throws" :expected :throws :actual "(unchecked-divide-int 1 0)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-remainder-int" :expected "1" :actual "(unchecked-remainder-int 7 2)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-remainder-int negative" :expected "-1" :actual "(unchecked-remainder-int -7 2)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-int truncates" :expected "3" :actual "(unchecked-int 3.7)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-int negative" :expected "-3" :actual "(unchecked-int -3.7)"} + {:suite "numbers / promoting & unchecked aliases" :label "unchecked-long" :expected "3" :actual "(unchecked-long 3.7)"} + {:suite "numbers / promoting & unchecked aliases" :label "int? on integer" :expected "true" :actual "(int? 5)"} + {:suite "numbers / promoting & unchecked aliases" :label "int? on double" :expected "false" :actual "(int? 5.5)"} + {:suite "numbers / promoting & unchecked aliases" :label "int? on non-number" :expected "false" :actual "(int? \"5\")"} + {:suite "numbers / promoting & unchecked aliases" :label "num passes a number through" :expected "5" :actual "(num 5)"} + {:suite "numbers / promoting & unchecked aliases" :label "num on a double" :expected "5.5" :actual "(num 5.5)"} + {:suite "numbers / promoting & unchecked aliases" :label "num throws on non-number" :expected :throws :actual "(num \"x\")"} + {:suite "numbers / == numeric equality" :label "== single arg" :expected "true" :actual "(== :a)"} + {:suite "numbers / == numeric equality" :label "== equal" :expected "true" :actual "(== 2 2)"} + {:suite "numbers / == numeric equality" :label "== unequal" :expected "false" :actual "(== 2 3)"} + {:suite "numbers / == numeric equality" :label "== chained" :expected "true" :actual "(== 2 2 2)"} + {:suite "numbers / == numeric equality" :label "== chained unequal" :expected "false" :actual "(== 2 2 3)"} + {:suite "numbers / == numeric equality" :label "== int and double" :expected "true" :actual "(== 1 1.0)"} + {:suite "numbers / == numeric equality" :label "== throws on non-number" :expected :throws :actual "(== 1 :a)"} + {:suite "numbers / == numeric equality" :label "== throws on two keywords" :expected :throws :actual "(== :a :a)"} + {:suite "numbers / variadic bit ops" :label "bit-and 2" :expected "4" :actual "(bit-and 12 6)"} + {:suite "numbers / variadic bit ops" :label "bit-and 3" :expected "4" :actual "(bit-and 12 6 7)"} + {:suite "numbers / variadic bit ops" :label "bit-and 4" :expected "0" :actual "(bit-and 12 6 7 3)"} + {:suite "numbers / variadic bit ops" :label "bit-or 3" :expected "7" :actual "(bit-or 1 2 4)"} + {:suite "numbers / variadic bit ops" :label "bit-xor 3" :expected "7" :actual "(bit-xor 1 2 4)"} + {:suite "numbers / variadic bit ops" :label "bit-xor folds left" :expected "1" :actual "(bit-xor 5 6 2)"} + {:suite "numbers / variadic bit ops" :label "bit-and-not 2" :expected "8" :actual "(bit-and-not 12 6)"} + {:suite "numbers / variadic bit ops" :label "bit-and-not 3" :expected "8" :actual "(bit-and-not 12 6 3)"} + {:suite "numbers / variadic bit ops" :label "bit-and single arg throws" :expected :throws :actual "(bit-and 5)"} + {:suite "numbers / variadic bit ops" :label "bit-or keeps binary fast path" :expected "3" :actual "(bit-or 1 2)"} + {:suite "predicates / nil & boolean" :label "nil? true" :expected "true" :actual "(nil? nil)"} + {:suite "predicates / nil & boolean" :label "nil? false" :expected "false" :actual "(nil? 0)"} + {:suite "predicates / nil & boolean" :label "some? true" :expected "true" :actual "(some? 0)"} + {:suite "predicates / nil & boolean" :label "some? on nil" :expected "false" :actual "(some? nil)"} + {:suite "predicates / nil & boolean" :label "true?" :expected "true" :actual "(true? true)"} + {:suite "predicates / nil & boolean" :label "false?" :expected "true" :actual "(false? false)"} + {:suite "predicates / nil & boolean" :label "boolean? true" :expected "true" :actual "(boolean? false)"} + {:suite "predicates / nil & boolean" :label "not nil" :expected "true" :actual "(not nil)"} + {:suite "predicates / nil & boolean" :label "not 0 is false" :expected "false" :actual "(not 0)"} + {:suite "predicates / nil & boolean" :label "boolean of nil" :expected "false" :actual "(boolean nil)"} + {:suite "predicates / nil & boolean" :label "boolean of value" :expected "true" :actual "(boolean 5)"} + {:suite "predicates / types" :label "string?" :expected "true" :actual "(string? \"x\")"} + {:suite "predicates / types" :label "number?" :expected "true" :actual "(number? 1)"} + {:suite "predicates / types" :label "keyword?" :expected "true" :actual "(keyword? :a)"} + {:suite "predicates / types" :label "symbol?" :expected "true" :actual "(symbol? (quote a))"} + {:suite "predicates / types" :label "char?" :expected "true" :actual "(char? \\a)"} + {:suite "predicates / types" :label "fn? on fn" :expected "true" :actual "(fn? inc)"} + {:suite "predicates / types" :label "ifn? on keyword" :expected "true" :actual "(ifn? :a)"} + {:suite "predicates / types" :label "vector?" :expected "true" :actual "(vector? [1])"} + {:suite "predicates / types" :label "list?" :expected "true" :actual "(list? (list 1))"} + {:suite "predicates / types" :label "map?" :expected "true" :actual "(map? {:a 1})"} + {:suite "predicates / types" :label "set?" :expected "true" :actual "(set? #{1})"} + {:suite "predicates / types" :label "coll? vector" :expected "true" :actual "(coll? [1])"} + {:suite "predicates / types" :label "coll? map" :expected "true" :actual "(coll? {:a 1})"} + {:suite "predicates / types" :label "coll? on number" :expected "false" :actual "(coll? 1)"} + {:suite "predicates / types" :label "seq? list" :expected "true" :actual "(seq? (list 1))"} + {:suite "predicates / types" :label "seq? vector" :expected "false" :actual "(seq? [1])"} + {:suite "predicates / types" :label "sequential? vector" :expected "true" :actual "(sequential? [1])"} + {:suite "predicates / types" :label "associative? map" :expected "true" :actual "(associative? {:a 1})"} + {:suite "predicates / types" :label "associative? vec" :expected "true" :actual "(associative? [1])"} + {:suite "predicates / types" :label "associative? list" :expected "false" :actual "(associative? '(1 2))"} + {:suite "predicates / types" :label "associative? set" :expected "false" :actual "(associative? #{1})"} + {:suite "predicates / types" :label "reversible? vec" :expected "true" :actual "(reversible? [1 2])"} + {:suite "predicates / types" :label "reversible? list" :expected "false" :actual "(reversible? '(1 2))"} + {:suite "predicates / types" :label "reversible? smap" :expected "true" :actual "(reversible? (sorted-map :a 1))"} + {:suite "predicates / types" :label "reversible? hmap" :expected "false" :actual "(reversible? (hash-map :a 1))"} + {:suite "predicates / types" :label "indexed? vector" :expected "true" :actual "(indexed? [1])"} + {:suite "predicates / types" :label "counted? vector" :expected "true" :actual "(counted? [1])"} + {:suite "predicates / idents" :label "ident? keyword" :expected "true" :actual "(ident? :a)"} + {:suite "predicates / idents" :label "ident? symbol" :expected "true" :actual "(ident? (quote a))"} + {:suite "predicates / idents" :label "simple-keyword?" :expected "true" :actual "(simple-keyword? :a)"} + {:suite "predicates / idents" :label "qualified-keyword?" :expected "true" :actual "(qualified-keyword? :a/b)"} + {:suite "predicates / idents" :label "simple-symbol?" :expected "true" :actual "(simple-symbol? (quote a))"} + {:suite "predicates / idents" :label "qualified-symbol?" :expected "true" :actual "(qualified-symbol? (quote a/b))"} + {:suite "predicates / idents" :label "name of keyword" :expected "\"a\"" :actual "(name :a)"} + {:suite "predicates / idents" :label "name of qualified" :expected "\"b\"" :actual "(name :a/b)"} + {:suite "predicates / idents" :label "namespace" :expected "\"a\"" :actual "(namespace :a/b)"} + {:suite "predicates / idents" :label "namespace simple" :expected "nil" :actual "(namespace :a)"} + {:suite "predicates / idents" :label "keyword constructor" :expected ":foo" :actual "(keyword \"foo\")"} + {:suite "predicates / idents" :label "keyword ns + name" :expected ":a/b" :actual "(keyword \"a\" \"b\")"} + {:suite "predicates / idents" :label "symbol constructor" :expected "(quote x)" :actual "(symbol \"x\")"} + {:suite "predicates / idents" :label "name of string" :expected "\"s\"" :actual "(name \"s\")"} + {:suite "predicates / overlay-migrated" :label "not-any? true" :expected "true" :actual "(not-any? even? [1 3 5])"} + {:suite "predicates / overlay-migrated" :label "not-any? false" :expected "false" :actual "(not-any? even? [1 2 3])"} + {:suite "predicates / overlay-migrated" :label "not-every? true" :expected "true" :actual "(not-every? even? [2 4 5])"} + {:suite "predicates / overlay-migrated" :label "not-every? false" :expected "false" :actual "(not-every? even? [2 4 6])"} + {:suite "predicates / overlay-migrated" :label "ident? number" :expected "false" :actual "(ident? 1)"} + {:suite "predicates / overlay-migrated" :label "qualified-ident?" :expected "true" :actual "(qualified-ident? :a/b)"} + {:suite "predicates / overlay-migrated" :label "qualified-ident? no" :expected "false" :actual "(qualified-ident? :a)"} + {:suite "predicates / overlay-migrated" :label "simple-ident?" :expected "true" :actual "(simple-ident? :a)"} + {:suite "predicates / overlay-migrated" :label "ratio?" :expected "false" :actual "(ratio? 3)"} + {:suite "predicates / overlay-migrated" :label "decimal?" :expected "false" :actual "(decimal? 3)"} + {:suite "predicates / overlay-migrated" :label "class? of value" :expected "false" :actual "(class? \"s\")"} + {:suite "predicates / overlay-migrated" :label "class? of symbol" :expected "false" :actual "(class? 'java.lang.String)"} + {:suite "predicates / overlay-migrated" :label "rational? int" :expected "true" :actual "(rational? 3)"} + {:suite "predicates / overlay-migrated" :label "rational? float" :expected "false" :actual "(rational? 3.5)"} + {:suite "predicates / overlay-migrated" :label "nat-int? zero" :expected "true" :actual "(nat-int? 0)"} + {:suite "predicates / overlay-migrated" :label "nat-int? neg" :expected "false" :actual "(nat-int? -1)"} + {:suite "predicates / overlay-migrated" :label "pos-int?" :expected "true" :actual "(pos-int? 5)"} + {:suite "predicates / overlay-migrated" :label "neg-int?" :expected "true" :actual "(neg-int? -3)"} + {:suite "predicates / overlay-migrated" :label "NaN? on nan" :expected "true" :actual "(NaN? (/ 0.0 0.0))"} + {:suite "predicates / overlay-migrated" :label "NaN? on number" :expected "false" :actual "(NaN? 5)"} + {:suite "predicates / overlay-migrated" :label "abs negative" :expected "3" :actual "(abs -3)"} + {:suite "predicates / overlay-migrated" :label "abs positive" :expected "2.5" :actual "(abs 2.5)"} + {:suite "predicates / overlay-migrated" :label "object?" :expected "false" :actual "(object? 1)"} + {:suite "predicates / overlay-migrated" :label "undefined?" :expected "false" :actual "(undefined? 1)"} + {:suite "predicates / overlay-migrated" :label "keyword-identical?" :expected "true" :actual "(keyword-identical? :a :a)"} + {:suite "predicates / overlay-migrated" :label "keyword-identical? no" :expected "false" :actual "(keyword-identical? :a :b)"} + {:suite "predicates / map? & coll? strictness" :label "map? symbol" :expected "false" :actual "(map? (quote sym))"} + {:suite "predicates / map? & coll? strictness" :label "map? char" :expected "false" :actual "(map? \\a)"} + {:suite "predicates / map? & coll? strictness" :label "map? uuid" :expected "false" :actual "(map? (random-uuid))"} + {:suite "predicates / map? & coll? strictness" :label "map? literal" :expected "true" :actual "(map? {:a 1})"} + {:suite "predicates / map? & coll? strictness" :label "map? hash-map" :expected "true" :actual "(map? (hash-map :a 1))"} + {:suite "predicates / map? & coll? strictness" :label "map? sorted-map" :expected "true" :actual "(map? (sorted-map :a 1))"} + {:suite "predicates / map? & coll? strictness" :label "map? record" :expected "true" :actual "(do (defrecord Mr [a]) (map? (->Mr 1)))"} + {:suite "predicates / map? & coll? strictness" :label "map? sorted-set" :expected "false" :actual "(map? (sorted-set 1))"} + {:suite "predicates / map? & coll? strictness" :label "map? vector" :expected "false" :actual "(map? [1])"} + {:suite "predicates / map? & coll? strictness" :label "coll? symbol" :expected "false" :actual "(coll? (quote sym))"} + {:suite "predicates / map? & coll? strictness" :label "coll? char" :expected "false" :actual "(coll? \\a)"} + {:suite "predicates / map? & coll? strictness" :label "coll? uuid" :expected "false" :actual "(coll? (random-uuid))"} + {:suite "predicates / map? & coll? strictness" :label "coll? keyword" :expected "false" :actual "(coll? :k)"} + {:suite "predicates / map? & coll? strictness" :label "coll? string" :expected "false" :actual "(coll? \"s\")"} + {:suite "predicates / map? & coll? strictness" :label "coll? map literal" :expected "true" :actual "(coll? {:a 1})"} + {:suite "predicates / map? & coll? strictness" :label "coll? sorted-map" :expected "true" :actual "(coll? (sorted-map :a 1))"} + {:suite "predicates / map? & coll? strictness" :label "coll? sorted-set" :expected "true" :actual "(coll? (sorted-set 1))"} + {:suite "predicates / map? & coll? strictness" :label "coll? record" :expected "true" :actual "(do (defrecord Cr [a]) (coll? (->Cr 1)))"} + {:suite "predicates / map? & coll? strictness" :label "coll? vector" :expected "true" :actual "(coll? [1])"} + {:suite "predicates / map? & coll? strictness" :label "coll? list" :expected "true" :actual "(coll? (list 1))"} + {:suite "predicates / map? & coll? strictness" :label "coll? set" :expected "true" :actual "(coll? #{1})"} + {:suite "predicates / map? & coll? strictness" :label "coll? lazy seq" :expected "true" :actual "(coll? (map inc [1]))"} + {:suite "predicates / tagged-value (Phase 4)" :label "atom? yes" :expected "true" :actual "(atom? (atom 1))"} + {:suite "predicates / tagged-value (Phase 4)" :label "atom? no" :expected "false" :actual "(atom? 1)"} + {:suite "predicates / tagged-value (Phase 4)" :label "volatile? yes" :expected "true" :actual "(volatile? (volatile! 1))"} + {:suite "predicates / tagged-value (Phase 4)" :label "volatile? no" :expected "false" :actual "(volatile? (atom 1))"} + {:suite "predicates / tagged-value (Phase 4)" :label "record? yes" :expected "true" :actual "(do (defrecord Rp [a]) (record? (->Rp 1)))"} + {:suite "predicates / tagged-value (Phase 4)" :label "record? no map" :expected "false" :actual "(record? {:a 1})"} + {:suite "predicates / tagged-value (Phase 4)" :label "record? no nil" :expected "false" :actual "(record? nil)"} + {:suite "predicates / tagged-value (Phase 4)" :label "tagged-literal? yes" :expected "true" :actual "(tagged-literal? (tagged-literal (quote inst) \"2020\"))"} + {:suite "predicates / tagged-value (Phase 4)" :label "tagged-literal? no" :expected "false" :actual "(tagged-literal? 1)"} + {:suite "predicates / tagged-value (Phase 4)" :label "reader-conditional? no" :expected "false" :actual "(reader-conditional? 1)"} + {:suite "predicates / tagged-value (Phase 4)" :label "chunked-seq? always false" :expected "true" :actual "(chunked-seq? (seq [1 2 3]))"} + {:suite "predicates / equality & identity" :label "= same" :expected "true" :actual "(= 1 1)"} + {:suite "predicates / equality & identity" :label "= vectors" :expected "true" :actual "(= [1 2] [1 2])"} + {:suite "predicates / equality & identity" :label "= vector & list" :expected "true" :actual "(= [1 2] (list 1 2))"} + {:suite "predicates / equality & identity" :label "= maps" :expected "true" :actual "(= {:a 1} {:a 1})"} + {:suite "predicates / equality & identity" :label "= sets" :expected "true" :actual "(= #{1 2} #{2 1})"} + {:suite "predicates / equality & identity" :label "= nested" :expected "true" :actual "(= {:a [1 2]} {:a [1 2]})"} + {:suite "predicates / equality & identity" :label "not= differs" :expected "true" :actual "(not= [1 2] [1 3])"} + {:suite "predicates / equality & identity" :label "identical? same kw" :expected "true" :actual "(identical? :a :a)"} + {:suite "predicates / equality & identity" :label "compare strings" :expected "-1" :actual "(compare \"a\" \"b\")"} + {:suite "predicates / seqable, reduced & emptiness" :label "seqable? vector" :expected "true" :actual "(seqable? [1])"} + {:suite "predicates / seqable, reduced & emptiness" :label "seqable? map" :expected "true" :actual "(seqable? {:a 1})"} + {:suite "predicates / seqable, reduced & emptiness" :label "seqable? string" :expected "true" :actual "(seqable? \"s\")"} + {:suite "predicates / seqable, reduced & emptiness" :label "seqable? nil" :expected "true" :actual "(seqable? nil)"} + {:suite "predicates / seqable, reduced & emptiness" :label "seqable? number" :expected "false" :actual "(seqable? 5)"} + {:suite "predicates / seqable, reduced & emptiness" :label "integer? int" :expected "true" :actual "(integer? 5)"} + {:suite "predicates / seqable, reduced & emptiness" :label "integer? fraction" :expected "false" :actual "(integer? 5.5)"} + {:suite "predicates / seqable, reduced & emptiness" :label "reduced? wrapped" :expected "true" :actual "(reduced? (reduced 1))"} + {:suite "predicates / seqable, reduced & emptiness" :label "reduced? plain" :expected "false" :actual "(reduced? 1)"} + {:suite "predicates / seqable, reduced & emptiness" :label "deref reduced" :expected "9" :actual "(deref (reduced 9))"} + {:suite "predicates / seqable, reduced & emptiness" :label "unreduced wrapped" :expected "9" :actual "(unreduced (reduced 9))"} + {:suite "predicates / seqable, reduced & emptiness" :label "unreduced plain" :expected "9" :actual "(unreduced 9)"} + {:suite "predicates / seqable, reduced & emptiness" :label "not-empty full" :expected "[1]" :actual "(not-empty [1])"} + {:suite "predicates / seqable, reduced & emptiness" :label "not-empty empty" :expected "nil" :actual "(not-empty [])"} + {:suite "predicates / seqable, reduced & emptiness" :label "not-empty string" :expected "nil" :actual "(not-empty \"\")"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare =" :expected "0" :actual "(compare 1 1)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare <" :expected "-1" :actual "(compare 1 2)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare nil first" :expected "-1" :actual "(compare nil 1)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare nil nil" :expected "0" :actual "(compare nil nil)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare strings" :expected "-1" :actual "(compare \"a\" \"b\")"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare keywords" :expected "-1" :actual "(compare :a :b)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare symbols" :expected "-1" :actual "(compare (quote a) (quote b))"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare bools" :expected "-1" :actual "(compare false true)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare vec length" :expected "-1" :actual "(compare [1 2] [1 2 3])"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare vec elems" :expected "-1" :actual "(compare [1 2] [1 3])"} + {:suite "predicates / compare, type, any? (stage 3)" :label "compare cross-type throws" :expected :throws :actual "(compare 1 \"a\")"} + {:suite "predicates / compare, type, any? (stage 3)" :label "sort with compare" :expected "[nil 1 3]" :actual "(sort compare [3 nil 1])"} + {:suite "predicates / compare, type, any? (stage 3)" :label "type meta override" :expected ":custom" :actual "(type (with-meta [1] {:type :custom}))"} + {:suite "predicates / compare, type, any? (stage 3)" :label "type of record" :expected "false" :actual "(do (defrecord TyR [a]) (= (symbol (str (type (->TyR 1)))) (type (->TyR 1))))"} + {:suite "predicates / compare, type, any? (stage 3)" :label "any? value" :expected "true" :actual "(any? 5)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "any? nil" :expected "true" :actual "(any? nil)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "gensym is symbol" :expected "true" :actual "(symbol? (gensym))"} + {:suite "predicates / compare, type, any? (stage 3)" :label "gensym prefix" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/starts-with? (str (gensym \"p_\")) \"p_\"))"} + {:suite "predicates / compare, type, any? (stage 3)" :label "gensym distinct" :expected "false" :actual "(= (gensym) (gensym))"} + {:suite "predicates / compare, type, any? (stage 3)" :label "int? Inf false" :expected "false" :actual "(int? ##Inf)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "integer? Inf false" :expected "false" :actual "(integer? ##Inf)"} + {:suite "predicates / compare, type, any? (stage 3)" :label "integer? NaN false" :expected "false" :actual "(integer? ##NaN)"} + {:suite "predicates / ifn?" :label "fn" :expected "true" :actual "(ifn? inc)"} + {:suite "predicates / ifn?" :label "keyword" :expected "true" :actual "(ifn? :k)"} + {:suite "predicates / ifn?" :label "symbol" :expected "true" :actual "(ifn? (quote s))"} + {:suite "predicates / ifn?" :label "map" :expected "true" :actual "(ifn? {})"} + {:suite "predicates / ifn?" :label "sorted map" :expected "true" :actual "(ifn? (sorted-map))"} + {:suite "predicates / ifn?" :label "set" :expected "true" :actual "(ifn? #{1})"} + {:suite "predicates / ifn?" :label "vector" :expected "true" :actual "(ifn? [1])"} + {:suite "predicates / ifn?" :label "var" :expected "true" :actual "(ifn? (var first))"} + {:suite "predicates / ifn?" :label "list NOT" :expected "false" :actual "(ifn? (list 1 2))"} + {:suite "predicates / ifn?" :label "lazy NOT" :expected "false" :actual "(ifn? (map inc [1]))"} + {:suite "predicates / ifn?" :label "string NOT" :expected "false" :actual "(ifn? \"s\")"} + {:suite "predicates / ifn?" :label "number NOT" :expected "false" :actual "(ifn? 5)"} + {:suite "predicates / ifn?" :label "nil NOT" :expected "false" :actual "(ifn? nil)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "zero? zero" :expected "true" :actual "(zero? 0)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "zero? nonzero" :expected "false" :actual "(zero? 3)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "zero? throws" :expected :throws :actual "(zero? :a)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "zero? throws on nil" :expected :throws :actual "(zero? nil)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "pos? positive" :expected "true" :actual "(pos? 2)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "pos? zero" :expected "false" :actual "(pos? 0)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "pos? throws" :expected :throws :actual "(pos? \"x\")"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "neg? throws" :expected :throws :actual "(neg? \"x\")"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? all pass" :expected "true" :actual "(every? odd? [1 3 5])"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? one fails" :expected "false" :actual "(every? odd? [1 2 5])"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? vacuous" :expected "true" :actual "(every? odd? [])"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? nil coll" :expected "true" :actual "(every? odd? nil)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "every? infinite short-circuit" :expected "false" :actual "(every? pos? (range))"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "char? char" :expected "true" :actual "(char? \\x)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "char? string" :expected "false" :actual "(char? \"x\")"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "char? number" :expected "false" :actual "(char? 97)"} + {:suite "predicates / numeric guards & every? (overlay moves)" :label "char? nil" :expected "false" :actual "(char? nil)"} + {:suite "protocols / defprotocol & dispatch" :label "protocol on record" :expected "16" :actual "(do (defprotocol Shape (area [s])) (defrecord Sq [side] Shape (area [_] (* side side))) (area (->Sq 4)))"} + {:suite "protocols / defprotocol & dispatch" :label "protocol on deftype" :expected "16" :actual "(do (defprotocol Shape (area [s])) (deftype Sq [side] Shape (area [_] (* side side))) (area (->Sq 4)))"} + {:suite "protocols / defprotocol & dispatch" :label "multiple methods" :expected "[1 2]" :actual "(do (defprotocol P (m [s]) (n [s])) (defrecord R [a b] P (m [_] a) (n [_] b)) [(m (->R 1 2)) (n (->R 1 2))])"} + {:suite "protocols / defprotocol & dispatch" :label "multiple protocols" :expected "[:a :b]" :actual "(do (defprotocol P1 (p1 [s])) (defprotocol P2 (p2 [s])) (deftype T [] P1 (p1 [_] :a) P2 (p2 [_] :b)) [(p1 (->T)) (p2 (->T))])"} + {:suite "protocols / defprotocol & dispatch" :label "method args" :expected "7" :actual "(do (defprotocol P (add [s x])) (defrecord R [n] P (add [_ x] (+ n x))) (add (->R 5) 2))"} + {:suite "protocols / defprotocol & dispatch" :label "extend-type" :expected "10" :actual "(do (defprotocol P (twice [s])) (extend-type Number P (twice [n] (* n 2))) (twice 5))"} + {:suite "protocols / defprotocol & dispatch" :label "extend-protocol" :expected "[2 4]" :actual "(do (defprotocol P (dbl [s])) (extend-protocol P Number (dbl [n] (* n 2))) [(dbl 1) (dbl 2)])"} + {:suite "protocols / records" :label "record field access" :expected "1" :actual "(do (defrecord R [a b]) (:a (->R 1 2)))"} + {:suite "protocols / records" :label "record map access" :expected "2" :actual "(do (defrecord R [a b]) (get (->R 1 2) :b))"} + {:suite "protocols / records" :label "record equality" :expected "true" :actual "(do (defrecord R [a b]) (= (->R 1 2) (->R 1 2)))"} + {:suite "protocols / records" :label "record inequality" :expected "false" :actual "(do (defrecord R [a b]) (= (->R 1 2) (->R 3 4)))"} + {:suite "protocols / records" :label "map-> factory" :expected "1" :actual "(do (defrecord R [a b]) (:a (map->R {:a 1 :b 2})))"} + {:suite "protocols / records" :label "record? true" :expected "true" :actual "(do (defrecord R [a]) (record? (->R 1)))"} + {:suite "protocols / records" :label "assoc on record" :expected "9" :actual "(do (defrecord R [a]) (:a (assoc (->R 1) :a 9)))"} + {:suite "protocols / reify & satisfies" :label "reify dispatch" :expected "42" :actual "(do (defprotocol P (m [_])) (m (reify P (m [_] 42))))"} + {:suite "protocols / reify & satisfies" :label "reify multi-method" :expected "[1 2]" :actual "(do (defprotocol P (a [_]) (b [_])) (let [r (reify P (a [_] 1) (b [_] 2))] [(a r) (b r)]))"} + {:suite "protocols / reify & satisfies" :label "satisfies? true" :expected "true" :actual "(do (defprotocol P (m [_])) (defrecord R [] P (m [_] 1)) (satisfies? P (->R)))"} + {:suite "protocols / reify & satisfies" :label "satisfies? false" :expected "false" :actual "(do (defprotocol P (m [_])) (defrecord R []) (satisfies? P (->R)))"} + {:suite "protocols / reify & satisfies" :label "satisfies? reify" :expected "true" :actual "(do (defprotocol P (m [_])) (satisfies? P (reify P (m [_] 1))))"} + {:suite "protocols / reify & satisfies" :label "satisfies? reify multi-protocol" :expected "[true true]" :actual "(do (defprotocol P (m [_])) (defprotocol Q (n [_])) (let [r (reify P (m [_] 1) Q (n [_] 2))] [(satisfies? P r) (satisfies? Q r)]))"} + {:suite "protocols / reify & satisfies" :label "satisfies? reify other proto" :expected "false" :actual "(do (defprotocol P (m [_])) (defprotocol Q (n [_])) (satisfies? Q (reify P (m [_] 1))))"} + {:suite "protocols / reify & satisfies" :label "instance? record" :expected "true" :actual "(do (defrecord R [a]) (instance? R (->R 1)))"} + {:suite "protocols / reify & satisfies" :label "dot constructor" :expected "5" :actual "(do (deftype P [n]) (.-n (P. 5)))"} + {:suite "protocols / reify & satisfies" :label "dot ctor + method" :expected "5" :actual "(do (defprotocol G (val-of [_])) (deftype P [n] G (val-of [_] n)) (val-of (P. 5)))"} + {:suite "protocols / defprotocol options" :label "docstring + option + method" :expected ":hi" :actual "(do (defprotocol Pdoc \"docs\" :extend-via-metadata true (greet [x])) (extend-protocol Pdoc String (greet [s] :hi)) (greet \"x\"))"} + {:suite "protocols / defprotocol options" :label "option only" :expected "3" :actual "(do (defprotocol Popt :extend-via-metadata true (plus2 [x])) (extend-protocol Popt Long (plus2 [n] (+ n 2))) (plus2 1))"} + {:suite "reader / anonymous fn #()" :label "no args" :expected "3" :actual "(#(+ 1 2))"} + {:suite "reader / anonymous fn #()" :label "one arg %" :expected "6" :actual "(#(* % 2) 3)"} + {:suite "reader / anonymous fn #()" :label "positional %1 %2" :expected "[1 2]" :actual "(#(do [%1 %2]) 1 2)"} + {:suite "reader / anonymous fn #()" :label "rest %&" :expected "[1 2 3]" :actual "(#(do %&) 1 2 3)"} + {:suite "reader / anonymous fn #()" :label "fixed + rest" :expected "[2 3]" :actual "(#(do % %&) 1 2 3)"} + {:suite "reader / anonymous fn #()" :label "%2 + rest" :expected "[3]" :actual "(#(do %2 %&) 1 2 3)"} + {:suite "reader / anonymous fn #()" :label "%2 only (placeholder p1)" :expected "20" :actual "(#(* %2 2) 1 10)"} + {:suite "reader / anonymous fn #()" :label "% and %1 same" :expected "10" :actual "(#(+ % %1) 5)"} + {:suite "reader / var-quote #'" :label "var-quote = var" :expected "true" :actual "(= (var str) #'str)"} + {:suite "reader / var-quote #'" :label "is a var" :expected "true" :actual "(var? #'str)"} + {:suite "reader / var-quote #'" :label "deref var-quote" :expected "5" :actual "(do (def w 5) (deref #'w))"} + {:suite "reader / metadata ^" :label "meta on map" :expected "true" :actual "(:foo (meta ^:foo {}))"} + {:suite "reader / metadata ^" :label "meta on vector" :expected "true" :actual "(:foo (meta ^:foo [1 2]))"} + {:suite "reader / metadata ^" :label "meta on set" :expected "true" :actual "(:foo (meta ^:foo #{}))"} + {:suite "reader / metadata ^" :label "meta map form" :expected "1" :actual "(:a (meta ^{:a 1} {}))"} + {:suite "reader / metadata ^" :label "meta on quoted sym" :expected "true" :actual "(:foo (meta (quote ^:foo bar)))"} + {:suite "reader / metadata ^" :label "with-meta map" :expected "true" :actual "(:k (meta (with-meta {} {:k true})))"} + {:suite "reader / metadata ^" :label "with-meta vector" :expected "true" :actual "(:k (meta (with-meta [] {:k true})))"} + {:suite "reader / metadata ^" :label "non-metadatable num" :expected "nil" :actual "(meta 100)"} + {:suite "reader / metadata ^" :label "non-metadatable str" :expected "nil" :actual "(meta \"\")"} + {:suite "reader / metadata ^" :label "non-metadatable bool" :expected "nil" :actual "(meta true)"} + {:suite "reader / syntax-quote" :label "plain literal" :expected "[1 2 3]" :actual "`[1 2 3]"} + {:suite "reader / syntax-quote" :label "gensym distinct" :expected "true" :actual "(not= `meow# `meow#)"} + {:suite "reader / syntax-quote" :label "gensym stable" :expected "true" :actual "(let [s `[meow# meow#]] (= (first s) (second s)))"} + {:suite "reader / syntax-quote" :label "qualifies unresolved" :expected "(quote user/foo)" :actual "`foo"} + {:suite "reader / syntax-quote" :label "qualifies core sym" :expected "(quote clojure.core/str)" :actual "`str"} + {:suite "reader / syntax-quote" :label "unquote value" :expected "[1 2 3]" :actual "(let [a [1 2 3]] `~a)"} + {:suite "reader / syntax-quote" :label "unquote in call" :expected "(quote (clojure.core/str [1 2 3]))" :actual "(let [a [1 2 3]] `(str ~a))"} + {:suite "reader / syntax-quote" :label "splice empty" :expected "(quote (clojure.core/str))" :actual "(let [e []] `(str ~@e))"} + {:suite "reader / syntax-quote" :label "splice values" :expected "(quote (clojure.core/str 1 2 3))" :actual "(let [a [1 2 3]] `(str ~@a))"} + {:suite "reader / syntax-quote" :label "splice in vector" :expected "[1 2 3 0 1 2 3]" :actual "(let [b [0] a [1 2 3] e []] `[~@e ~@a ~@b ~@a ~@e])"} + {:suite "reader / syntax-quote" :label "splice in set" :expected "#{0 1 3 2}" :actual "(let [b [0] a [1 2 3] e []] `#{~@e ~@a ~@b})"} + {:suite "reader / syntax-quote" :label "unquote in set" :expected "#{9 5}" :actual "(let [x 5] `#{~x 9})"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "discard simple" :expected "2" :actual "(do #_1 2)"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "discard in vector" :expected "[1 3]" :actual "[1 #_2 3]"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "discard stacks" :expected "3" :actual "(do #_ #_ 1 2 3)"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "##Inf" :expected "true" :actual "(= ##Inf (/ 1.0 0.0))"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "##-Inf" :expected "true" :actual "(= ##-Inf (/ -1.0 0.0))"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "##NaN not self-equal" :expected "false" :actual "(= ##NaN ##NaN)"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "##NaN is NaN?" :expected "true" :actual "(NaN? ##NaN)"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "conditional :default reachable" :expected "2" :actual "#?(:no-such-dialect 1 :default 2)"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "var-quote qualified" :expected "true" :actual "(= (var clojure.core/str) #'clojure.core/str)"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "gensym stable in template" :expected "true" :actual "(let [syms `[meow# meow#]] (= (first syms) (second syms)))"} + {:suite "reader / discard, symbolic values, conditionals (spec 2.3)" :label "gensym fresh across templates" :expected "false" :actual "(= `meow# `meow#)"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "string once" :expected "true" :actual "(= \"meow\" `\"meow\")"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "string nested" :expected "true" :actual "(= \"meow\" ``\"meow\")"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "string triple" :expected "true" :actual "(= \"meow\" ```\"meow\")"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "number nested" :expected "true" :actual "(= 42 ``42)"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "keyword nested" :expected "true" :actual "(= :k ``:k)"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "nil nested" :expected "false" :actual "(nil? ``nil)"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "char nested" :expected "true" :actual "(= \\a ``\\a)"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "bool nested" :expected "false" :actual "(= true ``true)"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "symbol still qualifies" :expected "true" :actual "(= (quote clojure.core/map) `map)"} + {:suite "reader / syntax-quote literal collapse (spec 2.4 S25)" :label "vector still templates" :expected "true" :actual "(= [1 2] `[1 ~(inc 1)])"} + {:suite "reader / scalar literals" :label "integer" :expected "42" :actual "42"} + {:suite "reader / scalar literals" :label "negative" :expected "-7" :actual "-7"} + {:suite "reader / scalar literals" :label "float" :expected "1.5" :actual "1.5"} + {:suite "reader / scalar literals" :label "string" :expected "\"hi\"" :actual "\"hi\""} + {:suite "reader / scalar literals" :label "boolean true" :expected "true" :actual "true"} + {:suite "reader / scalar literals" :label "nil" :expected "nil" :actual "nil"} + {:suite "reader / scalar literals" :label "keyword" :expected ":a" :actual ":a"} + {:suite "reader / scalar literals" :label "namespaced keyword" :expected "true" :actual "(= :a/b :a/b)"} + {:suite "reader / scalar literals" :label "char" :expected "\\a" :actual "\\a"} + {:suite "reader / scalar literals" :label "char newline" :expected "true" :actual "(= \\newline (first \"\\n\"))"} + {:suite "reader / scalar literals" :label "char open-brace" :expected "123" :actual "(int \\{)"} + {:suite "reader / scalar literals" :label "char open-paren" :expected "40" :actual "(int \\()"} + {:suite "reader / scalar literals" :label "char comma" :expected "44" :actual "(int \\,)"} + {:suite "reader / scalar literals" :label "char percent" :expected "37" :actual "(int \\%)"} + {:suite "reader / scalar literals" :label "char unicode" :expected "65" :actual "(int \\u0041)"} + {:suite "reader / scalar literals" :label "hex literal" :expected "255" :actual "0xff"} + {:suite "reader / scalar literals" :label "hex uppercase" :expected "31" :actual "0X1F"} + {:suite "reader / scalar literals" :label "bigint suffix N" :expected "42N" :actual "42N"} + {:suite "reader / scalar literals" :label "bigdec suffix M" :expected "1.5M" :actual "1.5M"} + {:suite "reader / scalar literals" :label "ratio -> double" :expected "3/4" :actual "3/4"} + {:suite "reader / scalar literals" :label "radix integer" :expected "255" :actual "16rFF"} + {:suite "reader / scalar literals" :label "exponent" :expected "1500.0" :actual "1.5e3"} + {:suite "reader / scalar literals" :label "symbolic Infinity" :expected "true" :actual "(infinite? ##Inf)"} + {:suite "reader / scalar literals" :label "symbolic NaN" :expected "true" :actual "(NaN? ##NaN)"} + {:suite "reader / scalar literals" :label "symbol via quote" :expected "'foo" :actual "'foo"} + {:suite "reader / collection literals" :label "vector" :expected "[1 2 3]" :actual "[1 2 3]"} + {:suite "reader / collection literals" :label "list quoted" :expected "[1 2 3]" :actual "'(1 2 3)"} + {:suite "reader / collection literals" :label "map" :expected "{:a 1}" :actual "{:a 1}"} + {:suite "reader / collection literals" :label "set" :expected "#{1 3 2}" :actual "#{1 2 3}"} + {:suite "reader / collection literals" :label "nested" :expected "{:a [1 {:b 2}]}" :actual "{:a [1 {:b 2}]}"} + {:suite "reader / collection literals" :label "empty vector" :expected "[]" :actual "[]"} + {:suite "reader / collection literals" :label "empty map" :expected "{}" :actual "{}"} + {:suite "reader / collection literals" :label "empty set" :expected "#{}" :actual "#{}"} + {:suite "reader / dispatch & sugar" :label "anon fn #()" :expected "3" :actual "(#(+ %1 %2) 1 2)"} + {:suite "reader / dispatch & sugar" :label "anon fn single %" :expected "2" :actual "(#(inc %) 1)"} + {:suite "reader / dispatch & sugar" :label "anon fn %&" :expected "[2 3]" :actual "(#(vec %&) 2 3)"} + {:suite "reader / dispatch & sugar" :label "discard #_" :expected "[1 3]" :actual "[1 #_2 3]"} + {:suite "reader / dispatch & sugar" :label "regex literal" :expected "true" :actual "(= \"abc\" (re-find #\"abc\" \"xabcx\"))"} + {:suite "reader / dispatch & sugar" :label "reader conditional" :expected "1" :actual "#?(:clj 1 :cljs 2 :default 3)"} + {:suite "reader / dispatch & sugar" :label "reader cond :jolt" :expected "1" :actual "#?(:clj 1 :jolt 4 :default 3)"} + {:suite "reader / dispatch & sugar" :label "reader cond clause order" :expected "5" :actual "#?(:default 5 :jolt 6)"} + {:suite "reader / dispatch & sugar" :label "reader cond no match" :expected "[1]" :actual "[#?(:clj 1 :cljs 2)]"} + {:suite "reader / dispatch & sugar" :label "reader cond splice" :expected "[]" :actual "[#?@(:jolt [1 2 3] :cljs [4 5])]"} + {:suite "reader / dispatch & sugar" :label "reader cond splice no match" :expected "[1 2 3]" :actual "[#?@(:clj [1 2 3] :cljs [4 5])]"} + {:suite "reader / dispatch & sugar" :label "inst literal reads" :expected "true" :actual "(some? #inst \"2020-01-01T00:00:00Z\")"} + {:suite "reader / dispatch & sugar" :label "uuid literal" :expected "\"550e8400-e29b-41d4-a716-446655440000\"" :actual "(str #uuid \"550e8400-e29b-41d4-a716-446655440000\")"} + {:suite "reader / dispatch & sugar" :label "tagged literal var" :expected "true" :actual "(var? #'+)"} + {:suite "reader / dispatch & sugar" :label "deref sugar" :expected "5" :actual "(let [a (atom 5)] @a)"} + {:suite "reader / dispatch & sugar" :label "meta sugar" :expected "{:t 1}" :actual "(meta ^{:t 1} [])"} + {:suite "reader / comments inside maps" :label "comment in value slot" :expected "{:a 1}" :actual "{:a ; note\n 1}"} + {:suite "reader / comments inside maps" :label "comment before key" :expected "{:a 1}" :actual "{; lead\n :a 1}"} + {:suite "reader / comments inside maps" :label "comment between entries" :expected "{:a 1, :b 2}" :actual "{:a 1 ; mid\n :b 2}"} + {:suite "reader / comments inside maps" :label "discard in value slot" :expected "{:a 1}" :actual "{:a #_9 1}"} + {:suite "reader / comments inside maps" :label "comment with parens" :expected "{:a {:b 1}}" :actual "{:a ; dev (REPL, etc)\n {:b 1}}"} + {:suite "reader / comments inside maps" :label "nested with comments" :expected "{:x {:y 2}}" :actual "{:x ; outer\n {:y ; inner\n 2}}"} + {:suite "regex / literals & predicate" :label "regex? literal" :expected "true" :actual "(regex? #\"\\d+\")"} + {:suite "regex / literals & predicate" :label "regex? non-regex" :expected "false" :actual "(regex? \"\\d+\")"} + {:suite "regex / literals & predicate" :label "escaped digits" :expected "\"42\"" :actual "(re-find #\"\\d+\" \"x42y\")"} + {:suite "regex / literals & predicate" :label "escaped ws/non-ws" :expected "\"x a\"" :actual "(re-find #\"\\S\\s\\S\" \"x a b y\")"} + {:suite "regex / re-find" :label "match" :expected "\"123\"" :actual "(re-find #\"\\d+\" \"abc123def\")"} + {:suite "regex / re-find" :label "no match nil" :expected "nil" :actual "(re-find #\"\\d+\" \"abc\")"} + {:suite "regex / re-find" :label "with groups" :expected "[\"a1\" \"a\" \"1\"]" :actual "(re-find #\"([a-z])(\\d)\" \"--a1--\")"} + {:suite "regex / re-find" :label "first match only" :expected "\"1\"" :actual "(re-find #\"\\d\" \"1 2 3\")"} + {:suite "regex / re-matches" :label "full match" :expected "\"123\"" :actual "(re-matches #\"\\d+\" \"123\")"} + {:suite "regex / re-matches" :label "partial = nil" :expected "nil" :actual "(re-matches #\"\\d+\" \"123abc\")"} + {:suite "regex / re-matches" :label "groups" :expected "[\"12\" \"1\" \"2\"]" :actual "(re-matches #\"(\\d)(\\d)\" \"12\")"} + {:suite "regex / re-matches" :label "no match nil" :expected "nil" :actual "(re-matches #\"x+\" \"yyy\")"} + {:suite "regex / re-seq" :label "all matches" :expected "[\"1\" \"22\" \"333\"]" :actual "(re-seq #\"\\d+\" \"a1b22c333\")"} + {:suite "regex / re-seq" :label "empty when none" :expected "nil" :actual "(seq (re-seq #\"z\" \"abc\"))"} + {:suite "regex / re-seq" :label "words" :expected "[\"foo\" \"bar\"]" :actual "(re-seq #\"\\w+\" \"foo bar\")"} + {:suite "regex / re-pattern & string ops" :label "re-pattern build" :expected "\"hi\"" :actual "(re-find (re-pattern \"\\\\w+\") \"hi!\")"} + {:suite "regex / re-pattern & string ops" :label "re-pattern is regex?" :expected "true" :actual "(regex? (re-pattern \"a\"))"} + {:suite "regex / re-pattern & string ops" :label "split on regex" :expected "[\"a\" \"b\" \"c\"]" :actual "(do (require '[clojure.string :as s]) (s/split \"a1b2c\" #\"\\d\"))"} + {:suite "regex / re-pattern & string ops" :label "replace regex" :expected "\"X-X\"" :actual "(do (require '[clojure.string :as s]) (s/replace \"a-b\" #\"[a-z]\" \"X\"))"} + {:suite "regex / re-pattern & string ops" :label "replace $1" :expected "\"[a][b]\"" :actual "(do (require '[clojure.string :as s]) (s/replace \"ab\" #\"([a-z])\" \"[$1]\"))"} + {:suite "regex / \\p property classes" :label "p{L} ascii" :expected "\"hello\"" :actual "(re-matches #\"^\\p{L}+$\" \"hello\")"} + {:suite "regex / \\p property classes" :label "p{L} utf-8" :expected "true" :actual "(boolean (re-matches #\"^\\p{L}+$\" \"héllo\"))"} + {:suite "regex / \\p property classes" :label "p{L} rejects digits" :expected "false" :actual "(boolean (re-matches #\"^\\p{L}+$\" \"ab1\"))"} + {:suite "regex / \\p property classes" :label "p{N}" :expected "[\"12\" \"345\"]" :actual "(re-seq #\"\\p{N}+\" \"a12b345\")"} + {:suite "regex / \\p property classes" :label "P{N} negation" :expected "\"abc\"" :actual "(re-matches #\"^\\P{N}+$\" \"abc\")"} + {:suite "regex / \\p property classes" :label "inside class" :expected "\"a-1_b\"" :actual "(re-matches #\"^[\\p{N}\\p{L}_-]+$\" \"a-1_b\")"} + {:suite "regex / \\p property classes" :label "p{Lu}/p{Ll}" :expected "\"aB\"" :actual "(re-matches #\"^\\p{Ll}\\p{Lu}$\" \"aB\")"} + {:suite "regex / \\p property classes" :label "p{Z} space" :expected "\" \"" :actual "(re-matches #\"(?u)^[\\s\\p{Z}]+$\" \" \")"} + {:suite "regex / \\p property classes" :label "p{Ps}/p{Pe}" :expected "\"(x)\"" :actual "(re-matches #\"^\\p{Ps}x\\p{Pe}$\" \"(x)\")"} + {:suite "regex / \\p property classes" :label "(?u) accepted" :expected "\"hi\"" :actual "(re-matches #\"(?u)^hi$\" \"hi\")"} + {:suite "regex / \\p property classes" :label "unknown class throws" :expected :throws :actual "(re-pattern \"\\p{Greek}\")"} + {:suite "regex / Pattern statics & String regex methods" :label "Pattern/compile is a regex" :expected "true" :actual "(regex? (Pattern/compile \"a.c\"))"} + {:suite "regex / Pattern statics & String regex methods" :label "compiled .split" :expected "[\"a\" \"b\" \"c\"]" :actual "(.split (Pattern/compile \",\") \"a,b,c\")"} + {:suite "regex / Pattern statics & String regex methods" :label "str/replace w/ Pattern" :expected "\"ab\"" :actual "(do (require '[clojure.string :as s]) (s/replace \"a1b2\" (Pattern/compile \"[0-9]\") \"\"))"} + {:suite "regex / Pattern statics & String regex methods" :label "Pattern/MULTILINE ^" :expected "true" :actual "(boolean (re-find (Pattern/compile \"^x\" Pattern/MULTILINE) \"y\\nx\"))"} + {:suite "regex / Pattern statics & String regex methods" :label "Pattern/quote literal" :expected "true" :actual "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"za.cy\"))"} + {:suite "regex / Pattern statics & String regex methods" :label "Pattern/quote not meta" :expected "false" :actual "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"zabcy\"))"} + {:suite "regex / Pattern statics & String regex methods" :label ".matches whole string" :expected "true" :actual "(.matches \"abc\" \"a.c\")"} + {:suite "regex / Pattern statics & String regex methods" :label ".matches partial -> false" :expected "false" :actual "(.matches \"abcd\" \"a.c\")"} + {:suite "regex / Pattern statics & String regex methods" :label ".replaceAll regex" :expected "\"a-b-c\"" :actual "(.replaceAll \"a_b_c\" \"_\" \"-\")"} + {:suite "regex / Pattern statics & String regex methods" :label ".replaceFirst regex" :expected "\"a-b_c\"" :actual "(.replaceFirst \"a_b_c\" \"_\" \"-\")"} + {:suite "regex / bounded quantifiers (jolt-3xur)" :label "exact {n}" :expected "\"aaa\"" :actual "(re-matches #\"a{3}\" \"aaa\")"} + {:suite "regex / bounded quantifiers (jolt-3xur)" :label "range {n,m} max" :expected "\"aaaa\"" :actual "(re-find #\"a{2,4}\" \"aaaaa\")"} + {:suite "regex / bounded quantifiers (jolt-3xur)" :label "zero lower {0,n}" :expected "\"aa\"" :actual "(re-find #\"a{0,3}\" \"aa\")"} + {:suite "regex / bounded quantifiers (jolt-3xur)" :label "{n,} unbounded" :expected "\"aaaa\"" :actual "(re-find #\"a{2,}\" \"aaaa\")"} + {:suite "regex / bounded quantifiers (jolt-3xur)" :label "nested bounds compile" :expected "true" :actual "(boolean (re-matches #\"[a-z](?:[a-z]{0,61}[a-z])?(?:-[a-z]{0,61}[a-z])*\" \"abc-def\"))"} + {:suite "regex / backreferences (jolt-xtss)" :label "repeated char" :expected "true" :actual "(boolean (re-find #\"(.)\\1\" \"abba\"))"} + {:suite "regex / backreferences (jolt-xtss)" :label "no repeat = nil" :expected "nil" :actual "(re-find #\"(.)\\1\" \"abc\")"} + {:suite "regex / backreferences (jolt-xtss)" :label "thematic-break run" :expected "true" :actual "(boolean (re-matches #\"([-*_])\\1\\1\" \"---\"))"} + {:suite "regex / backreferences (jolt-xtss)" :label "mismatched run" :expected "nil" :actual "(re-matches #\"([-*_])\\1\\1\" \"-*_\")"} + {:suite "regex / backreferences (jolt-xtss)" :label "repeated word" :expected "[\"the the\" \"the\"]" :actual "(re-find #\"(\\w+) \\1\" \"say the the word\")"} + {:suite "regex / backreferences (jolt-xtss)" :label "group still captures" :expected "[\"x=x\" \"x\"]" :actual "(re-matches #\"(\\w+)=\\1\" \"x=x\")"} + {:suite "regex / backreferences (jolt-xtss)" :label "html tag pair" :expected "true" :actual "(boolean (re-matches #\"<(\\w+)>.*\" \"hi\"))"} + {:suite "seq / access" :label "first of vector" :expected "1" :actual "(first [1 2 3])"} + {:suite "seq / access" :label "first of list" :expected "1" :actual "(first (list 1 2 3))"} + {:suite "seq / access" :label "first of empty is nil" :expected "nil" :actual "(first [])"} + {:suite "seq / access" :label "first of nil is nil" :expected "nil" :actual "(first nil)"} + {:suite "seq / access" :label "second" :expected "2" :actual "(second [1 2 3])"} + {:suite "seq / access" :label "last" :expected "3" :actual "(last [1 2 3])"} + {:suite "seq / access" :label "rest of vector" :expected "[2 3]" :actual "(rest [1 2 3])"} + {:suite "seq / access" :label "rest of single" :expected "[]" :actual "(rest [1])"} + {:suite "seq / access" :label "rest of empty" :expected "[]" :actual "(rest [])"} + {:suite "seq / access" :label "next of single is nil" :expected "nil" :actual "(next [1])"} + {:suite "seq / access" :label "next of empty is nil" :expected "nil" :actual "(next [])"} + {:suite "seq / access" :label "nth" :expected "30" :actual "(nth [10 20 30] 2)"} + {:suite "seq / access" :label "nth with default" :expected "99" :actual "(nth [10] 5 99)"} + {:suite "seq / access" :label "nth out of range" :expected :throws :actual "(nth [10] 5)"} + {:suite "seq / access" :label "ffirst" :expected "1" :actual "(ffirst [[1 2] [3 4]])"} + {:suite "seq / access" :label "fnext" :expected "2" :actual "(fnext [1 2 3])"} + {:suite "seq / access" :label "nnext" :expected "[3 4]" :actual "(nnext [1 2 3 4])"} + {:suite "seq / construction" :label "cons onto list" :expected "[0 1 2]" :actual "(cons 0 (list 1 2))"} + {:suite "seq / construction" :label "cons onto vector" :expected "[0 1 2]" :actual "(cons 0 [1 2])"} + {:suite "seq / construction" :label "cons onto nil" :expected "[0]" :actual "(cons 0 nil)"} + {:suite "seq / construction" :label "conj vector appends" :expected "[1 2 3]" :actual "(conj [1 2] 3)"} + {:suite "seq / construction" :label "conj list prepends" :expected "[0 1 2]" :actual "(conj (list 1 2) 0)"} + {:suite "seq / construction" :label "conj multiple on vec" :expected "[1 2 3 4]" :actual "(conj [1 2] 3 4)"} + {:suite "seq / construction" :label "conj multiple on list" :expected "[4 3 1 2]" :actual "(conj (list 1 2) 3 4)"} + {:suite "seq / construction" :label "seq of empty is nil" :expected "nil" :actual "(seq [])"} + {:suite "seq / construction" :label "seq of nil is nil" :expected "nil" :actual "(seq nil)"} + {:suite "seq / construction" :label "seq of string" :expected "[\\a \\b]" :actual "(seq \"ab\")"} + {:suite "seq / construction" :label "empty?" :expected "true" :actual "(empty? [])"} + {:suite "seq / construction" :label "not empty?" :expected "false" :actual "(empty? [1])"} + {:suite "seq / construction" :label "count" :expected "3" :actual "(count [1 2 3])"} + {:suite "seq / construction" :label "count of nil" :expected "0" :actual "(count nil)"} + {:suite "seq / construction" :label "count of string" :expected "3" :actual "(count \"abc\")"} + {:suite "seq / map filter reduce" :label "map" :expected "[2 3 4]" :actual "(map inc [1 2 3])"} + {:suite "seq / map filter reduce" :label "map two colls" :expected "[5 7 9]" :actual "(map + [1 2 3] [4 5 6])"} + {:suite "seq / map filter reduce" :label "map stops at shortest" :expected "[5 7]" :actual "(map + [1 2] [4 5 6])"} + {:suite "seq / map filter reduce" :label "map keeps nil elements" :expected "[[1 :a] [nil :b] [3 nil]]" :actual "(map vector [1 nil 3] [:a :b nil])"} + {:suite "seq / map filter reduce" :label "map 3 colls" :expected "[12 15 18]" :actual "(map + [1 2 3] [4 5 6] [7 8 9])"} + {:suite "seq / map filter reduce" :label "map 3 colls shortest" :expected "[12 15]" :actual "(map + [1 2] [4 5 6] [7 8 9])"} + {:suite "seq / map filter reduce" :label "map 4 colls" :expected "[16 20]" :actual "(map + [1 2] [3 4] [5 6] [7 8])"} + {:suite "seq / map filter reduce" :label "map 3 colls nils" :expected "[[1 :a 10] [nil :b 20] [3 nil 30]]" :actual "(map vector [1 nil 3] [:a :b nil] [10 20 30])"} + {:suite "seq / map filter reduce" :label "map empty coll" :expected "[]" :actual "(map + [] [1 2 3] [4 5 6])"} + {:suite "seq / map filter reduce" :label "map lazy+concrete" :expected "[11 22 33]" :actual "(map + (map identity [1 2 3]) [10 20 30])"} + {:suite "seq / map filter reduce" :label "map-indexed" :expected "[[0 :a] [1 :b]]" :actual "(map-indexed vector [:a :b])"} + {:suite "seq / map filter reduce" :label "mapv" :expected "[2 3 4]" :actual "(mapv inc [1 2 3])"} + {:suite "seq / map filter reduce" :label "filter" :expected "[2 4]" :actual "(filter even? [1 2 3 4])"} + {:suite "seq / map filter reduce" :label "filterv" :expected "[2 4]" :actual "(filterv even? [1 2 3 4])"} + {:suite "seq / map filter reduce" :label "remove" :expected "[1 3]" :actual "(remove even? [1 2 3 4])"} + {:suite "seq / map filter reduce" :label "reduce" :expected "10" :actual "(reduce + [1 2 3 4])"} + {:suite "seq / map filter reduce" :label "reduce with init" :expected "20" :actual "(reduce + 10 [1 2 3 4])"} + {:suite "seq / map filter reduce" :label "reduce empty with init" :expected "0" :actual "(reduce + 0 [])"} + {:suite "seq / map filter reduce" :label "reduce single no init" :expected "5" :actual "(reduce + [5])"} + {:suite "seq / map filter reduce" :label "reduced short-circuits" :expected "3" :actual "(reduce (fn [a x] (if (> a 2) (reduced a) (+ a x))) 0 [1 2 3 4 5])"} + {:suite "seq / map filter reduce" :label "reduce-kv" :expected "6" :actual "(reduce-kv (fn [a k v] (+ a v)) 0 {:a 1 :b 2 :c 3})"} + {:suite "seq / map filter reduce" :label "reduce-kv on vector" :expected "[[0 :a] [1 :b]]" :actual "(reduce-kv (fn [a i v] (conj a [i v])) [] [:a :b])"} + {:suite "seq / map filter reduce" :label "reduce-kv honors reduced" :expected "[:a]" :actual "(reduce-kv (fn [a i v] (if (= i 1) (reduced a) (conj a v))) [] [:a :b :c])"} + {:suite "seq / map filter reduce" :label "reduce-kv on nil" :expected "0" :actual "(reduce-kv (fn [a k v] (+ a v)) 0 nil)"} + {:suite "seq / map filter reduce" :label "reductions" :expected "[1 3 6]" :actual "(reductions + [1 2 3])"} + {:suite "seq / map filter reduce" :label "mapcat" :expected "[1 1 2 2]" :actual "(mapcat (fn [x] [x x]) [1 2])"} + {:suite "seq / map filter reduce" :label "mapcat two colls" :expected "[1 3 2 4]" :actual "(mapcat vector [1 2] [3 4])"} + {:suite "seq / map filter reduce" :label "mapcat three colls" :expected "[1 2 3]" :actual "(mapcat vector [1] [2] [3])"} + {:suite "seq / map filter reduce" :label "mapcat empty coll" :expected "[]" :actual "(mapcat vector [] [1 2] [3 4])"} + {:suite "seq / map filter reduce" :label "mapcat seqs" :expected "[1 2 3 4]" :actual "(mapcat identity [[1 2] [3 4]])"} + {:suite "seq / map filter reduce" :label "keep" :expected "[1 3]" :actual "(keep (fn [x] (if (odd? x) x nil)) [1 2 3 4])"} + {:suite "seq / map filter reduce" :label "some truthy" :expected "true" :actual "(some even? [1 2 3])"} + {:suite "seq / map filter reduce" :label "some nil" :expected "nil" :actual "(some even? [1 3 5])"} + {:suite "seq / map filter reduce" :label "every? true" :expected "true" :actual "(every? pos? [1 2 3])"} + {:suite "seq / map filter reduce" :label "every? false" :expected "false" :actual "(every? pos? [1 -2 3])"} + {:suite "seq / take drop slice" :label "take" :expected "[1 2 3]" :actual "(take 3 [1 2 3 4 5])"} + {:suite "seq / take drop slice" :label "take more than size" :expected "[1 2]" :actual "(take 5 [1 2])"} + {:suite "seq / take drop slice" :label "drop" :expected "[4 5]" :actual "(drop 3 [1 2 3 4 5])"} + {:suite "seq / take drop slice" :label "take-while" :expected "[1 2]" :actual "(take-while (fn [x] (< x 3)) [1 2 3 1])"} + {:suite "seq / take drop slice" :label "drop-while" :expected "[3 1]" :actual "(drop-while (fn [x] (< x 3)) [1 2 3 1])"} + {:suite "seq / take drop slice" :label "take-last" :expected "[4 5]" :actual "(take-last 2 [1 2 3 4 5])"} + {:suite "seq / take drop slice" :label "drop-last" :expected "[1 2 3]" :actual "(drop-last [1 2 3 4])"} + {:suite "seq / take drop slice" :label "take-nth" :expected "[1 3 5]" :actual "(take-nth 2 [1 2 3 4 5])"} + {:suite "seq / take drop slice" :label "partition" :expected "[[1 2] [3 4]]" :actual "(partition 2 [1 2 3 4 5])"} + {:suite "seq / take drop slice" :label "partition-all" :expected "[[1 2] [3]]" :actual "(partition-all 2 [1 2 3])"} + {:suite "seq / take drop slice" :label "split-at" :expected "[[1 2] [3 4]]" :actual "(split-at 2 [1 2 3 4])"} + {:suite "seq / transform" :label "reverse" :expected "[3 2 1]" :actual "(reverse [1 2 3])"} + {:suite "seq / transform" :label "sort" :expected "[1 2 3]" :actual "(sort [3 1 2])"} + {:suite "seq / transform" :label "sort with comparator" :expected "[3 2 1]" :actual "(sort > [1 3 2])"} + {:suite "seq / transform" :label "sort-by" :expected "[[1] [2 2]]" :actual "(sort-by count [[2 2] [1]])"} + {:suite "seq / transform" :label "distinct" :expected "[1 2 3]" :actual "(distinct [1 1 2 3 3])"} + {:suite "seq / transform" :label "dedupe" :expected "[1 2 1]" :actual "(dedupe [1 1 2 1])"} + {:suite "seq / transform" :label "interpose" :expected "[1 0 2 0 3]" :actual "(interpose 0 [1 2 3])"} + {:suite "seq / transform" :label "interleave" :expected "[1 :a 2 :b]" :actual "(interleave [1 2] [:a :b])"} + {:suite "seq / transform" :label "flatten" :expected "[1 2 3 4]" :actual "(flatten [1 [2 [3 [4]]]])"} + {:suite "seq / transform" :label "concat" :expected "[1 2 3 4]" :actual "(concat [1 2] [3 4])"} + {:suite "seq / transform" :label "into vector" :expected "[1 2 3 4]" :actual "(into [1 2] [3 4])"} + {:suite "seq / transform" :label "into list" :expected "[3 2 1]" :actual "(into (list) [1 2 3])"} + {:suite "seq / transform" :label "frequencies" :expected "{1 2, 2 1}" :actual "(frequencies [1 1 2])"} + {:suite "seq / transform" :label "group-by" :expected "{false [1 3], true [2 4]}" :actual "(group-by even? [1 2 3 4])"} + {:suite "seq / transform" :label "zipmap" :expected "{:a 1, :b 2}" :actual "(zipmap [:a :b] [1 2])"} + {:suite "seq / transform" :label "mapcat seqs" :expected "[1 2 3 4]" :actual "(mapcat identity [[1 2] [3 4]])"} + {:suite "seq / generators" :label "range n" :expected "[0 1 2 3]" :actual "(range 4)"} + {:suite "seq / generators" :label "range from to" :expected "[2 3 4]" :actual "(range 2 5)"} + {:suite "seq / generators" :label "range with step" :expected "[0 2 4]" :actual "(range 0 6 2)"} + {:suite "seq / generators" :label "take repeat" :expected "[:x :x :x]" :actual "(take 3 (repeat :x))"} + {:suite "seq / generators" :label "repeat n" :expected "[5 5]" :actual "(repeat 2 5)"} + {:suite "seq / generators" :label "take iterate" :expected "[1 2 4 8]" :actual "(take 4 (iterate (fn [x] (* x 2)) 1))"} + {:suite "seq / generators" :label "take cycle" :expected "[1 2 1 2 1]" :actual "(take 5 (cycle [1 2]))"} + {:suite "seq / generators" :label "take repeatedly" :expected "3" :actual "(count (take 3 (repeatedly (fn [] 1))))"} + {:suite "seq / generators" :label "take-last of range" :expected "[8 9]" :actual "(take-last 2 (range 10))"} + {:suite "seq / IFn values as functions" :label "map keyword" :expected "[1 2 3]" :actual "(map :a [{:a 1} {:a 2} {:a 3}])"} + {:suite "seq / IFn values as functions" :label "filter keyword" :expected "[{:ok true}]" :actual "(filter :ok [{:ok true} {:ok false}])"} + {:suite "seq / IFn values as functions" :label "remove keyword" :expected "[{:ok false}]" :actual "(remove :ok [{:ok true} {:ok false}])"} + {:suite "seq / IFn values as functions" :label "sort-by keyword" :expected "[{:a 1} {:a 2} {:a 3}]" :actual "(sort-by :a [{:a 3} {:a 1} {:a 2}])"} + {:suite "seq / IFn values as functions" :label "sort-by key + cmp" :expected "[{:a 3} {:a 2} {:a 1}]" :actual "(sort-by :a > [{:a 3} {:a 1} {:a 2}])"} + {:suite "seq / IFn values as functions" :label "filter set" :expected "[2 4]" :actual "(filter #{2 4} [1 2 3 4 5])"} + {:suite "seq / IFn values as functions" :label "remove set" :expected "[1 3 5]" :actual "(remove #{2 4} [1 2 3 4 5])"} + {:suite "seq / IFn values as functions" :label "group-by keyword" :expected "{1 [{:n 1}], 2 [{:n 2}]}" :actual "(group-by :n [{:n 1} {:n 2}])"} + {:suite "seq / IFn values as functions" :label "map a map" :expected "[1 nil 2]" :actual "(map {:a 1 :b 2} [:a :z :b])"} + {:suite "seq / IFn values as functions" :label "take-nth transducer" :expected "[0 2 4 6 8]" :actual "(into [] (take-nth 2) (range 10))"} + {:suite "seq / IFn values as functions" :label "interpose transducer" :expected "[1 :x 2]" :actual "(into [] (interpose :x) [1 2])"} + {:suite "seq / conj edge cases" :label "conj no args" :expected "[]" :actual "(conj)"} + {:suite "seq / conj edge cases" :label "conj nil one" :expected "[3]" :actual "(conj nil 3)"} + {:suite "seq / conj edge cases" :label "conj nil many" :expected "[2 1]" :actual "(conj nil 1 2)"} + {:suite "seq / conj edge cases" :label "conj vector" :expected "[1 2 3]" :actual "(conj [1 2] 3)"} + {:suite "seq / conj edge cases" :label "conj list prepend" :expected "[0 1 2]" :actual "(conj '(1 2) 0)"} + {:suite "seq / conj edge cases" :label "conj map + map" :expected "{:a 0, :b 1}" :actual "(conj {:a 0} {:b 1})"} + {:suite "seq / conj edge cases" :label "conj map + pair" :expected "{:a 0, :b 1}" :actual "(conj {:a 0} [:b 1])"} + {:suite "seq / conj edge cases" :label "conj map merge wins" :expected "{:a 2}" :actual "(conj {:a 0} {:a 1} {:a 2})"} + {:suite "seq / strictness (throws like Clojure)" :label "cons non-seqable num" :expected :throws :actual "(cons 1 42)"} + {:suite "seq / strictness (throws like Clojure)" :label "cons non-seqable kw" :expected :throws :actual "(cons 1 :k)"} + {:suite "seq / strictness (throws like Clojure)" :label "cons onto nil ok" :expected "[1]" :actual "(cons 1 nil)"} + {:suite "seq / strictness (throws like Clojure)" :label "cons onto seq ok" :expected "[0 1 2]" :actual "(cons 0 [1 2])"} + {:suite "seq / strictness (throws like Clojure)" :label "num non-number" :expected :throws :actual "(num \"x\")"} + {:suite "seq / strictness (throws like Clojure)" :label "num ok" :expected "5" :actual "(num 5)"} + {:suite "seq / strictness (throws like Clojure)" :label "realized? on number" :expected :throws :actual "(realized? 1)"} + {:suite "seq / strictness (throws like Clojure)" :label "realized? on nil" :expected :throws :actual "(realized? nil)"} + {:suite "seq / strictness (throws like Clojure)" :label "symbol from nil" :expected :throws :actual "(symbol nil)"} + {:suite "seq / strictness (throws like Clojure)" :label "symbol bad 2-arg" :expected :throws :actual "(symbol :a \"b\")"} + {:suite "seq / strictness (throws like Clojure)" :label "symbol from keyword" :expected "\"x\"" :actual "(name (symbol :x))"} + {:suite "seq / strictness (throws like Clojure)" :label "keyword bad 2-arg" :expected :throws :actual "(keyword \"abc\" nil)"} + {:suite "seq / strictness (throws like Clojure)" :label "keyword from symbol" :expected "\"x\"" :actual "(name (keyword 'x))"} + {:suite "seq / accessor strictness" :label "peek vector" :expected "3" :actual "(peek [1 2 3])"} + {:suite "seq / accessor strictness" :label "peek list" :expected "1" :actual "(peek '(1 2 3))"} + {:suite "seq / accessor strictness" :label "peek empty vec" :expected "nil" :actual "(peek [])"} + {:suite "seq / accessor strictness" :label "peek on set" :expected :throws :actual "(peek #{1 2})"} + {:suite "seq / accessor strictness" :label "peek on number" :expected :throws :actual "(peek 42)"} + {:suite "seq / accessor strictness" :label "pop empty vec" :expected :throws :actual "(pop [])"} + {:suite "seq / accessor strictness" :label "pop on number" :expected :throws :actual "(pop 0)"} + {:suite "seq / accessor strictness" :label "pop vector" :expected "[1 2]" :actual "(pop [1 2 3])"} + {:suite "seq / accessor strictness" :label "vec on number" :expected :throws :actual "(vec 42)"} + {:suite "seq / accessor strictness" :label "vec on keyword" :expected :throws :actual "(vec :a)"} + {:suite "seq / accessor strictness" :label "vec ok" :expected "[1 2]" :actual "(vec '(1 2))"} + {:suite "seq / accessor strictness" :label "key on nil" :expected :throws :actual "(key nil)"} + {:suite "seq / accessor strictness" :label "key on map" :expected :throws :actual "(key {})"} + {:suite "seq / accessor strictness" :label "val on number" :expected :throws :actual "(val 0)"} + {:suite "seq / accessor strictness" :label "key of entry" :expected ":a" :actual "(key (first {:a 1}))"} + {:suite "seq / accessor strictness" :label "val of entry" :expected "1" :actual "(val (first {:a 1}))"} + {:suite "seq / more strictness" :label "first on number" :expected :throws :actual "(first 42)"} + {:suite "seq / more strictness" :label "first on keyword" :expected :throws :actual "(first :a)"} + {:suite "seq / more strictness" :label "first ok vec" :expected "1" :actual "(first [1 2])"} + {:suite "seq / more strictness" :label "first ok nil" :expected "nil" :actual "(first nil)"} + {:suite "seq / more strictness" :label "rseq vector" :expected "[3 2 1]" :actual "(rseq [1 2 3])"} + {:suite "seq / more strictness" :label "rseq on string" :expected :throws :actual "(rseq \"ab\")"} + {:suite "seq / more strictness" :label "rseq on map" :expected :throws :actual "(rseq {:a 1})"} + {:suite "seq / more strictness" :label "rseq on number" :expected :throws :actual "(rseq 0)"} + {:suite "seq / more strictness" :label "assoc odd args" :expected :throws :actual "(assoc {:a 1} :b)"} + {:suite "seq / more strictness" :label "assoc on number" :expected :throws :actual "(assoc 5 :a 1)"} + {:suite "seq / more strictness" :label "assoc on set" :expected :throws :actual "(assoc #{} :a 1)"} + {:suite "seq / strictness round 3" :label "seq on number" :expected :throws :actual "(seq 1)"} + {:suite "seq / strictness round 3" :label "seq on fn" :expected :throws :actual "(seq (fn [] 1))"} + {:suite "seq / strictness round 3" :label "seq vector ok" :expected "[1 2]" :actual "(seq [1 2])"} + {:suite "seq / strictness round 3" :label "NaN? on nil" :expected :throws :actual "(NaN? nil)"} + {:suite "seq / strictness round 3" :label "NaN? on number ok" :expected "false" :actual "(NaN? 1.0)"} + {:suite "seq / strictness round 3" :label "shuffle on number" :expected :throws :actual "(shuffle 1)"} + {:suite "seq / strictness round 3" :label "shuffle on string" :expected :throws :actual "(shuffle \"abc\")"} + {:suite "seq / strictness round 3" :label "shuffle vec ok" :expected "3" :actual "(count (shuffle [1 2 3]))"} + {:suite "seq / strictness round 3" :label "nthrest nil count" :expected :throws :actual "(nthrest [0 1 2] nil)"} + {:suite "seq / strictness round 3" :label "nthrest negative" :expected "[0 1 2]" :actual "(nthrest [0 1 2] -1)"} + {:suite "seq / strictness round 3" :label "nthrest nil coll" :expected "nil" :actual "(nthrest nil 0)"} + {:suite "seq / strictness round 3" :label "nthnext nil count" :expected :throws :actual "(nthnext [0 1 2] nil)"} + {:suite "seq / strictness round 3" :label "update vec oob" :expected :throws :actual "(update [] 1 identity)"} + {:suite "seq / strictness round 3" :label "update vec kw key" :expected :throws :actual "(update [1 2 3] :k identity)"} + {:suite "seq / overlay-migrated fns" :label "nthrest exhausted -> ()" :expected "[]" :actual "(nthrest nil 100)"} + {:suite "seq / overlay-migrated fns" :label "nthrest vec exhausted" :expected "[]" :actual "(nthrest [1 2 3] 100)"} + {:suite "seq / overlay-migrated fns" :label "nthrest n<=0 keeps coll" :expected "[1 2 3]" :actual "(nthrest [1 2 3] 0)"} + {:suite "seq / overlay-migrated fns" :label "nthrest drops n" :expected "[3 4 5]" :actual "(nthrest [1 2 3 4 5] 2)"} + {:suite "seq / overlay-migrated fns" :label "nthnext exhausted -> nil" :expected "nil" :actual "(nthnext [1 2] 5)"} + {:suite "seq / overlay-migrated fns" :label "nthnext surprising nil" :expected "nil" :actual "(nthnext nil nil)"} + {:suite "seq / overlay-migrated fns" :label "nthnext drops n" :expected "[3 4]" :actual "(nthnext [1 2 3 4] 2)"} + {:suite "seq / overlay-migrated fns" :label "distinct? distinct" :expected "true" :actual "(distinct? 1 2 3)"} + {:suite "seq / overlay-migrated fns" :label "distinct? dup" :expected "false" :actual "(distinct? 1 2 1)"} + {:suite "seq / overlay-migrated fns" :label "distinct? equal colls" :expected "false" :actual "(distinct? [1 2] [1 2])"} + {:suite "seq / overlay-migrated fns" :label "distinct? single" :expected "true" :actual "(distinct? 5)"} + {:suite "seq / overlay-migrated fns" :label "replace maps elements" :expected "[:a 2 :c 2]" :actual "(replace {1 :a 3 :c} [1 2 3 2])"} + {:suite "seq / overlay-migrated fns" :label "replace preserves nil val" :expected "[1 nil 3]" :actual "(replace {2 nil} [1 2 3])"} + {:suite "seq / overlay-migrated fns" :label "take-last" :expected "[3 4]" :actual "(take-last 2 [1 2 3 4])"} + {:suite "seq / overlay-migrated fns" :label "take-last empty -> nil" :expected "nil" :actual "(take-last 2 [])"} + {:suite "seq / overlay-migrated fns" :label "take-last n>len" :expected "[1 2]" :actual "(take-last 9 [1 2])"} + {:suite "seq / overlay-migrated fns" :label "drop-last default 1" :expected "[1 2]" :actual "(drop-last [1 2 3])"} + {:suite "seq / overlay-migrated fns" :label "drop-last n" :expected "[1 2]" :actual "(drop-last 2 [1 2 3 4])"} + {:suite "seq / overlay-migrated fns" :label "split-with" :expected "[[2 4] [5 6]]" :actual "(split-with even? [2 4 5 6])"} + {:suite "seq / overlay-migrated fns" :label "replicate" :expected "[:x :x :x]" :actual "(replicate 3 :x)"} + {:suite "seq / overlay-migrated fns" :label "bounded-count" :expected "5" :actual "(bounded-count 3 [1 2 3 4 5])"} + {:suite "seq / overlay-migrated fns" :label "bounded-count uncounted" :expected "3" :actual "(bounded-count 3 (filter odd? (range 100)))"} + {:suite "seq / overlay-migrated fns" :label "run! side effects" :expected "6" :actual "(let [a (atom 0)] (run! (fn [x] (swap! a + x)) [1 2 3]) @a)"} + {:suite "seq / overlay-migrated fns" :label "completing wraps rf" :expected "3" :actual "((completing +) 1 2)"} + {:suite "seq / overlay-migrated fns" :label "comparator <" :expected "[1 2 3]" :actual "(sort (comparator <) [3 1 2])"} + {:suite "seq / overlay-migrated fns" :label "comparator >" :expected "[3 2 1]" :actual "(sort (comparator >) [3 1 2])"} + {:suite "seq / overlay-migrated fns" :label "reductions" :expected "[1 3 6 10]" :actual "(reductions + [1 2 3 4])"} + {:suite "seq / overlay-migrated fns" :label "reductions with init" :expected "[10 11 13 16]" :actual "(reductions + 10 [1 2 3])"} + {:suite "seq / overlay-migrated fns" :label "reductions empty calls f" :expected "[0]" :actual "(reductions + [])"} + {:suite "seq / overlay-migrated fns" :label "reductions empty + init" :expected "[5]" :actual "(reductions + 5 [])"} + {:suite "seq / overlay-migrated fns" :label "tree-seq pre-order" :expected "[[1 [2] 3] 1 [2] 2 3]" :actual "(tree-seq sequential? seq [1 [2] 3])"} + {:suite "seq / overlay-migrated fns" :label "some found" :expected "true" :actual "(some even? [1 3 4])"} + {:suite "seq / overlay-migrated fns" :label "some none -> nil" :expected "nil" :actual "(some even? [1 3 5])"} + {:suite "seq / overlay-migrated fns" :label "some keyword pred" :expected "7" :actual "(some :a [{:b 1} {:a 7}])"} + {:suite "seq / overlay-migrated fns" :label "some returns value" :expected "4" :actual "(some (fn [x] (when (even? x) x)) [1 3 4 5])"} + {:suite "seq / overlay-migrated fns" :label "flatten nested" :expected "[1 2 3 4 5]" :actual "(flatten [1 [2 [3 4]] 5])"} + {:suite "seq / overlay-migrated fns" :label "flatten lists too" :expected "[1 2 3]" :actual "(flatten [1 (list 2 3)])"} + {:suite "seq / overlay-migrated fns" :label "flatten scalar -> empty" :expected "[]" :actual "(flatten 5)"} + {:suite "seq / overlay-migrated fns" :label "interleave" :expected "[1 :a 2 :b]" :actual "(interleave [1 2 3] [:a :b])"} + {:suite "seq / overlay-migrated fns" :label "interleave empty" :expected "[]" :actual "(interleave)"} + {:suite "seq / overlay-migrated fns" :label "rationalize identity" :expected "5" :actual "(rationalize 5)"} + {:suite "seq / overlay-migrated fns" :label "dedupe consecutive" :expected "[1 2 3 1]" :actual "(dedupe [1 1 2 2 3 1 1])"} + {:suite "seq / overlay-migrated fns" :label "dedupe empty" :expected "[]" :actual "(dedupe [])"} + {:suite "seq / overlay-migrated fns" :label "dedupe no dups" :expected "[1 2 3]" :actual "(dedupe [1 2 3])"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv" :expected "[[1 2] [3 4]]" :actual "(partitionv 2 [1 2 3 4 5])"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv elems are vectors" :expected "true" :actual "(every? vector? (partitionv 2 [1 2 3 4]))"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv step" :expected "[[1 2] [3 4]]" :actual "(partitionv 2 2 [1 2 3 4 5])"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv pad" :expected "[[1 2] [3 :p]]" :actual "(partitionv 2 2 [:p] [1 2 3])"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv-all" :expected "[[1 2] [3]]" :actual "(partitionv-all 2 [1 2 3])"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "partitionv-all vectors" :expected "true" :actual "(every? vector? (partitionv-all 2 [1 2 3]))"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "splitv-at" :expected "[[1 2] [3 4]]" :actual "(splitv-at 2 [1 2 3 4])"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "splitv-at first is vector" :expected "true" :actual "(vector? (first (splitv-at 2 [1 2 3])))"} + {:suite "seq / partitionv & splitv-at (1.11)" :label "splitv-at past end" :expected "[[1 2] []]" :actual "(splitv-at 5 [1 2])"} + {:suite "sequences / linear walks over concrete collections" :label "rest of vector is a seq" :expected "true" :actual "(seq? (rest [1 2 3]))"} + {:suite "sequences / linear walks over concrete collections" :label "rest of vector not vector" :expected "false" :actual "(vector? (rest [1 2 3]))"} + {:suite "sequences / linear walks over concrete collections" :label "rest values" :expected "[2 3]" :actual "(rest [1 2 3])"} + {:suite "sequences / linear walks over concrete collections" :label "next of vector" :expected "[2 3]" :actual "(next [1 2 3])"} + {:suite "sequences / linear walks over concrete collections" :label "next exhausts to nil" :expected "nil" :actual "(next [1])"} + {:suite "sequences / linear walks over concrete collections" :label "rest exhausts to ()" :expected "[]" :actual "(rest [1])"} + {:suite "sequences / linear walks over concrete collections" :label "rest-loop scales (20k linear)" :expected "20000" :actual "(loop [xs (seq (vec (range 20000))) n 0] (if xs (recur (next xs) (inc n)) n))"} + {:suite "sequences / linear walks over concrete collections" :label "mapv scales (50k linear)" :expected "50000" :actual "(count (mapv inc (vec (range 50000))))"} + {:suite "sequences / linear walks over concrete collections" :label "nested walk" :expected "[2 3]" :actual "(vec (rest (mapv inc [0 1 2])))"} + {:suite "sequences / rest & next over set-like colls" :label "next of set" :expected "true" :actual "(let [n (next #{1 2})] (and (= 1 (count n)) (contains? #{1 2} (first n))))"} + {:suite "sequences / rest & next over set-like colls" :label "rest of set count" :expected "1" :actual "(count (rest #{1 2}))"} + {:suite "sequences / rest & next over set-like colls" :label "next of singleton set" :expected "nil" :actual "(next #{1})"} + {:suite "sequences / rest & next over set-like colls" :label "rest of empty set" :expected "0" :actual "(count (rest #{}))"} + {:suite "sequences / rest & next over set-like colls" :label "next of map" :expected "true" :actual "(let [n (next {:a 1 :b 2})] (and (= 1 (count n)) (map-entry? (first n))))"} + {:suite "sequences / rest & next over set-like colls" :label "next of singleton map" :expected "nil" :actual "(next {:a 1})"} + {:suite "sequences / rest & next over set-like colls" :label "rest of sorted-set" :expected "[2 3]" :actual "(rest (sorted-set 3 1 2))"} + {:suite "sequences / rest & next over set-like colls" :label "next of sorted-map" :expected "[[2 :b]]" :actual "(next (sorted-map 1 :a 2 :b))"} + {:suite "sequences / rest & next over set-like colls" :label "every? over set" :expected "true" :actual "(every? pos? #{1 2 3})"} + {:suite "sequences / rest & next over set-like colls" :label "every? over set false" :expected "false" :actual "(every? odd? #{1 2})"} + {:suite "sequences / rest & next over set-like colls" :label "every? over sorted-set" :expected "true" :actual "(every? pos? (sorted-set 1 2 3))"} + {:suite "sequences / rest & next over set-like colls" :label "every? over map entries" :expected "true" :actual "(every? map-entry? (seq {:a 1 :b 2}))"} + {:suite "set / construct & predicate" :label "literal" :expected "#{1 3 2}" :actual "#{1 2 3}"} + {:suite "set / construct & predicate" :label "hash-set" :expected "#{1 3 2}" :actual "(hash-set 1 2 3)"} + {:suite "set / construct & predicate" :label "set from vector" :expected "#{1 3 2}" :actual "(set [1 2 3 1])"} + {:suite "set / construct & predicate" :label "empty" :expected "#{}" :actual "#{}"} + {:suite "set / construct & predicate" :label "set? true" :expected "true" :actual "(set? #{1})"} + {:suite "set / construct & predicate" :label "set? false on vector" :expected "false" :actual "(set? [1])"} + {:suite "set / construct & predicate" :label "count dedups" :expected "3" :actual "(count (set [1 1 2 3]))"} + {:suite "set / construct & predicate" :label "equality order-indep" :expected "true" :actual "(= #{1 2 3} #{3 2 1})"} + {:suite "set / construct & predicate" :label "into set" :expected "#{:b :a}" :actual "(into #{} [:a :b])"} + {:suite "set / construct & predicate" :label "into non-empty set" :expected "#{1 3 2}" :actual "(into #{1} [2 3 2])"} + {:suite "set / operations" :label "conj adds" :expected "#{1 3 2}" :actual "(conj #{1 2} 3)"} + {:suite "set / operations" :label "conj dup no-op" :expected "#{1 2}" :actual "(conj #{1 2} 1)"} + {:suite "set / operations" :label "disj removes" :expected "#{1 2}" :actual "(disj #{1 2 3} 3)"} + {:suite "set / operations" :label "disj missing no-op" :expected "#{1 2}" :actual "(disj #{1 2} 9)"} + {:suite "set / operations" :label "contains?" :expected "true" :actual "(contains? #{1 2} 1)"} + {:suite "set / operations" :label "contains? missing" :expected "false" :actual "(contains? #{1 2} 9)"} + {:suite "set / operations" :label "get present" :expected "1" :actual "(get #{1 2} 1)"} + {:suite "set / operations" :label "get missing nil" :expected "nil" :actual "(get #{1 2} 9)"} + {:suite "set / operations" :label "set as fn present" :expected "2" :actual "(#{1 2 3} 2)"} + {:suite "set / operations" :label "set as fn missing" :expected "nil" :actual "(#{1 2 3} 9)"} + {:suite "set / literals & value elements" :label "literal evaluates elements" :expected "#{4 2}" :actual "#{(inc 1) (* 2 2)}"} + {:suite "set / literals & value elements" :label "map elements by value" :expected "true" :actual "(= #{{:a 1}} #{(hash-map :a 1)})"} + {:suite "set / literals & value elements" :label "contains? map by value" :expected "true" :actual "(contains? #{(hash-map :x 1)} {:x 1})"} + {:suite "set / literals & value elements" :label "dedup equal maps" :expected "1" :actual "(count (set [{:a 1} (hash-map :a 1)]))"} + {:suite "set / literals & value elements" :label "vector elements" :expected "true" :actual "(contains? #{[1 2]} (vec [1 2]))"} + {:suite "set / nil element (jolt-bn2p)" :label "set keeps nil" :expected "2" :actual "(count (set [nil 1 nil]))"} + {:suite "set / nil element (jolt-bn2p)" :label "contains? nil true" :expected "true" :actual "(contains? (set [nil 1]) nil)"} + {:suite "set / nil element (jolt-bn2p)" :label "contains? nil false" :expected "false" :actual "(contains? #{1} nil)"} + {:suite "set / nil element (jolt-bn2p)" :label "seq includes nil" :expected "true" :actual "(some nil? (seq (set [nil 1])))"} + {:suite "set / nil element (jolt-bn2p)" :label "disj nil" :expected "#{1}" :actual "(disj (set [nil 1]) nil)"} + {:suite "set / nil element (jolt-bn2p)" :label "disj nil count" :expected "1" :actual "(count (disj (set [nil 1]) nil))"} + {:suite "set / nil element (jolt-bn2p)" :label "conj nil count" :expected "2" :actual "(count (conj #{1} nil))"} + {:suite "set / nil element (jolt-bn2p)" :label "conj nil contains?" :expected "true" :actual "(contains? (conj #{1} nil) nil)"} + {:suite "set / nil element (jolt-bn2p)" :label "into #{} keeps nil" :expected "2" :actual "(count (into #{} [nil 1]))"} + {:suite "set / nil element (jolt-bn2p)" :label "into #{} contains? nil" :expected "true" :actual "(contains? (into #{} [nil 1]) nil)"} + {:suite "set / nil element (jolt-bn2p)" :label "into keeps existing nil" :expected "true" :actual "(contains? (into #{nil} [1]) nil)"} + {:suite "set / nil element (jolt-bn2p)" :label "transient conj! nil" :expected "2" :actual "(count (persistent! (conj! (transient #{}) nil 1)))"} + {:suite "set / nil element (jolt-bn2p)" :label "transient contains? nil" :expected "true" :actual "(contains? (persistent! (conj! (transient #{}) nil 1)) nil)"} + {:suite "set / nil element (jolt-bn2p)" :label "transient disj! nil cnt" :expected "1" :actual "(count (persistent! (disj! (conj! (transient #{}) nil 1) nil)))"} + {:suite "set / nil element (jolt-bn2p)" :label "transient disj! removes" :expected "false" :actual "(contains? (persistent! (disj! (conj! (transient #{}) nil 1) nil)) nil)"} + {:suite "set / nil element (jolt-bn2p)" :label "transient of set w/ nil" :expected "true" :actual "(contains? (persistent! (transient (set [nil 1]))) nil)"} + {:suite "clojure.set" :label "union" :expected "#{1 4 3 2}" :actual "(do (require (quote [clojure.set :as s])) (s/union #{1 2} #{3 4}))"} + {:suite "clojure.set" :label "intersection" :expected "#{2}" :actual "(do (require (quote [clojure.set :as s])) (s/intersection #{1 2} #{2 3}))"} + {:suite "clojure.set" :label "difference" :expected "#{1}" :actual "(do (require (quote [clojure.set :as s])) (s/difference #{1 2} #{2 3}))"} + {:suite "clojure.set" :label "subset? true" :expected "true" :actual "(do (require (quote [clojure.set :as s])) (s/subset? #{1} #{1 2}))"} + {:suite "clojure.set" :label "superset? true" :expected "true" :actual "(do (require (quote [clojure.set :as s])) (s/superset? #{1 2} #{1}))"} + {:suite "clojure.set" :label "select" :expected "#{4 2}" :actual "(do (require (quote [clojure.set :as s])) (s/select even? #{1 2 3 4}))"} + {:suite "clojure.set" :label "join" :expected "#{{:a 1, :b 2, :c 3}}" :actual "(do (require (quote [clojure.set :as s])) (s/join #{{:a 1 :b 2}} #{{:b 2 :c 3}}))"} + {:suite "clojure.set" :label "map-invert" :expected "{1 :a}" :actual "(do (require (quote [clojure.set :as s])) (s/map-invert {:a 1}))"} + {:suite "clojure.set" :label "rename-keys" :expected "{:b 1}" :actual "(do (require (quote [clojure.set :as s])) (s/rename-keys {:a 1} {:a :b}))"} + {:suite "set / set? across representations" :label "literal" :expected "true" :actual "(set? #{1})"} + {:suite "set / set? across representations" :label "empty literal" :expected "true" :actual "(set? #{})"} + {:suite "set / set? across representations" :label "sorted-set" :expected "true" :actual "(set? (sorted-set 1 2))"} + {:suite "set / set? across representations" :label "sorted-set-by" :expected "true" :actual "(set? (sorted-set-by > 1 2))"} + {:suite "set / set? across representations" :label "empty sorted" :expected "true" :actual "(set? (sorted-set))"} + {:suite "set / set? across representations" :label "map is not" :expected "false" :actual "(set? {})"} + {:suite "set / set? across representations" :label "vector is not" :expected "false" :actual "(set? [1])"} + {:suite "set / set? across representations" :label "coll? still true" :expected "true" :actual "(coll? (sorted-set 1))"} + {:suite "set / set? across representations" :label "ifn? sorted-set" :expected "true" :actual "(ifn? (sorted-set 1))"} + {:suite "set / bulk build boundaries" :label "set dedup count" :expected "3" :actual "(count (set [1 1 2 3 3 2]))"} + {:suite "set / bulk build boundaries" :label "set big count" :expected "1000" :actual "(count (set (range 1000)))"} + {:suite "set / bulk build boundaries" :label "into #{} count" :expected "500" :actual "(count (into #{} (range 500)))"} + {:suite "set / bulk build boundaries" :label "into #{} onto base" :expected "3" :actual "(count (into #{:a} [:a :b :c]))"} + {:suite "set / bulk build boundaries" :label "set contains" :expected "true" :actual "(contains? (set (range 1000)) 777)"} + {:suite "set / bulk build boundaries" :label "set missing" :expected "false" :actual "(contains? (set (range 1000)) 5000)"} + {:suite "set / bulk build boundaries" :label "set coll members" :expected "true" :actual "(contains? (set [[1 2] [3 4]]) [1 2])"} + {:suite "set / bulk build boundaries" :label "conj after bulk" :expected "true" :actual "(contains? (conj (set (range 100)) :x) :x)"} + {:suite "set / bulk build boundaries" :label "disj after bulk" :expected "false" :actual "(contains? (disj (set (range 100)) 50) 50)"} + {:suite "set / bulk build boundaries" :label "set = literal" :expected "true" :actual "(= #{0 1 2} (set (range 3)))"} + {:suite "sorted / construction & ordering" :label "sorted-set orders" :expected "[1 2 3]" :actual "(vec (seq (sorted-set 3 1 2)))"} + {:suite "sorted / construction & ordering" :label "sorted-set dedupes" :expected "[1 2 3]" :actual "(vec (seq (sorted-set 3 1 2 1 3)))"} + {:suite "sorted / construction & ordering" :label "sorted-set numeric" :expected "[1 2 10]" :actual "(vec (seq (sorted-set 10 1 2)))"} + {:suite "sorted / construction & ordering" :label "sorted-map ordered entries" :expected "[[:a 1] [:b 2] [:c 3]]" :actual "(vec (seq (sorted-map :c 3 :a 1 :b 2)))"} + {:suite "sorted / construction & ordering" :label "first is min" :expected "1" :actual "(first (sorted-set 5 3 9 1))"} + {:suite "sorted / sorted?" :label "sorted-set" :expected "true" :actual "(sorted? (sorted-set 1))"} + {:suite "sorted / sorted?" :label "sorted-map" :expected "true" :actual "(sorted? (sorted-map :a 1))"} + {:suite "sorted / sorted?" :label "plain set" :expected "false" :actual "(sorted? #{1})"} + {:suite "sorted / sorted?" :label "plain map" :expected "false" :actual "(sorted? {:a 1})"} + {:suite "sorted / sorted?" :label "vector" :expected "false" :actual "(sorted? [1 2])"} + {:suite "sorted / map ops" :label "get hit" :expected "2" :actual "(get (sorted-map :a 1 :b 2) :b)"} + {:suite "sorted / map ops" :label "get miss default" :expected ":none" :actual "(get (sorted-map :a 1) :z :none)"} + {:suite "sorted / map ops" :label "contains? yes" :expected "true" :actual "(contains? (sorted-map :a 1) :a)"} + {:suite "sorted / map ops" :label "contains? no" :expected "false" :actual "(contains? (sorted-map :a 1) :z)"} + {:suite "sorted / map ops" :label "assoc keeps order" :expected "[[:a 1] [:b 2] [:c 3]]" :actual "(vec (seq (assoc (sorted-map :c 3 :a 1) :b 2)))"} + {:suite "sorted / map ops" :label "dissoc" :expected "[[:a 1] [:c 3]]" :actual "(vec (seq (dissoc (sorted-map :a 1 :b 2 :c 3) :b)))"} + {:suite "sorted / map ops" :label "conj entry" :expected "[[:a 1] [:z 9]]" :actual "(vec (seq (conj (sorted-map :a 1) [:z 9])))"} + {:suite "sorted / map ops" :label "keys sorted" :expected "[:a :b :c]" :actual "(vec (keys (sorted-map :c 3 :a 1 :b 2)))"} + {:suite "sorted / map ops" :label "vals by key" :expected "[1 2 3]" :actual "(vec (vals (sorted-map :c 3 :a 1 :b 2)))"} + {:suite "sorted / map ops" :label "map as fn" :expected "2" :actual "((sorted-map :a 1 :b 2) :b)"} + {:suite "sorted / map ops" :label "map as fn miss" :expected ":d" :actual "((sorted-map :a 1) :z :d)"} + {:suite "sorted / set ops" :label "get present" :expected "2" :actual "(get (sorted-set 1 2 3) 2)"} + {:suite "sorted / set ops" :label "get absent" :expected ":none" :actual "(get (sorted-set 1 2 3) 9 :none)"} + {:suite "sorted / set ops" :label "contains? yes" :expected "true" :actual "(contains? (sorted-set 1 2 3) 2)"} + {:suite "sorted / set ops" :label "contains? no" :expected "false" :actual "(contains? (sorted-set 1 2 3) 9)"} + {:suite "sorted / set ops" :label "conj keeps order" :expected "[0 1 2 3 5]" :actual "(vec (seq (conj (sorted-set 1 2 3) 5 0)))"} + {:suite "sorted / set ops" :label "disj" :expected "[1 3]" :actual "(vec (seq (disj (sorted-set 1 2 3) 2)))"} + {:suite "sorted / set ops" :label "set as fn" :expected "3" :actual "((sorted-set 1 2 3) 3)"} + {:suite "sorted / set ops" :label "set as fn miss" :expected "nil" :actual "((sorted-set 1 2 3) 9)"} + {:suite "sorted / by comparator" :label "sorted-set-by desc" :expected "[10 3 2 1]" :actual "(vec (seq (sorted-set-by > 1 3 2 10)))"} + {:suite "sorted / by comparator" :label "sorted-map-by desc" :expected "[[3 :c] [2 :b] [1 :a]]" :actual "(vec (seq (sorted-map-by > 1 :a 3 :c 2 :b)))"} + {:suite "sorted / by comparator" :label "conj keeps comparator" :expected "[5 3 2 1 0]" :actual "(vec (seq (conj (sorted-set-by > 1 3 2) 5 0)))"} + {:suite "sorted / by comparator" :label "assoc keeps comparator" :expected "[3 2 1]" :actual "(vec (keys (assoc (sorted-map-by > 1 :a 3 :c) 2 :b)))"} + {:suite "sorted / by comparator" :label "disj keeps comparator" :expected "[3 1]" :actual "(vec (seq (disj (sorted-set-by > 1 2 3) 2)))"} + {:suite "sorted / by comparator" :label "by-comparator is sorted?" :expected "true" :actual "(sorted? (sorted-set-by > 1 2))"} + {:suite "sorted / subseq & rsubseq" :label "subseq >=" :expected "[3 4 5]" :actual "(vec (subseq (sorted-set 1 2 3 4 5) >= 3))"} + {:suite "sorted / subseq & rsubseq" :label "subseq <" :expected "[1 2]" :actual "(vec (subseq (sorted-set 1 2 3 4 5) < 3))"} + {:suite "sorted / subseq & rsubseq" :label "subseq range" :expected "[2 3 4]" :actual "(vec (subseq (sorted-set 1 2 3 4 5) > 1 < 5))"} + {:suite "sorted / subseq & rsubseq" :label "rsubseq <=" :expected "[3 2 1]" :actual "(vec (rsubseq (sorted-set 1 2 3 4 5) <= 3))"} + {:suite "sorted / subseq & rsubseq" :label "subseq on map" :expected "[[2 :b] [3 :c]]" :actual "(vec (subseq (sorted-map 1 :a 2 :b 3 :c) > 1))"} + {:suite "sorted / subseq & rsubseq" :label "subseq empty result" :expected "nil" :actual "(subseq (sorted-set 1 2) > 5)"} + {:suite "sorted / subseq & rsubseq" :label "rsubseq on map" :expected "[[2 :b] [1 :a]]" :actual "(vec (rsubseq (sorted-map 1 :a 2 :b 3 :c) < 3))"} + {:suite "sorted / predicates" :label "sorted-map? true" :expected "true" :actual "(sorted-map? (sorted-map 1 :a))"} + {:suite "sorted / predicates" :label "sorted-map? false" :expected "false" :actual "(sorted-map? {:a 1})"} + {:suite "sorted / predicates" :label "sorted-set? true" :expected "true" :actual "(sorted-set? (sorted-set 1))"} + {:suite "sorted / predicates" :label "sorted-set? false" :expected "false" :actual "(sorted-set? #{1})"} + {:suite "sorted / predicates" :label "map? sorted-map" :expected "true" :actual "(map? (sorted-map 1 :a))"} + {:suite "sorted / predicates" :label "coll? sorted-set" :expected "true" :actual "(coll? (sorted-set 1))"} + {:suite "sorted / lookup + membership use the comparator" :label "get cross-numeric" :expected ":a" :actual "(get (sorted-map 1 :a) 1.0)"} + {:suite "sorted / lookup + membership use the comparator" :label "contains? cross-numeric" :expected "true" :actual "(contains? (sorted-set 1) 1.0)"} + {:suite "sorted / lookup + membership use the comparator" :label "conj equal elem no-op" :expected "1" :actual "(count (conj (sorted-set 1) 1.0))"} + {:suite "sorted / lookup + membership use the comparator" :label "assoc equal key replaces" :expected "[[1 :z]]" :actual "(vec (seq (assoc (sorted-map 1 :a) 1.0 :z)))"} + {:suite "sorted / lookup + membership use the comparator" :label "first sorted-map" :expected "[1 :a]" :actual "(first (sorted-map 2 :b 1 :a))"} + {:suite "sorted / lookup + membership use the comparator" :label "dissoc missing no-op" :expected "2" :actual "(count (dissoc (sorted-map 1 :a 2 :b) 9))"} + {:suite "sorted / lookup + membership use the comparator" :label "conj map merges" :expected "3" :actual "(count (conj (sorted-map 1 :a) {2 :b 3 :c}))"} + {:suite "sorted / lookup + membership use the comparator" :label "conj nil no-op" :expected "1" :actual "(count (conj (sorted-map 1 :a) nil))"} + {:suite "sorted / lookup + membership use the comparator" :label "into sorted-map" :expected "[[1 :a] [2 :b]]" :actual "(vec (seq (into (sorted-map) [[2 :b] [1 :a]])))"} + {:suite "sorted / lookup + membership use the comparator" :label "source unchanged" :expected "[1 2]" :actual "(let [s (sorted-set 1 2)] (conj s 9) (vec (seq s)))"} + {:suite "sorted / lookup + membership use the comparator" :label "sorted-map odd kvs throws" :expected :throws :actual "(sorted-map 1 :a 2)"} + {:suite "sorted / equality is representation-agnostic" :label "sorted-map = literal" :expected "true" :actual "(= (sorted-map :a 1 :b 2) {:a 1 :b 2})"} + {:suite "sorted / equality is representation-agnostic" :label "literal = sorted-map" :expected "true" :actual "(= {:a 1 :b 2} (sorted-map :a 1 :b 2))"} + {:suite "sorted / equality is representation-agnostic" :label "sorted-map = hash-map" :expected "true" :actual "(= (sorted-map :a 1) (hash-map :a 1))"} + {:suite "sorted / equality is representation-agnostic" :label "sorted-map != more keys" :expected "false" :actual "(= (sorted-map :a 1) {:a 1 :b 2})"} + {:suite "sorted / equality is representation-agnostic" :label "sorted-set = literal" :expected "true" :actual "(= (sorted-set 1 2) #{1 2})"} + {:suite "sorted / equality is representation-agnostic" :label "literal = sorted-set" :expected "true" :actual "(= #{1 2} (sorted-set 2 1))"} + {:suite "sorted / equality is representation-agnostic" :label "sorted-set != diff" :expected "false" :actual "(= (sorted-set 1 2) #{1 3})"} + {:suite "sorted / equality is representation-agnostic" :label "two sorted-maps" :expected "true" :actual "(= (sorted-map 1 :a 2 :b) (sorted-map 2 :b 1 :a))"} + {:suite "sorted / equality is representation-agnostic" :label "cmp irrelevant to =" :expected "true" :actual "(= (sorted-map-by > 1 :a 2 :b) (sorted-map 1 :a 2 :b))"} + {:suite "sorted / equality is representation-agnostic" :label "sorted-map as map key" :expected ":hit" :actual "(get {(sorted-map :a 1) :hit} {:a 1})"} + {:suite "sorted / equality is representation-agnostic" :label "sorted-set as map key" :expected ":hit" :actual "(get {(sorted-set 1 2) :hit} #{2 1})"} + {:suite "sorted / empty + empty? + rseq + printing" :label "empty? empty map" :expected "true" :actual "(empty? (sorted-map))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "empty? non-empty" :expected "false" :actual "(empty? (sorted-map 1 :a))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "empty? empty set" :expected "true" :actual "(empty? (sorted-set))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "empty keeps sortedness" :expected "true" :actual "(sorted? (empty (sorted-map 1 :a)))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "empty keeps cmp" :expected "[3 1]" :actual "(vec (seq (into (empty (sorted-set-by > 1 2)) [1 3])))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "empty set kind" :expected "true" :actual "(sorted-set? (empty (sorted-set 1)))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "rseq map" :expected "[[2 :b] [1 :a]]" :actual "(vec (rseq (sorted-map 1 :a 2 :b)))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "rseq set" :expected "[3 2 1]" :actual "(vec (rseq (sorted-set 1 2 3)))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "pr-str sorted-map" :expected "\"{1 :a, 2 :b}\"" :actual "(pr-str (sorted-map 2 :b 1 :a))"} + {:suite "sorted / empty + empty? + rseq + printing" :label "pr-str sorted-set" :expected "\"#{1 2 3}\"" :actual "(pr-str (sorted-set 3 1 2))"} + {:suite "sorted / seq fn interop" :label "map over sorted-map" :expected "[1 2 3]" :actual "(vec (map first (sorted-map 2 :b 1 :a 3 :c)))"} + {:suite "sorted / seq fn interop" :label "map over sorted-set" :expected "[2 3 4]" :actual "(vec (map inc (sorted-set 3 1 2)))"} + {:suite "sorted / seq fn interop" :label "filter entries" :expected "[[2 :b]]" :actual "(vec (filter (fn [[k v]] (even? k)) (sorted-map 1 :a 2 :b)))"} + {:suite "sorted / seq fn interop" :label "reduce over set" :expected "6" :actual "(reduce + (sorted-set 1 2 3))"} + {:suite "sorted / seq fn interop" :label "vec of sorted-set" :expected "[1 2 3]" :actual "(vec (sorted-set 3 1 2))"} + {:suite "sorted / seq fn interop" :label "into vec" :expected "[[1 :a] [2 :b]]" :actual "(into [] (sorted-map 2 :b 1 :a))"} + {:suite "sorted / seq fn interop" :label "sorted-map-by 3way cmp" :expected "[3 2 1]" :actual "(vec (keys (sorted-map-by (fn [a b] (- b a)) 1 :a 2 :b 3 :c)))"} + {:suite "io / slurp, spit, printf, flush (host-classified)" :label "slurp returns string" :expected "true" :actual "(string? (slurp \"README.md\"))"} + {:suite "io / slurp, spit, printf, flush (host-classified)" :label "slurp content" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/includes? (slurp \"README.md\") \"jolt\"))"} + {:suite "io / slurp, spit, printf, flush (host-classified)" :label "spit + slurp round" :expected "\"hello\"" :actual "(do (spit \"/tmp/jolt-spit-test.txt\" \"hello\") (slurp \"/tmp/jolt-spit-test.txt\"))"} + {:suite "io / slurp, spit, printf, flush (host-classified)" :label "spit append" :expected "\"ab\"" :actual "(do (spit \"/tmp/jolt-spit-test.txt\" \"a\") (spit \"/tmp/jolt-spit-test.txt\" \"b\" :append true) (slurp \"/tmp/jolt-spit-test.txt\"))"} + {:suite "io / slurp, spit, printf, flush (host-classified)" :label "printf formats" :expected "\"x=1 y=a\"" :actual "(with-out-str (printf \"x=%d y=%s\" 1 \"a\"))"} + {:suite "io / slurp, spit, printf, flush (host-classified)" :label "printf no newline" :expected "false" :actual "(do (require (quote [clojure.string :as s])) (s/includes? (with-out-str (printf \"%d\" 1)) \"\\n\"))"} + {:suite "io / slurp, spit, printf, flush (host-classified)" :label "flush returns nil" :expected "nil" :actual "(flush)"} + {:suite "io / slurp, spit, printf, flush (host-classified)" :label "file-seq finds files" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (boolean (some (fn [p] (s/ends-with? p \"README.md\")) (file-seq \".\"))))"} + {:suite "ns / ns-map, ns-unmap, ns-refers" :label "ns-map has var" :expected "true" :actual "(do (def nmv 1) (some? (get (ns-map (quote user)) (quote nmv))))"} + {:suite "ns / ns-map, ns-unmap, ns-refers" :label "ns-unmap removes" :expected "nil" :actual "(do (def nuv 1) (ns-unmap (quote user) (quote nuv)) (resolve (quote nuv)))"} + {:suite "ns / ns-map, ns-unmap, ns-refers" :label "ns-refers sees refer" :expected "true" :actual "(do (require (quote clojure.string)) (refer (quote clojure.string)) (some? (get (ns-refers (quote user)) (quote join))))"} + {:suite "vars / thread-binding family" :label "bound? on def" :expected "true" :actual "(do (def bvv 1) (bound? (var bvv)))"} + {:suite "vars / thread-binding family" :label "with-bindings* binds" :expected "5" :actual "(do (def ^:dynamic dynv 1) (with-bindings* (array-map (var dynv) 5) (fn [] dynv)))"} + {:suite "vars / thread-binding family" :label "with-bindings* restores" :expected "1" :actual "(do (def ^:dynamic dynw 1) (with-bindings* (array-map (var dynw) 5) (fn [] nil)) dynw)"} + {:suite "vars / thread-binding family" :label "with-bindings macro" :expected "7" :actual "(do (def ^:dynamic dynx 1) (with-bindings (array-map (var dynx) 7) dynx))"} + {:suite "vars / thread-binding family" :label "thread-bound? inside" :expected "[true false]" :actual "(do (def ^:dynamic dyny 1) [(with-bindings* (array-map (var dyny) 2) (fn [] (thread-bound? (var dyny)))) (thread-bound? (var dyny))])"} + {:suite "vars / thread-binding family" :label "bound-fn* conveys" :expected "9" :actual "(do (def ^:dynamic dynz 1) (def f (with-bindings* (array-map (var dynz) 9) (fn [] (bound-fn* (fn [] dynz))))) (f))"} + {:suite "vars / thread-binding family" :label "get-thread-bindings" :expected "3" :actual "(do (def ^:dynamic dyng 1) (with-bindings* (array-map (var dyng) 3) (fn [] (get (get-thread-bindings) (var dyng)))))"} + {:suite "eval & load-string as values" :label "load-string evals all" :expected "3" :actual "(load-string \"(def lsv 1) (+ lsv 2)\")"} + {:suite "eval & load-string as values" :label "eval as value" :expected "[2 3]" :actual "(mapv eval [(quote (+ 1 1)) (quote (+ 1 2))])"} + {:suite "eval & load-string as values" :label "eval special still works" :expected "3" :actual "(eval (quote (+ 1 2)))"} + {:suite "clojure.edn / opts" :label "set literal" :expected "#{1 2}" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string \"#{1 2}\"))"} + {:suite "clojure.edn / opts" :label "uuid tag" :expected "true" :actual "(do (require (quote [clojure.edn :as e0])) (uuid? (e0/read-string \"#uuid \\\"550e8400-e29b-41d4-a716-446655440000\\\"\")))"} + {:suite "clojure.edn / opts" :label "inst tag" :expected "true" :actual "(do (require (quote [clojure.edn :as e0])) (inst? (e0/read-string \"#inst \\\"2020-01-01T00:00:00Z\\\"\")))"} + {:suite "clojure.edn / opts" :label ":eof on empty" :expected ":end" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:eof :end} \"\"))"} + {:suite "clojure.edn / opts" :label ":readers custom tag" :expected "[:custom 5]" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:readers {(quote custom) (fn [v] [:custom v])}} \"#custom 5\"))"} + {:suite "clojure.edn / opts" :label ":readers nested" :expected "[6 8]" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:readers {(quote w) (fn [v] (* 2 v))}} \"[#w 3 #w 4]\"))"} + {:suite "clojure.edn / opts" :label ":default fn" :expected "[:dflt 7]" :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:default (fn [t v] [:dflt v])} \"#unknown 7\"))"} + {:suite "clojure.edn / opts" :label "unknown tag throws" :expected :throws :actual "(do (require (quote [clojure.edn :as e0])) (e0/read-string \"#nope 1\"))"} + {:suite "state / atoms" :label "deref @" :expected "0" :actual "(let [a (atom 0)] @a)"} + {:suite "state / atoms" :label "deref fn" :expected "0" :actual "(deref (atom 0))"} + {:suite "state / atoms" :label "reset!" :expected "5" :actual "(let [a (atom 0)] (reset! a 5) @a)"} + {:suite "state / atoms" :label "reset! returns new" :expected "5" :actual "(let [a (atom 0)] (reset! a 5))"} + {:suite "state / atoms" :label "swap!" :expected "1" :actual "(let [a (atom 0)] (swap! a inc) @a)"} + {:suite "state / atoms" :label "swap! with args" :expected "10" :actual "(let [a (atom 1)] (swap! a + 2 3 4) @a)"} + {:suite "state / atoms" :label "swap! returns new" :expected "1" :actual "(let [a (atom 0)] (swap! a inc))"} + {:suite "state / atoms" :label "swap-vals!" :expected "[0 1]" :actual "(let [a (atom 0)] (swap-vals! a inc))"} + {:suite "state / atoms" :label "reset-vals!" :expected "[0 9]" :actual "(let [a (atom 0)] (reset-vals! a 9))"} + {:suite "state / atoms" :label "compare-and-set! ok" :expected "true" :actual "(let [a (atom 0)] (compare-and-set! a 0 1))"} + {:suite "state / atoms" :label "compare-and-set! no" :expected "false" :actual "(let [a (atom 0)] (compare-and-set! a 9 1))"} + {:suite "state / atoms" :label "atom?" :expected "true" :actual "(do (require (quote [clojure.core])) (instance? clojure.lang.Atom (atom 0)))"} + {:suite "state / atoms" :label "atom? predicate" :expected "true" :actual "(atom? (atom 0))"} + {:suite "state / atoms" :label "atom? on non-atom" :expected "false" :actual "(atom? 5)"} + {:suite "state / watches & validators" :label "add-watch fires" :expected "1" :actual "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (reset! seen 1))) (reset! a 5) @seen)"} + {:suite "state / watches & validators" :label "remove-watch" :expected "0" :actual "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (swap! seen inc))) (remove-watch a :k) (reset! a 5) @seen)"} + {:suite "state / watches & validators" :label "set-validator! ok" :expected "5" :actual "(let [a (atom 0)] (set-validator! a number?) (reset! a 5) @a)"} + {:suite "state / watches & validators" :label "set-validator! rejects" :expected :throws :actual "(let [a (atom 0)] (set-validator! a pos?) (reset! a -1))"} + {:suite "state / watches & validators" :label "get-validator" :expected "true" :actual "(let [a (atom 0)] (set-validator! a number?) (fn? (get-validator a)))"} + {:suite "state / volatiles & delays" :label "volatile! deref" :expected "0" :actual "(let [v (volatile! 0)] @v)"} + {:suite "state / volatiles & delays" :label "vreset!" :expected "5" :actual "(let [v (volatile! 0)] (vreset! v 5) @v)"} + {:suite "state / volatiles & delays" :label "vswap!" :expected "1" :actual "(let [v (volatile! 0)] (vswap! v inc) @v)"} + {:suite "state / volatiles & delays" :label "delay not forced" :expected "0" :actual "(let [c (atom 0) d (delay (swap! c inc))] @c)"} + {:suite "state / volatiles & delays" :label "delay force once" :expected "1" :actual "(let [c (atom 0) d (delay (swap! c inc))] (force d) (force d) @c)"} + {:suite "state / volatiles & delays" :label "delay value" :expected "5" :actual "(let [d (delay 5)] @d)"} + {:suite "state / volatiles & delays" :label "realized? before" :expected "false" :actual "(let [d (delay 5)] (realized? d))"} + {:suite "state / volatiles & delays" :label "realized? after" :expected "true" :actual "(let [d (delay 5)] (force d) (realized? d))"} + {:suite "state / promises" :label "promise deliver" :expected "5" :actual "(let [p (promise)] (deliver p 5) @p)"} + {:suite "state / promises" :label "promise undelivered" :expected "nil" :actual "(let [p (promise)] @p)"} + {:suite "state / agents (synchronous shim)" :label "agent deref" :expected "0" :actual "(deref (agent 0))"} + {:suite "state / agents (synchronous shim)" :label "agent with opts" :expected "0" :actual "(deref (agent 0 :error-mode :continue))"} + {:suite "state / agents (synchronous shim)" :label "send-off applies" :expected "0" :actual "(let [a (agent 0)] (send-off a + 5) (deref a))"} + {:suite "state / agents (synchronous shim)" :label "send applies" :expected "1" :actual "(let [a (agent 1)] (send a + 6) (deref a))"} + {:suite "state / agents (synchronous shim)" :label "agent-error nil" :expected "nil" :actual "(agent-error (agent 0))"} + {:suite "string / str & basics" :label "str concat" :expected "\"abc\"" :actual "(str \"a\" \"b\" \"c\")"} + {:suite "string / str & basics" :label "str of numbers" :expected "\"12\"" :actual "(str 1 2)"} + {:suite "string / str & basics" :label "str nil is empty" :expected "\"\"" :actual "(str nil)"} + {:suite "string / str & basics" :label "str mixed" :expected "\"a1:b\"" :actual "(str \"a\" 1 :b)"} + {:suite "string / str & basics" :label "str of coll" :expected "\"[1 2]\"" :actual "(str [1 2])"} + {:suite "string / str & basics" :label "count" :expected "3" :actual "(count \"abc\")"} + {:suite "string / str & basics" :label "subs from" :expected "\"bc\"" :actual "(subs \"abc\" 1)"} + {:suite "string / str & basics" :label "subs range" :expected "\"b\"" :actual "(subs \"abc\" 1 2)"} + {:suite "string / str & basics" :label "string? true" :expected "true" :actual "(string? \"x\")"} + {:suite "string / str & basics" :label "pr-str vector" :expected "\"[1 2 3]\"" :actual "(pr-str [1 2 3])"} + {:suite "string / str & basics" :label "pr-str quotes str" :expected "\"\\\"hi\\\"\"" :actual "(pr-str \"hi\")"} + {:suite "string / str & basics" :label "pr-str of a var" :expected "\"#'user/vv\"" :actual "(pr-str (def vv 1))"} + {:suite "string / str & basics" :label "str of a var" :expected "\"#'user/ww\"" :actual "(str (def ww 2))"} + {:suite "string / str & basics" :label "pr-str of a defn" :expected "\"#'user/gg\"" :actual "(pr-str (defn gg [x] x))"} + {:suite "string / str & basics" :label "seq of string" :expected "[\\a \\b]" :actual "(seq \"ab\")"} + {:suite "string as a seqable of chars (jolt-dl4s)" :label "vec of string" :expected "[\\a \\b]" :actual "(vec \"ab\")"} + {:suite "string as a seqable of chars (jolt-dl4s)" :label "into [] of string" :expected "[\\a \\b]" :actual "(into [] \"ab\")"} + {:suite "string as a seqable of chars (jolt-dl4s)" :label "set of string" :expected "true" :actual "(= #{\\a \\b} (set \"ab\"))"} + {:suite "string as a seqable of chars (jolt-dl4s)" :label "into #{} of string" :expected "true" :actual "(= #{\\a \\b} (into #{} \"ab\"))"} + {:suite "string as a seqable of chars (jolt-dl4s)" :label "set dedups chars" :expected "2" :actual "(count (set \"aab\"))"} + {:suite "string as a seqable of chars (jolt-dl4s)" :label "mapv over string" :expected "[\\a \\b]" :actual "(mapv identity \"ab\")"} + {:suite "clojure.string / split limit (jolt-ik3a)" :label "neg keeps trailing" :expected "[\"a\" \"\" \"\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\" -1))"} + {:suite "clojure.string / split limit (jolt-ik3a)" :label "zero trims trailing" :expected "[\"a\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\" 0))"} + {:suite "clojure.string / split limit (jolt-ik3a)" :label "omitted trims" :expected "[\"a\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\"))"} + {:suite "clojure.string / split limit (jolt-ik3a)" :label "positive caps parts" :expected "[\"a\" \"b,c\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,b,c\" #\",\" 2))"} + {:suite "clojure.string / split limit (jolt-ik3a)" :label "empty string" :expected "[\"\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"\" #\",\"))"} + {:suite "clojure.string / split limit (jolt-ik3a)" :label "interior empties kept" :expected "[\"a\" \"\" \"b\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,,b\" #\",\"))"} + {:suite "clojure.string" :label "join" :expected "\"a,b,c\"" :actual "(do (require (quote [clojure.string :as s])) (s/join \",\" [\"a\" \"b\" \"c\"]))"} + {:suite "clojure.string" :label "join no sep" :expected "\"abc\"" :actual "(do (require (quote [clojure.string :as s])) (s/join [\"a\" \"b\" \"c\"]))"} + {:suite "clojure.string" :label "split" :expected "[\"a\" \"b\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,b\" #\",\"))"} + {:suite "clojure.string" :label "split-lines" :expected "[\"a\" \"b\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split-lines \"a\\nb\"))"} + {:suite "clojure.string" :label "upper-case" :expected "\"ABC\"" :actual "(do (require (quote [clojure.string :as s])) (s/upper-case \"abc\"))"} + {:suite "clojure.string" :label "lower-case" :expected "\"abc\"" :actual "(do (require (quote [clojure.string :as s])) (s/lower-case \"ABC\"))"} + {:suite "clojure.string" :label "capitalize" :expected "\"Abc\"" :actual "(do (require (quote [clojure.string :as s])) (s/capitalize \"abc\"))"} + {:suite "clojure.string" :label "trim" :expected "\"x\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim \" x \"))"} + {:suite "clojure.string" :label "triml" :expected "\"x \"" :actual "(do (require (quote [clojure.string :as s])) (s/triml \" x \"))"} + {:suite "clojure.string" :label "blank? true" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/blank? \" \"))"} + {:suite "clojure.string" :label "blank? false" :expected "false" :actual "(do (require (quote [clojure.string :as s])) (s/blank? \"x\"))"} + {:suite "clojure.string" :label "includes?" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/includes? \"hello\" \"ell\"))"} + {:suite "clojure.string" :label "starts-with?" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/starts-with? \"hello\" \"he\"))"} + {:suite "clojure.string" :label "ends-with?" :expected "true" :actual "(do (require (quote [clojure.string :as s])) (s/ends-with? \"hello\" \"lo\"))"} + {:suite "clojure.string" :label "replace" :expected "\"hexxo\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" \"l\" \"x\"))"} + {:suite "clojure.string" :label "reverse" :expected "\"cba\"" :actual "(do (require (quote [clojure.string :as s])) (s/reverse \"abc\"))"} + {:suite "clojure.string" :label "index-of" :expected "2" :actual "(do (require (quote [clojure.string :as s])) (s/index-of \"hello\" \"l\"))"} + {:suite "string / subs strictness" :label "subs basic" :expected "\"bcd\"" :actual "(subs \"abcde\" 1 4)"} + {:suite "string / subs strictness" :label "subs to end" :expected "\"cde\"" :actual "(subs \"abcde\" 2)"} + {:suite "string / subs strictness" :label "subs start>end" :expected :throws :actual "(subs \"abcde\" 2 1)"} + {:suite "string / subs strictness" :label "subs negative" :expected :throws :actual "(subs \"abcde\" -1)"} + {:suite "string / subs strictness" :label "subs end past len" :expected :throws :actual "(subs \"abcde\" 1 6)"} + {:suite "string / subs strictness" :label "subs nil start" :expected :throws :actual "(subs \"abcde\" nil 2)"} + {:suite "string / subs strictness" :label "subs on nil" :expected :throws :actual "(subs nil 1 2)"} + {:suite "string / namespace-munge" :label "hyphens to underscores" :expected "\"a_b_c\"" :actual "(namespace-munge \"a-b-c\")"} + {:suite "string / namespace-munge" :label "from a symbol" :expected "\"foo_bar\"" :actual "(namespace-munge (quote foo-bar))"} + {:suite "string / namespace-munge" :label "no hyphens unchanged" :expected "\"ok\"" :actual "(namespace-munge \"ok\")"} + {:suite "strings / get indexes a string" :label "get returns the char" :expected "true" :actual "(= (get \"a:b\" 1) \\:)"} + {:suite "strings / get indexes a string" :label "get first char" :expected "\\a" :actual "(get \"abc\" 0)"} + {:suite "strings / get indexes a string" :label "get out of range nil" :expected "nil" :actual "(get \"abc\" 9)"} + {:suite "strings / get indexes a string" :label "get negative nil" :expected "nil" :actual "(get \"abc\" -1)"} + {:suite "strings / get indexes a string" :label "get default honored" :expected ":none" :actual "(get \"abc\" 9 :none)"} + {:suite "clojure.string / trim-newline" :label "trailing newline" :expected "\"x\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"x\\n\"))"} + {:suite "clojure.string / trim-newline" :label "trailing \\r\\n" :expected "\"x\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"x\\r\\n\"))"} + {:suite "clojure.string / trim-newline" :label "no trailing" :expected "\"ab\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"ab\"))"} + {:suite "clojure.string / trim-newline" :label "only newlines" :expected "\"\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"\\n\\n\"))"} + {:suite "clojure.string / trim-newline" :label "interior kept" :expected "\"a\\nb\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim-newline \"a\\nb\\n\"))"} + {:suite "transducers / into" :label "map xform" :expected "[2 3 4]" :actual "(into [] (map inc) [1 2 3])"} + {:suite "transducers / into" :label "filter xform" :expected "[2 4]" :actual "(into [] (filter even?) [1 2 3 4])"} + {:suite "transducers / into" :label "remove xform" :expected "[1 3]" :actual "(into [] (remove even?) [1 2 3 4])"} + {:suite "transducers / into" :label "take xform" :expected "[1 2]" :actual "(into [] (take 2) [1 2 3 4])"} + {:suite "transducers / into" :label "drop xform" :expected "[3 4]" :actual "(into [] (drop 2) [1 2 3 4])"} + {:suite "transducers / into" :label "take-while xform" :expected "[1 2]" :actual "(into [] (take-while (fn [x] (< x 3))) [1 2 3 1])"} + {:suite "transducers / into" :label "keep xform" :expected "[1 3]" :actual "(into [] (keep (fn [x] (if (odd? x) x nil))) [1 2 3 4])"} + {:suite "transducers / into" :label "map-indexed xform" :expected "[[0 :a] [1 :b]]" :actual "(into [] (map-indexed vector) [:a :b])"} + {:suite "transducers / into" :label "mapcat xform" :expected "[1 1 2 2]" :actual "(into [] (mapcat (fn [x] [x x])) [1 2])"} + {:suite "transducers / into" :label "cat xform" :expected "[1 2 3 4]" :actual "(into [] cat [[1 2] [3 4]])"} + {:suite "transducers / into" :label "into a set" :expected "#{4 3 2}" :actual "(into #{} (map inc) [1 2 3])"} + {:suite "transducers / compose" :label "comp map+filter" :expected "[2 4 6 8]" :actual "(into [] (comp (map (fn [x] (* x 2))) (filter even?)) [1 2 3 4])"} + {:suite "transducers / compose" :label "comp filter+map" :expected "[2 4]" :actual "(into [] (comp (filter odd?) (map inc)) [1 2 3 4])"} + {:suite "transducers / compose" :label "comp three" :expected "[2]" :actual "(into [] (comp (map inc) (filter even?) (take 1)) [1 2 3 4])"} + {:suite "transducers / transduce & sequence" :label "transduce sum" :expected "9" :actual "(transduce (map inc) + [1 2 3])"} + {:suite "transducers / transduce & sequence" :label "transduce init" :expected "19" :actual "(transduce (map inc) + 10 [1 2 3])"} + {:suite "transducers / transduce & sequence" :label "transduce filter" :expected "6" :actual "(transduce (filter even?) + [1 2 3 4])"} + {:suite "transducers / transduce & sequence" :label "sequence xform" :expected "[2 3 4]" :actual "(sequence (map inc) [1 2 3])"} + {:suite "transducers / transduce & sequence" :label "eduction" :expected "[2 3 4]" :actual "(into [] (eduction (map inc) [1 2 3]))"} + {:suite "transducers / transduce & sequence" :label "completing" :expected "9" :actual "(transduce (map inc) (completing +) 0 [1 2 3])"} + {:suite "transducers / halt-when" :label "halt returns the halting input" :expected "7" :actual "(transduce (halt-when (fn [x] (> x 5))) conj [1 2 7 3])"} + {:suite "transducers / halt-when" :label "no halt is a plain reduction" :expected "[1 2 3]" :actual "(transduce (halt-when (fn [x] (> x 5))) conj [1 2 3])"} + {:suite "transducers / halt-when" :label "retf combines acc and input" :expected "[[1 2] 7]" :actual "(transduce (halt-when (fn [x] (> x 5)) (fn [r i] [r i])) conj [1 2 7 3])"} + {:suite "transducers / halt-when" :label "halt-when through into" :expected "3" :actual "(into [] (halt-when odd?) [2 4 3 6])"} + {:suite "transducers / short-circuit over infinite seqs" :label "into take (range)" :expected "[0 1 2 3 4]" :actual "(into [] (take 5) (range))"} + {:suite "transducers / short-circuit over infinite seqs" :label "transduce take (range)" :expected "3" :actual "(transduce (take 3) + 0 (range))"} + {:suite "transducers / short-circuit over infinite seqs" :label "sequence take (range)" :expected "[0 1 2 3 4]" :actual "(sequence (take 5) (range))"} + {:suite "transducers / short-circuit over infinite seqs" :label "take-while over (range)" :expected "[0 1 2]" :actual "(into [] (take-while (fn [x] (< x 3))) (range))"} + {:suite "transducers / short-circuit over infinite seqs" :label "comp take over (range)" :expected "[1 3 5]" :actual "(into [] (comp (filter odd?) (take 3)) (range))"} + {:suite "transducers / short-circuit over infinite seqs" :label "into take iterate" :expected "[0 1 2 3 4]" :actual "(into [] (take 5) (iterate inc 0))"} + {:suite "reduce / honors reduced" :label "reduced short-circuits inf" :expected "105" :actual "(reduce (fn [a x] (if (> a 100) (reduced a) (+ a x))) 0 (range))"} + {:suite "reduce / honors reduced" :label "reduce take inf" :expected "10" :actual "(reduce + (take 5 (range)))"} + {:suite "reduce / honors reduced" :label "reduce no-init first elem" :expected "6" :actual "(reduce + [1 2 3])"} + {:suite "reduce / honors reduced" :label "reduce no-init single" :expected "42" :actual "(reduce + [42])"} + {:suite "reduce / honors reduced" :label "reduce empty calls f" :expected "0" :actual "(reduce + [])"} + {:suite "reduce / honors reduced" :label "reduce with-init" :expected "16" :actual "(reduce + 10 [1 2 3])"} + {:suite "reduce / honors reduced" :label "reduce reduced immediate" :expected ":x" :actual "(reduce (fn [a x] (reduced :x)) :init [1 2 3])"} + {:suite "transducers / into & eduction (overlay)" :label "into list prepends" :expected "[4 3 1 2]" :actual "(into (quote (1 2)) [3 4])"} + {:suite "transducers / into & eduction (overlay)" :label "into sorted-map" :expected "{1 :a, 2 :b}" :actual "(into (sorted-map) [[2 :b] [1 :a]])"} + {:suite "transducers / into & eduction (overlay)" :label "into from map entry" :expected "[:a 1]" :actual "(into [] (first {:a 1}))"} + {:suite "transducers / into & eduction (overlay)" :label "into xform on map" :expected "{:a 2}" :actual "(into {} (map (fn [e] [(key e) (inc (val e))])) {:a 1})"} + {:suite "transducers / into & eduction (overlay)" :label "eduction multiple xforms" :expected "[4]" :actual "(into [] (eduction (filter odd?) (map inc) [2 3 4]))"} + {:suite "transducers / into & eduction (overlay)" :label "->Eduction" :expected "[2 3]" :actual "(->Eduction (map inc) [1 2])"} + {:suite "transducers / into & eduction (overlay)" :label "transduce no init uses (f)" :expected "5" :actual "(transduce (map inc) + [1 2])"} + {:suite "transient / vector" :label "conj! then persistent!" :expected "[1 2]" :actual "(persistent! (conj! (conj! (transient []) 1) 2))"} + {:suite "transient / vector" :label "reduce conj!" :expected "[0 1 2 3 4]" :actual "(persistent! (reduce conj! (transient []) (range 5)))"} + {:suite "transient / vector" :label "conj! many args" :expected "[1 2 3]" :actual "(persistent! (conj! (transient [1]) 2 3))"} + {:suite "transient / vector" :label "assoc! existing" :expected "[1 9 3]" :actual "(persistent! (assoc! (transient [1 2 3]) 1 9))"} + {:suite "transient / vector" :label "assoc! at count grows" :expected "[1 2 3]" :actual "(persistent! (assoc! (transient [1 2]) 2 3))"} + {:suite "transient / vector" :label "pop!" :expected "[1 2]" :actual "(persistent! (pop! (transient [1 2 3])))"} + {:suite "transient / vector" :label "from existing vector" :expected "[1 2 3 4]" :actual "(persistent! (conj! (transient [1 2 3]) 4))"} + {:suite "transient / vector" :label "count" :expected "3" :actual "(count (transient [1 2 3]))"} + {:suite "transient / vector" :label "nth" :expected "2" :actual "(nth (transient [1 2 3]) 1)"} + {:suite "transient / vector" :label "get" :expected "2" :actual "(get (transient [1 2 3]) 1)"} + {:suite "transient / vector" :label "persistent! is a vector" :expected "true" :actual "(vector? (persistent! (transient [1])))"} + {:suite "transient / vector" :label "transient? true" :expected "true" :actual "(transient? (transient []))"} + {:suite "transient / vector" :label "transient? false" :expected "false" :actual "(transient? [1 2])"} + {:suite "transient / map" :label "assoc! then persistent!" :expected "{:a 1, :b 2}" :actual "(persistent! (assoc! (assoc! (transient {}) :a 1) :b 2))"} + {:suite "transient / map" :label "assoc! many" :expected "{:a 1, :b 2}" :actual "(persistent! (assoc! (transient {}) :a 1 :b 2))"} + {:suite "transient / map" :label "dissoc!" :expected "{:b 2}" :actual "(persistent! (dissoc! (transient {:a 1 :b 2}) :a))"} + {:suite "transient / map" :label "conj! map entry" :expected "{:a 1}" :actual "(persistent! (conj! (transient {}) [:a 1]))"} + {:suite "transient / map" :label "from existing map" :expected "{:a 1, :b 2}" :actual "(persistent! (assoc! (transient {:a 1}) :b 2))"} + {:suite "transient / map" :label "get" :expected "1" :actual "(get (transient {:a 1}) :a)"} + {:suite "transient / map" :label "get missing default" :expected ":x" :actual "(get (transient {:a 1}) :z :x)"} + {:suite "transient / map" :label "contains?" :expected "true" :actual "(contains? (transient {:a 1}) :a)"} + {:suite "transient / map" :label "count" :expected "2" :actual "(count (transient {:a 1 :b 2}))"} + {:suite "transient / map" :label "collection key by value" :expected ":v" :actual "(get (persistent! (assoc! (transient {}) [1 2] :v)) [1 2])"} + {:suite "transient / map" :label "persistent! is a map" :expected "true" :actual "(map? (persistent! (transient {:a 1})))"} + {:suite "transient / map" :label "reduce build" :expected "{0 0, 1 1, 2 2}" :actual "(persistent! (reduce (fn [t i] (assoc! t i i)) (transient {}) (range 3)))"} + {:suite "transient / set" :label "conj! dedups" :expected "#{1 2 3}" :actual "(persistent! (conj! (transient #{}) 1 2 2 3))"} + {:suite "transient / set" :label "disj!" :expected "#{1 3}" :actual "(persistent! (disj! (transient #{1 2 3}) 2))"} + {:suite "transient / set" :label "from existing set" :expected "#{1 3 2}" :actual "(persistent! (conj! (transient #{1 2}) 3))"} + {:suite "transient / set" :label "contains?" :expected "true" :actual "(contains? (transient #{1 2}) 1)"} + {:suite "transient / set" :label "count" :expected "2" :actual "(count (transient #{1 2}))"} + {:suite "transient / set" :label "persistent! is a set" :expected "true" :actual "(set? (persistent! (transient #{1})))"} + {:suite "transient / set" :label "map elements by value" :expected "1" :actual "(count (persistent! (conj! (transient #{}) {:a 1} (hash-map :a 1))))"} + {:suite "transient / immutability of source" :label "source vector unchanged" :expected "true" :actual "(let [v [1 2 3] _ (persistent! (conj! (transient v) 4))] (= v [1 2 3]))"} + {:suite "transient / immutability of source" :label "source map unchanged" :expected "true" :actual "(let [m {:a 1} _ (persistent! (assoc! (transient m) :b 2))] (= m {:a 1}))"} + {:suite "transient / invokable lookup" :label "vector index" :expected "20" :actual "((transient [10 20 30]) 1)"} + {:suite "transient / invokable lookup" :label "map key as fn" :expected "7" :actual "((transient {:x 7}) :x)"} + {:suite "transient / invokable lookup" :label "map key default" :expected "99" :actual "((transient {:x 7}) :z 99)"} + {:suite "transient / invokable lookup" :label "keyword on transient" :expected "7" :actual "(:x (transient {:x 7}))"} + {:suite "transient / invokable lookup" :label "set membership" :expected "2" :actual "((transient #{1 2 3}) 2)"} + {:suite "transient / invokable lookup" :label "set miss default" :expected ":no" :actual "((transient #{1 2 3}) 42 :no)"} + {:suite "transient / invokable lookup" :label "collection key" :expected ":v" :actual "((transient {[1 2] :v}) [1 2])"} + {:suite "transient / assoc! odd args throw" :label "map dangling key" :expected "{:a 1, :b nil}" :actual "(persistent! (assoc! (transient {}) :a 1 :b))"} + {:suite "transient / assoc! odd args throw" :label "map lone key" :expected :throws :actual "(persistent! (assoc! (transient {}) :a))"} + {:suite "transient / assoc! odd args throw" :label "vector dangling" :expected "[9 nil]" :actual "(persistent! (apply assoc! (transient []) [0 9 1]))"} + {:suite "transient / assoc! odd args throw" :label "even args still ok" :expected "true" :actual "(= {:a 1, :b 2} (persistent! (assoc! (transient {}) :a 1 :b 2)))"} + {:suite "transient / invalidation" :label "conj! after persistent!" :expected :throws :actual "(let [t (transient [])] (persistent! t) (conj! t 1))"} + {:suite "transient / invalidation" :label "assoc! after persistent!" :expected :throws :actual "(let [t (transient {})] (persistent! t) (assoc! t :a 1))"} + {:suite "transient / invalidation" :label "persistent! twice" :expected :throws :actual "(let [t (transient [])] (persistent! t) (persistent! t))"} + {:suite "transient / invalidation" :label "pop! empty" :expected :throws :actual "(pop! (transient []))"} + {:suite "transient / strictness" :label "conj! on persistent" :expected :throws :actual "(conj! [1 2] 3)"} + {:suite "transient / strictness" :label "assoc! on persistent" :expected :throws :actual "(assoc! {:a 1} :b 2)"} + {:suite "transient / strictness" :label "persistent! on vector" :expected :throws :actual "(persistent! [1 2])"} + {:suite "transient / strictness" :label "persistent! on nil" :expected :throws :actual "(persistent! nil)"} + {:suite "transient / strictness" :label "pop! on transient map" :expected :throws :actual "(pop! (transient {:a 1}))"} + {:suite "transient / strictness" :label "dissoc! on tset" :expected :throws :actual "(dissoc! (transient #{1}) 1)"} + {:suite "transient / strictness" :label "conj! map bad item" :expected :throws :actual "(conj! (transient {}) #{:a 1})"} + {:suite "transient / strictness" :label "conj! no args" :expected "[]" :actual "(persistent! (conj!))"} + {:suite "transient / strictness" :label "conj! identity" :expected "[1 2]" :actual "(conj! [1 2])"} + {:suite "transient / strictness" :label "conj! map merges map" :expected "{:a 1, :b 2}" :actual "(persistent! (conj! (transient {:a 1}) {:b 2}))"} + {:suite "transient / assoc! bounds" :label "assoc! existing idx" :expected "[1 9 3]" :actual "(persistent! (assoc! (transient [1 2 3]) 1 9))"} + {:suite "transient / assoc! bounds" :label "assoc! at count grows" :expected "[1 2 3]" :actual "(persistent! (assoc! (transient [1 2]) 2 3))"} + {:suite "transient / assoc! bounds" :label "assoc! out of bounds" :expected :throws :actual "(assoc! (transient [0 1 2]) 4 4)"} + {:suite "transient / assoc! bounds" :label "assoc! negative" :expected :throws :actual "(assoc! (transient []) -1 0)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "nil is falsy" :expected ":f" :actual "(if nil :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "false is falsy" :expected ":f" :actual "(if false :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "zero is truthy" :expected ":t" :actual "(if 0 :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "zero float truthy" :expected ":t" :actual "(if 0.0 :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "empty string truthy" :expected ":t" :actual "(if \"\" :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "empty list truthy" :expected ":t" :actual "(if (list) :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "empty vector truthy" :expected ":t" :actual "(if [] :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "empty map truthy" :expected ":t" :actual "(if {} :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "empty set truthy" :expected ":t" :actual "(if #{} :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "number truthy" :expected ":t" :actual "(if 42 :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "string truthy" :expected ":t" :actual "(if \"x\" :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "keyword truthy" :expected ":t" :actual "(if :kw :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "symbol truthy" :expected ":t" :actual "(if (quote abc) :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "coll truthy" :expected ":t" :actual "(if [1 2] :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "map truthy" :expected ":t" :actual "(if {:a 1} :t :f)"} + {:suite "truthiness / if (only nil & false are falsy)" :label "if no else -> nil" :expected "nil" :actual "(if false :t)"} + {:suite "truthiness / not" :label "not nil" :expected "true" :actual "(not nil)"} + {:suite "truthiness / not" :label "not false" :expected "true" :actual "(not false)"} + {:suite "truthiness / not" :label "not zero" :expected "false" :actual "(not 0)"} + {:suite "truthiness / not" :label "not empty vector" :expected "false" :actual "(not [])"} + {:suite "truthiness / not" :label "not empty string" :expected "false" :actual "(not \"\")"} + {:suite "truthiness / not" :label "not number" :expected "false" :actual "(not 42)"} + {:suite "truthiness / not" :label "not true" :expected "false" :actual "(not true)"} + {:suite "truthiness / and" :label "empty is true" :expected "true" :actual "(and)"} + {:suite "truthiness / and" :label "single value" :expected "5" :actual "(and 5)"} + {:suite "truthiness / and" :label "all truthy -> last" :expected "3" :actual "(and 1 2 3)"} + {:suite "truthiness / and" :label "stops at false" :expected "false" :actual "(and 1 false 3)"} + {:suite "truthiness / and" :label "stops at nil" :expected "nil" :actual "(and 1 nil 3)"} + {:suite "truthiness / and" :label "false alone" :expected "false" :actual "(and false)"} + {:suite "truthiness / and" :label "nil alone" :expected "nil" :actual "(and nil)"} + {:suite "truthiness / and" :label "zero is truthy" :expected "0" :actual "(and 1 0)"} + {:suite "truthiness / or" :label "empty is nil" :expected "nil" :actual "(or)"} + {:suite "truthiness / or" :label "first truthy" :expected "1" :actual "(or 1 2)"} + {:suite "truthiness / or" :label "skips nil/false" :expected "5" :actual "(or nil false 5)"} + {:suite "truthiness / or" :label "all falsy -> last" :expected "false" :actual "(or nil false)"} + {:suite "truthiness / or" :label "nil chain -> false" :expected "false" :actual "(or nil nil nil false)"} + {:suite "truthiness / or" :label "zero is truthy" :expected "0" :actual "(or 0 1)"} + {:suite "truthiness / or" :label "false alone" :expected "false" :actual "(or false)"} + {:suite "truthiness / if-not & boolean" :label "if-not false" :expected ":yes" :actual "(if-not false :yes :no)"} + {:suite "truthiness / if-not & boolean" :label "if-not truthy" :expected ":no" :actual "(if-not 0 :yes :no)"} + {:suite "truthiness / if-not & boolean" :label "when-not nil" :expected "1" :actual "(when-not nil 1)"} + {:suite "truthiness / if-not & boolean" :label "when-not truthy" :expected "nil" :actual "(when-not 5 1)"} + {:suite "truthiness / if-not & boolean" :label "boolean of nil" :expected "false" :actual "(boolean nil)"} + {:suite "truthiness / if-not & boolean" :label "boolean of false" :expected "false" :actual "(boolean false)"} + {:suite "truthiness / if-not & boolean" :label "boolean of 0" :expected "true" :actual "(boolean 0)"} + {:suite "truthiness / if-not & boolean" :label "boolean of value" :expected "true" :actual "(boolean :x)"} + {:suite "truthiness / if-not & boolean" :label "true?/false?" :expected "true" :actual "(and (true? true) (false? false) (not (true? 1)))"} + {:suite "untested / primed + division + bit ops" :label "+'" :expected "3" :actual "(+' 1 2)"} + {:suite "untested / primed + division + bit ops" :label "-'" :expected "3" :actual "(-' 5 2)"} + {:suite "untested / primed + division + bit ops" :label "*'" :expected "12" :actual "(*' 3 4)"} + {:suite "untested / primed + division + bit ops" :label "inc'" :expected "2.5" :actual "(inc' 1.5)"} + {:suite "untested / primed + division + bit ops" :label "dec'" :expected "1.5" :actual "(dec' 2.5)"} + {:suite "untested / primed + division + bit ops" :label "/" :expected "2" :actual "(/ 6 3)"} + {:suite "untested / primed + division + bit ops" :label "/ ratio-as-double" :expected "1/2" :actual "(/ 1 2)"} + {:suite "untested / primed + division + bit ops" :label "bit-not" :expected "-6" :actual "(bit-not 5)"} + {:suite "untested / primed + division + bit ops" :label "bit-and-not" :expected "4" :actual "(bit-and-not 12 10)"} + {:suite "untested / primed + division + bit ops" :label "bit-flip" :expected "3" :actual "(bit-flip 2 0)"} + {:suite "untested / primed + division + bit ops" :label "unsigned-bit-shift-right" :expected "2" :actual "(unsigned-bit-shift-right 8 2)"} + {:suite "untested / hash family" :label "hash stable" :expected "true" :actual "(= (hash :a) (hash :a))"} + {:suite "untested / hash family" :label "hash int" :expected "true" :actual "(int? (hash [1 2]))"} + {:suite "untested / hash family" :label "hash-combine" :expected "true" :actual "(int? (hash-combine 1 2))"} + {:suite "untested / hash family" :label "hash-ordered-coll" :expected "true" :actual "(int? (hash-ordered-coll [1 2]))"} + {:suite "untested / hash family" :label "hash-unordered-coll" :expected "true" :actual "(int? (hash-unordered-coll #{1}))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "make-array" :expected "[nil nil nil]" :actual "(vec (make-array Object 3))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "into-array" :expected "[1 2]" :actual "(vec (into-array [1 2]))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "to-array" :expected "[1 2]" :actual "(vec (to-array [1 2]))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aclone vec" :expected "[1 2]" :actual "(vec (aclone (int-array [1 2])))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aclone independent" :expected "[9 2]" :actual "(let [a (aclone (to-array [1 2]))] (aset a 0 9) (seq a))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset/aget" :expected "9" :actual "(let [a (to-array [1 2 3])] (aset a 0 9) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset-int" :expected "7" :actual "(let [a (to-array [1 2])] (aset-int a 0 7) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset-boolean" :expected "true" :actual "(let [a (to-array [1])] (aset-boolean a 0 true) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset-byte" :expected "9" :actual "(let [a (to-array [0])] (aset-byte a 0 9) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset-char" :expected "\\a" :actual "(let [a (to-array [0])] (aset-char a 0 \\a) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset-double" :expected "1.5" :actual "(let [a (to-array [0])] (aset-double a 0 1.5) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset-float" :expected "2.5" :actual "(let [a (to-array [0])] (aset-float a 0 2.5) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset-long" :expected "3" :actual "(let [a (to-array [0])] (aset-long a 0 3) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "aset-short" :expected "4" :actual "(let [a (to-array [0])] (aset-short a 0 4) (aget a 0))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "boolean-array" :expected "[false false]" :actual "(vec (boolean-array 2))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "int-array" :expected "[1 2]" :actual "(vec (int-array [1 2]))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "long-array" :expected "[0 0]" :actual "(vec (long-array 2))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "double-array" :expected "[0.0 0.0]" :actual "(vec (double-array 2))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "float-array" :expected "[0.0 0.0]" :actual "(vec (float-array 2))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "short-array" :expected "[0 0]" :actual "(vec (short-array 2))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "char-array count" :expected "2" :actual "(count (char-array 2))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "byte-array bytes?" :expected "true" :actual "(bytes? (byte-array 2))"} + {:suite "untested / array stubs (vectors + host buffers)" :label "bytes? not vec" :expected "false" :actual "(bytes? [1])"} + {:suite "untested / typed coercion views" :label "booleans" :expected "(quote (true))" :actual "(booleans [true])"} + {:suite "untested / typed coercion views" :label "doubles" :expected "[1.0]" :actual "(vec (doubles (double-array [1.0])))"} + {:suite "untested / typed coercion views" :label "floats" :expected "[1.0]" :actual "(vec (floats (float-array [1.0])))"} + {:suite "untested / typed coercion views" :label "ints" :expected "(quote (1))" :actual "(ints [1])"} + {:suite "untested / typed coercion views" :label "longs" :expected "(quote (1))" :actual "(longs [1])"} + {:suite "untested / typed coercion views" :label "shorts" :expected "(quote (1))" :actual "(shorts [1])"} + {:suite "untested / typed coercion views" :label "chars first" :expected "\\a" :actual "(first (chars [\\a]))"} + {:suite "untested / typed coercion views" :label "bytes view" :expected "true" :actual "(bytes? (bytes [65]))"} + {:suite "untested / typed coercion views" :label "byte" :expected "65" :actual "(byte 65)"} + {:suite "untested / typed coercion views" :label "short" :expected "1" :actual "(short 1)"} + {:suite "untested / typed coercion views" :label "long truncates" :expected "1" :actual "(long 1.7)"} + {:suite "untested / typed coercion views" :label "double" :expected "3.0" :actual "(double 3)"} + {:suite "untested / typed coercion views" :label "float" :expected "3.0" :actual "(float 3)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-add" :expected "3" :actual "(unchecked-add 1 2)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-add-int" :expected "3" :actual "(unchecked-add-int 1 2)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-subtract" :expected "3" :actual "(unchecked-subtract 5 2)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-subtract-int" :expected "3" :actual "(unchecked-subtract-int 5 2)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-multiply" :expected "6" :actual "(unchecked-multiply 2 3)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-multiply-int" :expected "6" :actual "(unchecked-multiply-int 2 3)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-inc" :expected "2" :actual "(unchecked-inc 1)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-inc-int" :expected "2" :actual "(unchecked-inc-int 1)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-dec" :expected "2" :actual "(unchecked-dec 3)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-dec-int" :expected "2" :actual "(unchecked-dec-int 3)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-negate" :expected "-4" :actual "(unchecked-negate 4)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-negate-int" :expected "-4" :actual "(unchecked-negate-int 4)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-divide-int" :expected "3" :actual "(unchecked-divide-int 7 2)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-remainder-int" :expected "1" :actual "(unchecked-remainder-int 7 2)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-int" :expected "3" :actual "(unchecked-int 3.7)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-long" :expected "3" :actual "(unchecked-long 3.7)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-double" :expected "3.0" :actual "(unchecked-double 3)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-float" :expected "3.0" :actual "(unchecked-float 3)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-byte" :expected "65" :actual "(unchecked-byte 65)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-char" :expected "\\a" :actual "(unchecked-char 97)"} + {:suite "untested / unchecked-* are plain ops" :label "unchecked-short" :expected "5" :actual "(unchecked-short 5)"} + {:suite "untested / chunk family (eager equivalents) + cat" :label "chunk round-trip" :expected "1" :actual "(let [cb (chunk-buffer 4)] (chunk-append cb 1) (chunk-first (chunk-cons (chunk cb) nil)))"} + {:suite "untested / chunk family (eager equivalents) + cat" :label "cat transducer" :expected "[1 2 3]" :actual "(into [] cat [[1] [2 3]])"} + {:suite "untested / chunk family (eager equivalents) + cat" :label "ensure-reduced wraps" :expected "true" :actual "(reduced? (ensure-reduced 5))"} + {:suite "untested / chunk family (eager equivalents) + cat" :label "ensure-reduced keeps reduced" :expected "true" :actual "(reduced? (ensure-reduced (reduced 5)))"} + {:suite "untested / chunk family (eager equivalents) + cat" :label "halt-when" :expected "4" :actual "(transduce (halt-when even?) conj [] [1 3 4 5])"} + {:suite "untested / chunk family (eager equivalents) + cat" :label "chunk-next exhausted" :expected "nil" :actual "(let [cb (chunk-buffer 2)] (chunk-append cb 1) (chunk-next (chunk-cons (chunk cb) nil)))"} + {:suite "untested / chunk family (eager equivalents) + cat" :label "chunk-rest seqable" :expected "[]" :actual "(let [cb (chunk-buffer 2)] (chunk-append cb 1) (vec (chunk-rest (chunk-cons (chunk cb) nil))))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "class number" :expected "java.lang.Long" :actual "(class 1)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "class string" :expected "java.lang.String" :actual "(class \"s\")"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "class keyword" :expected "clojure.lang.Keyword" :actual "(class :k)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "class nil" :expected "nil" :actual "(class nil)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "bean is the map" :expected "{:a 1}" :actual "(bean {:a 1})"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "biginteger" :expected "\"5\"" :actual "(str (biginteger 5))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "proxy resolves nil" :expected "nil" :actual "(proxy [Object] [] (toString [] \"x\"))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "construct-proxy throws" :expected :throws :actual "(construct-proxy nil)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "get-proxy-class throws" :expected :throws :actual "(get-proxy-class)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "init-proxy" :expected "nil" :actual "(init-proxy nil {})"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "update-proxy" :expected "nil" :actual "(update-proxy nil {})"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "proxy-mappings" :expected "{}" :actual "(proxy-mappings nil)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "proxy-call-with-super calls" :expected "1" :actual "(proxy-call-with-super (fn [] 1) nil \"m\")"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "memfn upper" :expected "\"ABC\"" :actual "((memfn toUpperCase) \"abc\")"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "memfn with args" :expected "2" :actual "((memfn indexOf needle) \"hello\" \"l\")"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "memfn length" :expected "3" :actual "((memfn length) \"abc\")"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "array-seq" :expected "(quote (1 2 3))" :actual "(array-seq (to-array [1 2 3]))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "array-seq empty" :expected "nil" :actual "(array-seq (to-array []))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "proxy-super throws" :expected :throws :actual "(proxy-super count [1])"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "re-groups throws" :expected :throws :actual "(re-groups (re-matcher #\"a\" \"b\"))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "re-matcher builds" :expected "false" :actual "(nil? (re-matcher #\"a\" \"abc\"))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "print-dup nil writer throws" :expected :throws :actual "(print-dup 1 nil)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "print-method nil writer throws" :expected :throws :actual "(print-method 1 nil)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "uri? string" :expected "false" :actual "(uri? \"http://x\")"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "uri? nil" :expected "false" :actual "(uri? nil)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "definterface defines" :expected "false" :actual "(var? (definterface IFoo (foo [x])))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "enumeration-seq" :expected "(quote (1 2))" :actual "(enumeration-seq [1 2])"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "iterator-seq" :expected "(quote (1 2))" :actual "(iterator-seq [1 2])"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "seque passthrough" :expected "[1 2]" :actual "(seque [1 2])"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "delay? true" :expected "true" :actual "(delay? (delay 1))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "delay? false" :expected "false" :actual "(delay? 1)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "future-call" :expected "42" :actual "(deref (future-call (fn [] 42)))"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label ". calls String surface" :expected "3" :actual "(. \"abc\" length)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label ".. threads members" :expected "\"ABC\"" :actual "(.. \"abc\" toUpperCase)"} + {:suite "untested / JVM-shape stubs (documented jolt behavior)" :label "unknown String member throws" :expected :throws :actual "(. \"abc\" frobnicate)"} + {:suite "untested / protocols: extend + extends?" :label "extend registers" :expected ":str" :actual "(do (defprotocol Pe (pe [x])) (extend (quote String) Pe {:pe (fn [x] :str)}) (pe \"s\"))"} + {:suite "untested / protocols: extend + extends?" :label "extend two methods" :expected "[1 2]" :actual "(do (defprotocol P3 (pa [x]) (pb [x])) (extend (quote Long) P3 {:pa (fn [x] 1) :pb (fn [x] 2)}) [(pa 0) (pb 0)])"} + {:suite "untested / protocols: extend + extends?" :label "extends? after extend" :expected "true" :actual "(do (defprotocol P4 (pc [x])) (extend (quote Long) P4 {:pc (fn [x] 1)}) (extends? P4 (quote Long)))"} + {:suite "untested / protocols: extend + extends?" :label "extends? without" :expected "false" :actual "(do (defprotocol P5 (pd [x])) (extends? P5 (quote Long)))"} + {:suite "untested / ns + REPL machinery" :label "all-ns non-empty" :expected "true" :actual "(pos? (count (all-ns)))"} + {:suite "untested / ns + REPL machinery" :label "ns-interns sees def" :expected "true" :actual "(do (def zz 1) (pos? (count (ns-interns (quote user)))))"} + {:suite "untested / ns + REPL machinery" :label "ns-interns countable" :expected "true" :actual "(map? (ns-interns (quote user)))"} + {:suite "untested / ns + REPL machinery" :label "ns-imports empty user" :expected "96" :actual "(count (ns-imports (quote user)))"} + {:suite "untested / ns + REPL machinery" :label "reset-meta!" :expected "{:doc \"d\"}" :actual "(do (def vv 1) (reset-meta! (var vv) {:doc \"d\"}))"} + {:suite "untested / ns + REPL machinery" :label "prefers empty" :expected "{}" :actual "(do (defmulti mm identity) (prefers mm))"} + {:suite "untested / ns + REPL machinery" :label "refer-clojure" :expected "nil" :actual "(refer-clojure)"} + {:suite "untested / ns + REPL machinery" :label "special-symbol? if" :expected "true" :actual "(special-symbol? (quote if))"} + {:suite "untested / ns + REPL machinery" :label "special-symbol? fn name" :expected "false" :actual "(special-symbol? (quote foo))"} + {:suite "untested / ns + REPL machinery" :label "destructure expands" :expected "true" :actual "(pos? (count (destructure (quote [[a b] x]))))"} + {:suite "untested / ns + REPL machinery" :label "seq-to-map-for-destructuring" :expected "{:a 1}" :actual "(seq-to-map-for-destructuring (quote (:a 1)))"} + {:suite "untested / ns + REPL machinery" :label "s2m trailing map passes through" :expected "{:b 2}" :actual "(seq-to-map-for-destructuring (list {:b 2}))"} + {:suite "untested / ns + REPL machinery" :label "s2m unpaired key throws" :expected :throws :actual "(seq-to-map-for-destructuring (quote (:a 1 :b)))"} + {:suite "untested / ns + REPL machinery" :label "s2m kwargs trailing map call" :expected "2" :actual "((fn [& {:keys [b]}] b) {:b 2})"} + {:suite "untested / ns + REPL machinery" :label "*clojure-version* major" :expected "1" :actual "(:major *clojure-version*)"} + {:suite "untested / ns + REPL machinery" :label "*ns* user" :expected "\"user\"" :actual "(str *ns*)"} + {:suite "untested / ns + REPL machinery" :label "*1 nil outside repl" :expected "nil" :actual "*1"} + {:suite "untested / ns + REPL machinery" :label "*2 nil" :expected "nil" :actual "*2"} + {:suite "untested / ns + REPL machinery" :label "*3 nil" :expected "nil" :actual "*3"} + {:suite "untested / ns + REPL machinery" :label "*e nil" :expected "nil" :actual "*e"} + {:suite "untested / ns + REPL machinery" :label "*unchecked-math*" :expected "false" :actual "*unchecked-math*"} + {:suite "untested / ns + REPL machinery" :label "*in* bound" :expected "false" :actual "(map? *in*)"} + {:suite "untested / misc seqs + binding machinery" :label "nfirst" :expected "[2]" :actual "(nfirst [[1 2] [3]])"} + {:suite "untested / misc seqs + binding machinery" :label "xml-seq root" :expected "1" :actual "(count (xml-seq {:tag :a :content []}))"} + {:suite "untested / misc seqs + binding machinery" :label "xml-seq walks" :expected "2" :actual "(count (xml-seq {:tag :a :content [{:tag :b :content []}]}))"} + {:suite "untested / misc seqs + binding machinery" :label "comp keyword stage" :expected "[1 2]" :actual "((comp seq :content) {:content [1 2]})"} + {:suite "untested / misc seqs + binding machinery" :label "comp three stages" :expected "4" :actual "((comp inc inc :n) {:n 2})"} + {:suite "untested / misc seqs + binding machinery" :label "random-sample all" :expected "[1 2]" :actual "(random-sample 1.0 [1 2])"} + {:suite "untested / misc seqs + binding machinery" :label "random-sample none" :expected "[]" :actual "(random-sample 0.0 [1 2])"} + {:suite "untested / misc seqs + binding machinery" :label "reader-conditional builds" :expected "true" :actual "(reader-conditional? (reader-conditional (quote (:clj 1)) false))"} + {:suite "untested / misc seqs + binding machinery" :label "->Eduction" :expected "[2 3]" :actual "(vec (->Eduction (map inc) [1 2]))"} + {:suite "untested / misc seqs + binding machinery" :label "bound-fn calls" :expected "42" :actual "((bound-fn [] 42))"} + {:suite "untested / misc seqs + binding machinery" :label "push/pop-thread-bindings" :expected ":ok" :actual "(do (push-thread-bindings {}) (pop-thread-bindings) :ok)"} + {:suite "uuid / random-uuid" :label "returns a uuid" :expected "true" :actual "(uuid? (random-uuid))"} + {:suite "uuid / random-uuid" :label "str is 36 chars" :expected "36" :actual "(count (str (random-uuid)))"} + {:suite "uuid / random-uuid" :label "8-4-4-4-12 shape" :expected "[8 4 4 4 12]" :actual "(do (require (quote [clojure.string :as s])) (mapv count (s/split (str (random-uuid)) #\"-\")))"} + {:suite "uuid / random-uuid" :label "version nibble is 4" :expected "\\4" :actual "(nth (str (random-uuid)) 14)"} + {:suite "uuid / random-uuid" :label "variant nibble 8-b" :expected "true" :actual "(contains? #{\\8 \\9 \\a \\b} (nth (seq (str (random-uuid))) 19))"} + {:suite "uuid / random-uuid" :label "distinct" :expected "10" :actual "(count (set (repeatedly 10 random-uuid)))"} + {:suite "uuid / random-uuid" :label "all hex digits" :expected "true" :actual "(every? (fn [c] (contains? (set (seq \"0123456789abcdef-\")) c)) (seq (str (random-uuid))))"} + {:suite "uuid / parse-uuid" :label "valid round-trips" :expected "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" :actual "(str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"} + {:suite "uuid / parse-uuid" :label "parses to uuid" :expected "true" :actual "(uuid? (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"} + {:suite "uuid / parse-uuid" :label "case-insensitive =" :expected "true" :actual "(= (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\") (parse-uuid \"B6883C0A-0342-4007-9966-BC2DFA6B109E\"))"} + {:suite "uuid / parse-uuid" :label "empty -> nil" :expected "nil" :actual "(parse-uuid \"\")"} + {:suite "uuid / parse-uuid" :label "short -> nil" :expected "nil" :actual "(parse-uuid \"0\")"} + {:suite "uuid / parse-uuid" :label "garbage -> nil" :expected "nil" :actual "(parse-uuid \"df0993\")"} + {:suite "uuid / parse-uuid" :label "too long -> nil" :expected "nil" :actual "(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109eb\")"} + {:suite "uuid / parse-uuid" :label "leading extra -> nil" :expected "nil" :actual "(parse-uuid \"ab6883c0a-0342-4007-9966-bc2dfa6b109e\")"} + {:suite "uuid / parse-uuid" :label "non-hex -> nil" :expected "nil" :actual "(parse-uuid \"g6883c0a-0342-4007-9966-bc2dfa6b109e\")"} + {:suite "uuid / parse-uuid" :label "bad dashes -> nil" :expected "nil" :actual "(parse-uuid \"b6883c0a00342-4007-9966-bc2dfa6b109e\")"} + {:suite "uuid / parse-uuid" :label "non-string throws" :expected :throws :actual "(parse-uuid 1000)"} + {:suite "uuid / parse-uuid" :label "keyword throws" :expected :throws :actual "(parse-uuid :key)"} + {:suite "uuid / parse-uuid" :label "map throws" :expected :throws :actual "(parse-uuid {})"} + {:suite "uuid / value semantics" :label "equal by value" :expected "true" :actual "(= (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\") (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"} + {:suite "uuid / value semantics" :label "unequal differs" :expected "false" :actual "(= (random-uuid) (random-uuid))"} + {:suite "uuid / value semantics" :label "works as map key" :expected ":v" :actual "(let [u (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")] (get {u :v} (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")))"} + {:suite "uuid / value semantics" :label "works in a set" :expected "true" :actual "(contains? #{(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")} (parse-uuid \"B6883C0A-0342-4007-9966-BC2DFA6B109E\"))"} + {:suite "uuid / value semantics" :label "uuid? false on string" :expected "false" :actual "(uuid? \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")"} + {:suite "uuid / value semantics" :label "uuid? false on nil" :expected "false" :actual "(uuid? nil)"} + {:suite "uuid / #uuid reader literal" :label "reads to uuid" :expected "true" :actual "(uuid? #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")"} + {:suite "uuid / #uuid reader literal" :label "= parse-uuid" :expected "true" :actual "(= #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\" (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"} + {:suite "uuid / #uuid reader literal" :label "str of literal" :expected "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" :actual "(str #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")"} + {:suite "uuid / #uuid reader literal" :label "pr-str round-trips" :expected "\"#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"\"" :actual "(pr-str #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")"} + {:suite "vector / construct & predicate" :label "literal" :expected "[1 2 3]" :actual "[1 2 3]"} + {:suite "vector / construct & predicate" :label "vector" :expected "[1 2 3]" :actual "(vector 1 2 3)"} + {:suite "vector / construct & predicate" :label "vector zero args" :expected "[]" :actual "(vector)"} + {:suite "vector / construct & predicate" :label "vec from list" :expected "[1 2 3]" :actual "(vec (list 1 2 3))"} + {:suite "vector / construct & predicate" :label "vec from range" :expected "[0 1 2]" :actual "(vec (range 3))"} + {:suite "vector / construct & predicate" :label "vec of map yields entries" :expected "[[:a 1]]" :actual "(vec {:a 1})"} + {:suite "vector / construct & predicate" :label "vector? true" :expected "true" :actual "(vector? [1])"} + {:suite "vector / construct & predicate" :label "vector? false on list" :expected "false" :actual "(vector? (list 1))"} + {:suite "vector / construct & predicate" :label "vector = list elts" :expected "true" :actual "(= [1 2 3] (list 1 2 3))"} + {:suite "vector / access" :label "nth" :expected ":b" :actual "(nth [:a :b :c] 1)"} + {:suite "vector / access" :label "nth default" :expected ":x" :actual "(nth [:a] 5 :x)"} + {:suite "vector / access" :label "get by index" :expected ":b" :actual "(get [:a :b] 1)"} + {:suite "vector / access" :label "get out of range nil" :expected "nil" :actual "(get [:a] 5)"} + {:suite "vector / access" :label "get default" :expected ":x" :actual "(get [:a] 5 :x)"} + {:suite "vector / access" :label "first" :expected "1" :actual "(first [1 2 3])"} + {:suite "vector / access" :label "last" :expected "3" :actual "(last [1 2 3])"} + {:suite "vector / access" :label "peek is last" :expected "3" :actual "(peek [1 2 3])"} + {:suite "vector / access" :label "count" :expected "3" :actual "(count [1 2 3])"} + {:suite "vector / access" :label "contains? index" :expected "true" :actual "(contains? [:a :b] 1)"} + {:suite "vector / access" :label "contains? past end" :expected "false" :actual "(contains? [:a] 3)"} + {:suite "vector / access" :label "vector as fn" :expected ":b" :actual "([:a :b :c] 1)"} + {:suite "vector / access" :label "vector-in-local as fn" :expected "20" :actual "(let [v [10 20 30]] (v 1))"} + {:suite "vector / access" :label "keyword-in-local as fn" :expected "7" :actual "(let [k :a] (k {:a 7}))"} + {:suite "vector / access" :label "meta vector as fn" :expected "10" :actual "((with-meta [10 20] {:k 1}) 0)"} + {:suite "vector / update (persistent)" :label "conj appends" :expected "[1 2 3]" :actual "(conj [1 2] 3)"} + {:suite "vector / update (persistent)" :label "conj many" :expected "[1 2 3 4]" :actual "(conj [1 2] 3 4)"} + {:suite "vector / update (persistent)" :label "assoc index" :expected "[1 9 3]" :actual "(assoc [1 2 3] 1 9)"} + {:suite "vector / update (persistent)" :label "assoc at count appends" :expected "[1 2 3]" :actual "(assoc [1 2] 2 3)"} + {:suite "vector / update (persistent)" :label "update" :expected "[1 3 3]" :actual "(update [1 2 3] 1 inc)"} + {:suite "vector / update (persistent)" :label "pop drops last" :expected "[1 2]" :actual "(pop [1 2 3])"} + {:suite "vector / update (persistent)" :label "subvec start end" :expected "[2 3]" :actual "(subvec [1 2 3 4] 1 3)"} + {:suite "vector / update (persistent)" :label "subvec to end" :expected "[3 4]" :actual "(subvec [1 2 3 4] 2)"} + {:suite "vector / update (persistent)" :label "mapv" :expected "[2 3 4]" :actual "(mapv inc [1 2 3])"} + {:suite "vector / update (persistent)" :label "filterv" :expected "[2 4]" :actual "(filterv even? [1 2 3 4])"} + {:suite "vector / immutability & nesting" :label "conj does not mutate" :expected "true" :actual "(let [v [1 2] w (conj v 3)] (and (= v [1 2]) (= w [1 2 3])))"} + {:suite "vector / immutability & nesting" :label "assoc does not mutate" :expected "true" :actual "(let [v [1 2 3] w (assoc v 0 9)] (and (= v [1 2 3]) (= w [9 2 3])))"} + {:suite "vector / immutability & nesting" :label "get-in" :expected "2" :actual "(get-in [[1 2] [3 4]] [0 1])"} + {:suite "vector / immutability & nesting" :label "assoc-in" :expected "[[1 9]]" :actual "(assoc-in [[1 2]] [0 1] 9)"} + {:suite "vector / immutability & nesting" :label "update-in" :expected "[[1 3]]" :actual "(update-in [[1 2]] [0 1] inc)"} + {:suite "vector / immutability & nesting" :label "large vector nth" :expected "1500" :actual "(nth (vec (range 2000)) 1500)"} + {:suite "vector / immutability & nesting" :label "large vector count" :expected "2000" :actual "(count (vec (range 2000)))"} + {:suite "vector / immutability & nesting" :label "large conj immutable" :expected "true" :actual "(let [v (vec (range 1000)) w (conj v :end)] (and (= 1000 (count v)) (= 1001 (count w))))"} + {:suite "vector / bulk build boundaries" :label "count at 1025" :expected "1025" :actual "(count (vec (range 1025)))"} + {:suite "vector / bulk build boundaries" :label "into = vec at 1025" :expected "true" :actual "(= (vec (range 1025)) (into [] (range 1025)))"} + {:suite "vector / bulk build boundaries" :label "nth at leaf boundary" :expected "32" :actual "(nth (vec (range 1025)) 32)"} + {:suite "vector / bulk build boundaries" :label "nth at root boundary" :expected "1024" :actual "(nth (vec (range 1025)) 1024)"} + {:suite "vector / bulk build boundaries" :label "vec=into at 33" :expected "true" :actual "(= (vec (range 33)) (into [] (range 33)))"} + {:suite "vector / bulk build boundaries" :label "conj after bulk 1024" :expected "1025" :actual "(count (conj (vec (range 1024)) :x))"} + {:suite "vector / bulk build boundaries" :label "conj-after reads back" :expected ":x" :actual "(nth (conj (vec (range 1024)) :x) 1024)"} + {:suite "vector / bulk build boundaries" :label "assoc into bulk vec" :expected "9" :actual "(nth (assoc (vec (range 1025)) 1000 9) 1000)"} + {:suite "vector / bulk build boundaries" :label "into onto non-empty" :expected "[0 1 2 0 1]" :actual "(into (vec (range 3)) (range 2))"} + {:suite "clojure.walk / lists + seqs" :label "postwalk-replace symbol keys in a list" :expected "(quote (+ 2 2))" :actual "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {(quote x) 2} (quote (+ x x))))"} + {:suite "clojure.walk / lists + seqs" :label "postwalk descends a list" :expected "[:a :a]" :actual "(do (require (quote [clojure.walk :as w])) (w/postwalk (fn [n] (if (symbol? n) :a n)) (quote (x y))))"} + {:suite "clojure.walk / lists + seqs" :label "prewalk-replace in a list" :expected "(quote (* 3 3))" :actual "(do (require (quote [clojure.walk :as w])) (w/prewalk-replace {(quote *) (quote *) (quote y) 3} (quote (* y y))))"} + {:suite "clojure.walk / lists + seqs" :label "nested list + vector" :expected "[1 [2 1]]" :actual "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {:a 1 :b 2} (quote (:a [:b :a]))))"} + {:suite "clojure.walk / lists + seqs" :label "postwalk-replace in a vector" :expected "[:one 2 :one]" :actual "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {1 :one} [1 2 1]))"} + {:suite "clojure.walk / lists + seqs" :label "keywordize-keys still works" :expected "{:a 1}" :actual "(do (require (quote [clojure.walk :as w])) (w/keywordize-keys {\"a\" 1}))"} + {:suite "clojure.walk / lists + seqs" :label "apply-template substitutes" :expected "(quote (+ 1 2))" :actual "(do (require (quote [clojure.template :as t])) (t/apply-template (quote [x y]) (quote (+ x y)) (quote (1 2))))"} + {:suite "conformance / CRITICAL: lazy sequences" :label "self-ref lazy-cat fib" :expected "[0 1 1 2 3 5 8 13 21 34]" :actual "(do (def fib-seq (lazy-cat [0 1] (map + (rest fib-seq) fib-seq))) (take 10 fib-seq))"} + {:suite "conformance / CRITICAL: multi-collection map" :label "map two colls" :expected "[11 22 33]" :actual "(map + [1 2 3] [10 20 30])"} + {:suite "conformance / CRITICAL: multi-collection map" :label "map three colls" :expected "[12 24 36]" :actual "(map + [1 2 3] [10 20 30] [1 2 3])"} + {:suite "conformance / CRITICAL: multi-collection map" :label "map uneven (shortest)" :expected "[[1 :a] [2 :b]]" :actual "(map vector [1 2 3] [:a :b])"} + {:suite "conformance / CRITICAL: multi-collection map" :label "map over range+vec" :expected "[1 3 5]" :actual "(map + (range 3) [1 2 3])"} + {:suite "conformance / CRITICAL: multi-collection map" :label "map fn list arg" :expected "[2 3 4]" :actual "(map inc (list 1 2 3))"} + {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "iterate" :expected "[0 1 2 3 4]" :actual "(take 5 (iterate inc 0))"} + {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "iterate double" :expected "[1 2 4 8 16]" :actual "(take 5 (iterate (fn [x] (* 2 x)) 1))"} + {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "range over inf map" :expected "[1 2 3]" :actual "(take 3 (map inc (range)))"} + {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "count of take" :expected "100" :actual "(count (take 100 (range)))"} + {:suite "conformance / CRITICAL: iterate / infinite seqs" :label "last of take" :expected "5" :actual "(last (take 5 (iterate inc 1)))"} + {:suite "conformance / CRITICAL: collections as IFn" :label "map as fn miss" :expected "nil" :actual "({:a 1} :z)"} + {:suite "conformance / CRITICAL: collections as IFn" :label "map as fn default" :expected "99" :actual "({:a 1} :z 99)"} + {:suite "conformance / CRITICAL: collections as IFn" :label "set literal computed" :expected "true" :actual "(= #{1 2} #{(inc 0) 2})"} + {:suite "conformance / CRITICAL: collections as IFn" :label "empty set literal" :expected "true" :actual "(empty? #{})"} + {:suite "conformance / CRITICAL: collections as IFn" :label "set literal count" :expected "3" :actual "(count #{1 2 3})"} + {:suite "conformance / CRITICAL: collections as IFn" :label "set literal in let" :expected "true" :actual "(let [x 5] (= #{5 6} #{x (inc x)}))"} + {:suite "conformance / CRITICAL: collections as IFn" :label "set? true" :expected "true" :actual "(set? #{1 2 3})"} + {:suite "conformance / CRITICAL: collections as IFn" :label "set? false" :expected "false" :actual "(set? [1 2])"} + {:suite "conformance / CRITICAL: collections as IFn" :label "disj one" :expected "#{1 3}" :actual "(disj #{1 2 3} 2)"} + {:suite "conformance / CRITICAL: collections as IFn" :label "disj many" :expected "#{1}" :actual "(disj #{1 2 3} 2 3)"} + {:suite "conformance / CRITICAL: collections as IFn" :label "disj absent" :expected "#{1 2}" :actual "(disj #{1 2} 5)"} + {:suite "conformance / CRITICAL: collections as IFn" :label "map fn over coll" :expected "[1 3]" :actual "(map {:a 1 :b 3} [:a :b])"} + {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "vec of map-result" :expected "[2 3 4]" :actual "(vec (map inc [1 2 3]))"} + {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "vec of range" :expected "[0 1 2 3 4]" :actual "(vec (range 5))"} + {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "into vec" :expected "[1 2 3 4 5 6]" :actual "(into [1 2 3] [4 5 6])"} + {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "into vec from lazy" :expected "[2 3 4]" :actual "(into [] (map inc [1 2 3]))"} + {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "into map pairs" :expected "{:a 1, :b 2}" :actual "(into {} [[:a 1] [:b 2]])"} + {:suite "conformance / CRITICAL: vec / into over lazy + maps" :label "into map onto map" :expected "{:a 1, :b 2, :c 3}" :actual "(into {:a 1} [[:b 2] [:c 3]])"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "map vec is seq" :expected "true" :actual "(seq? (map inc [1 2 3]))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "map vec not vector" :expected "false" :actual "(vector? (map inc [1 2 3]))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "filter vec is seq" :expected "true" :actual "(seq? (filter odd? [1 2 3]))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "take vec is seq" :expected "true" :actual "(seq? (take 2 [1 2 3]))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "map over set" :expected "true" :actual "(= #{2 3 4} (set (map inc #{1 2 3})))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "filter over map ev" :expected "[[:b 2]]" :actual "(filter (fn [[k v]] (> v 1)) {:a 1 :b 2})"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "cons cons lazy" :expected "[1 2 3]" :actual "(cons 1 (cons 2 (lazy-seq (cons 3 nil))))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "next empty lazy" :expected "nil" :actual "(next (take 1 [1]))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "drop vec is seq" :expected "true" :actual "(seq? (drop 1 [1 2 3]))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "distinct vec is seq" :expected "true" :actual "(seq? (distinct [1 1 2]))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "map-indexed is seq" :expected "true" :actual "(seq? (map-indexed vector [1 2]))"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "nth lazy false elem" :expected "false" :actual "(nth (map identity [false 1 2]) 0)"} + {:suite "conformance / Option A: lazy transformers return seqs, not vectors" :label "nth lazy past false" :expected "2" :actual "(nth (drop 1 (list false 1 2)) 1)"} + {:suite "conformance / HIGH: destructuring" :label "destr nested seq" :expected "[1 2 3]" :actual "(let [[a [b c]] [1 [2 3]]] [a b c])"} + {:suite "conformance / HIGH: destructuring" :label "destr rest+as" :expected "[1 [2 3] [1 2 3]]" :actual "(let [[a & r :as all] [1 2 3]] [a r all])"} + {:suite "conformance / HIGH: destructuring" :label "destr map :keys" :expected "[1 2]" :actual "(let [{:keys [a b]} {:a 1 :b 2}] [a b])"} + {:suite "conformance / HIGH: destructuring" :label "destr map :or" :expected "[1 99]" :actual "(let [{:keys [a b] :or {b 99}} {:a 1}] [a b])"} + {:suite "conformance / HIGH: destructuring" :label "destr map :strs" :expected "[1 2]" :actual "(let [{:strs [a b]} {\"a\" 1 \"b\" 2}] [a b])"} + {:suite "conformance / HIGH: destructuring" :label "destr nested map" :expected "5" :actual "(let [{{:keys [x]} :pos} {:pos {:x 5}}] x)"} + {:suite "conformance / HIGH: destructuring" :label "destr fn-param map" :expected "3" :actual "((fn [{:keys [a b]}] (+ a b)) {:a 1 :b 2})"} + {:suite "conformance / HIGH: destructuring" :label "destr let map key" :expected "1" :actual "(let [{a :a} {:a 1}] a)"} + {:suite "conformance / HIGH: update / assoc-in on map literals" :label "update extra args" :expected "{:a 111}" :actual "(update {:a 1} :a + 10 100)"} + {:suite "conformance / HIGH: update / assoc-in on map literals" :label "get-in" :expected "1" :actual "(get-in {:a {:b {:c 1}}} [:a :b :c])"} + {:suite "conformance / native-op parity (compile emits janet ops at guarded arities)" :label "native mod floored" :expected "2" :actual "(mod -7 3)"} + {:suite "conformance / native-op parity (compile emits janet ops at guarded arities)" :label "native rem truncated" :expected "-1" :actual "(rem -7 3)"} + {:suite "conformance / native-op parity (compile emits janet ops at guarded arities)" :label "native unary div" :expected "1/2" :actual "(/ 2)"} + {:suite "conformance / native-op parity (compile emits janet ops at guarded arities)" :label "native chained div" :expected "1" :actual "(/ 6 3 2)"} + {:suite "conformance / native-op parity (compile emits janet ops at guarded arities)" :label "native bit-and" :expected "8" :actual "(bit-and 12 10)"} + {:suite "conformance / native-op parity (compile emits janet ops at guarded arities)" :label "native bit-xor" :expected "6" :actual "(bit-xor 12 10)"} + {:suite "conformance / native-op parity (compile emits janet ops at guarded arities)" :label "native shifts" :expected "[16 2]" :actual "[(bit-shift-left 4 2) (bit-shift-right 8 2)]"} + {:suite "conformance / multimethod preferences (jolt-heo)" :label "prefer-method breaks tie" :expected ":rect" :actual "(do (derive :cm/sq :cm/rect) (derive :cm/sq :cm/shape) (defmulti cmf identity) (defmethod cmf :cm/rect [x] :rect) (defmethod cmf :cm/shape [x] :shape) (prefer-method cmf :cm/rect :cm/shape) (cmf :cm/sq))"} + {:suite "conformance / HIGH: str semantics" :label "str concat nil" :expected "\"a1\"" :actual "(str \"a\" 1 nil)"} + {:suite "conformance / HIGH: str semantics" :label "str keyword" :expected "\":b\"" :actual "(str :b)"} + {:suite "conformance / HIGH: str semantics" :label "str symbol" :expected "\"foo\"" :actual "(str (quote foo))"} + {:suite "conformance / HIGH: str semantics" :label "str mixed" :expected "\"a:b1\"" :actual "(str \"a\" :b 1)"} + {:suite "conformance / HIGH: str semantics" :label "str seq" :expected "\"[1 2 3]\"" :actual "(str [1 2 3])"} + {:suite "conformance / HIGH: dispatch" :label "multimethod" :expected "9" :actual "(do (defmulti area :shape) (defmethod area :sq [s] (* (:s s) (:s s))) (area {:shape :sq :s 3}))"} + {:suite "conformance / HIGH: dispatch" :label "multimethod default" :expected ":def" :actual "(do (defmulti f identity) (defmethod f :default [x] :def) (f 99))"} + {:suite "conformance / HIGH: dispatch" :label "protocol on record" :expected "16" :actual "(do (defprotocol Sh (ar [s])) (defrecord Sq [side] Sh (ar [_] (* side side))) (ar (->Sq 4)))"} + {:suite "conformance / HIGH: dispatch" :label "deftype inline methods" :expected "7" :actual "(do (defprotocol Pi (mi [x])) (deftype Ti [v] Pi (mi [x] v)) (mi (->Ti 7)))"} + {:suite "conformance / HIGH: dispatch" :label "deftype two protocols" :expected "[1 2]" :actual "(do (defprotocol Pa (ma [x])) (defprotocol Pb (mb [x])) (deftype Tab [a b] Pa (ma [x] a) Pb (mb [x] b)) (let [t (->Tab 1 2)] [(ma t) (mb t)]))"} + {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "var-get + call" :expected "2" :actual "((var-get (var inc)) 1)"} + {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "var? true" :expected "true" :actual "(var? (var map))"} + {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "var? false" :expected "false" :actual "(var? 5)"} + {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "intern + find-var" :expected "41" :actual "(do (intern (quote user) (quote iv) 41) (var-get (find-var (quote user/iv))))"} + {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "alter-var-root rest args" :expected "11" :actual "(do (def avr 1) (alter-var-root (var avr) + 4 6) avr)"} + {:suite "conformance / var fns as ordinary invokes (Stage 2 tier 6)" :label "alter-meta! + meta" :expected "7" :actual "(do (def amv 1) (alter-meta! (var amv) assoc :k 7) (:k (meta (var amv))))"} + {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "find-ns + ns-name" :expected "(quote clojure.core)" :actual "(ns-name (find-ns (quote clojure.core)))"} + {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "find-ns absent" :expected "nil" :actual "(find-ns (quote no.such.ns))"} + {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "create-ns + find" :expected "true" :actual "(do (create-ns (quote made.ns)) (some? (find-ns (quote made.ns))))"} + {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "remove-ns" :expected "nil" :actual "(do (create-ns (quote gone.ns)) (remove-ns (quote gone.ns)) (find-ns (quote gone.ns)))"} + {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "the-ns of symbol" :expected "(quote user)" :actual "(ns-name (the-ns (quote user)))"} + {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "ns-resolve + call" :expected "3" :actual "((var-get (ns-resolve (quote clojure.core) (quote inc))) 2)"} + {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "resolve + call" :expected "3" :actual "((var-get (resolve (quote inc))) 2)"} + {:suite "conformance / ns introspection fns as ordinary invokes (Stage 2 tier 6b)" :label "resolve absent" :expected "nil" :actual "(resolve (quote no-such-sym-xyz))"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "get-method + call" :expected "1" :actual "(do (defmulti t6f :k) (defmethod t6f :a [x] 1) ((get-method t6f :a) {:k :a}))"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "remove-method" :expected "nil" :actual "(do (defmulti t6g :k) (defmethod t6g :b [x] 2) (remove-method t6g :b) (get (methods t6g) :b))"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "remove-all-methods" :expected "nil" :actual "(do (defmulti t6h :k) (defmethod t6h :c [x] 3) (remove-all-methods t6h) (get (methods t6h) :c))"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "prefer-method records" :expected "true" :actual "(do (defmulti t6p identity) (prefer-method t6p :rect :shape) (contains? (get (prefers t6p) :rect) :shape))"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "instance? deftype" :expected "true" :actual "(do (deftype T6i [a]) (instance? T6i (->T6i 1)))"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "instance? String" :expected "true" :actual "(instance? String \"s\")"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "locking evals body" :expected "3" :actual "(locking :anything (+ 1 2))"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "locking evals monitor" :expected "[3 1]" :actual "(let [a (atom 0)] [(locking (swap! a inc) 3) @a])"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "defonce keeps first" :expected "5" :actual "(do (defonce d6o 5) (defonce d6o 9) d6o)"} + {:suite "conformance / dispatch-table ops + misc as macros/fns (Stage 2 tier 6c)" :label "read-string + eval" :expected "3" :actual "(eval (read-string \"(+ 1 2)\"))"} + {:suite "conformance / uuid (jolt-6s2)" :label "uuid as map key" :expected ":v" :actual "(get {(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\") :v} (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"} + {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "parse-long bad" :expected "nil" :actual "(parse-long \"4.2\")"} + {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "update-keys" :expected "{\"a\" 1}" :actual "(update-keys {:a 1} name)"} + {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "update-vals" :expected "{:a 2}" :actual "(update-vals {:a 1} inc)"} + {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "partition pad" :expected "[[0 1 2 3] [4 5 6 7] [8 9 :a]]" :actual "(partition 4 4 [:a] (range 10))"} + {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "with-redefs" :expected "[42 1]" :actual "(do (defn cwr [] 1) [(with-redefs [cwr (fn [] 42)] (cwr)) (cwr)])"} + {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "macroexpand" :expected "true" :actual "(= (quote if) (first (macroexpand (quote (when-not false 1)))))"} + {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "require bare symbol" :expected "\"a,b\"" :actual "(do (require (quote clojure.string)) (clojure.string/join \",\" [\"a\" \"b\"]))"} + {:suite "conformance / 1.11 additions + ns fns (spec 35-var batch A)" :label "ns-publics lookup" :expected "true" :actual "(do (def cnp 7) (some? (get (ns-publics (quote user)) (quote cnp))))"} + {:suite "conformance / #inst + syntax-quote literal collapse (spec 2.4/2.3)" :label "inst partial = full" :expected "true" :actual "(= #inst \"2020\" #inst \"2020-01-01T00:00:00Z\")"} + {:suite "conformance / #inst + syntax-quote literal collapse (spec 2.4/2.3)" :label "sq number collapse" :expected "42" :actual "``42"} + {:suite "conformance / stage 3: proper vars replace the Janet root-env leak" :label "compare total order" :expected "[-1 0 1]" :actual "[(compare nil 1) (compare :a :a) (compare \"b\" \"a\")]"} + {:suite "conformance / stage 3: proper vars replace the Janet root-env leak" :label "any? anything" :expected "true" :actual "(and (any? nil) (any? 1) (any? :k))"} + {:suite "conformance / stage 3: proper vars replace the Janet root-env leak" :label "macroexpand-1 when" :expected "2" :actual "(count (rest (macroexpand-1 (quote (when true 1)))))"} + {:suite "conformance / HIGH: aliased namespace calls" :label "require :as alias" :expected "\"1,2,3\"" :actual "(do (require (quote [clojure.string :as s])) (s/join \",\" [1 2 3]))"} + {:suite "conformance / HIGH: aliased namespace calls" :label "ns form + alias" :expected "\"HI\"" :actual "(do (ns my.a (:require [clojure.string :as s])) (s/upper-case \"hi\"))"} + {:suite "conformance / HIGH: aliased namespace calls" :label "ns :use refers" :expected "42" :actual "(do (ns src.u) (def helper 42) (ns dst.u (:use [src.u])) helper)"} + {:suite "conformance / MED: missing core fns" :label "subvec" :expected "[2 3]" :actual "(subvec [1 2 3 4 5] 1 3)"} + {:suite "conformance / MED: missing core fns" :label "subvec to-end" :expected "[3 4 5]" :actual "(subvec [1 2 3 4 5] 2)"} + {:suite "conformance / MED: missing core fns" :label "reduce-kv" :expected "{:a 2, :b 3}" :actual "(reduce-kv (fn [m k v] (assoc m k (inc v))) {} {:a 1 :b 2})"} + {:suite "conformance / iterating maps yields entries" :label "reduce over map" :expected "6" :actual "(reduce (fn [a [k v]] (+ a v)) 0 {:a 1 :b 2 :c 3})"} + {:suite "conformance / iterating maps yields entries" :label "into transform map" :expected "{:a 2, :b 3}" :actual "(into {} (map (fn [[k v]] [k (inc v)]) {:a 1 :b 2}))"} + {:suite "conformance / iterating maps yields entries" :label "filter over map" :expected "true" :actual "(= [[:b 2]] (filterv (fn [[k v]] (> v 1)) {:a 1 :b 2}))"} + {:suite "conformance / iterating maps yields entries" :label "tree-seq" :expected "[1 2 3]" :actual "(map (fn [x] x) (filter (complement coll?) (tree-seq coll? seq [1 [2 [3]]])))"} + {:suite "conformance / iterating maps yields entries" :label "key/val" :expected "true" :actual "(let [e (first {:k 9})] (and (= :k (key e)) (= 9 (val e))))"} + {:suite "conformance / iterating maps yields entries" :label "nat-int?" :expected "true" :actual "(and (nat-int? 0) (nat-int? 5) (not (nat-int? -1)))"} + {:suite "conformance / iterating maps yields entries" :label "list* prepend" :expected "[1 2 3 4]" :actual "(list* 1 2 [3 4])"} + {:suite "conformance / iterating maps yields entries" :label "cycle" :expected "[1 2 3 1 2 3 1]" :actual "(take 7 (cycle [1 2 3]))"} + {:suite "conformance / iterating maps yields entries" :label "partition-all" :expected "[[1 2] [3 4] [5]]" :actual "(partition-all 2 [1 2 3 4 5])"} + {:suite "conformance / iterating maps yields entries" :label "reductions init" :expected "[0 1 3 6]" :actual "(reductions + 0 [1 2 3])"} + {:suite "conformance / iterating maps yields entries" :label "dedupe" :expected "[1 2 3 1]" :actual "(dedupe [1 1 2 3 3 1])"} + {:suite "conformance / iterating maps yields entries" :label "partition-by odd?" :expected "[[1 1] [2] [3 3]]" :actual "(partition-by odd? [1 1 2 3 3])"} + {:suite "conformance / iterating maps yields entries" :label "reductions inf" :expected "[0 1 3 6]" :actual "(take 4 (reductions + (range)))"} + {:suite "conformance / iterating maps yields entries" :label "tree-seq strict" :expected "10" :actual "(reduce + 0 (filter (complement coll?) (tree-seq coll? seq [1 [2 [3 4]]])))"} + {:suite "conformance / iterating maps yields entries" :label "case nil + default" :expected "[:nilr :def]" :actual "(let [f (fn [x] (case x 1 :one nil :nilr :def))] [(f nil) (f 9)])"} + {:suite "conformance / iterating maps yields entries" :label "case collection consts" :expected "[:v :m :s]" :actual "(let [f (fn [x] (case x [1 2] :v {:a 1} :m #{3} :s :def))] [(f [1 2]) (f {:a 1}) (f #{3})])"} + {:suite "conformance / iterating maps yields entries" :label "seq of nil-first" :expected "true" :actual "(boolean (seq (cons nil (list 1))))"} + {:suite "conformance / iterating maps yields entries" :label "reverse nil elem" :expected "[2 nil 1]" :actual "(vec (reverse (list 1 nil 2)))"} + {:suite "conformance / iterating maps yields entries" :label "map non-seqable throws" :expected "true" :actual "(try (doall (map inc 5)) false (catch Throwable _ true))"} + {:suite "conformance / iterating maps yields entries" :label "keep-indexed" :expected "[:b :d]" :actual "(keep-indexed (fn [i x] (if (odd? i) x)) [:a :b :c :d])"} + {:suite "conformance / iterating maps yields entries" :label "map-indexed" :expected "[[0 :a] [1 :b]]" :actual "(map-indexed (fn [i x] [i x]) [:a :b])"} + {:suite "conformance / iterating maps yields entries" :label "trampoline" :expected ":done" :actual "(do (defn a [n] (if (zero? n) :done (fn [] (a (dec n))))) (trampoline a 5))"} + {:suite "conformance / iterating maps yields entries" :label "format" :expected "\"1-x\"" :actual "(format \"%d-%s\" 1 \"x\")"} + {:suite "conformance / iterating maps yields entries" :label "read-string" :expected "(quote (+ 1 2))" :actual "(read-string \"(+ 1 2)\")"} + {:suite "conformance / iterating maps yields entries" :label "letfn mutual" :expected "true" :actual "(letfn [(ev? [n] (if (= n 0) true (od? (dec n)))) (od? [n] (if (= n 0) false (ev? (dec n))))] (ev? 10))"} + {:suite "conformance / iterating maps yields entries" :label "doseq side" :expected "[1 2 3]" :actual "(do (def a (atom [])) (doseq [x [1 2 3]] (swap! a conj x)) @a)"} + {:suite "conformance / iterating maps yields entries" :label "doseq nested" :expected "4" :actual "(do (def c (atom 0)) (doseq [x [1 2] y [10 20]] (swap! c inc)) @c)"} + {:suite "conformance / MED: lazy filter / take-while over infinite seqs" :label "lazy filter inf" :expected "[1 3 5 7 9]" :actual "(take 5 (filter odd? (range)))"} + {:suite "conformance / MED: lazy filter / take-while over infinite seqs" :label "lazy take-while inf" :expected "[0 1 2 3 4]" :actual "(take-while (fn [x] (< x 5)) (range))"} + {:suite "conformance / MED: lazy filter / take-while over infinite seqs" :label "lazy remove inf" :expected "[0 2 4 6 8]" :actual "(take 5 (remove odd? (range)))"} + {:suite "conformance / MED: lazy filter / take-while over infinite seqs" :label "filter finite" :expected "[2 4]" :actual "(filter even? [1 2 3 4 5])"} + {:suite "conformance / atoms (full support)" :label "swap! args" :expected "7" :actual "(do (def a (atom 1)) (swap! a + 2 4) @a)"} + {:suite "conformance / atoms (full support)" :label "reset! ret" :expected "9" :actual "(do (def a (atom 1)) (reset! a 9))"} + {:suite "conformance / atoms (full support)" :label "compare-and-set!" :expected "true" :actual "(do (def a (atom 1)) (compare-and-set! a 1 2))"} + {:suite "conformance / atoms (full support)" :label "compare-and-set! no" :expected "false" :actual "(do (def a (atom 1)) (compare-and-set! a 5 2))"} + {:suite "conformance / atoms (full support)" :label "swap-vals!" :expected "[1 2]" :actual "(do (def a (atom 1)) (swap-vals! a inc))"} + {:suite "conformance / atoms (full support)" :label "reset-vals!" :expected "[1 9]" :actual "(do (def a (atom 1)) (reset-vals! a 9))"} + {:suite "conformance / atoms (full support)" :label "atom map swap" :expected "{:a 1, :b 2}" :actual "(do (def a (atom {:a 1})) (swap! a assoc :b 2) @a)"} + {:suite "conformance / atoms (full support)" :label "add-watch" :expected "[:k 1 2]" :actual "(do (def lg (atom nil)) (def a (atom 1)) (add-watch a :k (fn [k r o n] (reset! lg [k o n]))) (swap! a inc) @lg)"} + {:suite "conformance / atoms (full support)" :label "atom validator" :expected "5" :actual "(do (def a (atom 1 :validator pos?)) (reset! a 5) @a)"} + {:suite "conformance / atoms (full support)" :label "instance? Atom" :expected "true" :actual "(instance? clojure.lang.Atom (atom 1))"} + {:suite "conformance / volatiles / delays" :label "volatile" :expected "2" :actual "(do (def v (volatile! 1)) (vreset! v 2) @v)"} + {:suite "conformance / volatiles / delays" :label "vswap!" :expected "2" :actual "(do (def v (volatile! 1)) (vswap! v inc) @v)"} + {:suite "conformance / volatiles / delays" :label "delay force" :expected "3" :actual "(force (delay (+ 1 2)))"} + {:suite "conformance / volatiles / delays" :label "delay deref once" :expected "1" :actual "(do (def c (atom 0)) (def d (delay (swap! c inc))) @d @d @c)"} + {:suite "conformance / volatiles / delays" :label "realized? delay" :expected "true" :actual "(do (def d (delay 1)) @d (realized? d))"} + {:suite "conformance / volatiles / delays" :label "realized? not" :expected "false" :actual "(realized? (delay 1))"} + {:suite "conformance / numbers / math" :label "quot neg" :expected "-2" :actual "(quot -7 3)"} + {:suite "conformance / numbers / math" :label "bit ops" :expected "[4 14 10]" :actual "[(bit-and 12 6) (bit-or 12 6) (bit-xor 12 6)]"} + {:suite "conformance / numbers / math" :label "bit-shift" :expected "[8 2]" :actual "[(bit-shift-left 1 3) (bit-shift-right 8 2)]"} + {:suite "conformance / numbers / math" :label "Math/sqrt" :expected "3.0" :actual "(Math/sqrt 9)"} + {:suite "conformance / numbers / math" :label "Math/pow" :expected "8.0" :actual "(Math/pow 2 3)"} + {:suite "conformance / numbers / math" :label "min-key" :expected "1" :actual "(min-key abs 1 -2 3)"} + {:suite "conformance / numbers / math" :label "max-key" :expected "-4" :actual "(max-key abs 1 -2 -4 3)"} + {:suite "conformance / strings (clojure.string)" :label "str/trim" :expected "\"hi\"" :actual "(do (require (quote [clojure.string :as s])) (s/trim \" hi \"))"} + {:suite "conformance / strings (clojure.string)" :label "str/split regex" :expected "[\"a\" \"b\" \"c\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a,b,c\" #\",\"))"} + {:suite "conformance / strings (clojure.string)" :label "str/split ws" :expected "[\"a\" \"b\" \"c\"]" :actual "(do (require (quote [clojure.string :as s])) (s/split \"a b c\" #\"\\s+\"))"} + {:suite "conformance / strings (clojure.string)" :label "str/replace" :expected "\"hexxo\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" \"ll\" \"xx\"))"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "str/replace regex" :expected "\"ab\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"a1b2\" #\"[0-9]\" \"\"))"} + {:suite "conformance / strings (clojure.string)" :label "subs" :expected "\"ell\"" :actual "(subs \"hello\" 1 4)"} + {:suite "conformance / regex" :label "re-find" :expected "\"123\"" :actual "(re-find #\"[0-9]+\" \"abc123def\")"} + {:suite "conformance / regex" :label "re-matches" :expected "\"abc\"" :actual "(re-matches #\"a.c\" \"abc\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-matches no" :expected "nil" :actual "(re-matches #\"a.c\" \"abcd\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-seq" :expected "[\"12\" \"34\"]" :actual "(re-seq #\"[0-9]+\" \"a12b34\")"} + {:suite "conformance / sequences" :label "split-at" :expected "[[1 2] [3 4 5]]" :actual "(split-at 2 [1 2 3 4 5])"} + {:suite "conformance / sequences" :label "split-with" :expected "[[1 2] [3 4 1]]" :actual "(split-with (fn [x] (< x 3)) [1 2 3 4 1])"} + {:suite "conformance / sequences" :label "partition step" :expected "[[1 2] [3 4]]" :actual "(partition 2 2 [1 2 3 4 5])"} + {:suite "conformance / sequences" :label "not-every?" :expected "true" :actual "(not-every? pos? [1 -2 3])"} + {:suite "conformance / overlay migration (jolt-1j0): run in all 3 modes" :label "not-any?" :expected "true" :actual "(not-any? neg? [1 2 3])"} + {:suite "conformance / sequences" :label "take-nth" :expected "[0 2 4]" :actual "(take-nth 2 [0 1 2 3 4])"} + {:suite "conformance / sequences" :label "butlast" :expected "[1 2]" :actual "(butlast [1 2 3])"} + {:suite "conformance / sequences" :label "empty" :expected "[]" :actual "(empty [1 2 3])"} + {:suite "conformance / sequences" :label "replace map" :expected "[:a :b :a]" :actual "(replace {1 :a 2 :b} [1 2 1])"} + {:suite "conformance / data structures" :label "sorted-map seq" :expected "[[:a 1] [:b 2] [:c 3]]" :actual "(seq (sorted-map :c 3 :a 1 :b 2))"} + {:suite "conformance / data structures" :label "sorted-set seq" :expected "[1 2 3]" :actual "(seq (sorted-set 3 1 2))"} + {:suite "conformance / data structures" :label "coll? set" :expected "true" :actual "(coll? #{1 2})"} + {:suite "conformance / data structures" :label "conj map entry" :expected "{:a 1, :b 2}" :actual "(conj {:a 1} [:b 2])"} + {:suite "conformance / metadata / vars" :label "vary-meta" :expected "{:x 2}" :actual "(meta (vary-meta (with-meta [1] {:x 1}) update :x inc))"} + {:suite "conformance / metadata / vars" :label "defonce no-redef" :expected "1" :actual "(do (defonce dv1 1) (defonce dv1 2) dv1)"} + {:suite "conformance / metadata / vars" :label "binding dynamic" :expected "10" :actual "(do (def ^:dynamic *x* 1) (binding [*x* 10] *x*))"} + {:suite "conformance / try / catch" :label "try catch" :expected ":caught" :actual "(try (throw (ex-info \"e\" {})) (catch :default e :caught))"} + {:suite "conformance / try / catch" :label "ex-data" :expected "{:a 1}" :actual "(try (throw (ex-info \"m\" {:a 1})) (catch :default e (ex-data e)))"} + {:suite "conformance / try / catch" :label "ex-message" :expected "\"m\"" :actual "(try (throw (ex-info \"m\" {})) (catch :default e (ex-message e)))"} + {:suite "conformance / macros" :label "macroexpand-1" :expected "true" :actual "(do (defmacro mm [x] (list (quote inc) x)) (= (quote (inc 5)) (macroexpand-1 (quote (mm 5)))))"} + {:suite "conformance / macros" :label "doto" :expected "{:a 1}" :actual "(deref (doto (atom {}) (swap! assoc :a 1)))"} + {:suite "conformance / printing" :label "prn-str" :expected "\"1\\n\"" :actual "(prn-str 1)"} + {:suite "conformance / characters" :label "char not string" :expected "false" :actual "(= \\a \"a\")"} + {:suite "conformance / characters" :label "char eq" :expected "true" :actual "(= \\a \\a)"} + {:suite "conformance / characters" :label "int of char" :expected "97" :actual "(int \\a)"} + {:suite "conformance / characters" :label "char of int" :expected "true" :actual "(= \\A (char 65))"} + {:suite "conformance / characters" :label "str of chars" :expected "\"abc\"" :actual "(str \\a \\b \\c)"} + {:suite "conformance / characters" :label "first of string" :expected "\\h" :actual "(first \"hello\")"} + {:suite "conformance / characters" :label "nth of string" :expected "\\e" :actual "(nth \"hello\" 1)"} + {:suite "conformance / characters" :label "char newline" :expected "10" :actual "(int \\newline)"} + {:suite "conformance / characters" :label "char space" :expected "32" :actual "(int \\space)"} + {:suite "conformance / characters" :label "pr-str char" :expected "\"\\\\a\"" :actual "(pr-str \\a)"} + {:suite "conformance / characters" :label "chars in vec" :expected "[\\a \\b]" :actual "[\\a \\b]"} + {:suite "conformance / characters" :label "apply str chars" :expected "\"hi\"" :actual "(apply str [\\h \\i])"} + {:suite "conformance / transducers" :label "transduce map" :expected "9" :actual "(transduce (map inc) + 0 [1 2 3])"} + {:suite "conformance / transducers" :label "transduce comp" :expected "12" :actual "(transduce (comp (map inc) (filter even?)) + 0 [1 2 3 4 5])"} + {:suite "conformance / transducers" :label "transduce conj" :expected "[2 3 4]" :actual "(transduce (map inc) conj [] [1 2 3])"} + {:suite "conformance / transducers" :label "into comp xform" :expected "[1 9 25]" :actual "(into [] (comp (filter odd?) (map (fn [x] (* x x)))) [1 2 3 4 5])"} + {:suite "conformance / transducers" :label "into take xform" :expected "[0 1 2]" :actual "(into [] (take 3) (range 100))"} + {:suite "conformance / transducers" :label "transduce no-init" :expected "6" :actual "(transduce (map inc) + [0 1 2])"} + {:suite "conformance / transducers" :label "transduce drop" :expected "[3 4 5]" :actual "(into [] (drop 2) [1 2 3 4 5])"} + {:suite "conformance / transducers" :label "transduce remove" :expected "[1 3 5]" :actual "(into [] (remove even?) [1 2 3 4 5])"} + {:suite "conformance / transducers" :label "transduce take-while" :expected "[1 2]" :actual "(into [] (take-while (fn [x] (< x 3))) [1 2 3 4 1])"} + {:suite "conformance / transducers" :label "transduce map-indexed" :expected "[[0 :a] [1 :b]]" :actual "(into [] (map-indexed (fn [i x] [i x])) [:a :b])"} + {:suite "conformance / transducers" :label "partition-all xform" :expected "[[1 2] [3 4] [5]]" :actual "(into [] (partition-all 2) [1 2 3 4 5])"} + {:suite "conformance / transducers" :label "partition-all xform comp" :expected "[2 2 1]" :actual "(into [] (comp (partition-all 2) (map count)) [1 2 3 4 5])"} + {:suite "conformance / transducers" :label "partition-by xform" :expected "[[1 1] [2 4] [5]]" :actual "(into [] (partition-by odd?) [1 1 2 4 5])"} + {:suite "conformance / transducers" :label "partition-by xform reduced" :expected "[[1 1] [2 4]]" :actual "(into [] (comp (partition-by odd?) (take 2)) [1 1 2 4 5 5])"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-find groups" :expected "[\"12-34\" \"12\" \"34\"]" :actual "(re-find #\"(\\d+)-(\\d+)\" \"x12-34y\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-find no-groups" :expected "\"123\"" :actual "(re-find #\"\\d+\" \"ab123\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "re-matches groups" :expected "[\"1.2\" \"1\" \"2\"]" :actual "(re-matches #\"(\\d+)\\.(\\d+)\" \"1.2\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "greedy backtrack" :expected "\"xxfoo\"" :actual "(re-find #\".*foo\" \"xxfoo\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "greedy thru group" :expected "[\"a,b,c\" \"a,b\" \"c\"]" :actual "(re-find #\"(.*),(.*)\" \"a,b,c\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "lazy quantifier" :expected "[\"\" \"a\"]" :actual "(re-find #\"<(.+?)>\" \"\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "flag case-insens" :expected "\"CAT\"" :actual "(re-find #\"(?i)cat\" \"a CAT\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "lookahead" :expected "\"foo\"" :actual "(re-find #\"foo(?=bar)\" \"foobar\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "neg-lookahead" :expected "\"foo\"" :actual "(re-find #\"foo(?!bar)\" \"foobaz\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "word-boundary" :expected "\"word\"" :actual "(re-find #\"\\bword\\b\" \"a word!\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "word-boundary no" :expected "nil" :actual "(re-find #\"\\bword\\b\" \"swordfish\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "optional group" :expected "[\"1.2.3\" \"1\" \"2\" \"3\" nil]" :actual "(re-find #\"(\\d+)\\.(\\d+)\\.(\\d+)(?:-([a-z]+))?\" \"1.2.3\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "alternation" :expected "\"dog\"" :actual "(re-find #\"cat|dog\" \"a dog cat\")"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "str/replace $1" :expected "\"he[ll]o\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" #\"(l+)\" \"[$1]\"))"} + {:suite "conformance / regex (capturing groups, backtracking, flags, lookahead)" :label "str/replace regex (2)" :expected "\"X-X\"" :actual "(do (require (quote [clojure.string :as s])) (s/replace \"a-b\" #\"[a-z]\" \"X\"))"} + {:suite "conformance / map literals evaluate their values" :label "map literal var" :expected "{:k 5}" :actual "(let [x 5] {:k x})"} + {:suite "conformance / map literals evaluate their values" :label "map literal nested" :expected "{:a {:b 2}}" :actual "(let [y 2] {:a {:b y}})"} + {:suite "conformance / map literals evaluate their values" :label "map literal keyfn" :expected "{:x 1}" :actual "(let [k :x] {k 1})"} + {:suite "conformance / map literals evaluate their values" :label "map literal in fn" :expected "6" :actual "(do (defn mk [a b] {:sum (+ a b)}) (:sum (mk 2 4)))"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "def 3-arg docstring" :expected "42" :actual "(do (def dd \"the doc\" 42) dd)"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "def docstring value type" :expected "true" :actual "(do (def ds \"doc\" [1 2]) (vector? ds))"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "def ^{:map} name" :expected "5" :actual "(do (def ^{:private true} mmv 5) mmv)"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "defn ^{:map} name" :expected "25" :actual "(do (defn ^{:private true} sqf [x] (* x x)) (sqf 5))"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "defmacro arity-clause" :expected "10" :actual "(do (defmacro m2c ([x] (list (quote *) x 2))) (m2c 5))"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "defmacro doc + arity" :expected "30" :actual "(do (defmacro m3c \"doc\" ([x] (list (quote *) x 3))) (* (m3c 5) 2))"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "defmulti docstring" :expected "\"A\"" :actual "(do (defmulti gmm \"the doc\" identity) (defmethod gmm :a [_] \"A\") (gmm :a))"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "try multi-body last" :expected "3" :actual "(try 1 2 3 (catch :default e 0))"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "try finally on ok+catch" :expected "9" :actual "(let [a (atom 0)] (try 1 2 (catch :default e :c) (finally (reset! a 9))) @a)"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "ns restored after catch" :expected "\"user\"" :actual "(do (ns cf.boom) (defn bz [] (throw (Exception. \"e\"))) (in-ns (quote user)) (try (cf.boom/bz) (catch :default e nil)) (str *ns*))"} + {:suite "conformance / migratus enablement: def/defmacro/defmulti forms, assoc, try, ns" :label "cross-ns methods visible" :expected "[:sql]" :actual "(do (ns cf.mm) (defmulti ext identity) (defmethod ext :default [_] :d) (defn allk [] (vec (for [[k v] (methods ext) :when (not= k :default)] k))) (ns cf.mmi) (defmethod cf.mm/ext :sql [_] :s) (in-ns (quote user)) (cf.mm/allk))"} + {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "defmacro multi-arity" :expected "[6 5 6]" :actual "(do (defmacro mar ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b)) ([a b c] (list (quote +) a b c))) [(mar 5) (mar 2 3) (mar 1 2 3)])"} + {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "defmacro doc + attr-map" :expected "10" :actual "(do (defmacro mam \"doc\" {:arglists (quote ([x]))} [x] (list (quote inc) x)) (mam 9))"} + {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "syntax-quote resolves alias" :expected "\"HI\"" :actual "(do (ns sq.lib (:require [clojure.string :as s])) (defmacro up [x] `(s/upper-case ~x)) (in-ns (quote user)) (sq.lib/up \"hi\"))"} + {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "ns name with ^{:map} meta" :expected "5" :actual "(do (ns ^{:author \"a\" :doc \"d\"} nm.meta) (def q 5) (in-ns (quote user)) nm.meta/q)"} + {:suite "conformance / defmacro surface + syntax-quote/ns (enabling real clojure libs)" :label "unquote *ns* in template" :expected "true" :actual "(do (defmacro cur-ns [] `(str ~*ns*)) (string? (cur-ns)))"} +] diff --git a/test/chez/ffi-server-test.ss b/test/chez/ffi-server-test.ss new file mode 100644 index 0000000..1925baa --- /dev/null +++ b/test/chez/ffi-server-test.ss @@ -0,0 +1,71 @@ +;; FFI + threading regression. Run from repo root: +;; chez --script test/chez/ffi-server-test.ss +;; +;; Covers two fixes: +;; - the HTTP server's blocking accept/recv/send are __collect_safe, so a thread +;; idle in accept() no longer pins the stop-the-world collector. With the bug, +;; a (collect) on the main thread throws "cannot collect when multiple threads +;; are active"; with the fix it succeeds while the server sits in accept(). +;; - jolt.http-client temp-file paths are unique per process+thread (no clobber). +;; Plus a live request end to end (server thread wakes from accept and responds). + +(import (chezscheme)) + +;; mirror cli.ss's load sequence through http-server.ss +(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") +(load "host/chez/http-client.ss") +(load "host/chez/sqlite.ss") +(load "host/chez/http-server.ss") +(load "host/chez/loader.ss") ; defines jolt-sh-out, used by http-client + +(define total 0) (define fails 0) +(define (ok name pred) (set! total (+ total 1)) (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) + +(define port 8391) +(define run-server (var-deref "jolt.http.server" "run-server")) +(define stop-server (var-deref "jolt.http.server" "stop-server")) +(define http-get (var-deref "jolt.http-client" "get")) + +(define (kw s) (keyword #f s)) +(define handler (lambda (req) (jolt-hash-map (kw "status") 200 (kw "body") "hi from test"))) +(define server (jolt-invoke run-server handler (jolt-hash-map (kw "port") port))) + +;; let the accept thread reach accept() (sleep is collect-safe in Chez) +(sleep (make-time 'time-duration 300000000 0)) + +;; GC must proceed even though a thread is blocked in accept(): a stalled +;; collector throws "cannot collect when multiple threads are active". +(ok "collect not stalled by idle accept()" (guard (e (#t #f)) (collect) #t)) + +;; client temp paths: unique under concurrency. Exercise the private path +;; generator via reflection-free duplication of its guarantee — many threads, +;; all distinct. +(let ((seen (make-hashtable string-hash string=?)) (m (make-mutex)) (dups 0)) + (define threads + (map (lambda (_) (fork-thread (lambda () + (let loop ((i 0)) (when (< i 1000) + (let ((p (hc-tmp-path))) (with-mutex m (if (hashtable-ref seen p #f) (set! dups (+ dups 1)) (hashtable-set! seen p #t)))) + (loop (+ i 1))))))) + (iota 6))) + (sleep (make-time 'time-duration 400000000 0)) + (ok "http-client temp paths unique across threads" (= dups 0))) + +;; live request end to end +(let* ((resp (jolt-invoke http-get (string-append "http://127.0.0.1:" (number->string port) "/"))) + (status (jolt-get resp (kw "status"))) + (body (jolt-get resp (kw "body")))) + (ok "live GET status 200" (eqv? 200 status)) + (ok "live GET body" (and (string? body) (string=? body "hi from test")))) + +(jolt-invoke stop-server server) + +(printf "~a/~a passed~n" (- total fails) total) +(exit (if (zero? fails) 0 1)) diff --git a/test/chez/transient-test.ss b/test/chez/transient-test.ss new file mode 100644 index 0000000..f643d14 --- /dev/null +++ b/test/chez/transient-test.ss @@ -0,0 +1,48 @@ +;; Transient regression: mutable backing + snapshot-on-persist (jolt-kl2l). Run: +;; chez --script test/chez/transient-test.ss +;; Semantics are covered broadly by the corpus; this pins the invariants the +;; mutable port must keep AND that large builds stay linear (a copy-on-write +;; regression would make the 200k builds quadratic and time the gate out). + +(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 total 0) (define fails 0) +(define (ok name pred) (set! total (+ total 1)) (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) +(define (ev s) (jolt-final-str (jolt-compile-eval (string-append "(do " s ")") "user"))) +(define (is name s expect) (ok (string-append name " => " expect) (string=? (ev s) expect))) + +;; --- mutation is in place; persistent! snapshots back ----------------------- +(is "vector build" "(persistent! (reduce conj! (transient []) (range 5)))" "[0 1 2 3 4]") +(is "map build" "(= {0 0 1 1 2 2} (persistent! (reduce (fn [t i] (assoc! t i i)) (transient {}) (range 3))))" "true") +(is "set build" "(count (persistent! (reduce conj! (transient #{}) [1 2 2 3])))" "3") +(is "pop!" "(persistent! (pop! (conj! (transient [1 2]) 3)))" "[1 2]") +(is "dissoc!" "(persistent! (dissoc! (assoc! (transient {}) :a 1 :b 2) :a))" "{:b 2}") +(is "disj!" "(persistent! (disj! (conj! (transient #{}) :x :y) :x))" "#{:y}") + +;; --- a transient never mutates its source ----------------------------------- +(is "source map unchanged" "(let [m {:a 1} _ (persistent! (assoc! (transient m) :b 2))] (= m {:a 1}))" "true") +(is "source vector unchanged" "(let [v [1 2] _ (persistent! (conj! (transient v) 3))] (= v [1 2]))" "true") + +;; --- edges the port must keep ----------------------------------------------- +(is "nil key" "(get (persistent! (assoc! (transient {}) nil :v)) nil)" ":v") +(is "collection key" "(get (persistent! (assoc! (transient {}) [1 2] :v)) [1 2])" ":v") +(is "dangling key pads" "(= {:a 1 :b nil} (persistent! (assoc! (transient {}) :a 1 :b)))" "true") +(is "vector? is false" "(vector? (transient []))" "false") +(is "transient sorted (cow)" "(persistent! (assoc! (transient (sorted-map :b 2)) :a 1))" "{:a 1, :b 2}") +(ok "lone key throws" (guard (e (#t #t)) (ev "(persistent! (assoc! (transient {}) :a))") #f)) +(ok "use after persistent!" (guard (e (#t #t)) (ev "(let [t (transient [])] (persistent! t) (conj! t 1))") #f)) + +;; --- linear, not quadratic: 200k builds finish near-instantly --------------- +(is "big vector build" "(count (persistent! (reduce conj! (transient []) (range 200000))))" "200000") +(is "big map build" "(count (persistent! (reduce (fn [t i] (assoc! t i i)) (transient {}) (range 200000))))" "200000") + +(printf "~a/~a passed~n" (- total fails) total) +(exit (if (zero? fails) 0 1)) diff --git a/test/chez/unit.edn b/test/chez/unit.edn new file mode 100644 index 0000000..b94695f --- /dev/null +++ b/test/chez/unit.edn @@ -0,0 +1,462 @@ +[ + {:suite "atomwatch" :expr "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (reset! seen 1))) (reset! a 5) @seen)" :expected "1"} + {:suite "atomwatch" :expr "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (swap! seen inc))) (remove-watch a :k) (reset! a 5) @seen)" :expected "0"} + {:suite "atomwatch" :expr "(let [a (atom 0) log (atom [])] (add-watch a :k (fn [k r o n] (swap! log conj [o n]))) (reset! a 1) (reset! a 2) @log)" :expected "[[0 1] [1 2]]"} + {:suite "atomwatch" :expr "(let [a (atom 0)] (set-validator! a number?) (reset! a 5) @a)" :expected "5"} + {:suite "atomwatch" :expr "(let [a (atom 5)] (set-validator! a pos?) (swap! a inc) @a)" :expected "6"} + {:suite "atomwatch" :expr "(let [a (atom 0)] (set-validator! a number?) (fn? (get-validator a)))" :expected "true"} + {:suite "atomwatch" :expr "(let [a (atom 0)] (nil? (get-validator a)))" :expected "true"} + {:suite "atomwatch" :expr "(let [a (atom 0)] (set-validator! a pos?) (reset! a -1))" :expected :throws} + {:suite "atomwatch" :expr "(let [a (atom 5)] (set-validator! a pos?) (swap! a (fn [_] -1)) @a)" :expected :throws} + {:suite "atomwatch" :expr "(let [a (atom 0) c (atom 0)] (add-watch a :k (fn [k r o n] (swap! c inc))) (swap! a inc) (swap! a inc) @c)" :expected "2"} + {:suite "class" :expr "String" :expected "java.lang.String"} + {:suite "class" :expr "Number" :expected "java.lang.Number"} + {:suite "class" :expr "Keyword" :expected "clojure.lang.Keyword"} + {:suite "class" :expr "File" :expected "java.io.File"} + {:suite "class" :expr "Exception" :expected "java.lang.Exception"} + {:suite "class" :expr "MapEntry" :expected "clojure.lang.MapEntry"} + {:suite "class" :expr "(class 1)" :expected "java.lang.Long"} + {:suite "class" :expr "(class 1.5)" :expected "java.lang.Double"} + {:suite "class" :expr "(class \"s\")" :expected "java.lang.String"} + {:suite "class" :expr "(class :k)" :expected "clojure.lang.Keyword"} + {:suite "class" :expr "(class true)" :expected "java.lang.Boolean"} + {:suite "class" :expr "(class false)" :expected "java.lang.Boolean"} + {:suite "class" :expr "(class nil)" :expected ""} + {:suite "class" :expr "(= String (class \"abc\"))" :expected "true"} + {:suite "class" :expr "(= Number (class 7))" :expected "false"} + {:suite "class" :expr "(= String (class 7))" :expected "false"} + {:suite "class" :expr "(do (defmulti cm (fn [x] (class x))) (defmethod cm String [x] :str) (cm \"a\"))" :expected ":str"} + {:suite "class" :expr "(do (defmulti cn (fn [x] (class x))) (defmethod cn nil [x] :nil) (defmethod cn String [x] :str) (cn nil))" :expected ":nil"} + {:suite "class" :expr "(do (defmulti cn (fn [x] (class x))) (defmethod cn nil [x] :nil) (defmethod cn String [x] :str) (cn \"z\"))" :expected ":str"} + {:suite "dotform" :expr "(. \"HI\" toLowerCase)" :expected "hi"} + {:suite "dotform" :expr "(. \"abc\" length)" :expected "3"} + {:suite "dotform" :expr "(. \"abc\" toUpperCase)" :expected "ABC"} + {:suite "dotform" :expr "(. [1 2 3] count)" :expected "3"} + {:suite "dotform" :expr "(. [10 20 30] nth 1)" :expected "20"} + {:suite "dotform" :expr "(. {:a 1 :b 2} count)" :expected "2"} + {:suite "dotform" :expr "(. {:a 1 :b 2} get :b)" :expected "2"} + {:suite "dotform" :expr "(. {:a 1} containsKey :a)" :expected "true"} + {:suite "dotform" :expr "(. {:count 99} count)" :expected "1"} + {:suite "dotform" :expr "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)" :expected "v=41"} + {:suite "dotform" :expr "(. {:greet (fn [self n] (str \"Hello \" n))} greet \"Alice\")" :expected "Hello Alice"} + {:suite "dotform" :expr "(. {:value 41} value)" :expected "41"} + {:suite "dotform" :expr "(.-value {:value 41})" :expected "41"} + {:suite "dotform" :expr "(.-x {:x 7 :y 9})" :expected "7"} + {:suite "dotform" :expr "(. {:value 41} -value)" :expected "41"} + {:suite "dotform" :expr "(do (defrecord Rf [x]) (.-x (->Rf 7)))" :expected "7"} + {:suite "dotform" :expr "(do (defrecord Rg [a b]) (.-b (->Rg 1 2)))" :expected "2"} + {:suite "dotform" :expr "(do (defprotocol Greet (hi [_])) (defrecord Rh [nm] Greet (hi [_] (str \"hi \" nm))) (. (->Rh \"x\") hi))" :expected "hi x"} + {:suite "dotform" :expr "(try (throw (ex-info \"bad\" {})) (catch Throwable e (.getMessage e)))" :expected "bad"} + {:suite "dotform" :expr "(try (throw (ex-info \"bad\" {:k 1})) (catch Throwable e (.getMessage e)))" :expected "bad"} + {:suite "dotform" :expr "(try (throw \"boom\") (catch Throwable e (.getMessage e)))" :expected "boom"} + {:suite "dotform" :expr "(try (throw (Exception. \"boom\")) (catch Throwable e (.getMessage e)))" :expected "boom"} + {:suite "dotform" :expr "(try (throw (IllegalArgumentException. \"bad\")) (catch Exception e (.getMessage e)))" :expected "bad"} + {:suite "dotform" :expr "(.equals \"a\" \"a\")" :expected "true"} + {:suite "dotform" :expr "(.equals \"a\" \"b\")" :expected "false"} + {:suite "dotform" :expr "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)" :expected "v=41"} + {:suite "dynbind" :expr "(do (def ^:dynamic *bx* 10) (binding [*bx* 99] *bx*))" :expected "99"} + {:suite "dynbind" :expr "(do (def ^:dynamic *by* 10) (binding [*by* 99] *by*) *by*)" :expected "10"} + {:suite "dynbind" :expr "(do (def ^:dynamic *bz* 0) (defn rdz [] *bz*) (binding [*bz* 7] (rdz)))" :expected "7"} + {:suite "dynbind" :expr "(do (def ^:dynamic *bv* 1) [(binding [*bv* 2] *bv*) *bv*])" :expected "[2 1]"} + {:suite "dynbind" :expr "(do (def ^:dynamic *bn* 1) (binding [*bn* 2] (binding [*bn* 3] *bn*)))" :expected "3"} + {:suite "dynbind" :expr "(do (def ^:dynamic *bo* 1) (binding [*bo* 2] (binding [*bo* 3] nil) *bo*))" :expected "2"} + {:suite "dynbind" :expr "(do (def ^:dynamic *z* 1) (binding [*z* 0] (var-set (var *z*) 5) *z*))" :expected "5"} + {:suite "dynbind" :expr "(do (def ^:dynamic *zr* 1) (binding [*zr* 0] (var-set (var *zr*) 5)) *zr*)" :expected "1"} + {:suite "dynbind" :expr "(do (def ^:dynamic *tb* 1) (thread-bound? (var *tb*)))" :expected "false"} + {:suite "dynbind" :expr "(do (def ^:dynamic *tc* 1) (binding [*tc* 2] (thread-bound? (var *tc*))))" :expected "true"} + {:suite "dynbind" :expr "(do (def ^:dynamic *wb* 1) (with-bindings* {(var *wb*) 7} (fn [] *wb*)))" :expected "7"} + {:suite "dynbind" :expr "(do (def ^:dynamic *cf* 1) (let [g (binding [*cf* 3] (bound-fn* (fn [] *cf*)))] (g)))" :expected "3"} + {:suite "dynbind" :expr "(do (def ^:dynamic *gb* 1) (binding [*gb* 9] (get (get-thread-bindings) (var *gb*))))" :expected "9"} + {:suite "dynbind" :expr "(with-local-vars [x 1] (var-get x))" :expected "1"} + {:suite "dynbind" :expr "(with-local-vars [x 1] (var-set x 2) (var-get x))" :expected "2"} + {:suite "dynbind" :expr "(with-local-vars [a 1 b 2] [(var-get a) (var-get b)])" :expected "[1 2]"} + {:suite "dynbind" :expr "(with-local-vars [x 0] (let [bump (fn [v] (var-set v (+ 5 (var-get v))))] (bump x) (var-get x)))" :expected "5"} + {:suite "dynbind" :expr "(let [y 3] (with-local-vars [x y] (var-get x)))" :expected "3"} + {:suite "dynbind" :expr "(with-local-vars [x 1] :done)" :expected ":done"} + {:suite "dynbind" :expr "(do (defn wrf [] 1) (with-redefs [wrf (fn [] 42)] (wrf)))" :expected "42"} + {:suite "dynbind" :expr "(do (defn wrg [] 1) (with-redefs [wrg (fn [] 42)]) (wrg))" :expected "1"} + {:suite "dynbind" :expr "(do (defn wrh [] 1) (try (with-redefs [wrh (fn [] 42)] (throw (ex-info \"x\" {}))) (catch :default e nil)) (wrh))" :expected "1"} + {:suite "dynbind" :expr "(do (defn wri [] 1) (with-redefs-fn {(var wri) (fn [] 42)} (fn [] (wri))))" :expected "42"} + {:suite "dynbind" :expr "(do (def av 1) (alter-var-root (var av) inc) av)" :expected "2"} + {:suite "insttime" :expr "(inst? #inst \"2020-01-01T00:00:00Z\")" :expected "true"} + {:suite "insttime" :expr "(inst-ms #inst \"1970-01-01T00:00:01Z\")" :expected "1000"} + {:suite "insttime" :expr "(inst-ms #inst \"1970-01-01T00:00:00.123Z\")" :expected "123"} + {:suite "insttime" :expr "(inst-ms #inst \"2020-01-01T00:00:00Z\")" :expected "1577836800000"} + {:suite "insttime" :expr "(inst-ms* #inst \"1970-01-01T00:00:00Z\")" :expected "0"} + {:suite "insttime" :expr "(some? #inst \"2020-01-01T00:00:00Z\")" :expected "true"} + {:suite "insttime" :expr "(str (type #inst \"2020-01-01T00:00:00Z\"))" :expected ":jolt/inst"} + {:suite "insttime" :expr "(= #inst \"2020\" #inst \"2020-01-01T00:00:00.000Z\")" :expected "true"} + {:suite "insttime" :expr "(= #inst \"2020-03\" #inst \"2020-03-01T00:00:00Z\")" :expected "true"} + {:suite "insttime" :expr "(= #inst \"2020-03-15\" #inst \"2020-03-15T00:00:00Z\")" :expected "true"} + {:suite "insttime" :expr "(= #inst \"2020-01-01T01:00:00+01:00\" #inst \"2020-01-01T00:00:00Z\")" :expected "true"} + {:suite "insttime" :expr "(= #inst \"2019-12-31T23:00:00-01:00\" #inst \"2020-01-01T00:00:00Z\")" :expected "true"} + {:suite "insttime" :expr "(= #inst \"2020-01-01T00:00:00Z\" #inst \"2020-01-01T00:00:01Z\")" :expected "false"} + {:suite "insttime" :expr "(get {#inst \"2020-01-01T00:00:00Z\" :v} #inst \"2020-01-01T00:00:00.000Z\")" :expected ":v"} + {:suite "insttime" :expr "(pr-str #inst \"2020-01-01T00:00:00Z\")" :expected "#inst \"2020-01-01T00:00:00.000-00:00\""} + {:suite "insttime" :expr "(str #inst \"2020-01-01T00:00:00Z\")" :expected "2020-01-01T00:00:00.000-00:00"} + {:suite "insttime" :expr "(uuid? #uuid \"550e8400-e29b-41d4-a716-446655440000\")" :expected "true"} + {:suite "insttime" :expr "(= #uuid \"550E8400-E29B-41D4-A716-446655440000\" #uuid \"550e8400-e29b-41d4-a716-446655440000\")" :expected "true"} + {:suite "insttime" :expr "(pr-str #uuid \"550e8400-e29b-41d4-a716-446655440000\")" :expected "#uuid \"550e8400-e29b-41d4-a716-446655440000\""} + {:suite "insttime" :expr "(.getTime #inst \"1970-01-01T00:00:00Z\")" :expected "0"} + {:suite "insttime" :expr "(instance? java.util.Date #inst \"2020-01-01T00:00:00Z\")" :expected "true"} + {:suite "insttime" :expr "(instance? java.sql.Timestamp #inst \"2020-01-01T00:00:00Z\")" :expected "false"} + {:suite "insttime" :expr "(.toEpochMilli (Instant/ofEpochMilli 1234))" :expected "1234"} + {:suite "insttime" :expr "(instance? java.time.Instant (Instant/ofEpochMilli 0))" :expected "true"} + {:suite "insttime" :expr "(> (.toEpochMilli (Instant/now)) 1500000000000)" :expected "true"} + {:suite "insttime" :expr "(instance? LocalDateTime (-> #inst \"2020-03-05T13:45:30Z\" (.toInstant) (.atZone (ZoneId/systemDefault)) (.toLocalDateTime)))" :expected "true"} + {:suite "insttime" :expr "(.format (DateTimeFormatter/ofPattern \"yyyy-MM-dd\") #inst \"2020-03-05T13:45:30Z\")" :expected "2020-03-05"} + {:suite "insttime" :expr "(boolean (re-matches #\"[A-Z][a-z]{2} \\d{1,2}, 2020 \\d{1,2}:\\d{2} [AP]M\" (.format (DateTimeFormatter/ofPattern \"MMM d, yyyy h:mm a\") #inst \"2020-03-05T13:45:30Z\")))" :expected "true"} + {:suite "insttime" :expr "(boolean (re-matches #\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\" (.format DateTimeFormatter/ISO_LOCAL_DATE_TIME #inst \"2020-03-05T13:45:30Z\")))" :expected "true"} + {:suite "insttime" :expr "(string? (.format (DateTimeFormatter/ofLocalizedDate FormatStyle/MEDIUM) #inst \"2020-03-05T13:45:30Z\"))" :expected "true"} + {:suite "insttime" :expr "(string? (.format (.withLocale (DateTimeFormatter/ofPattern \"yyyy\") (java.util.Locale. \"en\")) #inst \"2020-01-01T00:00:00Z\"))" :expected "true"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (str (io/file \"/a/b\")))" :expected "/a/b"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (str (io/file \"/a\" \"b\")))" :expected "/a/b"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.getName (io/file \"/a/b/c.txt\")))" :expected "c.txt"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.getPath (io/file \"/a\" \"b\")))" :expected "/a/b"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.isDirectory (io/file \"docs\")))" :expected "true"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.isFile (io/file \"README.md\")))" :expected "true"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.isFile (io/file \"docs\")))" :expected "false"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.exists (io/file \"/no/such/path/xyz\")))" :expected "false"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (.exists (io/file \"README.md\")))" :expected "true"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (instance? java.io.File (io/file \"/a/b\")))" :expected "true"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (instance? java.io.File \"/a/b\"))" :expected "false"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (str (type (io/file \"/a\"))))" :expected ":jolt/file"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (every? (fn [f] (instance? java.io.File f)) (file-seq (io/file \"docs\"))))" :expected "true"} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (pos? (count (filter (fn [f] (.isFile f)) (file-seq (io/file \"docs\"))))))" :expected "true"} + {:suite "io" :expr "(do (require (quote [clojure.string :as s])) (boolean (some (fn [p] (s/ends-with? p \"README.md\")) (file-seq \".\"))))" :expected "true"} + {:suite "io" :expr "(string? (slurp \"README.md\"))" :expected "true"} + {:suite "io" :expr "(do (spit \"/tmp/jolt-io-test.txt\" \"hello\") (slurp \"/tmp/jolt-io-test.txt\"))" :expected "hello"} + {:suite "io" :expr "(do (spit \"/tmp/jolt-io-test.txt\" \"a\") (spit \"/tmp/jolt-io-test.txt\" \"b\" :append true) (slurp \"/tmp/jolt-io-test.txt\"))" :expected "ab"} + {:suite "io" :expr "(flush)" :expected ""} + {:suite "io" :expr "(do (require (quote [clojure.java.io :as io])) (string? (slurp (io/file \"README.md\"))))" :expected "true"} + {:suite "ioreader" :expr "(apply str (char-array \"abc\"))" :expected "abc"} + {:suite "ioreader" :expr "(.read (StringReader. (apply str (char-array \"Qz\"))))" :expected "81"} + {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.read (io/reader (char-array \"abc\"))))" :expected "97"} + {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.read (io/reader (StringReader. \"k\"))))" :expected "107"} + {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (slurp (io/reader (char-array \"xyz\"))))" :expected "xyz"} + {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (string? (slurp (io/reader \"README.md\"))))" :expected "true"} + {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.toString (.toURL (io/file \"/tmp/x\"))))" :expected "file:/tmp/x"} + {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.toURI (io/file \"/tmp/x\")))" :expected "file:/tmp/x"} + {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.getPath (.toURL (io/file \"/tmp/x\"))))" :expected "/tmp/x"} + {:suite "ioreader" :expr "(do (require (quote [clojure.java.io :as io])) (.getAbsolutePath (io/file \"/a/b\")))" :expected "/a/b"} + {:suite "ioreader" :expr "(slurp (StringReader. \"a=1\"))" :expected "a=1"} + {:suite "ioreader" :expr "(slurp (StringReader. \"b\") :encoding \"UTF-8\")" :expected "b"} + {:suite "ioreader" :expr "(with-open [r (StringReader. \"a\")] (.read r))" :expected "97"} + {:suite "ioreader" :expr "(let [log (atom [])] (with-open [c {:close (fn [] (swap! log conj :closed))}] :r) (deref log))" :expected "[:closed]"} + {:suite "ioreader" :expr "(let [log (atom [])] (try (with-open [c {:close (fn [] (swap! log conj :closed))}] (throw (ex-info \"boom\" {}))) (catch Exception e nil)) (deref log))" :expected "[:closed]"} + {:suite "ioreader" :expr "(let [log (atom [])] (with-open [a {:close (fn [] (swap! log conj :outer))} b {:close (fn [] (swap! log conj :inner))}] :r) (deref log))" :expected "[:inner :outer]"} + {:suite "ioreader" :expr "(with-open [c {:close (fn [] nil) :v 5}] (:v c))" :expected "5"} + {:suite "javastatic" :expr "(Math/sqrt 16)" :expected "4.0"} + {:suite "javastatic" :expr "(Math/abs -3)" :expected "3"} + {:suite "javastatic" :expr "(Math/max 2 7)" :expected "7"} + {:suite "javastatic" :expr "(pos? Long/MAX_VALUE)" :expected "true"} + {:suite "javastatic" :expr "(String/valueOf 42)" :expected "42"} + {:suite "javastatic" :expr "(String/valueOf \"hi\")" :expected "hi"} + {:suite "javastatic" :expr "(String/valueOf :k)" :expected ":k"} + {:suite "javastatic" :expr "(String/valueOf nil)" :expected "null"} + {:suite "javastatic" :expr "(Long/parseLong \"42\")" :expected "42"} + {:suite "javastatic" :expr "(Long/valueOf \"42\")" :expected "42"} + {:suite "javastatic" :expr "(Integer/parseInt \"ff\" 16)" :expected "255"} + {:suite "javastatic" :expr "(.byteValue (Integer/valueOf \"ff\" 16))" :expected "-1"} + {:suite "javastatic" :expr "(Boolean/parseBoolean \"true\")" :expected "true"} + {:suite "javastatic" :expr "(Boolean/parseBoolean \"yes\")" :expected "false"} + {:suite "javastatic" :expr "(Character/isUpperCase \\A)" :expected "true"} + {:suite "javastatic" :expr "(Character/isLowerCase \\a)" :expected "true"} + {:suite "javastatic" :expr "(Character/isUpperCase \\a)" :expected "false"} + {:suite "javastatic" :expr "(Thread/interrupted)" :expected "false"} + {:suite "javastatic" :expr "(string? (System/getProperty \"os.name\"))" :expected "true"} + {:suite "javastatic" :expr "(string? (get (System/getenv) \"HOME\"))" :expected "true"} + {:suite "javastatic" :expr "(string? (System/getenv \"HOME\"))" :expected "true"} + {:suite "javastatic" :expr "(fn? System/exit)" :expected "true"} + {:suite "javastatic" :expr "(string? (get (System/getProperties) \"os.name\"))" :expected "true"} + {:suite "javastatic" :expr "(pos? (count (seq (System/getenv))))" :expected "true"} + {:suite "javastatic" :expr "(let [es (map (fn [[k v]] [k v]) (System/getenv))] (and (pos? (count es)) (every? vector? es)))" :expected "true"} + {:suite "javastatic" :expr "(.toString (StringBuilder. \"x\"))" :expected "x"} + {:suite "javastatic" :expr "(.toString (-> (StringBuilder.) (.append \"a\") (.append \\b) (.append 1)))" :expected "ab1"} + {:suite "javastatic" :expr "(.toString (.append (StringBuilder. 16) \"x\"))" :expected "x"} + {:suite "javastatic" :expr "(let [sb (StringBuilder.)] (.append sb \"abcd\") (.setLength sb 2) (.toString sb))" :expected "ab"} + {:suite "javastatic" :expr "(let [w (StringWriter.)] (.write w \"a\") (.append w \\b) (.toString w))" :expected "ab"} + {:suite "javastatic" :expr "(let [r (StringReader. \"ab\")] [(.read r) (.read r) (.read r)])" :expected "[97 98 -1]"} + {:suite "javastatic" :expr "(let [r (StringReader. \"ab\")] (.mark r 1) [(.read r) (do (.reset r) (.read r))])" :expected "[97 97]"} + {:suite "javastatic" :expr "(let [r (java.io.PushbackReader. (java.io.StringReader. \"ab\"))] [(.read r) (.read r)])" :expected "[97 98]"} + {:suite "javastatic" :expr "(let [r (PushbackReader. (StringReader. \"ab\")) a (.read r)] (.unread r a) [a (.read r) (.read r)])" :expected "[97 97 98]"} + {:suite "javastatic" :expr "(let [r (PushbackReader. (StringReader. \"a\"))] (.unread r \\x) [(.read r) (.read r)])" :expected "[120 97]"} + {:suite "javastatic" :expr "(BigInteger. \"123\")" :expected "123"} + {:suite "javastatic" :expr "(let [m (HashMap. {:a 1 :b 2})] (.get m :b))" :expected "2"} + {:suite "javastatic" :expr "(let [m (HashMap. {})] (.put m :x 1) (.put m :y 2) (.size m))" :expected "2"} + {:suite "javastatic" :expr "(let [t (StringTokenizer. \"a=1&b=2\" \"&\")] [(.nextToken t) (.nextToken t)])" :expected "[a=1 b=2]"} + {:suite "javastatic" :expr "(.toString (StringBuilder. \"x\"))" :expected "x"} + {:suite "javastatic" :expr "(URLEncoder/encode \"a b=c\")" :expected "a+b%3Dc"} + {:suite "javastatic" :expr "(URLDecoder/decode (URLEncoder/encode \"x &=%?\"))" :expected "x &=%?"} + {:suite "javastatic" :expr "(String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))" :expected "aGVsbG8="} + {:suite "javastatic" :expr "(String. (.decode (Base64/getDecoder) (String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))))" :expected "hello"} + {:suite "javastatic" :expr "(Integer/parseInt \"ff\" 16)" :expected "255"} + {:suite "javastatic" :expr "(regex? (Pattern/compile \"a.c\"))" :expected "true"} + {:suite "javastatic" :expr "(.split (Pattern/compile \",\") \"a,b,c\")" :expected "(a b c)"} + {:suite "javastatic" :expr "(do (require '[clojure.string :as s]) (s/replace \"a1b2\" (Pattern/compile \"[0-9]\") \"\"))" :expected "ab"} + {:suite "javastatic" :expr "(boolean (re-find (Pattern/compile \"^x\" Pattern/MULTILINE) \"y\\nx\"))" :expected "true"} + {:suite "javastatic" :expr "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"za.cy\"))" :expected "true"} + {:suite "javastatic" :expr "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"zabcy\"))" :expected "false"} + {:suite "ns" :expr "(some? (find-ns 'clojure.core))" :expected "true"} + {:suite "ns" :expr "(nil? (find-ns 'does.not.exist))" :expected "true"} + {:suite "ns" :expr "(var? (resolve '+))" :expected "true"} + {:suite "ns" :expr "(nil? (resolve 'totally-undefined-xyz))" :expected "true"} + {:suite "ns" :expr "(do (def npv 1) (some? (get (ns-publics 'user) 'npv)))" :expected "true"} + {:suite "ns" :expr "(do (def nmv 1) (some? (get (ns-map 'user) 'nmv)))" :expected "true"} + {:suite "ns" :expr "(map? (ns-aliases 'clojure.core))" :expected "true"} + {:suite "ns" :expr "(map? (ns-interns 'user))" :expected "true"} + {:suite "ns" :expr "(do (def q 1) (pos? (count (ns-interns 'user))))" :expected "true"} + {:suite "ns" :expr "(pos? (count (all-ns)))" :expected "true"} + {:suite "ns" :expr "(= (ns-name *ns*) (ns-name (find-ns 'user)))" :expected "true"} + {:suite "ns" :expr "(str (in-ns 'jolt.test-ns-b))" :expected "jolt.test-ns-b"} + {:suite "ns" :expr "(do (in-ns 'jolt.test-ns-a) (str *ns*))" :expected "jolt.test-ns-a"} + {:suite "ns" :expr "(do (def nuv 1) (ns-unmap 'user 'nuv) (nil? (resolve 'nuv)))" :expected "true"} + {:suite "ns" :expr "(do (in-ns 'my.ns) (symbol? 'x))" :expected "true"} + {:suite "ns" :expr "(str (ns-name *ns*))" :expected "user"} + {:suite "ns" :expr "(var? (find-var 'clojure.core/map))" :expected "true"} + {:suite "ns" :expr "(= 'user (ns-name (the-ns 'user)))" :expected "true"} + {:suite "ns" :expr "(= 'foo.bar (ns-name (create-ns 'foo.bar)))" :expected "true"} + {:suite "reader" :expr "(= 42 (read-string \"42\"))" :expected "true"} + {:suite "reader" :expr "(= 42 (read-string \"0x2A\"))" :expected "true"} + {:suite "reader" :expr "(== 0.5 (read-string \"1/2\"))" :expected "true"} + {:suite "reader" :expr "(= -3.5 (read-string \"-3.5\"))" :expected "true"} + {:suite "reader" :expr "(== 1000.0 (read-string \"1e3\"))" :expected "true"} + {:suite "reader" :expr "(= 1 (read-string \"1N\"))" :expected "true"} + {:suite "reader" :expr "(integer? (read-string \"7\"))" :expected "true"} + {:suite "reader" :expr "(= :foo (read-string \":foo\"))" :expected "true"} + {:suite "reader" :expr "(= :a/b (read-string \":a/b\"))" :expected "true"} + {:suite "reader" :expr "(= :foo (read-string \"::foo\"))" :expected "true"} + {:suite "reader" :expr "(= (quote sym) (read-string \"sym\"))" :expected "true"} + {:suite "reader" :expr "(= (quote ns/sym) (read-string \"ns/sym\"))" :expected "true"} + {:suite "reader" :expr "(nil? (read-string \"nil\"))" :expected "true"} + {:suite "reader" :expr "(true? (read-string \"true\"))" :expected "true"} + {:suite "reader" :expr "(false? (read-string \"false\"))" :expected "true"} + {:suite "reader" :expr "(= \\a (read-string \"\\\\a\"))" :expected "true"} + {:suite "reader" :expr "(= \\newline (read-string \"\\\\newline\"))" :expected "true"} + {:suite "reader" :expr "(= \\space (read-string \"\\\\space\"))" :expected "true"} + {:suite "reader" :expr "(= \"a\\nb\" (read-string \"\\\"a\\\\nb\\\"\"))" :expected "true"} + {:suite "reader" :expr "(= [1 2 3] (read-string \"[1 2 3]\"))" :expected "true"} + {:suite "reader" :expr "(= (quote (+ 1 2)) (read-string \"(+ 1 2)\"))" :expected "true"} + {:suite "reader" :expr "(= {:a 1 :b 2} (read-string \"{:a 1 :b 2}\"))" :expected "true"} + {:suite "reader" :expr "(:value (read-string \"#{1 2 3}\"))" :expected "[1 2 3]"} + {:suite "reader" :expr "(= :jolt/set (:jolt/type (read-string \"#{1 2 3}\")))" :expected "true"} + {:suite "reader" :expr "(= [1 [2 3] {:k :v}] (read-string \"[1 [2 3] {:k :v}]\"))" :expected "true"} + {:suite "reader" :expr "(= (quote (quote x)) (read-string \"'x\"))" :expected "true"} + {:suite "reader" :expr "(= (quote (clojure.core/deref a)) (read-string \"@a\"))" :expected "true"} + {:suite "reader" :expr "(= (quote (syntax-quote (a (unquote b)))) (read-string \"`(a ~b)\"))" :expected "true"} + {:suite "reader" :expr "(= (quote (unquote-splicing xs)) (read-string \"~@xs\"))" :expected "true"} + {:suite "reader" :expr "(= 42 (read-string \"; comment\\n42\"))" :expected "true"} + {:suite "reader" :expr "(= [1 2] (read-string \"[1 #_ 9 2]\"))" :expected "true"} + {:suite "reader" :expr "(nil? (read-string \"\"))" :expected "true"} + {:suite "reader" :expr "(nil? (read-string \" , ,\"))" :expected "true"} + {:suite "reader" :expr "(:tag (meta (read-string \"^String x\")))" :expected "String"} + {:suite "reader" :expr "(:foo (meta (read-string \"^:foo x\")))" :expected "true"} + {:suite "reader" :expr "(= 42 (with-in-str \"42\" (read)))" :expected "true"} + {:suite "reader" :expr "(= (quote (+ 1 2)) (with-in-str \"(+ 1 2)\" (read)))" :expected "true"} + {:suite "reader" :expr "(with-in-str \"1 2\" [(read) (read)])" :expected "[1 2]"} + {:suite "reader" :expr "(= :done (with-in-str \"\" (read *in* false :done)))" :expected "true"} + {:suite "reader" :expr "(let [[v s] (with-in-str \"42 rest\" (read+string))] (and (= v 42) (string? s)))" :expected "true"} + {:suite "reader" :expr "(= [1 2] (with-in-str \"1 2\" [(first (read+string)) (first (read+string))]))" :expected "true"} + {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (= #{1 2} (e0/read-string \"#{1 2}\")))" :expected "true"} + {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (uuid? (e0/read-string \"#uuid \\\"550e8400-e29b-41d4-a716-446655440000\\\"\")))" :expected "true"} + {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (inst? (e0/read-string \"#inst \\\"2020-01-01T00:00:00Z\\\"\")))" :expected "true"} + {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (= :end (e0/read-string {:eof :end} \"\")))" :expected "true"} + {:suite "reader" :expr "(do (require (quote [clojure.edn :as e0])) (= [:custom 5] (e0/read-string {:readers {(quote custom) (fn [v] [:custom v])}} \"#custom 5\")))" :expected "true"} + {:suite "reader" :expr "(do (require (quote clojure.edn)) (= {:a 1 :b 2} (clojure.edn/read-string \"{:a 1\\n :b 2}\")))" :expected "true"} + {:suite "seqpred" :expr "(seq? (map inc [1 2 3]))" :expected "true"} + {:suite "seqpred" :expr "(seq? (filter odd? [1 2 3]))" :expected "true"} + {:suite "seqpred" :expr "(seq? (lazy-seq (cons 1 nil)))" :expected "true"} + {:suite "seqpred" :expr "(seq? (take 3 (iterate inc 0)))" :expected "true"} + {:suite "seqpred" :expr "(seq? (cons 0 (range 3)))" :expected "true"} + {:suite "seqpred" :expr "(seq? [1 2 3])" :expected "false"} + {:suite "seqpred" :expr "(seq? {:a 1})" :expected "false"} + {:suite "seqpred" :expr "(seq? nil)" :expected "false"} + {:suite "seqpred" :expr "(sequential? (range 3))" :expected "true"} + {:suite "seqpred" :expr "(sequential? (map inc [1 2 3]))" :expected "true"} + {:suite "seqpred" :expr "(sequential? (filter odd? [1 2 3]))" :expected "true"} + {:suite "seqpred" :expr "(sequential? (lazy-seq (cons 1 nil)))" :expected "true"} + {:suite "seqpred" :expr "(sequential? (take 2 (repeat 9)))" :expected "true"} + {:suite "seqpred" :expr "(sequential? [1 2 3])" :expected "true"} + {:suite "seqpred" :expr "(sequential? '(1 2 3))" :expected "true"} + {:suite "seqpred" :expr "(sequential? {:a 1})" :expected "false"} + {:suite "seqpred" :expr "(sequential? #{1 2})" :expected "false"} + {:suite "seqpred" :expr "(sequential? nil)" :expected "false"} + {:suite "seqpred" :expr "(= [0 1 2] (range 3))" :expected "true"} + {:suite "seqpred" :expr "(= (range 3) [0 1 2])" :expected "true"} + {:suite "seqpred" :expr "(= (map inc [0 1]) '(1 2))" :expected "true"} + {:suite "seqpred" :expr "(contains? #{[0 1 2]} (vec (range 3)))" :expected "true"} + {:suite "stdlib" :expr "(< 1.4142 (clojure.math/sqrt 2) 1.4143)" :expected "true"} + {:suite "stdlib" :expr "(long (clojure.math/pow 2 10))" :expected "1024"} + {:suite "stdlib" :expr "(long (clojure.math/tan 0))" :expected "0"} + {:suite "stdlib" :expr "(clojure.math/round 2.6)" :expected "3"} + {:suite "stdlib" :expr "(clojure.math/floor 2.9)" :expected "2.0"} + {:suite "stdlib" :expr "(clojure.math/signum -7.2)" :expected "-1.0"} + {:suite "stdlib" :expr "(< 3.14 (clojure.math/to-radians 180) 3.15)" :expected "true"} + {:suite "stdlib" :expr "(< 3.14 clojure.math/PI 3.15)" :expected "true"} + {:suite "stdlib" :expr "(< 2.71 clojure.math/E 2.72)" :expected "true"} + {:suite "stdlib" :expr "(long (clojure.math/cbrt 27))" :expected "3"} + {:suite "stdlib" :expr "(< 4.6 (clojure.math/log 100) 4.7)" :expected "true"} + {:suite "stdlib" :expr "(< 2.99 (clojure.math/log10 1000) 3.01)" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.math :as m])) (long (m/hypot 3 4)))" :expected "5"} + {:suite "stdlib" :expr "(mapv (comp long clojure.math/sqrt) [1 4])" :expected "[1 2]"} + {:suite "stdlib" :expr "(long (clojure.math/atan2 0 1))" :expected "0"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{1 2 3 4} (s/union #{1 2} #{3 4})))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{2} (s/intersection #{1 2} #{2 3})))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{1} (s/difference #{1 2} #{2 3})))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (s/subset? #{1} #{1 2}))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (s/superset? #{1 2} #{1}))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= {1 :a 2 :b} (s/map-invert {:a 1 :b 2})))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{:a} (s/select keyword? #{:a})))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= #{{:a 1 :b 2}} (s/join #{{:a 1}} #{{:b 2}})))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= {:b 1} (s/rename-keys {:a 1} {:a :b})))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.set :as s])) (= 2 (count (s/index #{{:k 1} {:k 2}} [:k]))))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.pprint :as pp])) (= \"[1 2 3]\\n\" (with-out-str (pp/pprint [1 2 3]))))" :expected "true"} + {:suite "stdlib" :expr "(do (require (quote [clojure.pprint :as pp])) (pp/with-pprint-dispatch pp/code-dispatch 42))" :expected "42"} + {:suite "str" :expr "(.toLowerCase \"HI\")" :expected "hi"} + {:suite "str" :expr "(.toUpperCase \"hi\")" :expected "HI"} + {:suite "str" :expr "(.trim \" x \")" :expected "x"} + {:suite "str" :expr "(.length \"abc\")" :expected "3"} + {:suite "str" :expr "[(.isEmpty \"\") (.isEmpty \"a\")]" :expected "[true false]"} + {:suite "str" :expr "(.indexOf \"abc\" \"b\")" :expected "1"} + {:suite "str" :expr "(.indexOf \"abc\" \"z\")" :expected "-1"} + {:suite "str" :expr "(.indexOf \"abab\" \"a\" 1)" :expected "2"} + {:suite "str" :expr "(.indexOf \"a=b\" 61)" :expected "1"} + {:suite "str" :expr "(.lastIndexOf \"abab\" \"b\")" :expected "3"} + {:suite "str" :expr "(.substring \"abc\" 1)" :expected "bc"} + {:suite "str" :expr "(.substring \"abc\" 1 2)" :expected "b"} + {:suite "str" :expr "(.startsWith \"abc\" \"ab\")" :expected "true"} + {:suite "str" :expr "(.endsWith \"abc\" \"bc\")" :expected "true"} + {:suite "str" :expr "(.contains \"abc\" \"b\")" :expected "true"} + {:suite "str" :expr "(.replace \"abc\" \"b\" \"x\")" :expected "axc"} + {:suite "str" :expr "(.replace \"aaa\" \"a\" \"b\")" :expected "bbb"} + {:suite "str" :expr "(.charAt \"abc\" 1)" :expected "\\b"} + {:suite "str" :expr "(.equalsIgnoreCase \"AbC\" \"aBc\")" :expected "true"} + {:suite "str" :expr "(.toString \"hi\")" :expected "hi"} + {:suite "str" :expr "(.concat \"ab\" \"cd\")" :expected "abcd"} + {:suite "str" :expr "(.matches \"abc\" \"a.c\")" :expected "true"} + {:suite "str" :expr "(.matches \"abcd\" \"a.c\")" :expected "false"} + {:suite "str" :expr "(.replaceAll \"a_b_c\" \"_\" \"-\")" :expected "a-b-c"} + {:suite "str" :expr "(.replaceFirst \"a_b_c\" \"_\" \"-\")" :expected "a-b_c"} + {:suite "str" :expr "(vec (.split \"a,b,c\" \",\"))" :expected "[a b c]"} + {:suite "str" :expr "(.frobnicate \"abc\")" :expected :throws} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/upper-case \"abc\"))" :expected "ABC"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/lower-case \"ABC\"))" :expected "abc"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/capitalize \"hello\"))" :expected "Hello"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/trim \" x \"))" :expected "x"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (= \"x \" (s/triml \" x \")))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (= \" x\" (s/trimr \" x \")))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/blank? \"\"))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/blank? \" \"))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/blank? \"x\"))" :expected "false"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/blank? nil))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/includes? \"abcd\" \"bc\"))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/includes? \"abcd\" \"zz\"))" :expected "false"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/starts-with? \"abc\" \"ab\"))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/starts-with? \"abc\" \"bc\"))" :expected "false"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/ends-with? \"abc\" \"bc\"))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/join [\"a\" \"b\" \"c\"]))" :expected "abc"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/join \",\" [\"a\" \"b\" \"c\"]))" :expected "a,b,c"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/join \"-\" [1 2 3]))" :expected "1-2-3"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/split \"a,b,c\" \",\"))" :expected "[a b c]"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/split \"a1b2c\" #\"[0-9]\"))" :expected "[a b c]"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/split-lines \"a\\nb\\nc\"))" :expected "[a b c]"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/replace \"a_b_c\" \"_\" \"-\"))" :expected "a-b-c"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/replace \"a1b2\" #\"[0-9]\" \"\"))" :expected "ab"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/replace-first \"a_b_c\" \"_\" \"-\"))" :expected "a-b_c"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/reverse \"abc\"))" :expected "cba"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/index-of \"abc\" \"b\"))" :expected "1"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (nil? (s/index-of \"abc\" \"z\")))" :expected "true"} + {:suite "strns" :expr "(do (require (quote [clojure.string :as s])) (s/trim-newline \"abc\\n\\n\"))" :expected "abc"} + {:suite "type" :expr "(type 5)" :expected ":number"} + {:suite "type" :expr "(type 5.0)" :expected ":number"} + {:suite "type" :expr "(type (/ 10 2))" :expected ":number"} + {:suite "type" :expr "(type \"s\")" :expected ":string"} + {:suite "type" :expr "(type :k)" :expected ":keyword"} + {:suite "type" :expr "(type 'x)" :expected ":symbol"} + {:suite "type" :expr "(type true)" :expected ":boolean"} + {:suite "type" :expr "(type false)" :expected ":boolean"} + {:suite "type" :expr "(type nil)" :expected ""} + {:suite "type" :expr "(type \\a)" :expected ":char"} + {:suite "type" :expr "(type [1 2])" :expected ":vector"} + {:suite "type" :expr "(type [])" :expected ":vector"} + {:suite "type" :expr "(type {:a 1})" :expected ":map"} + {:suite "type" :expr "(type #{1})" :expected ":set"} + {:suite "type" :expr "(type '(1 2))" :expected ":seq"} + {:suite "type" :expr "(type '())" :expected ":seq"} + {:suite "type" :expr "(type (first {:a 1}))" :expected ":vector"} + {:suite "type" :expr "(type (map inc [1 2]))" :expected ":seq"} + {:suite "type" :expr "(type (filter odd? [1 2 3]))" :expected ":seq"} + {:suite "type" :expr "(type (lazy-seq (cons 1 nil)))" :expected ":seq"} + {:suite "type" :expr "(type (take 2 (iterate inc 0)))" :expected ":seq"} + {:suite "type" :expr "(type inc)" :expected ":fn"} + {:suite "type" :expr "(type (sorted-map :a 1))" :expected ":map"} + {:suite "type" :expr "(type (sorted-set 1))" :expected ":jolt/sorted-set"} + {:suite "type" :expr "(type (with-meta [1] {:type :custom}))" :expected ":custom"} + {:suite "type" :expr "(type (with-meta {:a 1} {:type :rec}))" :expected ":rec"} + {:suite "type" :expr "(type (with-meta [1] {:other 9}))" :expected ":vector"} + {:suite "type" :expr "(do (defrecord TyR [a]) (type (->TyR 1)))" :expected "user.TyR"} + {:suite "type" :expr "(do (defrecord TyR [a]) (= (symbol (str (type (->TyR 1)))) (type (->TyR 1))))" :expected "false"} + {:suite "type" :expr "(do (defrecord TyR [a]) (symbol? (type (->TyR 1))))" :expected "false"} + {:suite "type" :expr "(type (atom 1))" :expected ":jolt/atom"} + {:suite "type" :expr "(type (volatile! 1))" :expected ":jolt/volatile"} + {:suite "type" :expr "(type #\"re\")" :expected ":jolt/regex"} + {:suite "type" :expr "(do (def vx 1) (type (var vx)))" :expected ":jolt/var"} + {:suite "type" :expr "(type (transient []))" :expected ":jolt/transient"} + {:suite "type" :expr "(type (random-uuid))" :expected ":jolt/uuid"} + {:suite "type" :expr "(type (ex-info \"x\" {}))" :expected ":jolt/ex-info"} + {:suite "var_meta" :expr "(do (def ^:private pv 1) (:private (meta (var pv))))" :expected "true"} + {:suite "var_meta" :expr "(do (def ^String tv \"a\") (:tag (meta (var tv))))" :expected "java.lang.String"} + {:suite "var_meta" :expr "(do (def dv2 \"hi\" 1) (:doc (meta (var dv2))))" :expected "hi"} + {:suite "var_meta" :expr "(do (def mv 1) (:name (meta (var mv))))" :expected "mv"} + {:suite "var_meta" :expr "(do (def nv 1) (:ns (meta (var nv))))" :expected "user"} + {:suite "var_meta" :expr "(do (def pl 1) (nil? (:private (meta (var pl)))))" :expected "true"} + {:suite "walk" :expr "(list? (list 1 2))" :expected "true"} + {:suite "walk" :expr "(list? (list 1))" :expected "true"} + {:suite "walk" :expr "(list? '(1 2))" :expected "true"} + {:suite "walk" :expr "(list? '())" :expected "true"} + {:suite "walk" :expr "(list? (list))" :expected "true"} + {:suite "walk" :expr "(list? (cons 1 nil))" :expected "true"} + {:suite "walk" :expr "(list? (cons 1 [2]))" :expected "true"} + {:suite "walk" :expr "(list? (cons 1 '(2)))" :expected "true"} + {:suite "walk" :expr "(list? (conj (list 1) 0))" :expected "true"} + {:suite "walk" :expr "(list? (conj '() 1))" :expected "true"} + {:suite "walk" :expr "(list? (reverse [1 2]))" :expected "true"} + {:suite "walk" :expr "(list? (reverse '(1 2)))" :expected "true"} + {:suite "walk" :expr "(list? [1 2])" :expected "false"} + {:suite "walk" :expr "(list? {:a 1})" :expected "false"} + {:suite "walk" :expr "(list? (map inc [1 2]))" :expected "false"} + {:suite "walk" :expr "(list? (filter odd? [1 2 3]))" :expected "false"} + {:suite "walk" :expr "(list? (seq [1 2]))" :expected "false"} + {:suite "walk" :expr "(list? (rest (list 1 2)))" :expected "false"} + {:suite "walk" :expr "(list? (next (list 1 2)))" :expected "false"} + {:suite "walk" :expr "(list? (take 2 (list 1 2 3)))" :expected "false"} + {:suite "walk" :expr "(list? (concat '(1) '(2)))" :expected "false"} + {:suite "walk" :expr "(list? (rest [1 2]))" :expected "false"} + {:suite "walk" :expr "(list? 5)" :expected "false"} + {:suite "walk" :expr "(list? nil)" :expected "false"} + {:suite "walk" :expr "(vector? (first {:a 1}))" :expected "true"} + {:suite "walk" :expr "(vector? (first (seq {:a 1})))" :expected "true"} + {:suite "walk" :expr "(map-entry? (first {:a 1}))" :expected "true"} + {:suite "walk" :expr "(= (first {:a 1}) [:a 1])" :expected "true"} + {:suite "walk" :expr "(vector? [1 2])" :expected "true"} + {:suite "walk" :expr "(vector? (rest [1 2 3]))" :expected "false"} + {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk (fn [x] (if (number? x) (inc x) x)) {:a 1}))" :expected "{:a 2}"} + {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/keywordize-keys {\"a\" 1}))" :expected "{:a 1}"} + {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (= {\"a\" 1} (w/stringify-keys {:a 1})))" :expected "true"} + {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {'x 2} '(+ x x)))" :expected "(+ 2 2)"} + {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk (fn [n] (if (symbol? n) :a n)) '(x y)))" :expected "(:a :a)"} + {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/prewalk-replace {'* '* 'y 3} '(* y y)))" :expected "(* 3 3)"} + {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {:a 1 :b 2} '(:a [:b :a])))" :expected "(1 [2 1])"} + {:suite "walk" :expr "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {1 :one} [1 2 1]))" :expected "[:one 2 :one]"} + {:suite "walk" :expr "(do (require (quote [clojure.template :as t])) (t/apply-template '[x y] '(+ x y) '(1 2)))" :expected "(+ 1 2)"} + {:suite "shadowing" :expr "(let [if (fn [a b c] :L)] (if true 1 2))" :expected "1"} + {:suite "shadowing" :expr "(let [quote (fn [_] :L)] (quote x))" :expected "x"} + {:suite "shadowing" :expr "(let [if 5] if)" :expected "5"} + {:suite "shadowing" :expr "((fn [if] (+ if 1)) 7)" :expected "8"} + {:suite "shadowing" :expr "(let [when (fn [a b] :local)] (when 1 2))" :expected ":local"} + {:suite "macroexpand" :expr "(do (when true (defmacro m6 [x] `(* ~x 2))) (m6 3))" :expected "6"} + {:suite "macroexpand" :expr "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 10))" :expected "true"} + {:suite "deftype-mutable" :expr "(do (defprotocol IB (gv [_]) (sv [_ v])) (deftype B [^:unsynchronized-mutable val] IB (gv [_] val) (sv [_ v] (set! val v))) (let [b (->B 1)] (sv b 42) (gv b)))" :expected "42"} + {:suite "deftype-mutable" :expr "(do (defprotocol IC (bump [_]) (cur [_])) (deftype C [^:unsynchronized-mutable n] IC (bump [this] (set! n (inc n)) n) (cur [_] n)) (let [c (->C 5)] (bump c) (bump c) (bump c) (cur c)))" :expected "8"} + {:suite "deftype-mutable" :expr "(do (defprotocol IH (g [_]) (s [_ v])) (deftype H [^:volatile-mutable st] IH (g [_] st) (s [this v] (set! (.-st this) v))) (let [h (->H :old)] (s h :new) (g h)))" :expected ":new"} +] diff --git a/test/chez/values-test.ss b/test/chez/values-test.ss new file mode 100644 index 0000000..cb8ecb0 --- /dev/null +++ b/test/chez/values-test.ss @@ -0,0 +1,67 @@ +;; Phase 0a tests — Jolt value model on Chez. Run from repo root: +;; chez --script test/chez/values-test.ss +(import (chezscheme)) +(load "host/chez/values.ss") + +(define total 0) +(define fails 0) +(define (ok name pred) + (set! total (+ total 1)) + (unless pred (set! fails (+ fails 1)) (printf "FAIL: ~a\n" name))) + +;; nil distinct from #f and '() +(ok "nil not #f" (not (eq? jolt-nil #f))) +(ok "nil not '()" (not (eq? jolt-nil '()))) +(ok "nil? jolt-nil" (jolt-nil? jolt-nil)) +(ok "nil? not on #f" (not (jolt-nil? #f))) + +;; truthiness: only nil and false falsey +(ok "nil falsey" (not (jolt-truthy? jolt-nil))) +(ok "false falsey" (not (jolt-truthy? #f))) +(ok "true truthy" (jolt-truthy? #t)) +(ok "0 truthy" (jolt-truthy? 0)) +(ok "empty-str truthy" (jolt-truthy? "")) +(ok "empty-list truthy" (jolt-truthy? '())) + +;; keywords interned -> identity +(ok "kw eq" (eq? (keyword #f "foo") (keyword #f "foo"))) +(ok "kw ns eq" (eq? (keyword "a" "foo") (keyword "a" "foo"))) +(ok "kw diff ns" (not (eq? (keyword "a" "foo") (keyword #f "foo")))) +(ok "kw?" (keyword? (keyword #f "x"))) +(ok "kw not sym" (not (jolt-symbol? (keyword #f "x")))) + +;; symbols NOT interned but jolt= by ns/name +(ok "sym not eq" (not (eq? (jolt-symbol #f "x") (jolt-symbol #f "x")))) +(ok "sym jolt=" (jolt= (jolt-symbol #f "x") (jolt-symbol #f "x"))) +(ok "sym diff name" (not (jolt= (jolt-symbol #f "x") (jolt-symbol #f "y")))) +(ok "sym?" (jolt-symbol? (jolt-symbol "ns" "n"))) + +;; numbers: exactness-aware = (Clojure semantics) +(ok "1 = 1" (jolt= 1 1)) +(ok "1 not= 1.0" (not (jolt= 1 1.0))) +(ok "1.0 = 1.0" (jolt= 1.0 1.0)) +(ok "ratio =" (jolt= 1/2 1/2)) +(ok "bigint=int exact" (jolt= 2 (expt 2 1))) +(ok "= variadic" (jolt= 3 3 3)) +(ok "= variadic false" (not (jolt= 3 3 4))) + +;; strings / chars +(ok "str =" (jolt= "ab" "ab")) +(ok "str !=" (not (jolt= "ab" "ac"))) +(ok "char =" (jolt= #\a #\a)) + +;; hashing consistent with = +(ok "hash kw stable" (= (jolt-hash (keyword #f "k")) (jolt-hash (keyword #f "k")))) +(ok "hash sym stable" (= (jolt-hash (jolt-symbol #f "k")) (jolt-hash (jolt-symbol #f "k")))) +(ok "hash 1 != 1.0" (not (= (jolt-hash 1) (jolt-hash 1.0)))) +(ok "hash str stable" (= (jolt-hash "abc") (jolt-hash "abc"))) + +;; regression: keyword intern key must not collide across ns/name boundary +(ok "kw no boundary collide" (not (eq? (keyword "a" "b/c") (keyword "a/b" "c")))) +;; regression: jolt-hash must not throw on non-finite floats +(ok "hash +inf ok" (number? (jolt-hash +inf.0))) +(ok "hash +nan ok" (number? (jolt-hash +nan.0))) +(ok "hash inf != exact" (not (= (jolt-hash +inf.0) (jolt-hash 0)))) + +(printf "values-test: ~a/~a passed\n" (- total fails) total) +(exit (if (> fails 0) 1 0)) diff --git a/test/clojure-stdlib/clojure/data_test/diff.cljc b/test/clojure-stdlib/clojure/data_test/diff.cljc deleted file mode 100644 index 0b0415a..0000000 --- a/test/clojure-stdlib/clojure/data_test/diff.cljc +++ /dev/null @@ -1,149 +0,0 @@ -(ns clojure.data-test.diff - (:require [clojure.test :refer [deftest is testing]] -;; NOTE (jolt): sequential-diff expectations corrected to match real Clojure — -;; clojure.data pads only to the max differing index (e.g. (diff [1 2 3] [1 9 3]) -;; -> a=[nil 2], not [nil 2 nil]). The upstream clojurust fixtures had this wrong. - [clojure.data :refer [diff]])) - -;; ── Atoms ──────────────────────────────────────────────────────────────────── - -(deftest test-diff-equal-atoms - (testing "equal atoms" - (is (= [nil nil :a] (diff :a :a))) - (is (= [nil nil 1] (diff 1 1))) - (is (= [nil nil "hello"] (diff "hello" "hello"))) - (is (= [nil nil nil] (diff nil nil))) - (is (= [nil nil true] (diff true true))))) - -(deftest test-diff-unequal-atoms - (testing "unequal atoms" - (is (= [:a :b nil] (diff :a :b))) - (is (= [1 2 nil] (diff 1 2))) - (is (= ["a" "b" nil] (diff "a" "b"))) - (is (= [nil 1 nil] (diff nil 1))) - (is (= [true false nil] (diff true false))))) - -;; ── Maps ───────────────────────────────────────────────────────────────────── - -(deftest test-diff-equal-maps - (testing "equal maps" - (is (= [nil nil {:a 1 :b 2}] (diff {:a 1 :b 2} {:a 1 :b 2}))) - (is (= [nil nil {}] (diff {} {}))))) - -(deftest test-diff-maps-only-in-a - (testing "keys only in a" - (let [[a b both] (diff {:a 1 :b 2} {:a 1})] - (is (= {:b 2} a)) - (is (nil? b)) - (is (= {:a 1} both))))) - -(deftest test-diff-maps-only-in-b - (testing "keys only in b" - (let [[a b both] (diff {:a 1} {:a 1 :b 2})] - (is (nil? a)) - (is (= {:b 2} b)) - (is (= {:a 1} both))))) - -(deftest test-diff-maps-different-values - (testing "same keys, different values" - (let [[a b both] (diff {:a 1 :b 2} {:a 1 :b 9})] - (is (= {:b 2} a)) - (is (= {:b 9} b)) - (is (= {:a 1} both))))) - -(deftest test-diff-maps-nested - (testing "nested maps" - (let [[a b both] (diff {:a {:x 1 :y 2}} {:a {:x 1 :z 3}})] - (is (= {:a {:y 2}} a)) - (is (= {:a {:z 3}} b)) - (is (= {:a {:x 1}} both))))) - -(deftest test-diff-maps-disjoint - (testing "completely disjoint maps" - (let [[a b both] (diff {:a 1} {:b 2})] - (is (= {:a 1} a)) - (is (= {:b 2} b)) - (is (nil? both))))) - -;; ── Sets ───────────────────────────────────────────────────────────────────── - -(deftest test-diff-equal-sets - (testing "equal sets" - (is (= [nil nil #{1 2 3}] (diff #{1 2 3} #{1 2 3}))) - (is (= [nil nil #{}] (diff #{} #{}))))) - -(deftest test-diff-sets - (testing "overlapping sets" - (let [[a b both] (diff #{1 2 3} #{2 3 4})] - (is (= #{1} a)) - (is (= #{4} b)) - (is (= #{2 3} both))))) - -(deftest test-diff-disjoint-sets - (testing "disjoint sets" - (let [[a b both] (diff #{1 2} #{3 4})] - (is (= #{1 2} a)) - (is (= #{3 4} b)) - (is (nil? both))))) - -;; ── Vectors / Sequential ──────────────────────────────────────────────────── - -(deftest test-diff-equal-vectors - (testing "equal vectors" - (is (= [nil nil [1 2 3]] (diff [1 2 3] [1 2 3]))) - (is (= [nil nil []] (diff [] []))))) - -(deftest test-diff-vectors-same-length - (testing "same length, different elements" - (let [[a b both] (diff [1 2 3] [1 9 3])] - (is (= [nil 2] a)) - (is (= [nil 9] b)) - (is (= [1 nil 3] both))))) - -(deftest test-diff-vectors-different-length - (testing "different lengths" - (let [[a b both] (diff [1 2 3] [1 2])] - (is (= [nil nil 3] a)) - (is (nil? b)) - (is (= [1 2] both))) - (let [[a b both] (diff [1] [1 2 3])] - (is (nil? a)) - (is (= [nil 2 3] b)) - (is (= [1] both))))) - -(deftest test-diff-lists - (testing "lists treated as sequential" - (let [[a b both] (diff '(1 2 3) '(1 9 3))] - (is (= [nil 2] a)) - (is (= [nil 9] b)) - (is (= [1 nil 3] both))))) - -;; ── Mixed types ───────────────────────────────────────────────────────────── - -(deftest test-diff-mixed-types - (testing "different partition types treated as atoms" - (is (= [{:a 1} [1 2] nil] (diff {:a 1} [1 2]))) - (is (= [#{1} [1] nil] (diff #{1} [1]))) - (is (= [1 :a nil] (diff 1 :a))))) - -;; ── Nil handling ──────────────────────────────────────────────────────────── - -(deftest test-diff-nil - (testing "nil vs non-nil" - (is (= [nil 1 nil] (diff nil 1))) - (is (= [1 nil nil] (diff 1 nil))) - (is (= [nil {:a 1} nil] (diff nil {:a 1}))))) - -;; ── Deeply nested ─────────────────────────────────────────────────────────── - -(deftest test-diff-deeply-nested - (testing "deeply nested structures" - (let [[a b both] (diff {:a {:b {:c 1}}} {:a {:b {:c 2}}})] - (is (= {:a {:b {:c 1}}} a)) - (is (= {:a {:b {:c 2}}} b)) - (is (nil? both)))) - (testing "deeply nested with shared keys" - (let [[a b both] (diff {:a {:b 1 :c 2}} {:a {:b 1 :c 9}})] - (is (= {:a {:c 2}} a)) - (is (= {:a {:c 9}} b)) - (is (= {:a {:b 1}} both))))) diff --git a/test/clojure-stdlib/clojure/edn_test/read_string.cljc b/test/clojure-stdlib/clojure/edn_test/read_string.cljc deleted file mode 100644 index 515af5e..0000000 --- a/test/clojure-stdlib/clojure/edn_test/read_string.cljc +++ /dev/null @@ -1,107 +0,0 @@ -(ns clojure.edn-test.read-string - (:require [clojure.edn :as edn] - [clojure.test :refer [are deftest is testing]])) - -(deftest test-read-string-scalars - (testing "nil, booleans" - (is (nil? (edn/read-string "nil"))) - (is (true? (edn/read-string "true"))) - (is (false? (edn/read-string "false")))) - - (testing "integers" - (is (= 0 (edn/read-string "0"))) - (is (= 42 (edn/read-string "42"))) - (is (= -1 (edn/read-string "-1"))) - (is (= 1000000000000 (edn/read-string "1000000000000")))) - - (testing "floats" - (is (= 3.14 (edn/read-string "3.14"))) - (is (= -0.5 (edn/read-string "-0.5"))) - (is (= 1.0 (edn/read-string "1.0")))) - - (testing "bigints" - (is (= 42N (edn/read-string "42N")))) - - (testing "bigdecimals" - (is (= 3.14M (edn/read-string "3.14M")))) - - (testing "strings" - (is (= "" (edn/read-string "\"\""))) - (is (= "hello" (edn/read-string "\"hello\""))) - (is (= "line1\nline2" (edn/read-string "\"line1\\nline2\""))) - (is (= "tab\there" (edn/read-string "\"tab\\there\"")))) - - (testing "characters" - (is (= \a (edn/read-string "\\a"))) - (is (= \newline (edn/read-string "\\newline"))) - (is (= \space (edn/read-string "\\space"))) - (is (= \tab (edn/read-string "\\tab")))) - - (testing "keywords" - (is (= :foo (edn/read-string ":foo"))) - (is (= :bar/baz (edn/read-string ":bar/baz")))) - - (testing "symbols" - (is (= 'foo (edn/read-string "foo"))) - (is (= 'bar/baz (edn/read-string "bar/baz"))))) - -(deftest test-read-string-collections - (testing "vectors" - (is (= [] (edn/read-string "[]"))) - (is (= [1 2 3] (edn/read-string "[1 2 3]"))) - (is (= [1 [2 3] 4] (edn/read-string "[1 [2 3] 4]")))) - - (testing "lists" - (is (= '() (edn/read-string "()"))) - (is (= '(1 2 3) (edn/read-string "(1 2 3)"))) - (is (= '(+ 1 2) (edn/read-string "(+ 1 2)")))) - - (testing "maps" - (is (= {} (edn/read-string "{}"))) - (is (= {:a 1} (edn/read-string "{:a 1}"))) - (is (= {:a 1 :b 2} (edn/read-string "{:a 1 :b 2}"))) - (is (= {:nested {:deep true}} (edn/read-string "{:nested {:deep true}}")))) - - (testing "sets" - (is (= #{} (edn/read-string "#{}"))) - (is (= #{1 2 3} (edn/read-string "#{1 2 3}")))) - - (testing "mixed nested" - (is (= {:users [{:name "Alice" :age 30} - {:name "Bob" :age 25}]} - (edn/read-string "{:users [{:name \"Alice\" :age 30} {:name \"Bob\" :age 25}]}"))))) - -(deftest test-read-string-tagged-literals - (testing "#uuid" - (let [u (edn/read-string "#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"")] - (is (uuid? u)) - (is (= u (edn/read-string "#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"")))))) - -(deftest test-read-string-eof - (testing "empty string with :eof option" - (is (= :eof (edn/read-string {:eof :eof} ""))) - (is (= nil (edn/read-string {:eof nil} ""))) - (is (= 42 (edn/read-string {:eof 42} "")))) - - (testing "whitespace-only with :eof option" - (is (= :done (edn/read-string {:eof :done} " ")))) - - (testing "nil input returns nil" - (is (nil? (edn/read-string nil))))) - -(deftest test-read-string-comments - (testing "comments are skipped" - (is (= 42 (edn/read-string "; this is a comment\n42")))) - - (testing "discard reader macro" - (is (= 2 (edn/read-string "#_ 1 2"))))) - -(deftest test-read-string-only-first-form - (testing "reads only the first form" - (is (= 1 (edn/read-string "1 2 3"))) - (is (= :a (edn/read-string ":a :b :c"))))) - -(deftest test-read-string-ratios - (testing "ratios" - (is (= 1/2 (edn/read-string "1/2"))) - (is (= 3/4 (edn/read-string "3/4"))))) diff --git a/test/clojure-stdlib/clojure/walk_test/walk.cljc b/test/clojure-stdlib/clojure/walk_test/walk.cljc deleted file mode 100644 index 49a584e..0000000 --- a/test/clojure-stdlib/clojure/walk_test/walk.cljc +++ /dev/null @@ -1,101 +0,0 @@ -(ns clojure.walk-test.walk - (:require [clojure.test :refer [deftest is testing]] - [clojure.walk :as w])) - -(deftest test-walk - (testing "walk with identity" - (is (= [1 2 3] (w/walk identity identity [1 2 3]))) - (is (= '(1 2 3) (w/walk identity identity '(1 2 3)))) - (is (= #{1 2 3} (w/walk identity identity #{1 2 3})))) - - (testing "walk with inner transform" - (is (= [2 3 4] (w/walk inc identity [1 2 3]))) - (is (= [2 3 4] (w/walk inc vec [1 2 3])))) - - (testing "walk with outer transform" - (is (= [1 2 3] (w/walk identity vec '(1 2 3)))))) - -(deftest test-postwalk - (testing "postwalk with numbers" - (is (= [2 3 4] (w/postwalk #(if (number? %) (inc %) %) [1 2 3])))) - - (testing "postwalk with nested structures" - (is (= [2 [3 4] 5] - (w/postwalk #(if (number? %) (inc %) %) [1 [2 3] 4])))) - - (testing "postwalk preserves types" - (is (vector? (w/postwalk identity [1 2 3]))) - (is (list? (w/postwalk identity '(1 2 3)))) - (is (set? (w/postwalk identity #{1 2 3}))) - (is (map? (w/postwalk identity {:a 1 :b 2})))) - - (testing "postwalk on maps" - (is (= {:a 2 :b 3} - (w/postwalk #(if (number? %) (inc %) %) {:a 1 :b 2})))) - - (testing "postwalk on empty collections" - (is (= [] (w/postwalk identity []))) - (is (= {} (w/postwalk identity {}))) - (is (= #{} (w/postwalk identity #{}))) - (is (= '() (w/postwalk identity '()))))) - -(deftest test-prewalk - (testing "prewalk with numbers" - (is (= [2 3 4] (w/prewalk #(if (number? %) (inc %) %) [1 2 3])))) - - (testing "prewalk with nested structures" - (is (= [2 [3 4] 5] - (w/prewalk #(if (number? %) (inc %) %) [1 [2 3] 4])))) - - (testing "prewalk transforms before descending" - ;; prewalk applies f to the outer form first, so we can replace - ;; entire subtrees before they are walked - (is (= [:replaced] - (w/prewalk #(if (= % [1 2 3]) [:replaced] %) [1 2 3]))))) - -(deftest test-keywordize-keys - (testing "basic keywordize" - (is (= {:a 1 :b 2} (w/keywordize-keys {"a" 1 "b" 2})))) - - (testing "nested keywordize" - (is (= {:a {:b 2}} (w/keywordize-keys {"a" {"b" 2}})))) - - (testing "non-string keys unchanged" - (is (= {:a 1 42 2} (w/keywordize-keys {"a" 1 42 2})))) - - (testing "already keyword keys unchanged" - (is (= {:a 1} (w/keywordize-keys {:a 1}))))) - -(deftest test-stringify-keys - (testing "basic stringify" - (is (= {"a" 1 "b" 2} (w/stringify-keys {:a 1 :b 2})))) - - (testing "nested stringify" - (is (= {"a" {"b" 2}} (w/stringify-keys {:a {:b 2}})))) - - (testing "non-keyword keys unchanged" - (is (= {"a" 1 42 2} (w/stringify-keys {:a 1 42 2}))))) - -(deftest test-postwalk-replace - (testing "basic replacement" - (is (= [:x :y :c] (w/postwalk-replace {:a :x :b :y} [:a :b :c])))) - - (testing "nested replacement" - (is (= [:x [:y :c]] (w/postwalk-replace {:a :x :b :y} [:a [:b :c]])))) - - (testing "no matches" - (is (= [1 2 3] (w/postwalk-replace {:a :x} [1 2 3])))) - - (testing "empty smap" - (is (= [1 2 3] (w/postwalk-replace {} [1 2 3]))))) - -(deftest test-prewalk-replace - (testing "basic replacement" - (is (= [:x :y :c] (w/prewalk-replace {:a :x :b :y} [:a :b :c])))) - - (testing "nested replacement" - (is (= [:x [:y :c]] (w/prewalk-replace {:a :x :b :y} [:a [:b :c]])))) - - (testing "replaces before descending" - ;; prewalk-replace replaces the whole form first, then walks children - (is (= :replaced (w/prewalk-replace {[:a :b] :replaced} [:a :b]))))) diff --git a/test/clojure-stdlib/clojure/zip_test/zip.cljc b/test/clojure-stdlib/clojure/zip_test/zip.cljc deleted file mode 100644 index 076eb79..0000000 --- a/test/clojure-stdlib/clojure/zip_test/zip.cljc +++ /dev/null @@ -1,122 +0,0 @@ -(ns clojure.zip-test.zip - (:require [clojure.test :refer [deftest is testing run-tests]] - [clojure.zip :as zip])) - -(deftest test-vector-zip-navigation - (let [data [[1 2] [3 [4 5]]] - z (zip/vector-zip data)] - (testing "root node" - (is (= (zip/node z) [[1 2] [3 [4 5]]])) - (is (zip/branch? z))) - (testing "down" - (is (= (zip/node (zip/down z)) [1 2]))) - (testing "right" - (is (= (zip/node (zip/right (zip/down z))) [3 [4 5]]))) - (testing "down into nested" - (is (= (zip/node (zip/down (zip/right (zip/down z)))) 3))) - (testing "up returns parent" - (is (= (zip/node (zip/up (zip/down z))) [[1 2] [3 [4 5]]]))) - (testing "rights" - (is (= (zip/rights (zip/down z)) '([3 [4 5]])))) - (testing "lefts" - (is (= (zip/lefts (zip/right (zip/down z))) [[1 2]]))))) - -(deftest test-vector-zip-rightmost-leftmost - (let [z (zip/vector-zip [1 2 3])] - (testing "rightmost" - (is (= (zip/node (zip/rightmost (zip/down z))) 3))) - (testing "leftmost" - (is (= (zip/node (zip/leftmost (zip/rightmost (zip/down z)))) 1))))) - -(deftest test-seq-zip-navigation - (let [z (zip/seq-zip '(1 (2 3) 4))] - (testing "root" - (is (= (zip/node z) '(1 (2 3) 4)))) - (testing "down" - (is (= (zip/node (zip/down z)) 1))) - (testing "right" - (is (= (zip/node (zip/right (zip/down z))) '(2 3)))) - (testing "down into nested list" - (is (= (zip/node (zip/down (zip/right (zip/down z)))) 2))))) - -(deftest test-path - (let [z (zip/vector-zip [[1 2] [3 4]])] - (testing "path at root is nil" - (is (nil? (zip/path z)))) - (testing "path one level down" - (is (= (zip/path (zip/down z)) [[[1 2] [3 4]]]))) - (testing "path two levels down" - (is (= (zip/path (zip/down (zip/down z))) - [[[1 2] [3 4]] [1 2]]))))) - -(deftest test-edit - (let [z (zip/vector-zip [1 [2 3] [4 5]])] - (testing "edit a leaf" - (let [loc (-> z zip/down zip/right zip/down) - edited (zip/edit loc inc)] - (is (= (zip/root edited) [1 [3 3] [4 5]])))) - (testing "edit a branch" - (let [loc (-> z zip/down zip/right) - edited (zip/edit loc (fn [x] (vec (map inc x))))] - (is (= (zip/root edited) [1 [3 4] [4 5]])))))) - -(deftest test-replace - (let [z (zip/vector-zip '[a b c])] - (is (= (zip/root (zip/replace (zip/down z) 'x)) - '[x b c])))) - -(deftest test-insert-left-right - (let [z (zip/vector-zip [1 2 3]) - loc (-> z zip/down zip/right)] - (testing "insert-left" - (is (= (zip/root (zip/insert-left loc 'x)) [1 'x 2 3]))) - (testing "insert-right" - (is (= (zip/root (zip/insert-right loc 'y)) [1 2 'y 3]))))) - -(deftest test-insert-child-append-child - (let [z (zip/vector-zip [1 2 3])] - (testing "insert-child" - (is (= (zip/root (zip/insert-child z 0)) [0 1 2 3]))) - (testing "append-child" - (is (= (zip/root (zip/append-child z 4)) [1 2 3 4]))))) - -(deftest test-remove - (let [z (zip/vector-zip [1 2 3]) - loc (-> z zip/down zip/right)] - (is (= (zip/root (zip/remove loc)) [1 3])))) - -(deftest test-next-traversal - (let [z (zip/vector-zip [1 [2 3]])] - (testing "next enumerates depth-first" - (is (= (loop [loc z, acc []] - (if (zip/end? loc) - acc - (recur (zip/next loc) (conj acc (zip/node loc))))) - [[1 [2 3]] 1 [2 3] 2 3]))))) - -(deftest test-end? - (let [z (zip/vector-zip [1 2])] - (testing "not end at start" - (is (not (zip/end? z)))) - (testing "end after full traversal" - (is (zip/end? (-> z zip/next zip/next zip/next)))))) - -(deftest test-prev - (let [z (zip/vector-zip [1 [2 3]])] - (testing "prev from second child" - (let [loc (-> z zip/next zip/next)] - (is (= (zip/node loc) [2 3])) - (is (= (zip/node (zip/prev loc)) 1)))) - (testing "prev from leaf inside nested" - (let [loc (-> z zip/next zip/next zip/next)] - (is (= (zip/node loc) 2)) - (is (= (zip/node (zip/prev loc)) [2 3])))))) - -(deftest test-root-after-edits - (testing "root unwinds all the way after deep edits" - (let [z (zip/vector-zip [[1 2] [3 [4 5]]]) - loc (-> z zip/down zip/right zip/down zip/right zip/down) - edited (zip/edit loc inc)] - (is (= (zip/root edited) [[1 2] [3 [5 5]]]))))) - -(run-tests) diff --git a/test/conformance/README.md b/test/conformance/README.md new file mode 100644 index 0000000..2e5ffa6 --- /dev/null +++ b/test/conformance/README.md @@ -0,0 +1,63 @@ +# Conformance: certifying the corpus against reference Clojure + +> **See [SPEC.md](SPEC.md)** for the full host-neutral language-spec contract: the +> corpus schema, conformance levels, the feature profile, and how to host jolt on a +> new runtime. This README covers the certification tooling specifically. + + +The corpus (`test/chez/corpus.edn`) is jolt's host-neutral behavioral suite — one +row per case: `{:suite :label :expected :actual}`, where `:actual` is a Clojure +source expression and `:expected` its result (or `:throws`). The runtime harness +(`host/chez/run-corpus.ss`, invoked by `make corpus`) replays it on Chez and +compares by value-equality. + +Every `:expected` is sourced from reference JVM Clojure, so the corpus is both a +regression suite and a *specification* certified against Clojure rather than +against its authors' beliefs. This directory holds the certification tooling that +closes that gap. + +## What's here + +- **`certify.clj`** — runs every corpus row's `:actual` and `:expected` through + **reference JVM Clojure** (each in a fresh `user` namespace, output/stdin sunk, a + 5s per-case watchdog) and compares with Clojure's `=`. It buckets each row: + - `certified` / `certified-throws` — jolt's `:expected` matches real Clojure + - `divergent` — both evaluate but jolt's `:expected` disagrees with Clojure + - `throws-mismatch` — jolt and Clojure disagree on whether it throws + - `jvm-error` — `:actual` isn't runnable on vanilla Clojure (host-coupled / + jolt-specific) — informational, not certifiable + - `read-error` / `timeout` — won't read on the JVM reader, or ran too long + +- **`known-divergences.edn`** — every current divergence, classified. Most are + **deliberate** jolt-specific or host-model deltas (see `:legend`): the all-double + numeric model, snapshot-heap concurrency, the no-JVM host model, jolt reader + features, the jolt printer, intentional strictness. A few are genuine **`:bug`** + entries with a tracked bead. These categories become the `:features` flags in + conformance inc3. + +`make certify` is the gate wrapper. It skips cleanly when `clojure` (JVM) is not +installed; otherwise it runs `certify.clj` and fails the build on a **NEW** +(unclassified) divergence or a **stale** allowlist entry. Flaky entries (JVM +result is timing-dependent, e.g. `future-cancel`) are tolerated either way. + +## Running + +```sh +make certify # the gate wrapper (skips if clojure absent) +clojure -M test/conformance/certify.clj # gate directly (exit≠0 on new/stale) +clojure -M test/conformance/certify.clj test/chez/corpus.edn --edn /tmp/report.edn # full machine-readable report +``` + +## Current state + +Of ~2487 vanilla-certifiable rows, **>2410 match reference Clojure exactly**; the +~70 divergences are all classified (deliberate deltas + 4 tracked bugs). The corpus +is trustworthy as a spec, with the host-specific deltas made explicit rather than +hidden. + +## Adding / changing cases + +When you add corpus rows or change behavior, re-run the certifier. A NEW divergence +means either a real bug (file it, tag the allowlist entry `:bug` + `:bead`) or a +deliberate delta (classify it). A stale entry means a divergence was fixed — remove +it from `known-divergences.edn`. diff --git a/test/conformance/SPEC.md b/test/conformance/SPEC.md new file mode 100644 index 0000000..b4a575d --- /dev/null +++ b/test/conformance/SPEC.md @@ -0,0 +1,114 @@ +# The jolt conformance spec + +This directory defines jolt's behavior as a **host-neutral, executable language +specification**: a data file of cases, certified against reference Clojure, with a +feature profile that lets any runtime declare a conformance *level*. The goal is to +make hosting jolt on a new runtime (and proving it correct) a mechanical exercise: +read one data file, run each case, compare, report. + +## The artifacts + +| File | Role | Generated by | +|------|------|--------------| +| `test/chez/corpus.edn` | **The spec.** ~2900 cases of `{:suite :label :expected :actual}`, `:expected` **sourced from reference JVM Clojure**. | `test/conformance/regen-corpus.clj` | +| `test/conformance/profile.edn` | Per-case **feature classification** — which non-portable cases need which host capability. | `certify.clj --profile` | +| `test/conformance/known-divergences.edn` | The few rows whose JVM value is an opaque host object that can't round-trip to readable source (Java arrays/transients/atoms/beans/proxies print as `#object[..@addr]`), so the corpus keeps jolt's value. | `regen-corpus.clj` leftovers, hand-checked | +| `test/conformance/regen-corpus.clj` | Sources every `:expected` from reference **JVM Clojure** in one process. | — | +| `test/conformance/certify.clj` | Certifies `:expected` against reference **JVM Clojure**; gates on new/stale divergences; emits the profile. | — | + +`corpus.edn` is **JVM-sourced**: `regen-corpus.clj` evaluates each case's `:actual` +on reference JVM Clojure and writes the JVM value as `:expected`. **`corpus.edn` is +the canonical, frozen contract**: it is what every runtime consumes, what +`certify.clj` certifies, and where new cases are authored directly. + +## Row schema + +```edn +{:suite "numbers / arithmetic" ; grouping; " :: \" \"a\"]" "(re-find #\"<(.+?)>\" \"\")"] - ["flag case-insens" "\"CAT\"" "(re-find #\"(?i)cat\" \"a CAT\")"] - ["lookahead" "\"foo\"" "(re-find #\"foo(?=bar)\" \"foobar\")"] - ["neg-lookahead" "\"foo\"" "(re-find #\"foo(?!bar)\" \"foobaz\")"] - ["word-boundary" "\"word\"" "(re-find #\"\\bword\\b\" \"a word!\")"] - ["word-boundary no" "nil" "(re-find #\"\\bword\\b\" \"swordfish\")"] - ["optional group" "[\"1.2.3\" \"1\" \"2\" \"3\" nil]" "(re-find #\"(\\d+)\\.(\\d+)\\.(\\d+)(?:-([a-z]+))?\" \"1.2.3\")"] - ["alternation" "\"dog\"" "(re-find #\"cat|dog\" \"a dog cat\")"] - ["str/replace $1" "\"he[ll]o\"" "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" #\"(l+)\" \"[$1]\"))"] - ["str/replace regex" "\"X-X\"" "(do (require (quote [clojure.string :as s])) (s/replace \"a-b\" #\"[a-z]\" \"X\"))"] - - ### ==== map literals evaluate their values ==== - ["map literal expr" "{:a 3}" "{:a (+ 1 2)}"] - ["map literal var" "{:k 5}" "(let [x 5] {:k x})"] - ["map literal nested" "{:a {:b 2}}" "(let [y 2] {:a {:b y}})"] - ["map literal keyfn" "{:x 1}" "(let [k :x] {k 1})"] - ["map literal in fn" "6" "(do (defn mk [a b] {:sum (+ a b)}) (:sum (mk 2 4)))"] - - ### ---- overlay migration (jolt-1j0): run in all 3 modes ---- - # if-let/when-let bind only in the taken branch (else sees outer scope) - ["if-let else outer scope" "5" "(let [x 5] (if-let [x nil] :then x))"] - ["if-some else outer" "5" "(let [x 5] (if-some [x nil] :then x))"] - ["when-let body multi" "14" "(when-let [x 7] (inc x) (* x 2))"] - # nthrest returns () (not nil) for an exhausted n>0 walk; coll for n<=0 - ["nthrest exhausted" "(quote ())" "(nthrest nil 100)"] - ["nthrest n=0 keeps coll" "[1 2 3]" "(nthrest [1 2 3] 0)"] - ["nthnext surprising nil" "nil" "(nthnext nil nil)"] - # distinct? compares by value - ["distinct? equal colls" "false" "(distinct? [1 2] [1 2])"] - ["not-any?" "true" "(not-any? even? [1 3 5])"] - ["take-last" "[3 4]" "(take-last 2 [1 2 3 4])"] - ["replace nil val" "[1 nil 3]" "(replace {2 nil} [1 2 3])"] - - ### ---- migratus enablement: def/defmacro/defmulti forms, assoc, try, ns ---- - # (def name docstring value): the value is the 3rd form, not the docstring - # (jolt-6ym — the analyzer used to bind the docstring as the value). - ["def 3-arg docstring" "42" "(do (def dd \"the doc\" 42) dd)"] - ["def docstring value type" "true" "(do (def ds \"doc\" [1 2]) (vector? ds))"] - # ^{:map} metadata on a def/defn name reads as a with-meta form (jolt-8w2); - # def/defn/defmacro unwrap it instead of choking. - ["def ^{:map} name" "5" "(do (def ^{:private true} mmv 5) mmv)"] - ["defn ^{:map} name" "25" "(do (defn ^{:private true} sqf [x] (* x x)) (sqf 5))"] - # defmacro arity-clause form (jolt-whp) and a leading docstring (with-store shape) - ["defmacro arity-clause" "10" "(do (defmacro m2c ([x] (list (quote *) x 2))) (m2c 5))"] - ["defmacro doc + arity" "30" "(do (defmacro m3c \"doc\" ([x] (list (quote *) x 3))) (* (m3c 5) 2))"] - # defmulti drops a leading docstring (jolt-es4 — it used to be the dispatch fn) - ["defmulti docstring" "\"A\"" "(do (defmulti gmm \"the doc\" identity) (defmethod gmm :a [_] \"A\") (gmm :a))"] - # (assoc nil k v) yields a real map (jolt-w4s); assoc-in nests real maps - ["assoc nil is a map" "1" "(count (assoc nil :a 1))"] - ["assoc-in nested is a map" "1" "(count (:a (assoc-in {} [:a :b] 1)))"] - ["assoc-in deep get" "9" "(get-in (assoc-in {} [:a :b :c] 9) [:a :b :c])"] - # try: a multi-form body and finally that runs on the SUCCESS path with a - # catch present (jolt-0z9 — body forms past the first were dropped and - # finally was skipped on success). - ["try multi-body last" "3" "(try 1 2 3 (catch :default e 0))"] - ["try finally on ok+catch" "9" "(let [a (atom 0)] (try 1 2 (catch :default e :c) (finally (reset! a 9))) @a)"] - ["try finally on throw" "9" "(let [a (atom 0)] (try (throw (ex-info \"x\" {})) (catch :default e nil) (finally (reset! a 9))) @a)"] - # current-ns is restored after a caught throw (jolt-96m): the alias/ns seen by - # code after the catch is the one at the catch site, not the thrower's. - ["ns restored after catch" "\"user\"" - "(do (ns cf.boom) (defn bz [] (throw (Exception. \"e\"))) (in-ns (quote user)) (try (cf.boom/bz) (catch :default e nil)) (str *ns*))"] - # methods sees cross-ns defmethods through a bare multifn ref in its defining - # ns (jolt-9pu — it used to see an empty table). - ["cross-ns methods visible" "[:sql]" - "(do (ns cf.mm) (defmulti ext identity) (defmethod ext :default [_] :d) (defn allk [] (vec (for [[k v] (methods ext) :when (not= k :default)] k))) (ns cf.mmi) (defmethod cf.mm/ext :sql [_] :s) (in-ns (quote user)) (cf.mm/allk))"] - - ### ---- defmacro surface + syntax-quote/ns (enabling real clojure libs) ---- - # multi-arity defmacro (clojure.tools.logging/log has 4 arities) - ["defmacro multi-arity" "[6 5 6]" - "(do (defmacro mar ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b)) ([a b c] (list (quote +) a b c))) [(mar 5) (mar 2 3) (mar 1 2 3)])"] - # defmacro with docstring AND attr-map before the params (every tools.logging - # level macro is shaped this way) - ["defmacro doc + attr-map" "10" - "(do (defmacro mam \"doc\" {:arglists (quote ([x]))} [x] (list (quote inc) x)) (mam 9))"] - # syntax-quote resolves a namespace ALIAS to its target ns, so a macro's - # template resolves at the USE site (jolt-9av) - ["syntax-quote resolves alias" "\"HI\"" - "(do (ns sq.lib (:require [clojure.string :as s])) (defmacro up [x] `(s/upper-case ~x)) (in-ns (quote user)) (sq.lib/up \"hi\"))"] - # ^{:map} metadata on an ns name (jolt-8w2): the ns name is the bare symbol - ["ns name with ^{:map} meta" "5" - "(do (ns ^{:author \"a\" :doc \"d\"} nm.meta) (def q 5) (in-ns (quote user)) nm.meta/q)"] - # ~*ns* splices the live namespace object into a template (it self-evaluates) - ["unquote *ns* in template" "true" - "(do (defmacro cur-ns [] `(str ~*ns*)) (string? (cur-ns)))"] - ]) - -# Run every case under a given context factory and return the failures. The same -# cases run under both the interpreter and the compiler: results must match real -# Clojure semantics either way, so the compile path (hybrid: hot compiles, -# unsupported forms fall back to the interpreter) must not diverge. -# mode: {} interpret, {:compile? true} bootstrap compiler, {:selfhost true} the -# self-hosted pipeline (portable Clojure analyzer -> IR -> Janet back end). -(defn- run-cases [mode] - (def selfhost? (get mode :selfhost)) - (def init-opts (if selfhost? {} mode)) - (defn ev [ctx prog] - (if selfhost? (selfhost/compile-and-eval ctx (parse-string prog)) (eval-string ctx prog))) - # One expensive init per mode; every case runs on a cheap isolated fork (~2 ms) - # instead of its own init (~50 ms interpreted / ~900 ms compiled). Isolation is - # preserved — a fork shares nothing mutable with its siblings. For self-host - # mode, compile one form first so the lazily-built analyzer is in the snapshot. - (def base (init-cached init-opts)) - (when selfhost? (selfhost/compile-and-eval base (parse-string "1"))) - (def snap (snapshot base)) - (def fails @[]) - (each [name expected actual] cases - (def ctx (fork snap)) - (def prog (string "(= " expected " " actual ")")) - (def res (protect (ev ctx prog))) - (cond - (not= (res 0) true) - (array/push fails [name "ERROR" (string (res 1))]) - (= (res 1) true) - nil - (let [got (protect (ev (fork snap) actual))] - (array/push fails [name "MISMATCH" - (string "want=" expected - " got=" (if (= (got 0) true) (string/format "%q" (got 1)) (string "ERR:" (got 1))))])))) - fails) - -(defn- report [label fails] - (printf "=== CONFORMANCE (%s): %d/%d passed ===" label (- (length cases) (length fails)) (length cases)) - (unless (empty? fails) - (print "--- Failures ---") - (each [name kind detail] fails - (printf "[%s] %s: %s" kind name detail)))) - -(def interp-fails (run-cases {})) -(report "interpret" interp-fails) -(def compile-fails (run-cases {:compile? true})) -(report "compile" compile-fails) -(def selfhost-fails (run-cases {:selfhost true})) -(report "self-host" selfhost-fails) -(print) -(when (or (pos? (length interp-fails)) (pos? (length compile-fails)) - (pos? (length selfhost-fails))) - (os/exit 1)) diff --git a/test/integration/cross-ns-hints-test.janet b/test/integration/cross-ns-hints-test.janet deleted file mode 100644 index d67fa0c..0000000 --- a/test/integration/cross-ns-hints-test.janet +++ /dev/null @@ -1,72 +0,0 @@ -# Cross-namespace ^Type field hints (jolt-3ko follow-up): a record field hinted -# with a record type defined in ANOTHER namespace — referred (:refer) or aliased -# (:as) in — must resolve to that type's HOME ctor key in the record-shapes -# registry, the same as a same-namespace hint does. That resolved key is what -# lets the inference type a field read back to the foreign record type instead of -# :any (the lever for fast nested-record code across a multi-namespace program). -# Guards both the :refer and :as spellings — for record FIELD hints and for -# fn PARAM hints (which seed the inference so a record param's reads are typed -# across a namespace boundary without whole-program). Also guards that the -# reader keeps a tag's namespace qualifier (^g/Pt -> "g/Pt", not "Pt"). -(use ../../src/jolt/api) -(import ../../src/jolt/types :as ty) -(import ../../src/jolt/core :as jc) -(import ../../src/jolt/reader :as rd) - -(var failures 0) -(defn- check [label got want] - (unless (deep= got want) - (++ failures) - (printf "FAIL [%s] got %q want %q" label got want))) - -(def dir (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-xns-hints")) -(os/mkdir dir) -(os/mkdir (string dir "/geo")) -# Pt lives in geo.pt; shape records in geo.shape hint ^Pt across the boundary. -(spit (string dir "/geo/pt.clj") - "(ns geo.pt)\n(defrecord Pt [x y z])\n") -(spit (string dir "/geo/shape.clj") - (string "(ns geo.shape (:require [geo.pt :as g :refer [Pt]]))\n" - "(defrecord Seg [^Pt a ^Pt b])\n" # :refer field hint - "(defrecord Tri [^g/Pt a ^g/Pt b ^g/Pt c])\n" # :as field hint - # param hints, both spellings: ^Pt (referred), ^g/Pt (aliased) - "(defn mid [^Pt a ^g/Pt b] a)\n")) - -(def ctx (init {:compile? true :direct-linking? true})) -(array/push (get (ctx :env) :source-paths) dir) -(eval-string ctx "(require '[geo.shape])") -(def rs (get (ctx :env) :record-shapes)) - -(check ":refer ^Pt field hint resolves to home ctor key" - (get (get rs "geo.shape/->Seg") :tags) - ["geo.pt/->Pt" "geo.pt/->Pt"]) -(check ":as ^g/Pt field hint resolves to home ctor key" - (get (get rs "geo.shape/->Tri") :tags) - ["geo.pt/->Pt" "geo.pt/->Pt" "geo.pt/->Pt"]) -# the foreign type's own shape is registered under its home key -(check "home type registered" - (get (get rs "geo.pt/->Pt") :fields) - [:x :y :z]) - -# --- param hints: the arity carries [name ctor-key] for each record param, both -# the :refer (^Pt) and :as (^g/Pt) spellings resolved to the home key ---------- -(def shape-ns (ty/ctx-find-ns ctx "geo.shape")) -(def mid-ir (get (get (get shape-ns :mappings) "mid") :infer-ir)) -(def mid-arity (first (jc/vview (get (get mid-ir :init) :arities)))) -(def phints (when (get mid-arity :phints) - (map jc/vview (jc/vview (get mid-arity :phints))))) -(check "param hints resolve cross-ns (refer + as)" - phints - @[@["a" "geo.pt/->Pt"] @["b" "geo.pt/->Pt"]]) - -# --- reader keeps a tag's namespace qualifier --------------------------------- -(check "reader preserves qualified tag ^g/Pt" - (get (get (rd/parse-string "^g/Pt x") :meta) :tag) - "g/Pt") -(check "reader bare tag ^Pt unchanged" - (get (get (rd/parse-string "^Pt x") :meta) :tag) - "Pt") - -(if (= 0 failures) - (print "cross-ns-hints: all cases passed") - (do (printf "cross-ns-hints: %d FAILURES" failures) (os/exit 1))) diff --git a/test/integration/ctx-image-test.janet b/test/integration/ctx-image-test.janet deleted file mode 100644 index 67e3917..0000000 --- a/test/integration/ctx-image-test.janet +++ /dev/null @@ -1,78 +0,0 @@ -# init-cached: disk-cached AOT image of the fully-built context. -# -# init in compile mode costs ~2.4 s (tier loading, analyzer self-compile, macro -# recompilation). init-cached pays that once, marshals the built ctx to an image -# file (the same machinery as api/snapshot), and every later process unmarshals -# it instead of rebuilding. The cache key fingerprints the embedded .clj stdlib, -# the .janet seed sources, and the init opts, so any source change invalidates. -# -# The cross-process case is the one that matters (each `jpm test` file is its -# own janet process), so the warm-load checks run in a SUBPROCESS against the -# image this process bakes. -(use ../../src/jolt/api) - -(print "ctx image cache...") - -(def dir (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-img-test-" (os/getpid))) -(os/mkdir dir) -(os/setenv "JOLT_IMAGE_CACHE_DIR" dir) -# The cache is the test subject — undo an ambient opt-out (and for the subprocess). -(os/setenv "JOLT_NO_IMAGE_CACHE" nil) -(defer (do (each f (os/dir dir) (os/rm (string dir "/" f))) (os/rmdir dir)) - - # 1. Cold init: builds the ctx, writes an image, and is fully functional. - (def t0 (os/clock)) - (def ctx1 (init-cached {:compile? true})) - (def cold-s (- (os/clock) t0)) - (assert (= 3 (eval-string ctx1 "(+ 1 2)")) "cold ctx evaluates") - (def files (filter |(string/has-suffix? ".jimg" $) (os/dir dir))) - (assert (= 1 (length files)) (string "one image written, got " (length files))) - - # 2. Warm init in THIS process: loads the image, functional, and much faster. - (def t1 (os/clock)) - (def ctx2 (init-cached {:compile? true})) - (def warm-s (- (os/clock) t1)) - (assert (= 10 (eval-string ctx2 "(do (defn f [x] (* 2 x)) (f 5))")) "warm ctx compiles defns") - (assert (< warm-s (/ cold-s 4)) - (string/format "warm load (%.0f ms) at least 4x faster than cold (%.0f ms)" - (* 1000 warm-s) (* 1000 cold-s))) - - # 3. Different opts get a different image (no false sharing between modes). - (init-cached {}) - (def files2 (filter |(string/has-suffix? ".jimg" $) (os/dir dir))) - (assert (= 2 (length files2)) "interpret-mode image is keyed separately") - - # 4. Cross-process warm load: a fresh janet process loads the image this - # process baked and runs real work — compiled defns, redefinition, - # macros, lazy seqs, protocols, multimethods, stdlib require. - (def checks - ``(use ./src/jolt/api) - (def t0 (os/clock)) - (def ctx (init-cached {:compile? true})) - (def warm-ms (* 1000 (- (os/clock) t0))) - (def img-files (filter |(string/has-suffix? ".jimg" $) - (os/dir (os/getenv "JOLT_IMAGE_CACHE_DIR")))) - (assert (= 2 (length img-files)) "subprocess hit the cache (no new image)") - (assert (= 3 (eval-string ctx "(+ 1 2)")) "arith") - (assert (= 120 (eval-string ctx "(do (defn fact [n] (if (zero? n) 1 (* n (fact (dec n))))) (fact 5))")) "compiled defn") - (assert (= 7 (eval-string ctx "(do (def a 3) (def a 7) a)")) "redefinition") - (assert (= 6 (eval-string ctx "(-> 1 inc (* 3))")) "macros expand") - (assert (= 9 (eval-string ctx "(do (defmacro tw [x] `(* 3 ~x)) (tw 3))")) "defmacro works post-load") - (assert (= [2 4 6] (normalize-pvecs (eval-string ctx "(vec (map #(* 2 %) [1 2 3]))"))) "lazy/HOF") - (assert (= "a-b" (eval-string ctx "(do (require '[clojure.string :as str]) (str/join \"-\" [\"a\" \"b\"]))")) "stdlib require") - (assert (= 42 (eval-string ctx "(do (defprotocol P (pf [x])) (defrecord R [] P (pf [x] 42)) (pf (->R)))")) "protocols") - (assert (= :big (eval-string ctx "(do (defmulti m (fn [x] (if (> x 5) :big :small))) (defmethod m :big [_] :big) (m 10))")) "multimethods") - (print "subprocess warm load ok in " (math/round warm-ms) " ms")``) - (def code (os/execute ["janet" "-e" checks] :p)) - (assert (= 0 code) "cross-process warm load passes") - - # 5. A source change invalidates: poisoning the fingerprint env knob is not - # possible from here, but a corrupted image must fall back to a rebuild - # rather than crash. - (each f (os/dir dir) - (when (string/has-suffix? ".jimg" f) (spit (string dir "/" f) "garbage"))) - (def ctx3 (init-cached {:compile? true})) - (assert (= 3 (eval-string ctx3 "(+ 1 2)")) "corrupted image falls back to rebuild") - - (printf "ctx image cache passed! (cold %.0f ms, warm %.0f ms)" - (* 1000 cold-s) (* 1000 warm-s))) diff --git a/test/integration/deps-aliases-test.janet b/test/integration/deps-aliases-test.janet deleted file mode 100644 index 00b21f1..0000000 --- a/test/integration/deps-aliases-test.janet +++ /dev/null @@ -1,119 +0,0 @@ -# deps.edn aliases + user-level config merge (jolt-4go). -# -# Mirrors tools.deps semantics scoped to what jolt supports (git/:local, no -# maven): :aliases with :extra-paths / :extra-deps / :main-opts selected by -# keyword; a user deps.edn (under $JOLT_CONFIG, else $XDG_CONFIG_HOME/jolt, -# else ~/.jolt) merged UNDER the project file — :deps and :aliases merge per -# key with the project winning, :paths replaces. Local deps only: no network. - -(import ../../src/jolt/deps :as deps) - -(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-aliases-" (os/time))) -(defn rmrf [p] - (when (os/stat p) - (if (= :directory (os/stat p :mode)) - (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) - (os/rm p)))) -(rmrf base) - -(defn mkdirs [p] - (def abs (string/has-prefix? "/" p)) - (var acc nil) - (each seg (filter |(not= "" $) (string/split "/" p)) - (set acc (cond (nil? acc) (if abs (string "/" seg) seg) (string acc "/" seg))) - (unless (os/stat acc) (os/mkdir acc)))) - -(each d ["proj/src" "proj/dev" "proj/test" "a/src" "c/src" "u/src" "config"] - (mkdirs (string base "/" d))) - -# project: src + dep a; :dev alias adds dev/ + dep c; :test alias adds test/ -(spit (string base "/proj/deps.edn") - `{:paths ["src"] - :deps {my/a {:local/root "../a"}} - :aliases {:dev {:extra-paths ["dev"] - :extra-deps {my/c {:local/root "../c"}}} - :test {:extra-paths ["test"] - :main-opts ["-e" "(run-tests)"]} - :bench {:main-opts ["-e" "(bench)"]}}}`) -(spit (string base "/a/deps.edn") `{:paths ["src"]}`) -(spit (string base "/c/deps.edn") `{:paths ["src"]}`) -(spit (string base "/u/deps.edn") `{:paths ["src"]}`) - -# user-level config: a :user-tool alias the project file doesn't have, plus a -# :dev alias that the PROJECT's :dev must shadow (per-key merge, project wins) -(spit (string base "/config/deps.edn") - `{:aliases {:user-tool {:extra-deps {my/u {:local/root "BASE/u"}}} - :dev {:extra-paths ["should-not-win"]}}}`) -# :local/root in the user file is relative to... nothing useful; use absolute -(spit (string base "/config/deps.edn") - (string/replace "BASE" base (slurp (string base "/config/deps.edn")))) - -(var fails 0) -(defn check [label got expected] - (if (= got expected) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got)))) -(defn has-suffix-root [roots suff] - (truthy? (some |(string/has-suffix? suff $) roots))) - -(os/cd (string base "/proj")) -(os/setenv "JOLT_CONFIG" (string base "/config")) -(def tree (string base "/proj/jpm_tree")) - -# --- no aliases: plain resolution, dev/test/c absent --------------------------- -(def plain (deps/resolve-deps "deps.edn" tree)) -(check "plain: project src present" (has-suffix-root plain "/proj/src") true) -(check "plain: dep a present" (has-suffix-root plain "/a/src") true) -(check "plain: alias path absent" (has-suffix-root plain "/proj/dev") false) -(check "plain: alias dep absent" (has-suffix-root plain "/c/src") false) - -# --- :dev alias: extra-paths + extra-deps -------------------------------------- -(def dev (deps/resolve-deps "deps.edn" tree [:dev])) -(check "dev: extra path present" (has-suffix-root dev "/proj/dev") true) -(check "dev: extra dep present" (has-suffix-root dev "/c/src") true) -(check "dev: base dep still present" (has-suffix-root dev "/a/src") true) -(check "dev: project :dev shadows user :dev" - (has-suffix-root dev "/proj/should-not-win") false) - -# --- multiple aliases combine --------------------------------------------------- -(def both (deps/resolve-deps "deps.edn" tree [:dev :test])) -(check "multi: both extra paths" - (and (has-suffix-root both "/proj/dev") (has-suffix-root both "/proj/test")) true) - -# --- alias from the USER deps.edn ---------------------------------------------- -(def ut (deps/resolve-deps "deps.edn" tree [:user-tool])) -(check "user alias resolves its dep" (has-suffix-root ut "/u/src") true) - -# --- main-opts: from alias, last alias wins ------------------------------------ -(check "main-opts from alias" - (deps/alias-main-opts "deps.edn" [:test]) ["-e" "(run-tests)"]) -(check "main-opts last alias wins" - (deps/alias-main-opts "deps.edn" [:test :bench]) ["-e" "(bench)"]) -(check "main-opts absent is nil" - (deps/alias-main-opts "deps.edn" [:dev]) nil) - -# --- cached resolution keys on aliases + user config ---------------------------- -(check "cache: aliased result differs from plain" - (deep= (deps/resolve-deps-cached "deps.edn" tree) - (deps/resolve-deps-cached "deps.edn" tree [:dev])) - false) -(check "cache: same key returns same roots" - (deep= (deps/resolve-deps-cached "deps.edn" tree [:dev]) - (deps/resolve-deps-cached "deps.edn" tree [:dev])) - true) - -# --- unknown alias errors -------------------------------------------------------- -(check "unknown alias errors" - (let [r (protect (deps/resolve-deps "deps.edn" tree [:nope]))] (r 0)) - false) - -# --- works without a user config (env unset) ------------------------------------ -(os/setenv "JOLT_CONFIG" (string base "/no-such-dir")) -(check "no user config still resolves" - (has-suffix-root (deps/resolve-deps "deps.edn" tree) "/a/src") true) - -(os/cd "/") -(rmrf base) - -(if (> fails 0) - (error (string "deps-aliases-test: " fails " failing check(s)")) - (print "\nAll deps-aliases tests passed!")) diff --git a/test/integration/deps-cache-args-test.janet b/test/integration/deps-cache-args-test.janet deleted file mode 100644 index 502fdf1..0000000 --- a/test/integration/deps-cache-args-test.janet +++ /dev/null @@ -1,41 +0,0 @@ -# The deps-image cache must not drop -main's command-line args under -# whole-program (jolt-4mui). A cache HIT swaps the running ctx for the saved -# image; *command-line-args* must be (re)bound from the CURRENT invocation's -# argv, not the stale value baked into the image. Drives the built binary: -# first run builds the cache (arg "first"), second run (cache hit) passes "second" -# — both must echo their own arg. Skips if build/jolt is absent. -(def repo (os/cwd)) -(def jolt (string repo "/build/jolt")) -(if-not (os/stat jolt) - (do (print "deps-cache-args: SKIP (no build/jolt)") (os/exit 0))) - -(def dir (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-dca-" (os/time))) -(os/mkdir dir) -(spit (string dir "/echoargs.clj") - "(ns echoargs)\n(defn -main [& args] (println \"GOT\" (pr-str (vec args))))\n") -# fresh per-run image cache dir so the first run is a guaranteed miss -(def imgdir (string dir "/imgcache")) (os/mkdir imgdir) - -(each [k v] [["JOLT_DIRECT_LINK" "1"] ["JOLT_WHOLE_PROGRAM" "1"] - ["JOLT_PATH" dir] ["JOLT_APP_PATHS" dir] ["JOLT_IMAGE_CACHE_DIR" imgdir]] - (os/setenv k v)) -(defn- run [arg] - (def p (os/spawn [jolt "-m" "echoargs" arg] :p {:out :pipe :err :pipe})) - (def out (:read (p :out) :all)) - (os/proc-wait p) - (string (or out ""))) - -(var fails 0) -(defn check [label got want] - (if (string/find want got) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %p in %p" label want got)))) - -(def r1 (run "first")) # cache MISS — builds + saves the image -(check "first run passes its arg" r1 `GOT ["first"]`) -(def r2 (run "second")) # cache HIT — must use the NEW arg, not the baked one -(check "second run (cache hit) passes its arg, not the baked one" r2 `GOT ["second"]`) - -(defn rmrf [p] (when (os/stat p) (if (= :directory (os/stat p :mode)) (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) (os/rm p)))) -(rmrf dir) -(if (> fails 0) (do (printf "deps-cache-args: %d FAILED" fails) (os/exit 1)) - (print "deps-cache-args (jolt-4mui) passed!")) diff --git a/test/integration/deps-conflicts-test.janet b/test/integration/deps-conflicts-test.janet deleted file mode 100644 index dd082e4..0000000 --- a/test/integration/deps-conflicts-test.janet +++ /dev/null @@ -1,69 +0,0 @@ -# deps.edn conflict semantics (jolt-42f), tools.deps-shaped: -# a TOP-LEVEL :deps entry beats any transitive coordinate for the same lib -# (resolution is breadth-first, top level enqueued first), and when two -# DIFFERENT coordinates for one lib meet, a warning naming both goes to stderr. -# Local deps only: no network. - -(import ../../src/jolt/deps :as deps) - -(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-conflicts-" (os/time))) -(defn rmrf [p] - (when (os/stat p) - (if (= :directory (os/stat p :mode)) - (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) - (os/rm p)))) -(rmrf base) -(defn mkdirs [p] - (def abs (string/has-prefix? "/" p)) - (var acc nil) - (each seg (filter |(not= "" $) (string/split "/" p)) - (set acc (cond (nil? acc) (if abs (string "/" seg) seg) (string acc "/" seg))) - (unless (os/stat acc) (os/mkdir acc)))) - -# proj depends on A and on B@b2 (top level). A depends on B@b1 (transitive). -# DFS-first-wins would pick b1; tools.deps semantics pick the top-level b2. -(each d ["proj/src" "a/src" "b1/src" "b2/src"] (mkdirs (string base "/" d))) -(spit (string base "/proj/deps.edn") - `{:paths ["src"] - :deps {my/a {:local/root "../a"} - my/b {:local/root "../b2"}}}`) -(spit (string base "/a/deps.edn") - `{:paths ["src"] :deps {my/b {:local/root "../b1"}}}`) -(spit (string base "/b1/deps.edn") `{:paths ["src"]}`) -(spit (string base "/b2/deps.edn") `{:paths ["src"]}`) - -(var fails 0) -(defn check [label got expected] - (if (= got expected) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got)))) -(defn has-suffix-root [roots suff] - (truthy? (some |(string/has-suffix? suff $) roots))) - -(os/cd (string base "/proj")) -(def tree (string base "/proj/jpm_tree")) - -(def warn-buf @"") -(def roots (with-dyns [:err warn-buf] (deps/resolve-deps "deps.edn" tree))) - -(check "top-level coordinate wins" (has-suffix-root roots "/b2/src") true) -(check "transitive loser not on path" (has-suffix-root roots "/b1/src") false) -(check "dep a still resolved" (has-suffix-root roots "/a/src") true) -(check "conflict warning names the lib" - (truthy? (string/find "my/b" (string warn-buf))) true) -(check "conflict warning names both coordinates" - (and (truthy? (string/find "../b1" (string warn-buf))) - (truthy? (string/find "../b2" (string warn-buf)))) true) - -# same coordinate twice from different parents: no warning -(spit (string base "/a/deps.edn") - `{:paths ["src"] :deps {my/b {:local/root "../b2"}}}`) -(def warn2 @"") -(with-dyns [:err warn2] (deps/resolve-deps "deps.edn" tree)) -(check "agreeing coordinates warn nothing" (string warn2) "") - -(os/cd "/") -(rmrf base) - -(if (> fails 0) - (error (string "deps-conflicts-test: " fails " failing check(s)")) - (print "\nAll deps-conflicts tests passed!")) diff --git a/test/integration/deps-conformance-test.janet b/test/integration/deps-conformance-test.janet deleted file mode 100644 index 90a98ac..0000000 --- a/test/integration/deps-conformance-test.janet +++ /dev/null @@ -1,59 +0,0 @@ -# Conformance pass for deps.edn-loaded libraries: resolve a few real, pure-cljc -# git libraries and check that their namespaces load and a sample call works. -# -# Network-gated: set JOLT_CONFORMANCE=1 to run (it clones from GitHub). Skipped by -# default so CI stays offline. Findings are summarized in docs/tools-deps.md. - -(use ../../src/jolt/api) -(use ../../src/jolt/types) -(import ../../src/jolt/deps :as deps) -(use ../../src/jolt/reader) -# deps are clj/cljc libraries by definition (the jolt-dw4 premise): read them -# under clj-compat features so their #?(:clj ...) branches resolve (spec -# 02-reader S18 — features are a property of the loading context). -(reader-features-set! ["jolt" "clj" "default"]) - -(unless (os/getenv "JOLT_CONFORMANCE") - (print "deps-conformance: set JOLT_CONFORMANCE=1 to run (needs network) — skipped") - (os/exit 0)) - -(def libs - [{:name "medley" :url "https://github.com/weavejester/medley" :tag "1.4.0" - :ns "medley.core" :check "(medley.core/find-first odd? [2 4 5])" :expect "5"} - {:name "cuerdas" :url "https://github.com/funcool/cuerdas" :tag "2022.06.16-403" - :ns "cuerdas.core" :check "(cuerdas.core/kebab \"helloWorld\")" :expect "hello-world"} - {:name "dependency" :url "https://github.com/stuartsierra/dependency" :tag "dependency-1.0.0" - :ns "com.stuartsierra.dependency" - :check "(boolean (com.stuartsierra.dependency/graph))" :expect "true"}]) - -(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-conf-" (os/time))) -(os/mkdir base) - -(defn- try-lib [lib] - (def dir (string base "/" (lib :name))) - (os/mkdir dir) - (spit (string dir "/deps.edn") - (string "{:deps {the/lib {:git/url \"" (lib :url) "\" :git/tag \"" (lib :tag) "\"}}}")) - (def prev (os/cwd)) - (defer (os/cd prev) - (os/cd dir) - (def r (protect (deps/resolve-deps "deps.edn"))) - (if (not (r 0)) - [:resolve-failed (string (r 1))] - (let [ctx (init {:paths (r 1)})] - (ctx-set-current-ns ctx "user") - (def lr (protect (eval-string ctx (string "(require (quote [" (lib :ns) "]))")))) - (if (not (lr 0)) - [:load-failed (string (lr 1))] - (let [cr (protect (eval-string ctx (lib :check)))] - (cond - (not (cr 0)) [:check-error (string (cr 1))] - (= (string (normalize-pvecs (cr 1))) (lib :expect)) [:ok nil] - [:check-mismatch (string "got " (string (normalize-pvecs (cr 1))))]))))))) - -(print "deps conformance — pure-cljc git libs:\n") -(each lib libs - (def [status detail] (try (try-lib lib) ([err] [:crash (string err)]))) - (printf " %-12s %-16s %s" (lib :name) status (or detail ""))) -(print "") -(os/exit 0) diff --git a/test/integration/deps-loader-test.janet b/test/integration/deps-loader-test.janet deleted file mode 100644 index 96cca27..0000000 --- a/test/integration/deps-loader-test.janet +++ /dev/null @@ -1,48 +0,0 @@ -# The loader resolves namespaces against an ordered list of source roots (the -# stdlib first, then deps.edn-resolved dirs), trying .clj then .cljc. This is the -# foundation for loading Clojure libraries via deps.edn — here we point a root at -# a hand-written "library" and require it. - -(use ../../src/jolt/api) -(use ../../src/jolt/types) - -(def tmp (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-test-" (os/time))) -(os/mkdir tmp) -(os/mkdir (string tmp "/mylib")) -(os/mkdir (string tmp "/other")) - -# a .cljc library with its own ns form and a require of a sibling ns -(spit (string tmp "/mylib/core.cljc") - "(ns mylib.core (:require [other.util :as u]))\n(defn double [x] (* 2 x))\n(defn doubled-inc [x] (u/inc1 (double x)))\n") -# a .clj sibling, with a dash in the name (-> underscore in the path) -(os/mkdir (string tmp "/other")) -(spit (string tmp "/other/util.clj") "(ns other.util)\n(defn inc1 [x] (+ x 1))\n") - -(def ctx (init {:paths [tmp]})) -(ctx-set-current-ns ctx "user") - -(var fails 0) -(defn check [label expr expected] - (let [r (protect (eval-string ctx expr)) - got (if (r 0) (normalize-pvecs (r 1)) (string "ERR " (r 1)))] - (if (= got expected) - (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got))))) - -# require a .cljc lib from the added root and call it -(check "require .cljc lib" "(do (require (quote [mylib.core :as m])) (m/double 21))" 42) -# transitive require (mylib.core requires other.util) resolved from the root too -(check "transitive .clj require" "(mylib.core/doubled-inc 10)" 21) -# the stdlib still resolves from its default root -(check "stdlib still loads" "(do (require (quote [jolt.interop :as j])) (j/janet-type 1))" :number) - -# clean up -(defn rmrf [p] - (if (= :directory (os/stat p :mode)) - (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) - (os/rm p))) -(rmrf tmp) - -(if (> fails 0) - (error (string "deps-loader-test: " fails " failing check(s)")) - (print "\nAll deps-loader tests passed!")) diff --git a/test/integration/deps-merged-cli-test.janet b/test/integration/deps-merged-cli-test.janet deleted file mode 100644 index e5acfa2..0000000 --- a/test/integration/deps-merged-cli-test.janet +++ /dev/null @@ -1,98 +0,0 @@ -# jolt-deps folded into jolt: the single `jolt` binary resolves a deps.edn into -# JOLT_PATH in-process and dispatches the deps subcommands (path/-M/run/tasks/ -# task), and auto-resolves a deps.edn for runnable commands (repl/-m/-e/FILE). -# Drives the BUILT binary (baked overlay -> cwd-independent) from a fixture -# project dir so deps.edn in cwd is picked up. :local/root deps only — no -# network. Skips cleanly if build/jolt is absent (source-only run). - -(def repo-root (os/cwd)) -(def jolt (string repo-root "/build/jolt")) - -(if-not (os/stat jolt) - (do (print "deps-merged-cli: SKIP (no build/jolt — run from source)") (os/exit 0))) - -(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-merged-cli-" (os/time))) -(defn rmrf [p] - (when (os/stat p) - (if (= :directory (os/stat p :mode)) - (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) - (os/rm p)))) -(rmrf base) -(defn mkdirs [p] - (var acc nil) - (each seg (filter |(not= "" $) (string/split "/" p)) - (set acc (if (nil? acc) (string "/" seg) (string acc "/" seg))) - (unless (os/stat acc) (os/mkdir acc)))) - -# project depends on a local lib; an alias with :main-opts; an :extra-paths -# alias; a :tasks map (shell task) -(each d ["proj/src/app" "lib/src/mylib"] (mkdirs (string base "/" d))) -(spit (string base "/proj/deps.edn") - `{:paths ["src"] - :deps {my/lib {:local/root "../lib"}} - :aliases {:run {:main-opts ["-m" "app.core"]} - :dev {:extra-paths ["dev"]}} - :tasks {greet "echo hello-task"}}`) -(spit (string base "/lib/deps.edn") `{:paths ["src"]}`) -(spit (string base "/lib/src/mylib/core.clj") "(ns mylib.core)\n(defn answer [] 42)\n") -(spit (string base "/proj/src/app/core.clj") - "(ns app.core (:require [mylib.core :as m]))\n(defn -main [& args] (println \"MAIN\" (m/answer) (count args)))\n") -(spit (string base "/proj/script.clj") - "(require '[mylib.core :as m])\n(println \"SCRIPT\" (m/answer))\n") - -# Run the built jolt from a given dir (cwd matters: deps.edn is read from cwd). -# Direct spawn (no shell) so arbitrary -e exprs need no quoting. Returns out+err. -(defn- run-in [dir & args] - (def prev (os/cwd)) - (os/cd dir) - (def p (os/spawn [jolt ;args] :p {:out :pipe :err :pipe})) - (def out (:read (p :out) :all)) - (def err (:read (p :err) :all)) - (os/proc-wait p) - (os/cd prev) - (string (or out "") (or err ""))) - -(var fails 0) -(defn check [label got pred] - (if (pred got) (print " ok " label) - (do (++ fails) (printf " FAIL %s: got %q" label got)))) -(defn- has [sub] (fn [s] (truthy? (string/find sub s)))) - -(def proj (string base "/proj")) - -# `path` prints the resolved roots: project's own src + the local dep's src -(check "path includes project src" (run-in proj "path") (has "/proj/src")) -(check "path includes local dep src" (run-in proj "path") (has "/lib/src")) - -# `-M:run` runs the alias :main-opts (-m app.core), requiring the local dep -(check "-M:run runs -main through resolved deps" (run-in proj "-M:run" "x" "y") (has "MAIN 42 2")) - -# `run FILE` resolves deps then runs the file -(check "run FILE resolves deps" (run-in proj "run" "script.clj") (has "SCRIPT 42")) - -# `tasks` lists the :tasks entries; `task NAME` runs a shell task -(check "tasks lists greet" (run-in proj "tasks") (has "greet")) -(check "task runs shell command" (run-in proj "task" "greet") (has "hello-task")) - -# auto-resolve: a plain -e in a deps.edn dir can require the local dep -(check "-e auto-resolves deps.edn in cwd" - (run-in proj "-e" "(require '[mylib.core :as m]) (println (m/answer))") - (has "42")) - -# -A:alias forces resolution (with that alias) for a runnable command -(check "-A:dev with -e resolves + runs" - (run-in proj "-A:dev" "-e" "(println (+ 1 2))") - (has "3")) - -# no deps.edn: plain run is unaffected (resolver/jpm never touched) -(mkdirs (string base "/plain")) -(check "-e in a no-deps dir works unchanged" - (run-in (string base "/plain") "-e" "(println (* 6 7))") - (has "42")) -# help/version never trigger resolution -(check "version works in a deps dir" (run-in proj "--version") (has "jolt v")) - -(rmrf base) -(if (> fails 0) - (do (printf "deps-merged-cli: %d FAILED" fails) (os/exit 1)) - (print "deps-merged-cli: all cases passed")) diff --git a/test/integration/deps-resolve-test.janet b/test/integration/deps-resolve-test.janet deleted file mode 100644 index 5a22b88..0000000 --- a/test/integration/deps-resolve-test.janet +++ /dev/null @@ -1,156 +0,0 @@ -# deps.edn resolution into source roots, then loading a library through them. -# Uses :local/root deps only so it needs no network (the git path is the same -# code, exercised manually against real repos). - -(use ../../src/jolt/api) -(use ../../src/jolt/types) -(import ../../src/jolt/deps :as deps) - -# Captured before any os/cd: subprocess tests below re-import src/jolt/deps. -(def repo-root (os/cwd)) - -(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-resolve-" (os/time))) -(defn rmrf [p] - (when (os/stat p) - (if (= :directory (os/stat p :mode)) - (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) - (os/rm p)))) -(rmrf base) - -(defn mkdirs [p] - (def abs (string/has-prefix? "/" p)) - (var acc nil) - (each seg (filter |(not= "" $) (string/split "/" p)) - (set acc (cond (nil? acc) (if abs (string "/" seg) seg) (string acc "/" seg))) - (unless (os/stat acc) (os/mkdir acc)))) - -# project -> depends on lib-a (local), which depends on lib-b (local, transitive) -(each d ["proj/src" "a/src/liba" "b/src/libb"] (mkdirs (string base "/" d))) -(spit (string base "/proj/deps.edn") `{:paths ["src"] :deps {my/a {:local/root "../a"}}}`) -(spit (string base "/a/deps.edn") `{:paths ["src"] :deps {my/b {:local/root "../b"}}}`) -(spit (string base "/b/deps.edn") `{:paths ["src"]}`) -(spit (string base "/a/src/liba/core.clj") "(ns liba.core (:require [libb.core :as b]))\n(defn val [] (b/n))\n") -(spit (string base "/b/src/libb/core.clj") "(ns libb.core)\n(defn n [] 99)\n") - -(var fails 0) -(defn check [label got expected] - (if (= got expected) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got)))) - -(os/cd (string base "/proj")) -(def roots (deps/resolve-deps "deps.edn" (string base "/proj/jpm_tree"))) -# roots: proj/src, a/src (transitive: b/src) — at least the two dep srcs present -(check "resolves transitive local dep roots" - (truthy? (and (some |(string/has-suffix? "/a/src" $) roots) - (some |(string/has-suffix? "/b/src" $) roots))) - true) - -# load through the resolved roots: liba.core requires libb.core transitively -(def ctx (init {:paths roots})) -(ctx-set-current-ns ctx "user") -(let [r (protect (eval-string ctx "(do (require (quote [liba.core :as a])) (a/val))"))] - (check "require local lib + transitive dep" (if (r 0) (r 1) (string "ERR " (r 1))) 99)) - -# cached resolution returns the same roots without re-walking -(check "cached resolve matches" - (deep= roots (deps/resolve-deps-cached "deps.edn" (string base "/proj/jpm_tree"))) - true) - -# The cache must hit across PROCESSES: janet's (hash ...) is seeded per process, -# so a key built with it never matches a cached one and every invocation -# re-resolved (and re-fetched git deps). Detection: plant a sentinel root in the -# cache file — a fresh process that hits the cache returns it; a process that -# misses re-resolves and overwrites it. -(os/cd (string base "/proj")) -(def cache-file ".cpcache/jolt-deps.jdn") -(def cached-now (parse (slurp cache-file))) -(spit cache-file - (string/format "%j" (merge cached-now - {:roots [;(get cached-now :roots) "/SENTINEL"]}))) -(defn subprocess-roots [] - (def code - (string `(os/cd "` repo-root `") ` - `(import ./src/jolt/deps :as deps) ` - `(os/cd "` base "/proj" `") ` - `(print (string/join (deps/resolve-deps-cached "deps.edn" "` base "/proj/jpm_tree" `") ":"))`)) - (def p (os/spawn ["janet" "-e" code] :px {:out :pipe})) - (def out (ev/read (p :out) :all)) - (os/proc-wait p) - (string/trim (string out))) -(check "cache hits across processes" - (string/has-suffix? "/SENTINEL" (subprocess-roots)) - true) - -(os/cd "/") -(rmrf base) - -# Git-dep resolution must keep stdout clean: `JOLT_PATH=$(jolt-deps path)` is -# the documented capture, and git's checkout chatter ("HEAD is now at …") was -# corrupting it. Uses a file:// git dep so no network is needed. -(def gbase (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-gitout-" (os/time))) -(rmrf gbase) -(each d ["lib/src/glib" "proj2"] (mkdirs (string gbase "/" d))) -(spit (string gbase "/lib/src/glib/core.clj") "(ns glib.core)\n(defn n [] 7)\n") -(spit (string gbase "/lib/deps.edn") `{:paths ["src"]}`) -(defn sh-out [args &opt cwd] - (def p (os/spawn args :px {:out :pipe :err :pipe :cd (or cwd ".")})) - (def out (ev/read (p :out) :all)) - (os/proc-wait p) - (string/trim (string out))) -(def git-ok - (truthy? - (protect - (do (sh-out ["git" "-c" "init.defaultBranch=master" "init"] (string gbase "/lib")) - (sh-out ["git" "add" "-A"] (string gbase "/lib")) - (sh-out ["git" "-c" "user.email=t@t" "-c" "user.name=t" "commit" "-m" "init" "-q"] - (string gbase "/lib")))))) -(if (not git-ok) - (print " skip git-dep stdout test (git unavailable)") - (do - (def sha (sh-out ["git" "rev-parse" "HEAD"] (string gbase "/lib"))) - (spit (string gbase "/proj2/deps.edn") - (string `{:paths ["src"] :deps {my/glib {:git/url "file://` gbase `/lib" :git/sha "` sha `"}}}`)) - (os/setenv "JOLT_GITLIBS" (string gbase "/gitlibs")) - (def code - (string `(os/cd "` repo-root `") ` - `(import ./src/jolt/deps :as deps) ` - `(os/cd "` gbase "/proj2" `") ` - `(deps/resolve-deps "deps.edn" "` gbase "/proj2/jpm_tree" `") ` - `(eprint "done")`)) - (def p (os/spawn ["janet" "-e" code] :px {:out :pipe})) - (def out (ev/read (p :out) :all)) - (os/proc-wait p) - (os/setenv "JOLT_GITLIBS" nil) - (check "git-dep resolution keeps stdout clean" (string (or out "")) "")) - ) -(rmrf gbase) - -# --- :jpm/module deps: janet libraries installed through jpm ----------------- -# Verification only (jpm owns installation): an importable module passes and -# contributes no roots; a missing one errors with the install hint. jpm/pm is -# always importable wherever jpm itself runs (CI included). -(do - (def jbase (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-jpm-" (os/time))) - (mkdirs (string jbase "/src")) - (spit (string jbase "/deps.edn") - `{:paths ["src"] :deps {janet/jpm-pm {:jpm/module "jpm/pm"}}}`) - (def cwd (os/cwd)) - (os/cd jbase) - (def roots (deps/resolve-deps "deps.edn" (string jbase "/jpm_tree"))) - (os/cd cwd) - (check "jpm module dep resolves" true (not (nil? roots))) - (check "jpm module contributes no roots" 1 (length roots)) - - (spit (string jbase "/deps.edn") - `{:paths ["src"] :deps {janet/nope {:jpm/module "no/such-module-xyz"}}}`) - (os/cd jbase) - (def r (protect (deps/resolve-deps "deps.edn" (string jbase "/jpm_tree")))) - (os/cd cwd) - (check "missing jpm module errors" false (r 0)) - (check "error carries the install hint" true - (not (nil? (string/find "jpm install" (string (r 1)))))) - (rmrf jbase)) - -(if (> fails 0) - (error (string "deps-resolve-test: " fails " failing check(s)")) - (print "\nAll deps-resolve tests passed!")) diff --git a/test/integration/deps-tasks-test.janet b/test/integration/deps-tasks-test.janet deleted file mode 100644 index d45fc02..0000000 --- a/test/integration/deps-tasks-test.janet +++ /dev/null @@ -1,89 +0,0 @@ -# deps.edn :tasks (jolt-x4o) + the global gitlibs-style clone cache default -# (jolt-xkd). Tasks are the honest subset of babashka's: a STRING task is a -# shell command; a MAP task carries :main-opts (jolt args) and optional :doc. -# Local-only: no network, no jolt binary — the CLI wrappers stay thin. - -(import ../../src/jolt/deps :as deps) - -(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-deps-tasks-" (os/time))) -(defn rmrf [p] - (when (os/stat p) - (if (= :directory (os/stat p :mode)) - (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) - (os/rm p)))) -(rmrf base) -(defn mkdirs [p] - (def abs (string/has-prefix? "/" p)) - (var acc nil) - (each seg (filter |(not= "" $) (string/split "/" p)) - (set acc (cond (nil? acc) (if abs (string "/" seg) seg) (string acc "/" seg))) - (unless (os/stat acc) (os/mkdir acc)))) - -(each d ["proj/src" "config"] (mkdirs (string base "/" d))) -(spit (string base "/proj/deps.edn") - `{:paths ["src"] - :tasks {clean "rm -rf target" - test {:doc "run the suite" :main-opts ["-e" "(run-tests)"]} - fmt {:main-opts ["-e" "(fmt)"]}}}`) -# user-level task, and a project-shadowed name -(spit (string base "/config/deps.edn") - `{:tasks {lint "echo lint" clean "echo SHADOWED"}}`) - -(var fails 0) -(defn check [label got expected] - (if (= got expected) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got)))) - -(os/cd (string base "/proj")) -(os/setenv "JOLT_CONFIG" (string base "/config")) - -# --- task listing (merged user+project, sorted) --------------------------------- -(def listing (deps/tasks "deps.edn")) -(check "lists all task names" - (tuple ;(sort (map first listing))) ["clean" "fmt" "lint" "test"]) -(check "doc shows in listing" - (truthy? (some |(and (= (first $) "test") (= (get $ 1) "run the suite")) listing)) - true) - -# --- task lookup ------------------------------------------------------------------ -(check "string task is shell" - (deps/task-spec "deps.edn" "clean") {:type :shell :cmd "rm -rf target"}) -(check "project task shadows user task" - (get (deps/task-spec "deps.edn" "clean") :cmd) "rm -rf target") -(check "map task is jolt argv" - (deps/task-spec "deps.edn" "test") {:type :jolt :argv ["-e" "(run-tests)"]}) -(check "user-level task visible" - (deps/task-spec "deps.edn" "lint") {:type :shell :cmd "echo lint"}) -(check "unknown task is nil" - (deps/task-spec "deps.edn" "nope") nil) - -# --- tasks resolve with NO user config (regression: load-config skipped the -# name re-keying when only the project file existed) ----------------------------- -(os/setenv "JOLT_CONFIG" (string base "/no-such-dir")) -(check "task works without user config" - (deps/task-spec "deps.edn" "clean") {:type :shell :cmd "rm -rf target"}) -(check "listing works without user config" - (tuple ;(sort (map first (deps/tasks "deps.edn")))) ["clean" "fmt" "test"]) -(os/setenv "JOLT_CONFIG" (string base "/config")) - -# --- global clone-tree default (jolt-xkd) ---------------------------------------- -# resolution with :local deps never clones, but the default tree dir must come -# from $JOLT_GITLIBS (else (config-dir)/gitlibs), not ./jpm_tree -(os/setenv "JOLT_GITLIBS" (string base "/deep/nested/gitlibs")) -(deps/resolve-deps "deps.edn") -(check "JOLT_GITLIBS dir created (parents too)" - (truthy? (os/stat (string base "/deep/nested/gitlibs"))) true) -(check "no per-project jpm_tree" (os/stat (string base "/proj/jpm_tree")) nil) - -# roots cache is project-local .cpcache, not inside the clone tree -(deps/resolve-deps-cached "deps.edn") -(check "roots cache in ./.cpcache" - (truthy? (os/stat (string base "/proj/.cpcache/jolt-deps.jdn"))) true) - -(os/setenv "JOLT_GITLIBS" "") -(os/cd "/") -(rmrf base) - -(if (> fails 0) - (error (string "deps-tasks-test: " fails " failing check(s)")) - (print "\nAll deps-tasks tests passed!")) diff --git a/test/integration/devirt-test.janet b/test/integration/devirt-test.janet deleted file mode 100644 index 190a8e3..0000000 --- a/test/integration/devirt-test.janet +++ /dev/null @@ -1,43 +0,0 @@ -# Protocol-dispatch devirtualization (jolt-41m): when the inference proves a -# protocol call's receiver is a known record type, the call is compiled to a -# DIRECT method call, skipping the runtime dispatch registry. This must stay -# SOUND — same results as the dispatched path — including polymorphic dispatch -# (the right method per type), fallback when the receiver type is unknown, and -# heterogeneous collections. Runs a protocol+record program through the built -# binary (devirt needs infer-unit!, which runs on ns load, not eval-string) and -# checks the output. Skips cleanly if build/jolt is absent. -(def jolt "build/jolt") - -(defn- run [whole?] - (def dir (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-dv-test")) - (os/mkdir dir) - (spit (string dir "/dv.clj") - (string - "(ns dv)\n" - "(defprotocol Shape (area [s]) (kind [s]))\n" - "(defrecord Rect [w h] Shape (area [r] (* (:w r) (:h r))) (kind [_] :rect))\n" - "(defrecord Circ [r] Shape (area [c] (* 3 (:r c) (:r c))) (kind [_] :circ))\n" - "(defn poly [s] (area s))\n" # receiver unknown -> must fall back - "(defn -main []\n" - " (println (area (->Rect 3 4)) (area (->Circ 5))\n" # devirt: 12 75 - " (kind (->Rect 1 1)) (kind (->Circ 1))\n" # devirt: :rect :circ - " (poly (->Rect 3 4)) (poly (->Circ 5))\n" # fallback: 12 75 - " (mapv area [(->Rect 2 3) (->Circ 2)])))\n")) # heterogeneous: [6 12] - (def out (string dir "/out.txt")) - (def jbin (string (os/cwd) "/" jolt)) - # -m auto-enables whole-program under direct-linking now, so the per-ns case - # (whole? false) must explicitly opt out to test the dispatched/per-ns path. - (def cmd (string (if whole? "JOLT_WHOLE_PROGRAM=1 " "JOLT_NO_WHOLE_PROGRAM=1 ") - "JOLT_DIRECT_LINK=1 JOLT_PATH=" dir " " jbin " -m dv > " out " 2>&1")) - (os/execute ["sh" "-c" cmd] :p) - (string/trimr (slurp out))) - -(def expected "12 75 :rect :circ 12 75 [6 12]") -(if (not (os/stat jolt)) - (print "devirt: SKIP (no build/jolt — run from source)") - (let [per-ns (run false) whole (run true)] - (printf " per-ns: %s" per-ns) - (printf " whole-program: %s" whole) - (if (and (= per-ns expected) (= whole expected)) - (print "devirt: correct (dispatched == devirtualized)") - (do (printf "devirt: WRONG — expected %q" expected) (os/exit 1))))) diff --git a/test/integration/direct-linking-test.janet b/test/integration/direct-linking-test.janet deleted file mode 100644 index ba0e101..0000000 --- a/test/integration/direct-linking-test.janet +++ /dev/null @@ -1,76 +0,0 @@ -# Direct-linking / redefinition matrix (jolt-d9j, jolt-g86). -# -# Direct-linking is a per-compilation-UNIT property (Clojure model). A call -# compiles direct iff the unit has direct-linking on AND the target is not -# ^:redef/^:dynamic AND the target is an already-defined fn. Otherwise indirect -# (live var deref → redefinable). This pins the user-visible semantics: -# - default user/REPL unit (direct-linking off): redefine anything, callers see it -# - direct-linked unit: callers don't see a later redef (unless target ^:redef) -# - :aot-core? gates whether the core tiers compile direct-linked - -(use ../../src/jolt/api) - -(var failures 0) -(defn- check [label got want] - (unless (= got want) - (++ failures) - (printf "FAIL [%s] got %q want %q" label got want))) - -# 1. Default unit (direct-linking OFF): redefinition reaches compiled callers. -(let [ctx (init {:compile? true})] - (eval-string ctx "(defn add [a b] (+ a b))") - (eval-string ctx "(defn caller [] (add 1 2))") - (check "default before redef" (eval-string ctx "(caller)") 3) - (eval-string ctx "(defn add [a b] (* a b))") - (check "default sees redef (indirect)" (eval-string ctx "(caller)") 2)) - -# 2. Direct-linked unit: compiled caller keeps the original target after a redef. -(let [ctx (init {:compile? true :direct-linking? true})] - (eval-string ctx "(defn add [a b] (+ a b))") - (eval-string ctx "(defn caller [] (add 1 2))") - (check "direct before redef" (eval-string ctx "(caller)") 3) - (eval-string ctx "(defn add [a b] (* a b))") - (check "direct ignores redef (sealed)" (eval-string ctx "(caller)") 3) - # the var itself is still redefined; only the direct-linked call is frozen - (check "direct var still updated" (eval-string ctx "(add 3 4)") 12)) - -# 3. ^:redef opts a var OUT of direct-linking even in a direct-linked unit. -(let [ctx (init {:compile? true :direct-linking? true})] - (eval-string ctx "(defn ^:redef add [a b] (+ a b))") - (eval-string ctx "(defn caller [] (add 1 2))") - (check "redef-tagged before" (eval-string ctx "(caller)") 3) - (eval-string ctx "(defn ^:redef add [a b] (* a b))") - (check "redef-tagged sees redef" (eval-string ctx "(caller)") 2)) - -# 4. :aot-core? true (default): redefining a core fn (in clojure.core) is still -# seen by USER code, because user calls are indirect regardless of core being -# direct-linked internally. -(let [ctx (init {:compile? true})] - (eval-string ctx "(defn uses-last [] (last [1 2 3]))") - (check "core call before" (eval-string ctx "(uses-last)") 3) - (eval-string ctx "(in-ns (quote clojure.core))") - (eval-string ctx "(def last (fn [coll] :patched))") - (eval-string ctx "(in-ns (quote user))") - (check "user sees core redef (indirect)" (eval-string ctx "(uses-last)") :patched)) - -# 5. :aot-core? false: core compiles indirect too, so even core-internal callers -# see a redef — the whole language is redefinable. -(let [ctx (init {:compile? true :aot-core? false})] - (check "aot-core off still correct" (eval-string ctx "(last [1 2 3])") 3)) - -# 6. Redefining a record with REORDERED fields must rebind the ctor (jolt-wf4). -# deftype expands to (do (def R (make-deftype-ctor ...)) (def ->R R) ...): the -# `->R` alias references R in the SAME compiled unit. Direct-link embeds a var's -# root as a compile-time constant, but R's redefined root hasn't RUN yet when -# that unit compiles — so ->R must NOT seal to R's stale (pre-redef) ctor. -(let [ctx (init {:compile? true :direct-linking? true})] - (eval-string ctx "(defrecord R [x a])") - (eval-string ctx "(defrecord R [a x])") - (check "record field-reorder redefine: :a reads the new layout" - (eval-string ctx "(:a (->R 10 20))") 10) - (check "record field-reorder redefine: :x reads the new layout" - (eval-string ctx "(:x (->R 10 20))") 20)) - -(if (pos? failures) - (do (printf "direct-linking: %d failure(s)" failures) (os/exit 1)) - (print "direct-linking: all matrix cases passed")) diff --git a/test/integration/dispatch-cache-test.janet b/test/integration/dispatch-cache-test.janet deleted file mode 100644 index 334bd3a..0000000 --- a/test/integration/dispatch-cache-test.janet +++ /dev/null @@ -1,51 +0,0 @@ -# Protocol host-value dispatch cache (jolt-4ay). -# -# Host-value protocol dispatch used to recompute the candidate type-tag list and -# walk the registry on every call. It's now a generation-guarded cache keyed by -# (most-specific-host-tag, protocol, method); registering a protocol impl bumps -# the registry generation and invalidates it. This pins correctness: the cache -# must never hide a re-extension. - -(use ../../src/jolt/api) - -(var failures 0) -(defn- check [label got want] - (unless (= got want) - (++ failures) - (printf "FAIL [%s] got %q want %q" label got want))) - -(each mode [{:compile? true} {} {:aot-core? false}] - (def ctx (init-cached mode)) - (eval-string ctx "(defprotocol P (m [x]))") - (eval-string ctx "(extend-protocol P Number (m [x] (* x 2)))") - (check (string mode " host dispatch") (eval-string ctx "(m 5)") 10) - (check (string mode " cache hit (same class)") (eval-string ctx "(m 7)") 14) - # Re-extend: registry generation bumps, cache must invalidate. - (eval-string ctx "(extend-protocol P Number (m [x] (+ x 100)))") - (check (string mode " sees re-extension") (eval-string ctx "(m 5)") 105) - # Extending a different host class bumps gen too; number impl re-resolves. - (eval-string ctx "(extend-protocol P String (m [x] (str \"s:\" x)))") - (check (string mode " other class") (eval-string ctx "(m \"hi\")") "s:hi") - (check (string mode " number after other-class extend") (eval-string ctx "(m 3)") 103)) - -# Multimethod hierarchy-fallback cache (jolt-g8w): the isa? walk result for a -# dispatch value is cached; defmethod/remove-method must invalidate it. -(each mode [{:compile? true} {} {:aot-core? false}] - (def ctx (init-cached mode)) - (eval-string ctx "(derive ::circle ::shape)") - (eval-string ctx "(derive ::square ::shape)") - (eval-string ctx "(defmulti area identity)") - (eval-string ctx "(defmethod area ::shape [_] :generic)") - (check (string mode " mm hierarchy") (eval-string ctx "(area ::circle)") :generic) - (check (string mode " mm cache hit") (eval-string ctx "(area ::circle)") :generic) - # adding a more specific method must invalidate the cached hierarchy result - (eval-string ctx "(defmethod area ::circle [_] :specific)") - (check (string mode " mm sees new method") (eval-string ctx "(area ::circle)") :specific) - (check (string mode " mm other still hierarchy") (eval-string ctx "(area ::square)") :generic) - # removing it must re-expose the hierarchy fallback - (eval-string ctx "(remove-method area ::circle)") - (check (string mode " mm sees removal") (eval-string ctx "(area ::circle)") :generic)) - -(if (pos? failures) - (do (printf "dispatch-cache: %d failure(s)" failures) (os/exit 1)) - (print "dispatch-cache: all cases passed (compile, interpret, aot-core off)")) diff --git a/test/integration/embedded-stdlib-test.janet b/test/integration/embedded-stdlib-test.janet deleted file mode 100644 index 20ce338..0000000 --- a/test/integration/embedded-stdlib-test.janet +++ /dev/null @@ -1,33 +0,0 @@ -# The .clj stdlib (clojure.string, clojure.set, jolt.interop, …) is baked into the -# image at build time, so it loads even when the files aren't on disk. We simulate -# the shipped-binary-elsewhere case by clearing the filesystem source roots, so a -# require can only be satisfied by the embedded copy. - -(use ../../src/jolt/api) -(use ../../src/jolt/types) - -(def ctx (init-cached)) -(ctx-set-current-ns ctx "user") -(put (ctx :env) :source-paths @[]) # no FS roots — embedded fallback only - -(var fails 0) -(defn check [label expr expected] - (let [r (protect (eval-string ctx expr)) - got (if (r 0) (normalize-pvecs (r 1)) (string "ERR " (r 1)))] - (if (= got expected) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got))))) - -(assert (> (length (get (ctx :env) :embedded-sources)) 0) "embedded-sources should be populated") - -(check "clojure.string from embedded" - "(do (require (quote [clojure.string :as s])) (s/upper-case \"hi\"))" "HI") -(check "clojure.set from embedded" - "(do (require (quote [clojure.set :as set])) (vec (set/union #{1} #{2})))" [2 1]) -(check "clojure.walk from embedded" - "(do (require (quote [clojure.walk :as w])) (w/keywordize-keys {\"a\" 1}))" {:a 1}) -(check "jolt.interop from embedded" - "(do (require (quote [jolt.interop :as j])) (j/janet-type 1))" :number) - -(if (> fails 0) - (error (string "embedded-stdlib-test: " fails " failing check(s)")) - (print "\nAll embedded-stdlib tests passed!")) diff --git a/test/integration/fallback-zero-test.janet b/test/integration/fallback-zero-test.janet deleted file mode 100644 index 862833f..0000000 --- a/test/integration/fallback-zero-test.janet +++ /dev/null @@ -1,117 +0,0 @@ -# Fallback-zero verification (Stage 1 Task 3). -# -# self-host-test.janet checks observable RESULTS but not WHICH path ran — a form -# that silently fell back to the interpreter still "passes" there. This harness -# checks the path: it runs the portable analyzer (jolt.analyzer/analyze, via -# backend/analyze-form) on a corpus of NON-STATEFUL forms and asserts NONE raise -# :jolt/uncompilable — i.e. the self-hosted analyzer actually COMPILED them. -# -# As analyzer↔compiler.janet parity grows (Stage 1), move forms from the -# "intentional fallback" sanity list into the must-compile corpus. The day the -# fallback set equals the frozen intentional stateful set, the Janet bootstrap -# compiler is retireable. -# -# Mechanism: backend/analyze-form throws (a "jolt/uncompilable: …" string) for a -# punted form; (protect …) turns that into [false msg]. [true ir] == compiled. - -(import ../../src/jolt/backend :as backend) -(use ../../src/jolt/api) -(use ../../src/jolt/reader) - -(def ctx (init-cached)) - -(defn- analyzes? [s] - # true if the analyzer produced IR (compiled), false if it punted/uncompilable. - (def r (protect (backend/analyze-form ctx (parse-string s)))) - (and (r 0) true)) - -# --- Must compile: pure, non-stateful value production. NONE may punt. --- -(def must-compile - [# set literals (Task 1) - "#{1 2 3}" "#{}" "#{:a :b :c}" "#{(inc 0) 2}" "(conj #{1 2} 3)" - "[#{1 2} {:s #{3}}]" "(let [x 5] #{x (inc x)})" - # other literals - "[1 2 3]" "{:a 1 :b 2}" "{:k (inc 0)}" "[[1] [2 3]]" "42" ":kw" "\"str\"" - # control flow + binding - "(+ 1 2)" "(if true 1 2)" "(do 1 2 3)" "(let [a 1 b 2] (+ a b))" - "(fn [x] (* x x))" "(fn ([a] a) ([a b] (+ a b)))" - "(loop [i 0] (if (< i 3) (recur (inc i)) i))" - "(quote (a b c))" "(throw (ex-info \"x\" {}))" - "(try (inc 1) (catch :default e e))" - # def + calls into core - "(def answer 42)" "(map inc [1 2 3])" "(reduce + 0 [1 2 3])" - "(get {:a 1} :a)" "(vec (range 5))" - # set?/disj are plain fns now, not special forms (jolt-g3h) - "(set? #{1 2})" "(disj #{1 2 3} 2)" - # Stage 2 (jolt-eaa): stateful forms moved onto the compile path. (binding only - # compiles over an INTERNED var; the built-in dynamic vars aren't interned yet, - # so it's exercised end-to-end in the state spec instead.) - "(require (quote [clojure.string :as s]))" "(in-ns (quote foo.bar))" - "(ns foo.bar (:require [clojure.string :as s]))" - "(defprotocol P (m [x]))" "(extend-type Long P (m [x] x))" - "(reify P (m [this] 1))" "(var map)" - # Stage 2 tier 5: type/dispatch definitional forms compile too - "(deftype Pt [x y])" "(deftype Sq [s] P (m [this] s))" - "(defrecord Rec [a b])" "(defmulti mf :k)" "(defmethod mf :a [x] x)" - # Stage 2 tier 6: var fns are ordinary invokes now - "(var-get (var map))" "(var? (var map))" "(var-set (var map) map)" - "(alter-var-root (var map) identity)" "(find-var (quote clojure.core/map))" - "(intern (quote user) (quote tier6-sym) 42)" - "(alter-meta! (var map) assoc :k 1)" "(reset-meta! (var map) {})" - # Stage 2 tier 6b: ns-introspection fns are ordinary invokes now - "(find-ns (quote clojure.core))" "(create-ns (quote t6.created))" - "(remove-ns (quote t6.created))" "(count (all-ns))" - "(the-ns (quote clojure.core))" "(ns-interns (quote clojure.core))" - "(ns-aliases (quote user))" "(ns-imports (quote user))" - "(ns-resolve (quote clojure.core) (quote map))" "(resolve (quote map))" - "(refer (quote clojure.string))" - # Stage 2 tier 6c: dispatch-table ops + misc compile as macros/plain invokes - "(prefer-method mf :a :b)" "(remove-method mf :a)" "(remove-all-methods mf)" - # get-method/methods take the multimethod VALUE (Clojure semantics), so the - # arg must resolve — use a real multifn (print-method) rather than the - # never-defined mf the isolated analyzer can't resolve. - "(get-method print-method :default)" "(methods print-method)" - "(satisfies? P 5)" "(instance? String \"x\")" "(locking :x 1)" - "(defonce fz-once 1)" "(read-string \"[1 2]\")" - "(macroexpand-1 (quote (when true 1)))"]) - -# --- THE FROZEN PUNT SET (Stage 2 complete) --------------------------------- -# These are the ONLY heads that may reach the interpreter, exhaustively: -# defmacro — definitional host seam (the EXPANDERS are compiled; -# see backend/recompile-macros!) -# set! — host var-cell mutation special -# letfn — needs letrec IR (sequential let* can't express mutual -# recursion); permanent-interpret unless the IR gains it -# eval — compile-and-run entry (also loader stateful-head?) -# . / new / Foo. / — thin host-interop heads the back end doesn't model -# .method -# gen-class, monitor-enter, monitor-exit — JVM-compat stubs -# Growing this list is a REGRESSION: a new punt means the compiler lost -# coverage. Shrinking it (e.g. letfn via letrec IR) is progress — move the -# form to must-compile. -(def must-punt - ["(defmacro m [x] x)" - "(set! *warn-on-reflection* true)" - "(letfn [(f [n] (g n)) (g [n] (f n))] (f 1))" - "(eval (quote (+ 1 2)))" - "(.method obj)" - "(.-field obj)" - "(new Foo 1)" - "(Foo. 1)" - "(gen-class :name X)" - "(monitor-enter x)" - "(monitor-exit x)"]) - -(var fails @[]) -(each s must-compile - (unless (analyzes? s) (array/push fails (string "FALLBACK (should compile): " s)))) -(each s must-punt - (when (analyzes? s) (array/push fails (string "COMPILED (should punt): " s)))) - -(printf "fallback-zero: %d must-compile + %d must-punt — %d failures" - (length must-compile) (length must-punt) (length fails)) -(when (> (length fails) 0) - (print "\nFailures:") - (each f fails (printf " %s" f)) - (os/exit 1)) -(print "fallback-zero: OK (analyzer compiled the full non-stateful corpus)") diff --git a/test/integration/features-test.janet b/test/integration/features-test.janet deleted file mode 100644 index 318009d..0000000 --- a/test/integration/features-test.janet +++ /dev/null @@ -1,147 +0,0 @@ -# Feature regression tests: a broad sweep of Clojure features (destructuring, -# multimethods, protocols, laziness, …). Each case asserts (= expected actual) -# evaluated inside Jolt (so comparisons use Jolt's own Clojure-semantics =). -# Run via `jpm test`. -(use ../../src/jolt/api) - -(var pass 0) -(def fails @[]) - -(defn check [label expected actual] - # evaluate (= expected actual) in a fresh ctx; expects boolean true - (def ctx (init-cached)) - (def res (protect (eval-string ctx (string "(= " expected " " actual ")")))) - (cond - (not= (res 0) true) - (array/push fails [label "ERROR" (string (res 1))]) - (= (res 1) true) - (++ pass) - (let [got (protect (eval-string (init-cached) actual))] - (array/push fails [label "NEQ" - (string "want=" expected " got=" - (if (= (got 0) true) (string/format "%q" (got 1)) (string "ERR:" (got 1))))])))) - -(def cases - [ - ### 1. Destructuring - ["destr seq" "[10 20 30]" "(let [[a b c] [10 20 30]] [a b c])"] - ["destr map :or" "[\"Alice\" 30 \"Unknown\"]" - "(let [{:keys [name age city] :or {city \"Unknown\"}} {:name \"Alice\" :age 30}] [name age city])"] - ["destr nested map" "[1.0 2.5]" "(let [{[x y] :coords} {:coords [1.0 2.5]}] [x y])"] - ["destr :as" "[1 [1 2 3]]" "(let [[a :as all] [1 2 3]] [a all])"] - ["destr & rest" "[1 (quote (2 3))]" "(let [[a & r] [1 2 3]] [a r])"] - ["destr :strs" "[1 2]" "(let [{:strs [a b]} {\"a\" 1 \"b\" 2}] [a b])"] - ["destr fn-param" "7" "((fn [{:keys [a b]}] (+ a b)) {:a 3 :b 4})"] - - ### 2. Atoms - ["atom swap! inc" "1" "(do (def a (atom 0)) (swap! a inc) @a)"] - ["atom reset!" "100" "(do (def a (atom 0)) (reset! a 100) @a)"] - ["atom CAS ok" "true" "(do (def a (atom 5)) (compare-and-set! a 5 10))"] - ["atom CAS no" "false" "(do (def a (atom 5)) (compare-and-set! a 9 10))"] - ["atom thread-first swap!" "213" "(do (def a (atom 100)) (swap! a #(-> % (* 2) (+ 3))) (swap! a #(-> % (* 1) (+ 10))) @a)"] - ["atom swap! args" "10" "(do (def a (atom 1)) (swap! a + 2 3 4) @a)"] - ["atom swap-vals!" "[1 2]" "(do (def a (atom 1)) (swap-vals! a inc))"] - ["atom watch" "[1 2]" "(do (def lg (atom nil)) (def a (atom 1)) (add-watch a :k (fn [k r o n] (reset! lg [o n]))) (swap! a inc) @lg)"] - ["atom validator" "5" "(do (def a (atom 1 :validator pos?)) (reset! a 5) @a)"] - - ### 3. Lazy sequences - ["lazy filter inf" "(quote (0 2 4 6 8 10 12 14 16 18))" "(take 10 (filter even? (iterate inc 0)))"] - ["lazy take-while sq" "(quote (0 1 4 9 16 25 36 49))" "(take-while #(< % 50) (map #(* % %) (range)))"] - ["lazy cycle" "(quote (:a :b :c :a :b :c :a :b :c :a))" "(take 10 (cycle [:a :b :c]))"] - ["lazy-seq cons self" "(quote (1 2 4 8 16 32 64 128))" - "(do (defn my-it [f x] (lazy-seq (cons x (my-it f (f x))))) (take 8 (my-it #(* 2 %) 1)))"] - ["lazy self-ref fib" "(quote (0 1 1 2 3 5 8 13 21 34))" - "(do (def fib (lazy-cat [0 1] (map + (rest fib) fib))) (take 10 fib))"] - ["repeatedly" "(quote (1 1 1))" "(repeatedly 3 (fn [] 1))"] - ["range step" "(quote (0 2 4 6 8))" "(range 0 10 2)"] - - ### 4. Transducers - ["xf comp into" "[1 3 5 7 9]" "(into [] (comp (map inc) (filter odd?)) (range 10))"] - ["xf sequence" "(quote (1 3 5 7 9))" "(sequence (comp (map inc) (filter odd?)) (range 10))"] - ["xf transduce" "25" "(transduce (comp (map inc) (filter odd?)) + 0 (range 10))"] - ["xf take" "[0 1 2]" "(into [] (take 3) (range 100))"] - ["xf remove" "[1 3 5]" "(into [] (remove even?) [1 2 3 4 5])"] - - ### 5. Protocols & Records - ["record area circle" "78" "(do (defprotocol Sh (ar [t])) (defrecord Ci [r] Sh (ar [_] (int (* 3.14159 r r)))) (int (ar (->Ci 5))))"] - ["record field" "5" "(do (defrecord Ci [r]) (:r (->Ci 5)))"] - ["record map->" "3" "(do (defrecord P [x y]) (:x (map->P {:x 3 :y 4})))"] - ["protocol 2 methods" "[16 \"sq\"]" "(do (defprotocol Sh (ar [t]) (nm [t])) (defrecord Sq [s] Sh (ar [_] (* s s)) (nm [_] \"sq\")) (let [x (->Sq 4)] [(ar x) (nm x)]))"] - ["extend-protocol" "6" "(do (defprotocol G (g [x])) (extend-protocol G java.lang.Long (g [x] (inc x))) (g 5))"] - ["reify" "42" "(do (defprotocol P (m [_])) (m (reify P (m [_] 42))))"] - ["record equality" "true" "(do (defrecord R [a]) (= (->R 1) (->R 1)))"] - - ### 6. Multimethods - ["mm dispatch circle" "\"round\"" "(do (defmulti st :kind) (defmethod st :circle [_] \"round\") (defmethod st :default [_] \"unknown\") (st {:kind :circle}))"] - ["mm default" "\"unknown\"" "(do (defmulti st :kind) (defmethod st :circle [_] \"round\") (defmethod st :default [_] \"unknown\") (st {:kind :triangle}))"] - ["mm multi-arity" "[1 3]" "(do (defmulti f (fn [& a] (first a))) (defmethod f :x ([_ y] y) ([_ y z] (+ y z))) [(f :x 1) (f :x 1 2)])"] - - ### 7. Macros - ["macro log-call" "6" "(do (defmacro lc [e] `(let [r# ~e] r#)) (lc (* 2 3)))"] - ["macro quote arg" "(quote (* 2 3))" "(do (defmacro qa [e] `(quote ~e)) (qa (* 2 3)))"] - ["macroexpand-1" "true" "(do (defmacro mm [x] (list 'inc x)) (= '(inc 5) (macroexpand-1 '(mm 5))))"] - ["gensym distinct" "false" "(= (gensym) (gensym))"] - ["syntax-quote splice" "[1 2 3]" "(let [xs [1 2 3]] `[~@xs])"] - # syntax-quote fully-qualifies resolved core symbols to clojure.core/ (jolt-265). - ["syntax-quote unquote" "(quote (clojure.core/+ 1 5))" "(let [x 5] `(+ 1 ~x))"] - - ### 8. Recursion - ["recursion fact" "120" "(do (defn fact [n] (if (<= n 1) 1 (* n (fact (dec n))))) (fact 5))"] - ["recursion loop" "120" "(loop [i 5 acc 1] (if (zero? i) acc (recur (dec i) (* acc i))))"] - ["mutual recursion" "true" "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 6))"] - ["trampoline" ":done" "(do (defn a [n] (if (zero? n) :done (fn [] (a (dec n))))) (trampoline a 8))"] - - ### 9. Higher-order functions - ["partial" "15" "((partial + 5) 10)"] - ["comp" "8" "((comp #(* 2 %) inc) 3)"] - ["juxt" "[5 6 4]" "((juxt identity inc dec) 5)"] - ["every-pred" "true" "((every-pred pos? even?) 2 4 6)"] - ["some-fn" "true" "((some-fn even? neg?) 3 4)"] - ["fnil" "1" "((fnil inc 0) nil)"] - ["complement" "true" "((complement nil?) 1)"] - - ### 10. Threading macros - ["->> pipeline" "75" "(->> (range 20) (filter odd?) (map #(* % 3)) (take 5) (reduce +))"] - ["-> sqrt long" "15" "(-> 25 Math/sqrt long (+ 10))"] - ["some->" "2" "(some-> {:a {:b 1}} :a :b inc)"] - ["some-> nil" "nil" "(some-> {:a nil} :a :b)"] - ["cond->" "4" "(cond-> 1 true inc false (* 100) true (* 2))"] - ["as->" "20" "(as-> 1 x (inc x) (* x 10))"] - - ### 11. Exception handling - ["ex catch" "\"caught\"" "(try (throw (ex-info \"x\" {})) (catch :default e \"caught\"))"] - ["ex-message" "\"broke\"" "(try (throw (ex-info \"broke\" {:code 42})) (catch :default e (ex-message e)))"] - ["ex-data" "{:code 42}" "(try (throw (ex-info \"broke\" {:code 42})) (catch :default e (ex-data e)))"] - ["try finally" "[:body :fin]" "(do (def lg (atom [])) (try (swap! lg conj :body) (finally (swap! lg conj :fin))) @lg)"] - - ### 12. For comprehension - ["for nested :when" "(quote ([0 1] [0 2] [1 0] [1 2] [2 0] [2 1]))" - "(for [x (range 3) y (range 3) :when (not= x y)] [x y])"] - ["for :let" "(quote (1 4 9))" "(for [x [1 2 3] :let [sq (* x x)]] sq)"] - ["for :while" "(quote (0 1 2))" "(for [x (range 10) :while (< x 3)] x)"] - - ### 13b. Persistent lists — O(1) conj-prepend, immutable, value semantics - ["list conj prepends" "(quote (0 1 2 3))" "(conj (list 1 2 3) 0)"] - ["list conj multi" "(quote (:c :b :a))" "(conj (quote ()) :a :b :c)"] - ["list immutable" "true" "(let [l (list 1 2 3) l2 (conj l 9)] (and (= l (quote (1 2 3))) (= l2 (quote (9 1 2 3)))))"] - ["list? after conj" "true" "(list? (conj (list 1 2) 0))"] - ["list = vector elts" "true" "(= (quote (1 2 3)) [1 2 3])"] - ["reduce conj list" "(quote (2 1 0))" "(reduce conj (list) (range 3))"] - ["cons onto list" "(quote (0 1 2 3))" "(cons 0 (list 1 2 3))"] - - ### 14. Janet interop - ["interop method" "\"v=41\"" "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)"] - ["interop field" "41" "(.-value {:value 41})"] - # vectors are persistent vectors (Janet tables); lists are Janet arrays - ["interop janet-type" ":array" "(do (require '[jolt.interop :as j]) (j/janet-type (list 1 2 3)))"] - ]) - -(each [label expected actual] cases (check label expected actual)) - -(printf "\n=== features-test: %d/%d passed ===" pass (length cases)) -(unless (empty? fails) - (print "--- Failures ---") - (each [label kind detail] fails (printf "[%s] %s: %s" kind label detail))) -(when (pos? (length fails)) - (error (string (length fails) " feature regression(s)"))) -(print "All feature tests passed!") diff --git a/test/integration/inline-sra-test.janet b/test/integration/inline-sra-test.janet deleted file mode 100644 index b713dcd..0000000 --- a/test/integration/inline-sra-test.janet +++ /dev/null @@ -1,64 +0,0 @@ -# Inline + scalar-replacement passes (jolt-87f, Route 1 AOT escape analysis). -# When a unit opts into direct-linking (:inline?, JOLT_DIRECT_LINK=1), the IR -# pipeline inlines small direct-linked fns and then scalar-replaces the now- -# exposed non-escaping map allocations: (:r {:r a ..}) -> a. This pins the -# transform (allocations actually vanish) AND that it stays semantics-preserving. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/reader :as reader) - -(print "Inline + scalar replacement (jolt-87f)...") - -# A ctx with inlining ON (independent of the build-time JOLT_DIRECT_LINK). -(def ctx (api/init-cached {:compile? true})) -(put (ctx :env) :direct-linking? true) -(put (ctx :env) :inline? true) -(api/eval-string ctx "(ns rt)") -(each s ["(defn v3 [r g b] {:r r :g g :b b})" - "(defn scale [l n] {:r (* (:r l) n) :g (* (:g l) n) :b (* (:b l) n)})" - "(defn add [l r] {:r (+ (:r l) (:r r)) :g (+ (:g l) (:g r)) :b (+ (:b l) (:b r))})" - "(defn dot [l r] (+ (+ (* (:r l) (:r r)) (* (:g l) (:g r))) (* (:b l) (:b r))))" - "(defn sub [l r] {:r (- (:r l) (:r r)) :g (- (:g l) (:g r)) :b (- (:b l) (:b r))})" - "(defn reflect [v n] (sub v (scale n (* 2.0 (dot v n)))))" - # self-recursive: must NOT be inlined into callers (its body has a free - # local — the fn-name self-reference — that would dangle when spliced). - "(defn countdown [n] (if (< n 1) :done (countdown (- n 1))))"] - (api/eval-string ctx s)) - -(defn alloc-count [src] - # struct / build-map literal occurrences in the emitted Janet = surviving map - # allocations (jolt builds a struct, falling back to build-map-literal). - (def code (string/format "%p" (backend/emit-ir ctx (backend/analyze-form ctx (reader/parse-string src))))) - [(length (string/find-all "struct " code)) - (length (string/find-all "build-map" code))]) - -# A vec3 chain whose intermediates never escape collapses to ONE result map. -(let [[s b] (alloc-count "(fn [v n] (reflect v n))")] - (assert (= 1 s) (string "reflect keeps exactly one alloc, got " s " struct")) - (assert (= 1 b) (string "reflect keeps exactly one build-map fallback, got " b))) - -# A fully consumed chain (result not returned as a map) allocates NOTHING. -(let [[s b] (alloc-count "(fn [v n] (dot (reflect v n) (reflect v n)))")] - (assert (= 0 s) (string "fully-consumed chain allocates no struct, got " s)) - (assert (= 0 b) (string "fully-consumed chain has no build-map fallback, got " b))) - -# Loop bodies optimize too (recur is not a blanket escape). -(let [[s _] (alloc-count "(fn [k] (loop [i 0 acc 0.0] (if (< i k) (recur (inc i) (+ acc (dot (v3 1.0 2.0 3.0) (v3 0.1 0.2 0.3)))) acc)))")] - (assert (= 0 s) (string "loop body allocates no struct, got " s))) - -# Correctness: inlined results match the obvious computation. -(assert (= 32.0 (api/eval-string ctx "(dot (v3 1.0 2.0 3.0) (v3 4.0 5.0 6.0))")) "dot value") -(assert (= 9.0 (api/eval-string ctx "(:r (add (v3 1.0 0.0 0.0) (scale (v3 4.0 0.0 0.0) 2.0)))")) "add+scale value") -# the self-recursive fn still runs (the closed-body guard kept it un-inlined) -(assert (= :done (api/eval-string ctx "(countdown 5)")) "recursive fn still works") - -# A redefinable (^:redef) callee must NOT be inlined — it stays a live var call. -(api/eval-string ctx "(defn ^:redef wobble [x] {:v x})") -(let [[s _] (alloc-count "(fn [] (:v (wobble 1)))")] - # wobble is not inlined, so its map isn't visible to scalar replacement: the - # lookup stays a call, and the (:v ...) result is whatever wobble returns. - (assert (= 7 (do (api/eval-string ctx "(defn ^:redef wobble [x] {:v (+ x 6)})") - (api/eval-string ctx "(:v (wobble 1))"))) - "redef callee stays live (redefinition is visible)")) - -(print "Inline + scalar replacement passed!") diff --git a/test/integration/ir-passes-test.janet b/test/integration/ir-passes-test.janet deleted file mode 100644 index 11b0286..0000000 --- a/test/integration/ir-passes-test.janet +++ /dev/null @@ -1,51 +0,0 @@ -# IR pass pipeline (jolt-2om, nanopass-lite): jolt.passes/run-passes applies -# pure IR->IR rewrites between the analyzer and the back end. The first pass -# is constant folding — it computes with the ACTUAL jolt fns, so folded -# results match runtime semantics by construction. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/reader :as reader) - -(print "IR passes (constant folding)...") -(def ctx (api/init-cached {:compile? true})) -(defn ir [src] (backend/analyze-form ctx (reader/parse-string src))) - -(defn check-const [src want] - (def n (ir src)) - (assert (= :const (n :op)) (string src " folds to a constant")) - (assert (= want (n :val)) (string src " folds to " (string/format "%q" want)))) - -(check-const "(+ 1 2 3)" 6) -(check-const "(* 2 (+ 3 4))" 14) -(check-const "(quot 7 2)" 3) -(check-const "(mod -7 3)" 2) -(check-const "(if (< 1 2) :yes :no)" :yes) -# dead-branch elimination: the untaken branch never evaluates (it must still -# RESOLVE — unresolved symbols are analysis errors as in Clojure, jolt-2o7.3) -(check-const "(if false (throw (ex-info \"boom\" {})) 2)" 2) -# an unresolvable symbol errors even in a dead branch (analysis precedes folding) -(assert (not ((protect (ir "(if false (this-would-not-resolve) 2)")) 0)) - "unresolved symbol errors even in a dead branch") - -# non-constants stay calls; folding must be conservative. `xq` is a real var -# (defined here) so it resolves, but its VALUE must not be folded in. -(api/eval-string ctx "(def xq 1)") -(assert (= :invoke ((ir "(+ xq 2)") :op)) "var ref stays a call") -(assert (= :invoke ((ir "(mod xq 0)") :op)) "non-const args stay calls") -# a fold that would THROW is left for runtime -(assert (= :invoke ((ir "(mod 5 0)") :op)) "throwing fold left to runtime") - -# and the folded code evaluates identically (3-mode conformance covers the -# broader matrix; this pins a couple end-to-end) -(assert (= 6 (api/eval-string ctx "(+ 1 2 3)")) "folded eval") -(assert (= :yes (api/eval-string ctx "(if (< 1 2) :yes :no)")) "folded if eval") - -# Folding reaches into every op's children via map-ir-children (phase 3a) — it is -# now total, so a constant nested in a fn arity / loop / try body folds too -# (const-fold previously passed :try through unfolded). Sound: folding preserves -# runtime results regardless of position, so these eval end-to-end (3-mode -# conformance covers the broader matrix). -(assert (= 3 ((api/eval-string ctx "(fn [x] (+ 1 2))") 0)) "folded fn arity body eval") -(assert (= 10 (api/eval-string ctx "(loop [i 0] (if (< i (* 2 5)) (recur (inc i)) i))")) "folded loop eval") -(assert (= 5 (api/eval-string ctx "(try (+ 2 3) (catch Throwable e 0))")) "folded try eval") -(print "IR passes passed!") diff --git a/test/integration/ir-try-shape-test.janet b/test/integration/ir-try-shape-test.janet deleted file mode 100644 index 54c3c50..0000000 --- a/test/integration/ir-try-shape-test.janet +++ /dev/null @@ -1,43 +0,0 @@ -# IR shape hygiene for :try nodes (phase 3b, jolt-26dm). analyze-try used to -# assoc :catch-sym/:catch-body/:finally nil-when-absent, which made the node a -# phm (jolt's nil-valued-key map representation) and forced backend densification -# before every :op read. It now adds those keys only when the clause is present -# — same discipline as the arity :rest key — so a try node stays a fast struct. -# The change is behavior-invisible (the back end reads each key nil-safely and -# gates on it), so we also pin that tries still evaluate correctly. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/reader :as reader) - -(print "IR :try shape...") -(def ctx (api/init-cached {:compile? true})) -(defn try-node [src] (backend/analyze-form ctx (reader/parse-string src))) - -(defn check-struct [src] - (def n (try-node src)) - (assert (= :try (n :op)) (string src " is a :try node")) - # a struct (nil-free) — NOT a phm; phm nodes carry a :jolt/deftype tag - (assert (struct? n) (string src " analyzes to a struct, not a phm")) - (assert (nil? (get n :jolt/deftype)) (string src " is not a phm"))) - -# no catch, no finally — neither optional key should appear -(check-struct "(try 1)") -# finally only — :catch-sym/:catch-body must be ABSENT, not nil -(def fin (try-node "(try 1 (finally 2))")) -(assert (struct? fin) "(try .. finally) is a struct") -(assert (nil? (get fin :catch-body)) "no catch-body when there is no catch") -(assert (get fin :finally) "finally present") -# catch only -(def cat (try-node "(try 1 (catch Throwable e 2))")) -(assert (struct? cat) "(try .. catch) is a struct") -(assert (get cat :catch-sym) "catch-sym present") -(assert (nil? (get cat :finally)) "no finally when there is none") -# catch + finally -(check-struct "(try 1 (catch Throwable e 2) (finally 3))") - -# behavior unchanged across all shapes -(assert (= 1 (api/eval-string ctx "(try 1)")) "try value") -(assert (= 2 (api/eval-string ctx "(try (throw (ex-info \"x\" {})) (catch Throwable e 2))")) "catch value") -(assert (= 7 (api/eval-string ctx "(let [a (atom 0)] (try (reset! a 7) (finally nil)) @a)")) "finally runs") -(assert (= 2 (api/eval-string ctx "(try (throw (ex-info \"x\" {})) (catch Throwable e 2) (finally 9))")) "catch+finally") -(print "IR :try shape passed!") diff --git a/test/integration/jank-conformance-test.janet b/test/integration/jank-conformance-test.janet deleted file mode 100644 index 470bc80..0000000 --- a/test/integration/jank-conformance-test.janet +++ /dev/null @@ -1,54 +0,0 @@ -# jank conformance: runs the Clojure-language pass-tests from a local jank -# checkout (https://github.com/jank-lang/jank, MPL-2.0) against Jolt and asserts -# the number that pass stays at/above a baseline. This does NOT vendor jank's -# sources (license differs) — it references ~/src/jank if present and SKIPS -# cleanly when absent, so it is a local/dev regression aid. -# -# Each jank pass-test is an assertion script ending in `:success`. We load it in -# a fresh context and count it as passing when it returns :success. -(use ../../src/jolt/api) - -(def jank-dir (string (os/getenv "HOME") "/src/jank/compiler+runtime/test/jank")) - -# Baseline: the number of pass-tests Jolt currently handles. Raise this as Jolt -# gains features so regressions (a previously-passing test breaking) are caught. -(def baseline 120) - -# Tests that loop forever under Jolt's eager evaluation (skipped to avoid hangs; -# tracked as known gaps — variadic-recur arity selection and var-quote calls). -(def skip-patterns ["/cpp/" "var-quote" "fn/recur/pass-variadic-position"]) - -(defn- skip? [path] - (var s false) - (each p skip-patterns (when (string/find p path) (set s true))) - s) - -(defn- walk [dir acc] - (each e (os/dir dir) - (def p (string dir "/" e)) - (case ((os/stat p) :mode) - :directory (walk p acc) - :file (when (and (string/has-suffix? ".jank" p) - (string/find "/pass-" p) - (not (skip? p))) - (array/push acc p)))) - acc) - -(if (not (os/stat jank-dir)) - (print "jank-conformance: ~/src/jank not present — skipped") - (do - (def files (sort (walk jank-dir @[]))) - (var pass 0) - (def fails @[]) - (each f files - # A pass-test passes when no assertion throws (assert now errors on failure). - (def res (protect (load-string (init-cached) (slurp f)))) - (if (= (res 0) true) - (++ pass) - (array/push fails (string/slice f (+ 1 (length jank-dir)))))) - (printf "jank-conformance: %d/%d pass-tests pass (baseline %d)" pass (length files) baseline) - (when (< pass baseline) - (print "--- regressions (now failing, were within baseline) ---") - (each rel fails (print " " rel)) - (error (string "jank conformance dropped to " pass " (baseline " baseline ")"))) - (printf "jank conformance OK (%d known gaps)" (length fails)))) diff --git a/test/integration/lazy-infinite-test.janet b/test/integration/lazy-infinite-test.janet deleted file mode 100644 index 1e068e2..0000000 --- a/test/integration/lazy-infinite-test.janet +++ /dev/null @@ -1,125 +0,0 @@ -# Deadlined infinite-seq conformance harness (Phase 5 Step 0). -# -# Each case is [name expected-clj actual-clj]. The harness spawns a subprocess -# worker (test/support/lazy-eval.janet) that evaluates (= expected actual) and -# prints @@RESULT true/false. Workers run under a wall-clock deadline; a hang -# = a FAIL. This is the safety net that makes it safe to convert transformers -# to lazy — wrong answers hang instead of silently passing. -# -# Pattern mirrors clojure-test-suite-test.janet: os/spawn + ev/with-deadline -# + os/proc-kill on timeout. Never probe infinite cases in-process. - -(def per-case-timeout 5) - -(defn- run-case [expected actual] - (def proc (os/spawn ["janet" "test/support/lazy-eval.janet" expected actual] :p {:out :pipe})) - (def out (proc :out)) - (var data nil) - (def ok - (try - (ev/with-deadline per-case-timeout - (set data (ev/read out 0x10000)) - (os/proc-wait proc) - true) - ([err] false))) - (when (not ok) - (protect (os/proc-kill proc true)) - (protect (ev/with-deadline 2 (os/proc-wait proc)))) - (protect (:close out)) - (if (and ok data) (string data) nil)) - -(defn- parse-result [s] - (def prefix-len (length "@@RESULT ")) - (if (string/has-prefix? "@@RESULT " s) - (let [val (string/slice s prefix-len (dec (length s)))] - [:ok val]) - (if (string/has-prefix? "@@ERROR " s) - (let [msg (string/slice s (length "@@ERROR ") (dec (length s)))] - [:error msg]) - nil))) - -# ---- Cases from phase-5.md §6.2 ---- -# Expected values use Clojure quote syntax so the worker evaluates -# (= (quote ...) actual) with Clojure's = semantics. -(def cases - [ - ["nth of map inc range" "1001" "(nth (map inc (range)) 1000)"] - ["first filter even? drop range" "4" "(first (filter even? (drop 3 (range))))"] - ["take 3 remove odd? range" "(quote (0 2 4))" "(take 3 (remove odd? (range)))"] - ["take 3 drop-while <5 range" "(quote (5 6 7))" "(take 3 (drop-while (fn [x] (< x 5)) (range)))"] - ["take 4 interleave range iterate" "(quote (0 10 1 11))" "(take 4 (interleave (range) (iterate inc 10)))"] - ["take 4 reductions + range" "(quote (0 1 3 6))" "(take 4 (reductions + (range)))"] - ["take 3 tree-seq infinite" "(quote (0 0 0))" "(take 3 (tree-seq (fn [_] true) (fn [n] [n]) 0))"] - ["sequence xform lazy inf" "(quote (1 2 3))" "(take 3 (sequence (map inc) (range)))"] - ["sequence comp xform inf" "(quote (2 4 6))" "(take 3 (sequence (comp (filter odd?) (map inc)) (range)))"] - ["every? short-circuits on inf" "false" "(every? pos? (range))"] - ["not-every? short-circuits on inf" "true" "(not-every? pos? (range))"] - ["take 3 partition 2 range" "(quote ((0 1) (2 3) (4 5)))" "(take 3 (partition 2 (range)))"] - ["take 3 partition-all 2 range" "(quote ((0 1) (2 3) (4 5)))" "(take 3 (partition-all 2 (range)))"] - ["take 3 map-indexed vector range" "(quote ([0 0] [1 1] [2 2]))" "(take 3 (map-indexed vector (range)))"] - ["take 3 distinct cycle" "(quote (1 2 3))" "(take 3 (distinct (cycle [1 2 1 3 1])))"] - ["take 6 mapcat dup range" "(quote (0 0 1 1 2 2))" "(take 6 (mapcat (fn [x] [x x]) (range)))"] - ["first rest lazy" "1" "(let [[a & r] (range)] (first r))"] - ["take 3 rest lazy" "(quote (1 2 3))" "(let [[a & r] (range)] (take 3 r))"] - ["dedupe inf" "(quote (1 2 1 2 1))" "(take 5 (dedupe (cycle [1 1 2 2])))"] - ["take 3 take-nth 2 range" "(quote (0 2 4))" "(take 3 (take-nth 2 (range)))"] - ["take 3 interpose :x range" "(quote (0 :x 1))" "(take 3 (interpose :x (range)))"] - ["take 3 map vector range iterate" "(quote ([0 100] [1 101] [2 102]))" "(take 3 (map vector (range) (iterate inc 100)))"] - - # §6.3 Laziness counter tests — realize exactly the demanded prefix. Under - # Option A `take` is lazy, so the take result must be forced (dorun) to drive - # realization; reading the counter without forcing would (correctly) see 0. - ["LAZY map" "3" "(do (def c (atom 0)) (dorun (take 3 (map (fn [x] (swap! c inc) x) (range)))) @c)"] - ["LAZY filter" "6" "(do (def c (atom 0)) (dorun (take 3 (filter (fn [x] (swap! c inc) (odd? x)) (range)))) @c)"] - ["LAZY remove" "6" "(do (def c (atom 0)) (dorun (take 3 (remove (fn [x] (swap! c inc) (even? x)) (range)))) @c)"] - ["LAZY take-while" "6" "(do (def c (atom 0)) (dorun (take-while (fn [x] (swap! c inc) (< x 5)) (range))) @c)"] - ["LAZY drop-while" "6" "(do (def c (atom 0)) (dorun (take 3 (drop-while (fn [x] (swap! c inc) (< x 5)) (range)))) @c)"] - ["LAZY distinct" "4" "(do (def c (atom 0)) (dorun (take 3 (distinct (map (fn [x] (swap! c inc) x) (cycle [1 2 1 3 1]))))) @c)"] - # 5, was 7: the canonical lazy take-nth (40-lazy, jolt-ded batch 3) realizes - # only the elements the taken outputs and their drops touch. - ["LAZY take-nth" "5" "(do (def c (atom 0)) (dorun (take 3 (take-nth 2 (map (fn [x] (swap! c inc) x) (range))))) @c)"] - ["LAZY map-indexed" "3" "(do (def c (atom 0)) (dorun (take 3 (map-indexed (fn [i x] (swap! c inc) [i x]) (range)))) @c)"] - ["LAZY keep" "6" "(do (def c (atom 0)) (dorun (take 3 (keep (fn [x] (swap! c inc) (if (odd? x) x nil)) (range)))) @c)"] - ["LAZY keep-indexed" "6" "(do (def c (atom 0)) (dorun (take 3 (keep-indexed (fn [i x] (swap! c inc) (if (odd? i) x)) (range)))) @c)"] - ["LAZY interpose" "2" "(do (def c (atom 0)) (dorun (take 3 (interpose :x (map (fn [x] (swap! c inc) x) (range))))) @c)"] - ["LAZY partition" "6" "(do (def c (atom 0)) (dorun (take 3 (partition 2 (map (fn [x] (swap! c inc) x) (range))))) @c)"] - ["LAZY partition-all" "6" "(do (def c (atom 0)) (dorun (take 3 (partition-all 2 (map (fn [x] (swap! c inc) x) (range))))) @c)"] - ["LAZY mapcat" "3" "(do (def c (atom 0)) (dorun (take 6 (mapcat (fn [x] (swap! c inc) [x x]) (range)))) @c)"] - ["LAZY dedupe" "9" "(do (def c (atom 0)) (dorun (take 5 (dedupe (map (fn [x] (swap! c inc) x) (cycle [1 1 2 2]))))) @c)"] - ["LAZY repeated inc" "3" "(do (def c (atom 0)) (dorun (take 3 (map (fn [x] (swap! c inc) x) (iterate inc 0)))) @c)"] - - # Already-working cases (guard against regression) - ["take 5 iterate inc" "(quote (0 1 2 3 4))" "(take 5 (iterate inc 0))"] - ["take 3 range" "(quote (0 1 2))" "(take 3 (range))"] - ["take 3 repeat" "(quote (7 7 7))" "(take 3 (repeat 7))"] - ["take 3 cycle" "(quote (1 2 1))" "(take 3 (cycle [1 2]))"] - ["take 3 filter even? range" "(quote (0 2 4))" "(take 3 (filter even? (range)))"] - ["take 5 lazily filtered from range" "(quote (1 3 5 7 9))" "(take 5 (filter odd? (range)))"] - ]) - -# ---- Run ---- -(var fails @[]) -(var timeouts 0) -(var passed 0) - -(each [name expected expr] cases - (def out (run-case expected expr)) - (cond - (nil? out) - (do (++ timeouts) (array/push fails (string "TIMEOUT: " name))) - (let [res (parse-result out)] - (case (res 0) - :ok (if (= "true" (res 1)) - (++ passed) - (array/push fails (string "MISMATCH: " name " — expected " expected))) - :error (array/push fails (string "ERROR: " name " — " (res 1))) - (array/push fails (string "PARSE: " name " — raw: " (string/trim out))))))) - -(printf "lazy-infinite: %d cases — %d passed / %d timeouts / %d failures" - (length cases) passed timeouts (length fails)) -(when (> (length fails) 0) - (print "\nFailures:") - (each f fails (printf " %s" f))) - -(if (or (> (length fails) 0) (> timeouts 0)) - (os/exit 1)) diff --git a/test/integration/macro-expansion-test.janet b/test/integration/macro-expansion-test.janet deleted file mode 100644 index 4b4adfc..0000000 --- a/test/integration/macro-expansion-test.janet +++ /dev/null @@ -1,91 +0,0 @@ -# Compiled macro expansion in EVERY mode (jolt-tzo: the fast macro-expansion -# path that unblocks moving hot fns the 00-syntax expanders depend on). -# -# Macros are ordinary compiled fns in Clojure's model. Compile mode has had -# this since the staged bootstrap (ensure-macros-compiled! recompiles the -# early interpreted expanders once the analyzer is alive); interpret mode — -# the conformance battery's default — used to skip it, so every distinct -# (and ...) / (cond ...) / nested expansion ran an interpreted closure. -# Now interpret-mode init also builds the analyzer once at the end of the -# overlay load and compiles every stashed expander; JOLT_INTERPRET_MACROS=1 -# opts back into the pure interpreted oracle. - -(use ../../src/jolt/api) -(use ../../src/jolt/types) - -(print "compiled macro expansion...") -(os/setenv "JOLT_INTERPRET_MACROS" nil) - -(defn- macro-var [ctx nm] (ns-find (ctx-find-ns ctx "clojure.core") nm)) -(defn- user-var [ctx nm] (ns-find (ctx-find-ns ctx "user") nm)) - -(def probes - ["(= 3 (and 1 2 3))" - "(= 1 (or nil false 1))" - "(= :b (cond false :a :else :b))" - "(= 4 (when-not nil 4))" - "(= 6 (-> 1 inc (* 3)))" - "(= 15 (->> [1 2] (map inc) (reduce +) (* 3)))" - "(= 2 (if-let [x nil] 1 2))" - "(= [0 1] (vec (for [i (range 2)] i)))" - "(= 5 (case 2 1 :one 2 5 :dflt))" - "(= 10 (loop [i 0 a 0] (if (< i 5) (recur (inc i) (+ a 2)) a)))"]) - -(defn- run-probes [ctx label] - (each prog probes - (def got (protect (eval-string ctx prog))) - (assert (and (got 0) (= (got 1) true)) - (string label " probe failed: " prog " => " - (if (got 0) (string/format "%q" (got 1)) (string (got 1))))))) - -# 1. Interpret mode: expanders are COMPILED after init (the new path). -(def ictx (init {})) -(run-probes ictx "interpret") -(each m ["when" "when-not" "and" "or" "cond" "->" "->>" "if-let" "case" "doseq"] - (def v (macro-var ictx m)) - (assert v (string m " var exists")) - (assert (get v :macro-compiled) - (string m " expander is compiled in interpret mode"))) - -# 2. A USER defmacro in an interpret ctx gets a compiled expander too. -(eval-string ictx "(defmacro my-twice [x] `(* 2 ~x))") -(assert (= 10 (eval-string ictx "(my-twice 5)")) "user macro works") -(assert (get (user-var ictx "my-twice") :macro-compiled) - "user macro expander compiled in interpret mode") - -# 3. An expander whose body the analyzer can't compile (here: the `eval` -# special form) falls back to the interpreted closure and still works. -(eval-string ictx "(defmacro evalish [x] (eval `(+ ~x 1)))") -(assert (= 3 (eval-string ictx "(evalish 2)")) "uncompilable expander works") -(assert (not (get (user-var ictx "evalish") :macro-compiled)) - "uncompilable expander stays interpreted") - -# 4. Compile mode unchanged: expanders compiled (pre-existing behavior). -(def cctx (init {:compile? true})) -(run-probes cctx "compile") -(assert (get (macro-var cctx "cond") :macro-compiled) "compile-mode expanders compiled") - -# 5. JOLT_INTERPRET_MACROS=1: the pure interpreted oracle — same semantics, -# expanders NOT compiled. -(os/setenv "JOLT_INTERPRET_MACROS" "1") -(def octx (init {})) -(run-probes octx "oracle") -(assert (not (get (macro-var octx "cond") :macro-compiled)) - "oracle mode keeps interpreted expanders") -(os/setenv "JOLT_INTERPRET_MACROS" nil) - -(print "compiled macro expansion passed!") - -# 6. Early overlay DEFNS get the same staged-recompile treatment (jolt-4j3): -# 00-syntax fns (destructure, and the expander-called keys/vals/empty?) load -# interpreted pre-kernel, then compile in the same end-of-init pass. -(each nm ["destructure" "empty?" "keys" "vals"] - (def v (macro-var ictx nm)) - (assert v (string nm " var exists")) - (assert (get v :defn-compiled) - (string nm " early defn is compiled (interpret mode)"))) -(def cctx2 (init {:compile? true})) -(assert (get (macro-var cctx2 "destructure") :defn-compiled) - "early defn compiled in compile mode too") -(assert (not (get (macro-var octx "destructure") :defn-compiled)) - "oracle mode keeps early defns interpreted") diff --git a/test/integration/mutable-deftype-test.janet b/test/integration/mutable-deftype-test.janet deleted file mode 100644 index 261cee2..0000000 --- a/test/integration/mutable-deftype-test.janet +++ /dev/null @@ -1,57 +0,0 @@ -# Mutable deftype fields under shapes/direct-link (jolt-c3q). -# -# A deftype field tagged ^:unsynchronized-mutable / ^:volatile-mutable is set! at -# runtime. Immutable records are shape-recs (immutable tuples) where shapes are -# active (direct-link), so set! can't mutate them. A deftype with ANY mutable -# field opts out of the shape-rec layout and uses the mutable table form (which -# set! already mutates and field reads route through), regardless of :shapes?. -# Immutable deftypes/records keep the fast shape-rec. - -(use ../../src/jolt/api) - -(var failures 0) -(defn- check [label got want] - (unless (= got want) - (++ failures) - (printf "FAIL [%s] got %q want %q" label got want))) - -# direct-linking? true => :shapes? on (the mode where immutable records are -# tuples and this used to error "Can't set! field on non-deftype: tuple"). -(let [ctx (init {:compile? true :direct-linking? true})] - (eval-string ctx "(deftype Counter [^:unsynchronized-mutable n])") - (eval-string ctx "(def c (->Counter 0))") - (check "read initial mutable field" (eval-string ctx "(.-n c)") 0) - (eval-string ctx "(set! (.-n c) 5)") - (check "read after set!" (eval-string ctx "(.-n c)") 5) - (eval-string ctx "(set! (.-n c) (inc (.-n c)))") - (check "set! using prior value" (eval-string ctx "(.-n c)") 6) - # keyword access reads the same mutated field - (check "keyword access sees mutation" (eval-string ctx "(:n c)") 6)) - -# Mixed mutable + immutable fields: a method reads both, set! touches the mutable. -(let [ctx (init {:compile? true :direct-linking? true})] - (eval-string ctx "(deftype Cell [label ^:unsynchronized-mutable v] Object (toString [_] (str label \"=\" v)))") - (eval-string ctx "(def cell (->Cell \"x\" 1))") - (check "immutable field reads" (eval-string ctx "(.-label cell)") "x") - (check "custom toString before" (eval-string ctx "(str cell)") "x=1") - (eval-string ctx "(set! (.-v cell) 42)") - (check "mutable field after set!" (eval-string ctx "(.-v cell)") 42) - (check "custom toString after mutation" (eval-string ctx "(str cell)") "x=42") - (check "immutable field unchanged" (eval-string ctx "(.-label cell)") "x")) - -# volatile-mutable is treated the same (also a mutable field). -(let [ctx (init {:compile? true :direct-linking? true})] - (eval-string ctx "(deftype Box [^:volatile-mutable x])") - (eval-string ctx "(def b (->Box :a))") - (eval-string ctx "(set! (.-x b) :z)") - (check "volatile-mutable set!" (eval-string ctx "(.-x b)") :z)) - -# An all-immutable deftype/record is unaffected: still a shape-rec, fast reads. -(let [ctx (init {:compile? true :direct-linking? true})] - (eval-string ctx "(defrecord Pt [x y])") - (check "immutable record reads" (eval-string ctx "(:x (->Pt 3 4))") 3) - (check "immutable record reads y" (eval-string ctx "(:y (->Pt 3 4))") 4)) - -(if (pos? failures) - (do (printf "mutable-deftype: %d failure(s)" failures) (os/exit 1)) - (print "mutable-deftype: all cases passed")) diff --git a/test/integration/namespace-test.janet b/test/integration/namespace-test.janet deleted file mode 100644 index 4d05f50..0000000 --- a/test/integration/namespace-test.janet +++ /dev/null @@ -1,119 +0,0 @@ -(use ../../src/jolt/reader) -(use ../../src/jolt/types) -(use ../../src/jolt/evaluator) -(import ../../src/jolt/api :as api) - -# ns/in-ns/require/use are overlay macros + clojure.core fns now (Stage 2 jolt-eaa), -# so these interpreter tests need the full env (init loads the overlay + installs -# the stateful fns), not a bare make-ctx. -(defn- fresh-ctx [] (api/init)) - -# Helper: parse and eval in a fresh ctx -(defn eval-str [s] - (let [ctx (fresh-ctx) - form (parse-string s)] - (eval-form ctx @{} form))) - -(print "1: in-ns...") -(let [ctx (fresh-ctx)] - (def form (parse-string "(in-ns 'my.app)")) - (eval-form ctx @{} form) - (assert (= "my.app" (ctx-current-ns ctx)) "in-ns switches namespace")) -(print " passed") - -(print "2: def in different namespace...") -(let [ctx (fresh-ctx)] - (eval-form ctx @{} (parse-string "(in-ns 'my.app)")) - (eval-form ctx @{} (parse-string "(def x 42)")) - (let [ns (ctx-find-ns ctx "my.app") - v (ns-find ns "x")] - (assert (= 42 (var-get v)) "def works in new namespace"))) -(print " passed") - -(print "3: ns form...") -(let [ctx (fresh-ctx)] - (eval-form ctx @{} (parse-string "(ns my.lib)")) - (assert (= "my.lib" (ctx-current-ns ctx)) "ns sets current namespace")) -(print " passed") - -(print "4: ns with require...") -(let [ctx (fresh-ctx)] - # Set up a namespace with some vars - (let [other-ns (ctx-find-ns ctx "other.lib")] - (ns-intern other-ns "f" (fn [x] (inc x)))) - # Now ns with require - (eval-form ctx @{} (parse-string "(ns my.app (:require [other.lib :as o]))")) - # current-ns should be my.app - (assert (= "my.app" (ctx-current-ns ctx)) "ns with require sets current namespace") - # Alias should be registered - (let [ns (ctx-find-ns ctx "my.app") - aliased (ns-alias-lookup ns "o")] - (assert (= "other.lib" aliased) "alias o -> other.lib registered"))) -(print " passed") - -(print "5: require form (standalone)...") -(let [ctx (fresh-ctx)] - # Populate other.lib first — require of an unlocatable ns now throws - # (Clojure's FileNotFoundException), see namespaces-spec. - (let [other-ns (ctx-find-ns ctx "other.lib")] - (ns-intern other-ns "f" (fn [x] x))) - (eval-form ctx @{} (parse-string "(require '[other.lib :as o])")) - (let [ns (ctx-find-ns ctx "user") - aliased (ns-alias-lookup ns "o")] - (assert (= "other.lib" aliased) "standalone require registers alias"))) -(print " passed") - -(print "6: qualified symbol via alias...") -(let [ctx (fresh-ctx)] - # Set up target ns - (let [target (ctx-find-ns ctx "other.lib")] - (ns-intern target "f" (fn [x] (inc x)))) - # Register alias - (let [ns (ctx-find-ns ctx "user")] - (ns-import ns "o" "other.lib")) - # Resolve o/f and call it - (let [form (parse-string "(o/f 41)") - result (eval-form ctx @{} form)] - (assert (= 42 result) "qualified call via alias works"))) -(print " passed") - -(print "7: require then use alias...") -(let [ctx (fresh-ctx)] - # Set up target ns - (let [target (ctx-find-ns ctx "math.lib")] - (ns-intern target "add" (fn [a b] (+ a b)))) - # require + use - (eval-form ctx @{} (parse-string "(require '[math.lib :as m])")) - (let [result (eval-form ctx @{} (parse-string "(m/add 1 2)"))] - (assert (= 3 result) "require + alias + call chain works"))) -(print " passed") - -(print "8: ns form requires multiple...") -(let [ctx (fresh-ctx)] - (let [ns1 (ctx-find-ns ctx "a.lib")] - (ns-intern ns1 "f" (fn [x] (inc x)))) - (let [ns2 (ctx-find-ns ctx "b.lib")] - (ns-intern ns2 "g" (fn [x] (dec x)))) - (eval-form ctx @{} (parse-string "(ns user (:require [a.lib :as a] [b.lib :as b]))")) - (assert (= 43 (eval-form ctx @{} (parse-string "(a/f 42)"))) "alias a works") - (assert (= 41 (eval-form ctx @{} (parse-string "(b/g 42)"))) "alias b works")) -(print " passed") - -(print "\nAll namespace tests passed!") - -# An UNCAUGHT throw inside an interpreted fn body must restore the caller's -# current-ns (the body runs with current-ns rebound to the defining ns; the -# restore is a defer now). Pre-fix, the ctx was left stuck in the defining ns -# and every later alias-qualified lookup failed — the sci-bootstrap and -# clojure.edn "Unable to resolve alias/..." cascades. -(print "ns restored after uncaught throw...") -(let [ctx (fresh-ctx)] - (api/eval-string ctx "(in-ns (quote otherns))") - (api/eval-string ctx "(clojure.core/refer-clojure)") - (api/eval-string ctx "(defn boom [] (throw (ex-info \"x\" {})))") - (api/eval-string ctx "(in-ns (quote user))") - (assert (not ((protect (api/eval-string ctx "(otherns/boom)")) 0)) "boom throws") - (assert (= "user" (api/eval-string ctx "(str *ns*)")) "*ns* restored after uncaught throw") - (api/eval-string ctx "(require (quote [clojure.string :as s9]))") - (assert (= "A" (api/eval-string ctx "(s9/upper-case \"a\")")) "aliases still resolve")) -(print " ok") diff --git a/test/integration/nrepl-test.janet b/test/integration/nrepl-test.janet deleted file mode 100644 index 62ff718..0000000 --- a/test/integration/nrepl-test.janet +++ /dev/null @@ -1,109 +0,0 @@ -# Integration test: jolt.nrepl server + client over a real TCP/bencode wire. -# -# The server runs in a subprocess (`jolt nrepl PORT`) so the client (this -# process) isn't affected by the server's accept-loop fiber, which leaves the -# shared ctx's current-ns pointing at jolt.nrepl. The client uses the jolt.nrepl -# Clojure API, exercising both halves of the implementation. - -(use ../../src/jolt/api) -(use ../../src/jolt/types) - -(def port "17888") - -# Watchdog: never let a hang stall CI — bail out after 90s. -(ev/spawn (ev/sleep 90) (eprint "nrepl-test: watchdog fired (possible hang)") (os/exit 1)) - -# Prefer the built executable (its ctx is baked at build time, ~20ms start); -# source mode pays the full compile-mode init, which on a slow CI runner can -# outrun a short poll window. -(def server-cmd - (if (os/stat "build/jolt") - ["build/jolt" "nrepl" port] - ["janet" "src/jolt/main.janet" "nrepl" port])) -(print "Starting jolt.nrepl server subprocess on port " port " (" (first server-cmd) ") ...") -(def proc (os/spawn server-cmd :p {:out :pipe :err :pipe})) - -# Wait until the server accepts connections (poll up to ~60s — CI headroom). -(var ready false) -(var tries 0) -(while (and (not ready) (< tries 600)) - (let [r (protect (net/connect "127.0.0.1" port))] - (if (r 0) (do (:close (r 1)) (set ready true)) - (do (ev/sleep 0.1) (++ tries))))) -(unless ready - # Surface the server's stderr so a CI failure is diagnosable. - (eprint "server stderr: " (string (ev/read (proc :err) :all))) - (assert false "nREPL server did not start")) - -(def ctx (init-cached)) -(ctx-set-current-ns ctx "user") -(load-string ctx "(require '[jolt.nrepl])") -(load-string ctx (string "(def c (jolt.nrepl/connect {:port " port "}))")) - -(defn ev [e] (eval-string ctx e)) -(var fails 0) -(defn check [label expr expected] - (let [got (ev expr)] - (if (= got expected) - (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %q, got %q" label expected got))))) - -# describe advertises ops -(check "describe has ops" - "(boolean (get (first (jolt.nrepl/request c {\"op\" \"describe\"})) \"ops\"))" true) - -# clone yields a session id -(ev "(def s (jolt.nrepl/client-clone c))") -(check "clone session is string" "(string? s)" true) - -# eval returns a value -(check "eval (+ 1 2)" "(some #(get % \"value\") (jolt.nrepl/client-eval c \"(+ 1 2)\" s))" "3") - -# a def's value renders as #'ns/name (pr-str loops on a var's cyclic ns refs) -(check "def renders as #'ns/name" - "(some #(get % \"value\") (jolt.nrepl/client-eval c \"(def yy 21)\" s))" "#'user/yy") - -# defs persist across evals in the session -(check "def then use" "(some #(get % \"value\") (jolt.nrepl/client-eval c \"(* yy 2)\" s))" "42") - -# stdout is captured and streamed as an out message -(check "println captured as out" - "(some #(get % \"out\") (jolt.nrepl/client-eval c \"(do (println \\\"hi\\\") 9)\" s))" "hi\n") - -# the response carries the current ns -(check "ns field reported" - "(some #(get % \"ns\") (jolt.nrepl/client-eval c \"(+ 1 1)\" s))" "user") - -# in-ns switches the session ns, and it persists to the next eval -(check "in-ns switches ns" - "(some #(get % \"ns\") (jolt.nrepl/client-eval c \"(in-ns (quote foo.bar))\" s))" "foo.bar") -(check "ns persists across evals" - "(some #(get % \"ns\") (jolt.nrepl/client-eval c \"(+ 2 2)\" s))" "foo.bar") -# explicit :ns on the message overrides -(ev "(jolt.nrepl/request c {\"op\" \"eval\" \"code\" \"(+ 1 1)\" \"session\" s \"ns\" \"user\"})") - -# eval error -> eval-error status, and the connection keeps working afterward -(check "eval error status" - "(boolean (some #(let [st (get % \"status\")] (and (sequential? st) (some (fn [x] (= \"eval-error\" x)) st))) (jolt.nrepl/client-eval c \"(/ 1 :z)\" s)))" - true) -(check "still alive after error" - "(some #(get % \"value\") (jolt.nrepl/client-eval c \"(+ 5 5)\" s))" "10") - -# multiple forms in one eval -> a value per form (values arrive as strings) -(check "multiple forms" - "(= [\"2\" \"4\"] (mapv #(get % \"value\") (filter #(get % \"value\") (jolt.nrepl/client-eval c \"(+ 1 1) (+ 2 2)\" s))))" - true) - -# unknown op -> error/unknown-op/done -(check "unknown op status" - "(let [st (get (first (jolt.nrepl/request c {\"op\" \"nope\"})) \"status\")] (and (some #(= \"unknown-op\" %) st) true))" - true) - -# clean up -(ev "(jolt.nrepl/client-close c)") -(os/proc-kill proc true) -(when (os/stat ".nrepl-port") (os/rm ".nrepl-port")) - -(if (> fails 0) - (do (eprint "nrepl-test: " fails " failing check(s)") (os/exit 1)) - (do (print "\nAll nREPL tests passed!") (os/exit 0))) diff --git a/test/integration/phint-propagation-test.janet b/test/integration/phint-propagation-test.janet deleted file mode 100644 index abba90b..0000000 --- a/test/integration/phint-propagation-test.janet +++ /dev/null @@ -1,77 +0,0 @@ -# Declared record param hints propagate THROUGH the whole-program fixpoint -# (jolt-3ko). A ^Record param's field reads type to the field's record type, and -# when such a field-read value is passed to a SHARED helper (no hints, inferred -# from call sites), the helper's params must pick up that record type so its own -# field reads bare-index. Before the fix, ^-hints were applied only at the final -# re-emit (reinfer-def), not during the fixpoint, so a hinted param with no -# callers stayed :any during inference and never propagated to its callees — -# exactly why the ray tracer's vec ops (called with (:origin ray) etc.) stayed -# unproven even under whole-program optimization. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/types :as types) - -(print "phint propagation through the fixpoint (jolt-3ko)...") - -(def dir (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-phint-prop")) -(os/mkdir dir) -(spit (string dir "/pp.clj") - (string - "(ns pp)\n" - "(defrecord Vec3 [r g b])\n" - "(defrecord Ray [^Vec3 origin ^Vec3 direction])\n" - # shared ops, NO hints — must be inferred from the call sites below. A - # `loop` makes them inline-INELIGIBLE so they stay real calls (a small fn - # would be spliced into the caller, where the caller's hint already proves - # it); the point here is propagation to a separate callee's PARAMS. - "(defn dot [a b]\n" - " (loop [i 0 s 0.0]\n" - " (if (< i 1) (recur (inc i) (+ (+ (* (:r a) (:r b)) (* (:g a) (:g b))) (* (:b a) (:b b)))) s)))\n" - "(defn add [a b]\n" - " (loop [i 0 s nil]\n" - " (if (< i 1) (recur (inc i) (->Vec3 (+ (:r a) (:r b)) (+ (:g a) (:g b)) (+ (:b a) (:b b)))) s)))\n" - # callers pass field-read Vec3s from a ^Ray param into the shared ops - "(defn use-dot [^Ray r] (dot (:origin r) (:direction r)))\n" - "(defn use-add [^Ray r] (add (:origin r) (:direction r)))\n")) - -(os/setenv "JOLT_DIRECT_LINK" "1") -(os/setenv "JOLT_WHOLE_PROGRAM" "1") -(os/setenv "JOLT_PATH" dir) -(def ctx (api/init {:compile? true})) -(api/eval-string ctx "(require '[pp])") -(def report (backend/infer-program! ctx)) - -(def pns (types/ctx-find-ns ctx "jolt.passes")) -(def reinfer (types/var-get (types/ns-find pns "reinfer-def"))) -(def ppns (types/ctx-find-ns ctx "pp")) -(defn ptmap-for [fname params] - (def pts (get report (string "pp/" fname))) - (def m @{}) (when pts (var i 0) (each p params (put m p (get pts i)) (++ i))) m) -(defn guards [fname params] - (def cell (get (ppns :mappings) fname)) - (length (string/find-all ":jolt/type" - (string/format "%p" (backend/emit-ir ctx (reinfer (get cell :infer-ir) (ptmap-for fname params))))))) - -(var fails 0) -(defn check [label got expected] - (if (= got expected) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %p got %p" label expected got)))) - -# the shared ops' params get the Vec3 record type from the field-read call args, -# so all their field reads bare-index (no :jolt/type guard) -(check "dot params typed Vec3 -> reads bare" (guards "dot" ["a" "b"]) 0) -(check "add params typed Vec3 -> reads bare" (guards "add" ["a" "b"]) 0) -# the hinted callers were already fine (re-emit applies the phint) -(check "use-dot hinted reads bare" (guards "use-dot" ["r"]) 0) - -# the report shows the shared ops' params as a Vec3 struct (has :shape / :type) -(def dot-a (get (get report "pp/dot") 0)) -(check "dot param a is a struct type" (truthy? (and dot-a (or (get dot-a :shape) (get dot-a :struct)))) true) - -# correctness: results are unchanged -(check "dot computes" (api/eval-string ctx "(pp/dot (pp/->Vec3 1 2 3) (pp/->Vec3 4 5 6))") 32) -(check "use-dot computes" - (api/eval-string ctx "(pp/use-dot (pp/->Ray (pp/->Vec3 1 2 3) (pp/->Vec3 4 5 6)))") 32) - -(if (> fails 0) (do (printf "phint-propagation: %d FAILED" fails) (os/exit 1)) - (print "phint propagation (jolt-3ko) passed!")) diff --git a/test/integration/png-test.janet b/test/integration/png-test.janet deleted file mode 100644 index 6dc5664..0000000 --- a/test/integration/png-test.janet +++ /dev/null @@ -1,46 +0,0 @@ -# jolt.png: the host PNG encoder (src/jolt/png.janet) + the overlay wrapper -# (src/jolt/jolt/png.clj), reachable as janet.png/* through eval_base's -# module-load-env. Checks the encoder emits a structurally valid PNG (signature, -# IHDR dims, IEND) and that the overlay path writes the same. -(import ../../src/jolt/png :as png) -(import ../../src/jolt/api :as api) - -(print "jolt.png encoder + overlay...") -(var failures 0) -(defn check [label ok] (if ok (print " ok: " label) (do (++ failures) (eprintf " FAIL: %s" label)))) - -(defn- u32 [b o] - (+ (* (get b o) 16777216) (* (get b (+ o 1)) 65536) (* (get b (+ o 2)) 256) (get b (+ o 3)))) - -# --- host encoder --- -(def w 5) -(def h 3) -(def rgb (buffer/new (* w h 3))) -(for i 0 (* w h 3) (buffer/push-byte rgb (% (* i 7) 256))) -(def out (png/encode w h rgb)) -(check "PNG signature" (= (string/slice out 0 8) "\x89PNG\r\n\x1a\n")) -(check "IHDR length is 13" (= 13 (u32 out 8))) -(check "IHDR type" (= "IHDR" (string/slice out 12 16))) -(check "IHDR width" (= w (u32 out 16))) -(check "IHDR height" (= h (u32 out 20))) -(check "8-bit RGB colour type" (and (= 8 (get out 24)) (= 2 (get out 25)))) -(check "ends with an IEND chunk" (string/find "IEND" (string out))) -(check "encode rejects a wrong-sized buffer" - (= false (first (protect (png/encode w h (buffer/new 4)))))) - -# --- overlay (jolt.png from Clojure) writes a valid PNG --- -(def tmp (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-png-overlay-test.png")) -(def ctx (api/init-cached {:compile? true})) -(api/eval-string ctx "(require '[jolt.png :as png])") -(api/eval-string ctx - (string "(let [img (png/image 4 2)]" - " (doseq [_ (range 8)] (png/put! img 10 20 30))" - " (png/write img 4 2 \"" tmp "\"))")) -(def wrote (slurp tmp)) -(check "overlay wrote the PNG signature" (= (string/slice wrote 0 8) "\x89PNG\r\n\x1a\n")) -(check "overlay IHDR dims" (and (= 4 (u32 wrote 16)) (= 2 (u32 wrote 20)))) -(os/rm tmp) - -(if (= 0 failures) - (print "All tests passed.") - (do (eprintf "%d png check(s) failed" failures) (os/exit 1))) diff --git a/test/integration/predicate-fold-test.janet b/test/integration/predicate-fold-test.janet deleted file mode 100644 index 61afb2f..0000000 --- a/test/integration/predicate-fold-test.janet +++ /dev/null @@ -1,61 +0,0 @@ -# Predicate folding from inference (jolt-wcw): when the collection-type -# inference PROVES the argument's type, a type predicate (number?/string?/ -# keyword?/nil?/some?/record?) folds to a compile-time boolean constant, which -# the trailing const-fold then propagates — collapsing any `if` it gates to the -# taken branch. Sound: only a provable answer folds, and only when the argument -# is side-effect-free (a local or const), so dropping its evaluation is a no-op. -# Mirrors type-infer-test.janet's harness (count a marker in the emitted IR to -# prove the optimization fired, then evaluate to prove it stayed correct). -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/reader :as reader) - -(print "Predicate folding (jolt-wcw)...") - -(os/setenv "JOLT_DIRECT_LINK" "1") -(def ctx (api/init-cached {:compile? true})) -(api/eval-string ctx "(ns pf)") - -(defn code [src] - (string/format "%p" (backend/emit-ir ctx (backend/analyze-form ctx (reader/parse-string src))))) -(defn occurs [src needle] (length (string/find-all needle (code src)))) -(defn ev [src] (api/eval-string ctx src)) - -# --- the predicate call is gone where the type is proven -------------------- -(assert (= 0 (occurs "(fn [] (let [x (+ 1 2)] (number? x)))" "number?")) - "number? on proven :num -> folded, call eliminated") -(assert (= 0 (occurs "(fn [] (let [x \"hi\"] (string? x)))" "string?")) - "string? on proven :str -> folded") -(assert (= 0 (occurs "(fn [] (let [x :k] (keyword? x)))" "keyword?")) - "keyword? on proven :kw -> folded") -(assert (= 0 (occurs "(fn [] (let [x (+ 1 2)] (nil? x)))" "nil?")) - "nil? on a provably non-nil value -> folded") - -# --- the folded constant collapses an if it gates -------------------------- -# the dead branch's literal (200) must be gone after dead-branch removal -(assert (= 0 (occurs "(fn [] (let [x (+ 1 2)] (if (number? x) 100 200)))" "200")) - "true predicate folds the if to its then-branch (dead 200 dropped)") -(assert (= 0 (occurs "(fn [] (let [x (+ 1 2)] (if (string? x) 100 200)))" "100")) - "false predicate folds the if to its else-branch (dead 100 dropped)") - -# --- sound fallback: unknown type or impure arg keeps the call ------------- -# a param is :any (Phase 0 doesn't type it) -> no fold -(assert (= 1 (occurs "(fn [m] (number? m))" "number?")) - "unknown-type arg keeps the predicate call") -# arg type is proven :num but the arg has side effects (a call) -> must NOT -# drop its evaluation, so the predicate is left in place -(assert (>= (occurs "(fn [g] (number? (+ (g) 1)))" "number?") 1) - "impure arg (even with proven type) keeps the predicate call") - -# --- correctness: folded path evaluates to the dispatched path ------------- -(assert (= true (ev "((fn [] (let [x (+ 1 2)] (number? x))))")) "number? true value") -(assert (= false (ev "((fn [] (let [x \"hi\"] (number? x))))")) "number? false value") -(assert (= true (ev "((fn [] (let [x :k] (keyword? x))))")) "keyword? true value") -(assert (= false (ev "((fn [] (let [x 5] (nil? x))))")) "nil? false value") -(assert (= true (ev "((fn [] (let [x 5] (some? x))))")) "some? true value") -(assert (= :yes (ev "((fn [] (let [x 5] (if (number? x) :yes :no))))")) "gated if takes proven branch") -(assert (= :no (ev "((fn [] (let [x 5] (if (string? x) :yes :no))))")) "gated if drops false branch") -# impure arg still runs its side effect and returns the right answer -(assert (= 6 (ev "((fn [g] (if (number? (+ (g) 1)) (+ (g) 5) 0)) (fn [] 1))")) "impure-arg predicate stays correct") - -(print "Predicate folding (jolt-wcw) passed!") diff --git a/test/integration/record-declared-shape-test.janet b/test/integration/record-declared-shape-test.janet deleted file mode 100644 index 7d0cf30..0000000 --- a/test/integration/record-declared-shape-test.janet +++ /dev/null @@ -1,45 +0,0 @@ -# Records use declared-shape layout with fast field access (jolt-t34), by default -# in a direct-linking unit — no JOLT_SHAPE needed. The key property: a record is -# laid out in DECLARED field order, and field reads bare-index by that order, so -# fields that are NOT alphabetically sorted must still read correctly. This is -# what `sidx` reads off the :shape vector (declared order, not str-sorted). -(use ../../src/jolt/api) - -(var failures 0) -(defn- check [label got want] - (unless (= got want) - (++ failures) - (printf "FAIL [%s] got %q want %q" label got want))) - -# A direct-linking ctx: records are shape-recs, reads proven/bare-indexed. -(def dl (init {:compile? true :direct-linking? true})) - -# --- representation: a record is a shape-rec (tuple), not a table ------------- -(check "record is a shape-rec" - (tuple? (eval-string dl "(do (defrecord Sp [x y]) (->Sp 1 2))")) true) - -# --- DECLARED-ORDER field access: fields are NOT alphabetically sorted; each -# must read its own value, locally and through a fn boundary. Each case uses a -# DISTINCT record name (redefining a record with new fields is jolt-wf4). ------- -(def cases - [["decl-order local" "(do (defrecord Ra [b a c]) (let [r (->Ra 10 20 30)] (= [10 20 30] [(:b r) (:a r) (:c r)])))"] - ["decl-order via fn" "(do (defrecord Rb [b a c]) (defn rdb [r] [(:b r) (:a r) (:c r)]) (= [10 20 30] (rdb (->Rb 10 20 30))))"] - ["single field z-first" "(do (defrecord Rc [z m a]) (= 7 (:z (->Rc 7 8 9))))"] - ["protocol method body" "(do (defprotocol Sh (area [s])) (defrecord Box [w h] Sh (area [b] (* (:w b) (:h b)))) (= 12 (area (->Box 3 4))))"] - ["record? true" "(do (defrecord Rd [x y]) (record? (->Rd 1 2)))"] - ["record vs map not=" "(do (defrecord Re [x y]) (not (= (->Re 1 2) {:x 1 :y 2})))"] - ["assoc keeps type" "(do (defrecord Rf [x y]) (record? (assoc (->Rf 1 2) :x 9)))"] - ["pr declared order" "(do (defrecord Rg [b a c]) (= \"#user.Rg{:b 10, :a 20, :c 30}\" (pr-str (->Rg 10 20 30))))"] - # a record shape-rec is a Janet tuple, but a record is NOT a vector/sequential - # in Clojure — else map-destructuring it takes the kwargs coerce path and - # corrupts (reitit router crash, jolt-14k). - ["vector? record false" "(do (defrecord Rh [x y]) (not (vector? (->Rh 1 2))))"] - ["sequential? record false" "(do (defrecord Ri [x y]) (not (sequential? (->Ri 1 2))))"] - ["destructure record :or" "(do (defrecord Rj [a b c d e]) (let [{:keys [a e] :or {a 0}} (->Rj 1 2 3 4 5)] (= 6 (+ a e))))"]]) - -(each [label prog] cases - (check label (eval-string dl prog) true)) - -(if (pos? failures) - (do (printf "record-declared-shape: %d failure(s)" failures) (os/exit 1)) - (print "record-declared-shape: all cases passed")) diff --git a/test/integration/record-shape-test.janet b/test/integration/record-shape-test.janet deleted file mode 100644 index d929556..0000000 --- a/test/integration/record-shape-test.janet +++ /dev/null @@ -1,64 +0,0 @@ -# Records as shape-recs (jolt-t34 R3). A user record (defrecord/deftype) under -# JOLT_SHAPE is a shape-rec whose descriptor ALSO carries :type (the type tag), -# laid out in DECLARED field order. These build records directly via the runtime -# (make-record) and assert that every map/record operation treats them the way -# Clojure does — and crucially that type identity is preserved (a record is not -# a plain map, and two records are equal only when their types match). -(use ../../src/jolt/types) -(use ../../src/jolt/core) - -(var fails 0) -(defn check [label got want] - (if (deep= got want) (print " ok " label) - (do (++ fails) (printf " FAIL %s: got %j want %j" label got want)))) - -# (defrecord Point [x y]) instance (->Point 1 2) -(def P (make-record "my.Point" [:x :y] [1 2])) - -# --- it IS a shape-rec, and reports its type --------------------------------- -(check "shape-rec?" (shape-rec? P) true) -(check "record-tag" (record-tag P) "my.Point") -(check "map?" (core-map? P) true) - -# --- field access in declared order ------------------------------------------ -(check "get x" (core-get P :x nil) 1) -(check "get y" (core-get P :y nil) 2) -(check "get miss default" (core-get P :z :d) :d) -(check "count" (core-count P) 2) -(check "contains?" (core-contains? P :x) true) - -# --- the virtual :jolt/deftype key keeps every (get obj :jolt/deftype) site -# (record?/dispatch) working without special-casing each one ------------------ -(check "virtual deftype" (core-get P :jolt/deftype nil) "my.Point") - -# --- assoc preserves the type: in place for a declared field, and grows a -# slot Clojure-style for a new key (the result is still a record) ------------- -(def P2 (core-assoc P :x 9)) -(check "assoc field tag" (record-tag P2) "my.Point") -(check "assoc field val" (core-get P2 :x nil) 9) -(check "assoc keeps other" (core-get P2 :y nil) 2) -(def P3 (core-assoc P :z 3)) -(check "assoc new tag" (record-tag P3) "my.Point") -(check "assoc new val" (core-get P3 :z nil) 3) -(check "assoc new keeps" (core-get P3 :x nil) 1) - -# --- dissoc of a declared field demotes to a plain map (Clojure semantics) ---- -(def D (core-dissoc P :x)) -(check "dissoc demotes" (record-tag D) nil) -(check "dissoc gone" (core-get D :x :gone) :gone) -(check "dissoc keeps" (core-get D :y nil) 2) - -# --- equality is TYPE-AWARE: same type + same fields equal; a different type -# or a plain map with the same fields is NOT equal ---------------------------- -(check "= same type" (jolt-equal? P (make-record "my.Point" [:x :y] [1 2])) true) -(check "not= diff field" (jolt-equal? P (make-record "my.Point" [:x :y] [1 9])) false) -(check "not= diff type" (jolt-equal? P (make-record "my.Other" [:x :y] [1 2])) false) -(check "not= record vs map" (jolt-equal? P {:x 1 :y 2}) false) -(check "not= map vs record" (jolt-equal? {:x 1 :y 2} P) false) - -# --- printing: Clojure record syntax #ns.Type{:k v, ...}, fields in order ----- -(check "pr record" (core-pr-str1 P) "#my.Point{:x 1, :y 2}") - -(if (> fails 0) - (error (string "record-shape: " fails " failing check(s)")) - (print "\nRecord shape passed!")) diff --git a/test/integration/scalar-replace-record-test.janet b/test/integration/scalar-replace-record-test.janet deleted file mode 100644 index 977e543..0000000 --- a/test/integration/scalar-replace-record-test.janet +++ /dev/null @@ -1,61 +0,0 @@ -# Scalar-replacement of short-lived RECORD allocations (jolt-15jq). The pass -# already folds the const-key MAP-literal form ((:k {:k a ..}) -> a and drops a -# non-escaping let-bound map); this extends it to record CONSTRUCTORS. A record -# ctor (->Rec a b ..) is a positional struct whose declared field order lives in -# the record-shapes registry, so a field read on a non-escaping ctor result folds -# to the corresponding positional arg and the allocation disappears. -# -# Probe: count occurrences of the ctor var "->V3" in the analyzed IR. Folded => -# the ctor is gone (0). Mirrors type-infer-test's guard-counting harness. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/reader :as reader) - -(print "Scalar-replace of records (jolt-15jq)...") - -(os/setenv "JOLT_DIRECT_LINK" "1") -(def ctx (api/init-cached {:compile? true})) -(api/eval-string ctx "(ns srr)") -(api/eval-string ctx "(defrecord V3 [r g b])") - -(defn ctors [src] - (length (string/find-all "->V3" - (string/format "%p" (backend/analyze-form ctx (reader/parse-string src)))))) -(defn ev [src] (api/eval-string ctx src)) - -# --- direct form: (:field (->V3 a b c)) -> the positional arg ---------------- -(assert (= 0 (ctors "(fn [] (:r (->V3 1 2 3)))")) "direct record lookup :r -> arg, ctor gone") -(assert (= 0 (ctors "(fn [] (:g (->V3 1 2 3)))")) "direct record lookup :g -> arg, ctor gone") -(assert (= 0 (ctors "(fn [] (:b (->V3 1 2 3)))")) "direct record lookup :b -> arg, ctor gone") -# pure non-constant args fold too (each discarded sibling is pure) -(assert (= 0 (ctors "(fn [a b] (:r (->V3 (+ a 1) (* b 2) 7)))")) "direct fold with pure arith args") - -# --- let form: non-escaping let-bound record, field reads -> args ------------ -(assert (= 0 (ctors "(fn [a b c] (let [v (->V3 a b c)] (+ (:r v) (:g v) (:b v))))")) "let-bound record, all field reads folded") -(assert (= 0 (ctors "(fn [a b c] (let [v (->V3 a b c)] (:r v)))")) "let-bound record, single field read folded (siblings discarded, pure)") - -# --- sound fallbacks: keep the allocation ------------------------------------ -# escaping record (passed to a sink) must NOT be folded -(assert (>= (ctors "(fn [sink a b c] (let [v (->V3 a b c)] (sink v) (:r v)))") 1) "escaping record keeps the allocation") -# returning the record escapes it -(assert (>= (ctors "(fn [a b c] (->V3 a b c))") 1) "returned record keeps the allocation") -# a non-field key read (:jolt/deftype is a virtual key) -> not folded, keep alloc -(assert (>= (ctors "(fn [a b c] (let [v (->V3 a b c)] (:jolt/deftype v)))") 1) ":jolt/deftype lookup keeps the allocation") - -# --- correctness: folded path evaluates identically ------------------------- -(assert (= 1 (ev "((fn [] (:r (->V3 1 2 3))))")) "direct :r value") -(assert (= 2 (ev "((fn [] (:g (->V3 1 2 3))))")) "direct :g value") -(assert (= 3 (ev "((fn [] (:b (->V3 1 2 3))))")) "direct :b value") -(assert (= 6 (ev "((fn [a b c] (let [v (->V3 a b c)] (+ (:r v) (:g v) (:b v)))) 1 2 3)")) "let-bound sum value") -(assert (= 10 (ev "((fn [a b] (:r (->V3 (+ a 1) (* b 2) 7))) 9 5)")) "arith-arg direct value") -# correctness of the kept-allocation fallbacks -(assert (= 1 (ev "((fn [sink a b c] (let [v (->V3 a b c)] (sink v) (:r v))) (fn [_] nil) 1 2 3)")) "escaping record reads correctly") -(assert (= "srr.V3" (ev "((fn [a b c] (let [v (->V3 a b c)] (:jolt/deftype v))) 1 2 3)")) ":jolt/deftype reads the type tag") - -# --- nested records fold compositionally (bottom-up) ------------------------- -(api/eval-string ctx "(defrecord Ray [orig dir])") -# (:r (:orig (->Ray (->V3 a b c) d))): inner ctors both fold away -(assert (= 0 (ctors "(fn [a b c d] (:r (:orig (->Ray (->V3 a b c) d))))")) "nested record reads fold both ctors") -(assert (= 7 (ev "((fn [a b c d] (:r (:orig (->Ray (->V3 a b c) d)))) 7 8 9 0)")) "nested record fold value") - -(print "Scalar-replace of records passed!") diff --git a/test/integration/sci-bootstrap-test.janet b/test/integration/sci-bootstrap-test.janet deleted file mode 100644 index 38285af..0000000 --- a/test/integration/sci-bootstrap-test.janet +++ /dev/null @@ -1,122 +0,0 @@ -(use ../../src/jolt/evaluator) -(use ../../src/jolt/types) -(use ../../src/jolt/reader) -(use ../../src/jolt/api) -(use ../../src/jolt/reader) -# SCI is a clj/cljs-targeted library: its .cljc sources select implementation -# via #?(:clj ...) and have no :jolt branches — load it under clj-compat -# features (spec 02-reader S18: feature sets are a property of the loading -# context; the portable default is #{:jolt :default}). -(reader-features-set! ["jolt" "clj" "default"]) - -(def ctx (init-cached)) -# Best-effort loading: SCI's clj-targeted requires (borkdude.graal.locking, -# clojure.tools.reader.*) don't exist on this host; a strict require would fail -# whole ns forms and cascade. See maybe-require-ns. -(put (ctx :env) :lenient-require? true) - -(printf "Loading SCI stubs...\n") -(defn load-stubs [ctx filepath] - (var s (slurp filepath)) - (var count 0) - (while (> (length (string/trim s)) 0) - (def [form rest] (parse-next s)) - (set s rest) - (++ count) - (when (not (nil? form)) - (eval-form ctx @{} form))) - (printf " Loaded %d stub forms\n" count)) - -(load-stubs ctx "src/jolt/clojure/sci/lang_stubs.clj") -(load-stubs ctx "src/jolt/clojure/sci/io_stubs.clj") -(load-stubs ctx "src/jolt/clojure/sci/host_stubs.clj") - -# namespaces.cljc copies vars out of Jolt's own clojure.string/set/walk/edn, so -# make sure those are loaded before it runs. -(each lib ["clojure.string" "clojure.set" "clojure.walk" "clojure.edn"] - (protect (eval-form ctx @{} (first (parse-next (string "(require '[" lib "])")))))) - -(defn load-file [ctx path] - (var s (slurp path)) - (var count 0) - (var ok 0) - (var fail 0) - (var failures @[]) - (while (> (length (string/trim s)) 0) - (def [form rest] (parse-next s)) - (set s rest) - (++ count) - (if (not (nil? form)) - (do - (printf "eval form %d..." count) - (flush) - (if (try - (do (eval-form ctx @{} form) true) - ([err fib] - (printf " FAIL: %q\n" err) - (when (os/getenv "SCI_TRACE") (debug/stacktrace fib "")) - (array/push failures {:form-number count :error (string err) :form (string form)}) - false)) - (do - (printf " OK\n") - (++ ok)) - (++ fail))))) - {:ok ok :fail fail :total count :failures failures}) - -(def sci-base "vendor/sci/src/sci") - -(def load-order @[ - ["impl/macros.cljc" nil] - ["impl/protocols.cljc" nil] - ["impl/types.cljc" nil] - ["impl/unrestrict.cljc" nil] - ["impl/vars.cljc" nil] - ["lang.cljc" nil] - ["impl/utils.cljc" nil] - ["ctx_store.cljc" nil] - ["impl/deftype.cljc" nil] - ["impl/records.cljc" nil] - ["impl/core_protocols.cljc" nil] - ["impl/hierarchies.cljc" nil] - # pure-Clojure macro/expander modules (loadable from SCI's real source) - ["impl/destructure.cljc" nil] - ["impl/doseq_macro.cljc" nil] - ["impl/for_macro.cljc" nil] - ["impl/fns.cljc" nil] - ["impl/multimethods.cljc" nil] - ["impl/namespaces.cljc" nil] - ["core.cljc" nil] -]) - -(var total-ok 0) -(var total-fail 0) -(var all-failures @[]) - -(each [file expected-ns] load-order - (def path (string sci-base "/" file)) - (printf "\n=== Loading %s ===\n" file) - (def result (load-file ctx path)) - (printf " Result: %d ok, %d fail, %d total\n" (result :ok) (result :fail) (result :total)) - (+= total-ok (result :ok)) - (+= total-fail (result :fail)) - (each f (result :failures) - (array/push all-failures {:file file :form-number (f :form-number) :error (f :error) :form (f :form)}))) - -(printf "\n==============================\n") -(printf "TOTAL: %d ok, %d fail, %d total\n" total-ok total-fail (+ total-ok total-fail)) -(printf "==============================\n") - -(printf "\ncurrent ns: %s\n" (ctx-current-ns ctx)) -(printf "sci.core exists: %q\n" (not (nil? (ctx-find-ns ctx "sci.core")))) -(printf "total namespaces: %d\n" (length (keys ((ctx :env) :namespaces)))) - -(when (> (length all-failures) 0) - (printf "\n=== FAILURES ===\n") - (each f all-failures - (printf "[%s:%d] %s\n" (f :file) (f :form-number) (f :error)) - (printf " form: %s\n" (f :form)))) - -# Regression guard: every form in the loaded SCI modules must evaluate cleanly. -(assert (= 0 total-fail) - (string total-fail " SCI form(s) failed to load (see FAILURES above)")) -(print "\nAll SCI bootstrap forms loaded successfully.") diff --git a/test/integration/sci-runtime-test.janet b/test/integration/sci-runtime-test.janet deleted file mode 100644 index c647ca1..0000000 --- a/test/integration/sci-runtime-test.janet +++ /dev/null @@ -1,101 +0,0 @@ -(use ../../src/jolt/evaluator) -(use ../../src/jolt/types) -(use ../../src/jolt/reader) -(use ../../src/jolt/api) -(use ../../src/jolt/reader) -# SCI is a clj/cljs-targeted library: its .cljc sources select implementation -# via #?(:clj ...) and have no :jolt branches — load it under clj-compat -# features (spec 02-reader S18: feature sets are a property of the loading -# context; the portable default is #{:jolt :default}). -(reader-features-set! ["jolt" "clj" "default"]) - -(defn- load-stubs [ctx filepath] - (var s (slurp filepath)) - (while (> (length (string/trim s)) 0) - (def [form rest] (parse-next s)) - (set s rest) - (when (not (nil? form)) - (protect (eval-form ctx @{} form))))) - -(defn- load-file [ctx path] - (var s (slurp path)) - (while (> (length (string/trim s)) 0) - (def [form rest] (parse-next s)) - (set s rest) - (when (not (nil? form)) - # Tolerant: SCI's clojure.core registration maps reference the full - # clojure.core surface (redundant for Jolt's native core); skip forms - # that don't resolve rather than aborting the bootstrap. - (protect (eval-form ctx @{} form))))) - -# Run from project root so paths resolve -(def root (if (has-value? (dyn :syspath) 0) (first (dyn :syspath)) ".")) - -(def ctx (init-cached)) - -(load-stubs ctx (string root "/src/jolt/clojure/sci/lang_stubs.clj")) -(load-stubs ctx (string root "/src/jolt/clojure/sci/io_stubs.clj")) - -(def sci-base (string root "/vendor/sci/src/sci")) -(each file ["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/namespaces.cljc" "core.cljc"] - (load-file ctx (string sci-base "/" file))) - -# ── Verify sci.lang NS and Type ───────────────────────────────── -(assert (not (nil? (ctx-find-ns ctx "sci.lang"))) - "sci.lang namespace exists") -(assert (not (nil? (ctx-find-ns ctx "sci.core"))) - "sci.core namespace exists") - -# sci.lang has Type constructor -(def sci-lang (ctx-find-ns ctx "sci.lang")) -(def type-var (ns-find sci-lang "Type")) -(assert (not (nil? type-var)) "sci.lang/Type var exists") -(def ->Type (ns-find sci-lang "->Type")) -(assert (not (nil? ->Type)) "sci.lang/->Type constructor exists") - -# Instantiate a Type and check field access -(def type-inst ((var-get type-var) {:sci.impl/type-name "user.Foo"})) -(assert (table? type-inst) "Type instance is a table") -(assert (not (nil? (get type-inst :jolt/deftype))) "Type instance has deftype tag") -(assert (= "user.Foo" (get (get type-inst :data) :sci.impl/type-name)) "Type field access via data") - -# ── Verify sci.lang/Var ───────────────────────────────────────── -(def var-ctor-var (ns-find sci-lang "Var")) -(assert (not (nil? var-ctor-var)) "sci.lang/Var constructor exists") - -(def test-var ((var-get var-ctor-var) 42 'my-var nil nil nil nil nil)) -(assert (table? test-var) "Var instance is a table") -(assert (= 42 (get test-var :root)) "Var deref") - -# var? check — SCI Var is not a Jolt var but is a table with proper fields -(assert (not (nil? test-var)) "Var instance is not nil") - -# ── Verify sci.impl.types/IBox protocol ───────────────────────── -(def types-ns (ctx-find-ns ctx "sci.impl.types")) -(def vars-ns (ctx-find-ns ctx "sci.impl.vars")) -(assert (not (nil? types-ns)) "sci.impl.types namespace exists") -(assert (not (nil? vars-ns)) "sci.impl.vars namespace exists") - -(def ibox-getVal (ns-find types-ns "getVal")) -(def ibox-setVal (ns-find types-ns "setVal")) -(assert (not (nil? ibox-getVal)) "sci.impl.types/getVal exists") -(assert (not (nil? ibox-setVal)) "sci.impl.types/setVal exists") - -# Test IBox setVal/getVal exist but skip dispatch (SCI protocol machinery not fully booted) -(assert (function? (var-get ibox-setVal)) "sci.impl.types/setVal is callable") -(assert (function? (var-get ibox-getVal)) "sci.impl.types/getVal is callable") - -# ── Verify sci.impl.vars/IVar protocol methods exist ───────────── -(def ivar-toSymbol (ns-find vars-ns "toSymbol")) -(def ivar-hasRoot (ns-find vars-ns "hasRoot")) -(assert (not (nil? ivar-toSymbol)) "sci.impl.vars/toSymbol exists") -(assert (not (nil? ivar-hasRoot)) "sci.impl.vars/hasRoot exists") - -# ── Verify SCI eval function exists ───────────────────────────── -(def sci-core (ctx-find-ns ctx "sci.core")) -(assert (not (nil? sci-core)) "sci.core namespace exists") -(printf "\nAll SCI runtime tests passed!\n") diff --git a/test/integration/self-host-test.janet b/test/integration/self-host-test.janet deleted file mode 100644 index 3e1bcc3..0000000 --- a/test/integration/self-host-test.janet +++ /dev/null @@ -1,96 +0,0 @@ -# End-to-end proof of the self-hosting pipeline: a reader form is analyzed by the -# PORTABLE Clojure analyzer (jolt.analyzer, in jolt-core) into host-neutral IR, -# then the Janet back end lowers the IR to a Janet form and evaluates it. No use -# of compiler.janet's analyzer — this is the Clojure-in-Clojure front end. -(import ../../src/jolt/backend :as backend) -(use ../../src/jolt/api) -(use ../../src/jolt/reader) -(use ../../src/jolt/types) - -(defn ce [ctx s] (normalize-pvecs (backend/compile-and-eval ctx (parse-string s)))) - -(print "self-host pipeline (Clojure analyzer -> IR -> Janet)...") -(let [ctx (init-cached)] - # primitives + control flow - (assert (= 3 (ce ctx "(+ 1 2)")) "+") - (assert (= 6 (ce ctx "(* 2 3)")) "*") - (assert (= :a (ce ctx "(if true :a :b)")) "if true") - (assert (= :b (ce ctx "(if false :a :b)")) "if false") - (assert (= 10 (ce ctx "(let [x 4 y 6] (+ x y))")) "let") - (assert (= 6 (ce ctx "(do 1 2 6)")) "do") - - # literals - (assert (= [2 3 4] (ce ctx "(map inc [1 2 3])")) "vector literal + core fn") - (assert (= 1 (ce ctx "(get {:a 1 :b 2} :a)")) "map literal") - (assert (= 42 (ce ctx "(quote 42)")) "quote literal") - - # def + global reference (name-based var resolution) - (ce ctx "(def base 100)") - (assert (= 142 (ce ctx "(+ base 42)")) "def + later ref") - - # fn / defn (defn is a macro -> expand -> def of fn*) - (ce ctx "(defn add [a b] (+ a b))") - (assert (= 7 (ce ctx "(add 3 4)")) "defn") - (assert (= 49 (ce ctx "((fn [x] (* x x)) 7)")) "anon fn") - - # recursion through the var cell (no recur needed) - (ce ctx "(defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))") - (assert (= 55 (ce ctx "(fib 10)")) "recursive fib via var") - - # multi-arity + variadic - (ce ctx "(defn arity ([a] a) ([a b] (+ a b)) ([a b & more] (apply + a b more)))") - (assert (= 5 (ce ctx "(arity 5)")) "multi-arity 1") - (assert (= 7 (ce ctx "(arity 3 4)")) "multi-arity 2") - (assert (= 15 (ce ctx "(arity 1 2 3 4 5)")) "multi-arity variadic") - - # loop / recur - (assert (= 15 (ce ctx "(loop [i 0 acc 0] (if (< i 6) (recur (inc i) (+ acc i)) acc))")) "loop/recur") - # recur directly in a fixed-arity fn - (assert (= 15 (ce ctx "((fn [n acc] (if (zero? n) acc (recur (dec n) (+ acc n)))) 5 0)")) "recur in fn") - # try / catch / finally - (assert (= "caught" (ce ctx "(try (throw 42) (catch Exception e \"caught\"))")) "try/catch") - (assert (= 7 (ce ctx "(try 7 (finally 0))")) "try/finally") - - # higher-order + nesting - (assert (= 15 (ce ctx "(reduce + (map inc [0 1 2 3 4]))")) "reduce+map")) - -# eval-toplevel routing: :compile? IS the self-hosted pipeline now — the only -# compile path. Forms the analyzer can't handle (stateful / destructuring) fall -# back to the interpreter, with the same observable results. -(print "self-host via eval-toplevel routing...") -(let [ctx (init-cached {:compile? true})] - (defn ev [s] (normalize-pvecs (eval-one ctx (parse-string s)))) - (assert (= 3 (ev "(+ 1 2)")) "tl +") - (ev "(defn sq [x] (* x x))") # def via self-host - (assert (= 81 (ev "(sq 9)")) "tl defn") - (ev "(defmacro twice [x] (list (quote do) x x))") # stateful -> interp fallback - (assert (= 5 (ev "(do (twice 1) 5)")) "tl macro fallback") - (assert (= [1 2 3] (ev "(let [{:keys [a b c]} {:a 1 :b 2 :c 3}] [a b c])")) "tl destructuring fallback") - (assert (= 15 (ev "(reduce + (range 6))")) "tl reduce/range") - # Proof the self-hosted pipeline actually ran: only backend/ensure-analyzer - # populates jolt.analyzer. An interpret-only ctx never loads it. - (assert (pos? (length ((ctx-find-ns ctx "jolt.analyzer") :mappings))) "analyzer loaded under :compile?")) -# Interpret mode now loads the analyzer too — for compiled macro expansion -# (ensure-macros-compiled!, every mode). The fully-interpreted oracle is the -# :compile-macros? false ctx, which must never touch the analyzer. -(let [ctx (init-cached {})] - (eval-one ctx (parse-string "(+ 1 2)")) - (assert (pos? (length ((ctx-find-ns ctx "jolt.analyzer") :mappings))) - "analyzer loaded when interpreting (compiled expanders)")) -(let [ctx (init-cached {:compile-macros? false})] - (eval-one ctx (parse-string "(+ 1 2)")) - (assert (zero? (length ((ctx-find-ns ctx "jolt.analyzer") :mappings))) - "analyzer NOT loaded in the interpreted-macro oracle")) - -# clojure.core overlay: fns moved from core.janet to jolt-core/clojure/core.clj -# load into clojure.core at init and work the same compiled or interpreted. -(print "clojure.core overlay (Clojure-defined core fns)...") -(each opts [{:compile? true} {}] - (let [ctx (init-cached opts)] - (defn ev [s] (normalize-pvecs (eval-one ctx (parse-string s)))) - (assert (= 1 (ev "(ffirst [[1 2] [3 4]])")) "ffirst") - (assert (= [2] (ev "(nfirst [[1 2] [3 4]])")) "nfirst") - (assert (= 2 (ev "(fnext [1 2 3])")) "fnext") - (assert (= [3 4] (ev "(nnext [1 2 3 4])")) "nnext"))) - -(print "self-host pipeline passed!") diff --git a/test/integration/selmer-test.janet b/test/integration/selmer-test.janet deleted file mode 100644 index c5a646a..0000000 --- a/test/integration/selmer-test.janet +++ /dev/null @@ -1,61 +0,0 @@ -# Selmer acceptance (jolt-ea7): load the real Selmer template engine from -# ~/src/selmer and render through its full pipeline — the java.time shims -# (DateTimeFormatter/Instant/ZoneId/LocalDateTime), the java.io shims -# (StringReader/StringBuilder + char-array readers), vector :import sharing -# deftype ctors, and :refer :all. SKIPS cleanly if the checkout is absent -# (CI has no ~/src/selmer); the shim surface itself is covered by -# test/spec/host-interop-spec.janet either way. - -(import ../../src/jolt/api :as api) -(use ../../src/jolt/reader) - -(def selmer-src (string (os/getenv "HOME") "/src/selmer/src")) -(def selmer-res (string (os/getenv "HOME") "/src/selmer/resources")) - -(if (nil? (os/stat (string selmer-src "/selmer/parser.clj"))) - (print "selmer-test: ~/src/selmer not present, skipping") - (do - (reader-features-set! ["jolt" "clj" "default"]) - (def ctx (api/init {:paths [selmer-src selmer-res]})) - - (print "loading selmer.parser...") - (api/eval-string ctx "(require (quote [selmer.parser :as sp]))") - (print " ok") - - (defn render [tpl ctx-map-src] - (api/eval-string ctx (string "(sp/render " (describe tpl) " " ctx-map-src ")"))) - - (print "variable + filter...") - (assert (= "Hello WORLD!" (render "Hello {{name|upper}}!" "{:name \"world\"}"))) - (print " ok") - - (print "date filter (java.time path)...") - (def d (render "{{d|date:yyyy-MM-dd}}" "{:d #inst \"2020-03-05T10:00:00Z\"}")) - (assert (peg/match '(* :d :d :d :d "-" :d :d "-" :d :d -1) d) - (string "date filter renders a yyyy-MM-dd date, got: " d)) - (print " ok") - - (print "if / for tags...") - (assert (= "YES" (render "{% if ok %}YES{% else %}NO{% endif %}" "{:ok true}"))) - (assert (= "NO" (render "{% if ok %}YES{% else %}NO{% endif %}" "{:ok false}"))) - (assert (= "1,2,3," (render "{% for x in xs %}{{x}},{% endfor %}" "{:xs [1 2 3]}"))) - (print " ok") - - (print "nested lookup + escaping...") - (assert (= "7" (render "{{m.a.b}}" "{:m {:a {:b 7}}}"))) - (assert (= "<b>&" (render "{{x}}" "{:x \"&\"}"))) - (print " ok") - - (print "file templates (render-file + cache)...") - (def tpl-dir (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-selmer-test")) - (os/mkdir tpl-dir) - (spit (string tpl-dir "/t.html") "File says {{x|upper}}") - (api/eval-string ctx (string "(selmer.util/set-custom-resource-path! " (describe (string tpl-dir "/")) ")")) - (assert (= "File says HI" - (api/eval-string ctx "(sp/render-file \"t.html\" {:x \"hi\"})"))) - # second render goes through the template cache (last-modified check) - (assert (= "File says AGAIN" - (api/eval-string ctx "(sp/render-file \"t.html\" {:x \"again\"})"))) - (print " ok") - - (print "selmer-test: all passed"))) diff --git a/test/integration/shape-transparency-test.janet b/test/integration/shape-transparency-test.janet deleted file mode 100644 index 496803f..0000000 --- a/test/integration/shape-transparency-test.janet +++ /dev/null @@ -1,64 +0,0 @@ -# Shape-record transparency (jolt-t34 Round 1). A shape-rec is the compiler's -# cheap representation for a constant-key map literal — a Janet tuple -# [descriptor v0 v1 ...]. Every map operation must treat it EXACTLY like the -# equivalent struct map, so a shape value is transparent wherever it flows. -# These build shape-recs directly via the runtime (shape-for + tuple) and -# assert each op matches the struct map's behavior. -(use ../../src/jolt/types) -(use ../../src/jolt/core) - -(var fails 0) -(defn check [label got want] - (if (deep= got want) (print " ok " label) - (do (++ fails) (printf " FAIL %s: got %j want %j" label got want)))) - -# {:a 1 :b 2} as a shape-rec and as a struct — they must be indistinguishable -(def SH (shape-for [:a :b])) -(def r (tuple SH 1 2)) -(def s {:a 1 :b 2}) - -# --- access ------------------------------------------------------------------ -(check "get hit" (core-get r :a nil) 1) -(check "get hit 2" (core-get r :b nil) 2) -(check "get miss" (core-get r :z :d) :d) -(check "count" (core-count r) 2) -(check "contains? hit" (core-contains? r :a) true) -(check "contains? miss" (core-contains? r :z) false) -(check "map?" (core-map? r) true) - -# --- update (returns something that reads back correctly) -------------------- -(check "assoc existing" (core-get (core-assoc r :a 9) :a nil) 9) -(check "assoc new key" (core-get (core-assoc r :c 3) :c nil) 3) -(check "assoc keeps others" (core-get (core-assoc r :c 3) :b nil) 2) -(check "dissoc" (core-get (core-dissoc r :a) :a :gone) :gone) -(check "dissoc keeps" (core-get (core-dissoc r :a) :b nil) 2) - -# --- enumeration: entries via the central seq normalizer (what keys/vals/seq/ -# reduce-kv in the overlay all flow through) — order-independent --------------- -(defn entryset [m] (sorted (map |(string/format "%j" $) (realize-for-iteration m)))) -(check "entries match struct" (entryset r) (entryset s)) -(check "count of seq" (length (core-seq r)) 2) -(check "first is a 2-entry" (length (core-first r)) 2) - -# --- equality: a shape-rec equals the same struct map and vice versa --------- -(check "= shape vs struct" (jolt-equal? r s) true) -(check "= struct vs shape" (jolt-equal? s r) true) -(check "= shape vs shape" (jolt-equal? r (tuple (shape-for [:a :b]) 1 2)) true) -(check "not= diff value" (jolt-equal? r (tuple (shape-for [:a :b]) 1 9)) false) -(check "not= diff shape" (jolt-equal? r (tuple (shape-for [:a :b :c]) 1 2 3)) false) -(check "not= vs vector" (jolt-equal? r [1 2]) false) - -# --- IFn: a map is callable as a key lookup ---------------------------------- -(check "call as fn" (jolt-call r :a) 1) -(check "call as fn miss default" (jolt-call r :z :d) :d) - -# --- nil/false values are present (shape-recs store them positionally) -------- -(def rn (tuple (shape-for [:a :b]) nil false)) -(check "nil value present" (core-contains? rn :a) true) -(check "nil value get" (core-get rn :a :d) nil) -(check "false value get" (core-get rn :b :d) false) -(check "count with nils" (core-count rn) 2) - -(if (> fails 0) - (error (string "shape-transparency: " fails " failing check(s)")) - (print "\nShape transparency passed!")) diff --git a/test/integration/sorted-rbtree-test.janet b/test/integration/sorted-rbtree-test.janet deleted file mode 100644 index 6c5094f..0000000 --- a/test/integration/sorted-rbtree-test.janet +++ /dev/null @@ -1,63 +0,0 @@ -# sorted-map / sorted-set are a red-black tree (jolt-0hbr), ported from the -# ClojureScript PersistentTreeMap. assoc/dissoc are O(log n); the old sorted- -# vector rep was O(n) per op (O(n^2) to build — 55s for 2000 entries). This -# drives big shuffled insert/delete sequences (which stress rebalancing) through -# the built binary and checks ordering + a sub-quadratic build time. -(import ../../src/jolt/api :as api) - -(print "sorted-map/set red-black tree (jolt-0hbr)...") - -(os/setenv "JOLT_DIRECT_LINK" "1") -(def ctx (api/init-cached {:compile? true})) -(defn ev [s] (api/eval-string ctx s)) - -(var fails 0) -(defn check [label got expected] - (if (= got expected) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %p got %p" label expected got)))) - -# --- ordering is maintained through heavy rebalancing ----------------------- -(check "shuffled 500 keys come back sorted" - (ev "(= (vec (keys (apply sorted-map (interleave (shuffle (vec (range 500))) (range 500))))) (vec (range 500)))") - true) -(check "sorted-set of shuffled 500 is sorted" - (ev "(= (vec (apply sorted-set (shuffle (vec (range 500))))) (vec (range 500)))") - true) - -# --- delete maintains order + correctness (stresses delete rebalancing) ------ -(check "dissoc every even key, odds remain in order" - (ev "(let [m (apply sorted-map (interleave (shuffle (vec (range 200))) (range 200))) - m2 (reduce dissoc m (range 0 200 2))] - (= (vec (keys m2)) (vec (range 1 200 2))))") - true) -(check "disj down to empty then rebuild" - (ev "(let [s (apply sorted-set (range 100)) - s2 (reduce disj s (shuffle (vec (range 100))))] - (and (= 0 (count s2)) (= [1 2 3] (vec (conj s2 3 1 2 1)))))") - true) - -# --- comparator + lookup correctness ---------------------------------------- -(check "custom comparator (descending)" - (ev "(= (vec (keys (sorted-map-by > 1 :a 3 :c 2 :b))) [3 2 1])") true) -(check "get/contains go through comparator (1 vs 1.0)" - (ev "(and (contains? (sorted-set 1 2 3) 1.0) (= :a (get (sorted-map 1 :a) 1.0)))") true) -(check "first-inserted key kept on value replace" - (ev "(first (first (assoc (sorted-map 1 :a) 1.0 :b)))") 1) - -# --- count + subseq ---------------------------------------------------------- -(check "count after mixed ops" - (ev "(count (-> (apply sorted-map (interleave (range 50) (range 50))) (dissoc 10 20 30) (assoc 100 1 101 2)))") 49) -(check "subseq range" - (ev "(= (vec (map first (subseq (apply sorted-map (interleave (range 20) (range 20))) >= 5 < 9))) [5 6 7 8])") true) - -# --- complexity: building a big map must be sub-quadratic -------------------- -(def t0 (os/clock)) -(ev "(count (loop [i 0 m (sorted-map)] (if (< i 5000) (recur (inc i) (assoc m (mod (* i 7919) 10007) i)) m)))") -(def elapsed (- (os/clock) t0)) -(printf " 5000 assocs: %.2fs" elapsed) -(if (< elapsed 8.0) - (print " ok sorted assoc is sub-quadratic (< 8s)") - (do (++ fails) (printf " FAIL sorted build too slow (%.1fs) — O(n^2)?" elapsed))) - -(if (> fails 0) (do (printf "sorted-rbtree: %d FAILED" fails) (os/exit 1)) - (print "sorted-rbtree (jolt-0hbr) passed!")) diff --git a/test/integration/staged-bootstrap-test.janet b/test/integration/staged-bootstrap-test.janet deleted file mode 100644 index 7f2a54c..0000000 --- a/test/integration/staged-bootstrap-test.janet +++ /dev/null @@ -1,63 +0,0 @@ -# Staged-bootstrap soundness (jolt-vcx, under epic jolt-tzo). -# -# The self-hosted compiler's structural deps — second/peek/subvec/mapv/update — -# now come from the Clojure kernel tier (jolt-core/clojure/core/00-kernel.clj), -# bootstrap-compiled into clojure.core BEFORE the analyzer is built. This pins -# the two properties that make that safe: -# -# 1. Compile mode: the analyzer (which itself calls second/peek/subvec/mapv) -# compiles analyzer-exercising forms correctly — the exact case that broke -# when `second` was a plain overlay fn: (first {:a 1}) / (key (first ...)). -# 2. Bootstrap FIXPOINT: rebuilding the compiler (rebuild-compiler!) against the -# now Clojure-defined core still yields a correct compiler. This is the -# soundness gate for every future fractal turn (S2 -> S3). - -(use ../../src/jolt/api) -(import ../../src/jolt/backend :as backend) - -(var failures 0) - -# Each probe is a jolt boolean expression; compared with jolt's own `=`. -(def probes - ["(= 2 (second [1 2 3]))" - "(= nil (second [1]))" - "(= 3 (peek [1 2 3]))" - "(= 1 (peek (list 1 2 3)))" - "(= nil (peek []))" - "(= [2 3] (subvec [1 2 3 4 5] 1 3))" - "(= [3 4 5] (subvec [1 2 3 4 5] 2))" - "(= [2 3 4] (mapv inc [1 2 3]))" - "(= [11 22 33] (mapv + [1 2 3] [10 20 30]))" - "(= {:a 2} (update {:a 1} :a inc))" - "(= {:a 1 :b 1} (update {:a 1} :b (fnil inc 0)))" - # Regression: these run the analyzer's own second/map-pair path in compile mode. - "(= [:a 1] (first {:a 1}))" - "(= :a (key (first {:a 1})))" - "(= 1 (val (first {:a 1})))" - "(= 3 (let [[a b] [1 2]] (+ a b)))" - "(= 3 (loop [i 0 acc 0] (if (< i 3) (recur (inc i) (+ acc i)) acc)))"]) - -(defn- run-probes [ctx label] - (each prog probes - (def got (protect (eval-string ctx prog))) - (unless (and (got 0) (= (got 1) true)) - (++ failures) - (printf "FAIL [%s] %s => %s" label prog - (if (got 0) (string/format "%q" (got 1)) (string "ERR:" (got 1))))))) - -# Interpret mode: kernel tier interpreted, no analyzer involved. -(run-probes (init {}) "interpret") - -# Compile mode: kernel tier bootstrap-compiled, analyzer built against it. -(def cctx (init {:compile? true})) -(run-probes cctx "compile") - -# Fixpoint: rebuild the compiler against the current (Clojure-defined) core and -# re-run. A correct compiler recompiled on the language it just defined stays -# correct. -(backend/rebuild-compiler! cctx) -(run-probes cctx "compile+rebuilt") - -(if (pos? failures) - (do (printf "staged-bootstrap: %d failure(s)" failures) (os/exit 1)) - (print "staged-bootstrap: all probes passed (interpret, compile, compile+rebuilt)")) diff --git a/test/integration/struct-hint-test.janet b/test/integration/struct-hint-test.janet deleted file mode 100644 index 3fba4f2..0000000 --- a/test/integration/struct-hint-test.janet +++ /dev/null @@ -1,79 +0,0 @@ -# Type hints driving keyword-lookup specialization (jolt-94n). A local hinted -# ^:struct (a plain struct/record map) or ^Record (a defrecord/deftype) lets a -# constant-keyword lookup skip the :jolt/type guard and emit a bare get -# (~20ns vs ~36ns), the way Clojure type hints let the compiler specialize. -# Covers both (:k m) and (get m :k), hint propagation through inlining, the -# ^Record path, the JOLT_CHECK_HINTS dev aid, and that accurate hints preserve -# results. An inaccurate hint is a programmer error (like a wrong ^String): the -# raw get returns the wrong value, surfaced only under JOLT_CHECK_HINTS. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/reader :as reader) - -(print "Type hints (jolt-94n)...") - -(os/setenv "JOLT_DIRECT_LINK" "1") # inline on, so hint-through-inline is exercised -(def ctx (api/init-cached {:compile? true})) -(api/eval-string ctx "(ns sh)") -(api/eval-string ctx "(defrecord Vec3r [r g b])") -(each s ["(defn v3 [r g b] {:r r :g g :b b})" - "(defn dot [^:struct l ^:struct r] (+ (+ (* (:r l) (:r r)) (* (:g l) (:g r))) (* (:b l) (:b r))))" - "(defn sub [^:struct l ^:struct r] {:r (- (:r l) (:r r)) :g (- (:g l) (:g r)) :b (- (:b l) (:b r))})" - "(defn lensq [^:struct v] (dot v v))"] - (api/eval-string ctx s)) - -(defn guards [src] - (def code (string/format "%p" (backend/emit-ir ctx (backend/analyze-form ctx (reader/parse-string src))))) - (length (string/find-all ":jolt/type" code))) - -# --- guard removal ---------------------------------------------------------- -(assert (= 1 (guards "(fn [v] (:r v))")) "unhinted (:r v) keeps the guard") -(assert (= 0 (guards "(fn [^:struct v] (:r v))")) "^:struct (:r v) drops the guard") -(assert (= 0 (guards "(fn [^Vec3r v] (:r v))")) "^Record (:r v) drops the guard") -(assert (= 1 (guards "(fn [^String v] (:r v))")) "^String (not a record) still guards") -(assert (= 0 (guards "(fn [^:struct v] (+ (+ (:r v) (:g v)) (:b v)))")) "all three hinted lookups bare") -(assert (= 0 (guards "(fn [^:struct v] (lensq v))")) "hint survives through an inlined call") -# hints work on let bindings too, not just params (init is a plain local here, -# so the only candidate guard is the hinted (:r v)) -(assert (= 0 (guards "(fn [^:struct s] (let [^:struct v s] (:r v)))")) "^:struct on a let binding drops the guard") -(assert (= 1 (guards "(fn [s] (let [v s] (:r v)))")) "unhinted let binding keeps the guard") -# (get m :k) gets the same treatment as (:k m) -(assert (= 1 (guards "(fn [m] (get m :k))")) "unhinted (get m :k) is guarded-inline") -(assert (= 0 (guards "(fn [^:struct m] (get m :k))")) "^:struct (get m :k) drops the guard") -(assert (= 0 (guards "(fn [^Vec3r m] (get m :k 0))")) "^Record (get m :k d) drops the guard") -# a variable (non-constant) key isn't a keyword literal, so the inline doesn't -# fire — it falls through to core-get, which still indexes correctly. -(assert (= 2 (api/eval-string ctx "((fn [m kk] (get m kk)) {:a 2} :a)")) "variable-key get via core-get") -(assert (= 10 (api/eval-string ctx "((fn [m i] (get m i)) [10 20] 0)")) "variable-key get indexes a vector") - -# --- correctness (accurate hints preserve results) -------------------------- -(assert (= 32 (api/eval-string ctx "(dot (v3 1 2 3) (v3 4 5 6))")) "hinted dot value") -(assert (= 14 (api/eval-string ctx "(lensq (v3 1 2 3))")) "hinted lensq (inline-flow) value") -(assert (= 7 (api/eval-string ctx "(:r (sub (v3 9 8 7) (v3 2 0 0)))")) "hinted sub field") -(api/eval-string ctx "(defn hit [^:struct ray ^:struct c] (lensq (sub (:origin ray) c)))") -(assert (= 48 (api/eval-string ctx "(hit {:origin (v3 5 5 5) :direction (v3 0 0 0)} (v3 1 1 1))")) - "hinted value through nested inline reads correctly") -(assert (= nil (api/eval-string ctx "((fn [^:struct m] (:absent m)) (v3 1 2 3))")) "hinted struct miss -> nil") -(assert (= 9 (api/eval-string ctx "((fn [^:struct m] (get m :absent 9)) (v3 1 2 3))")) "hinted get default") -# field access on a real record instance through a ^Record hint -(api/eval-string ctx "(defn vr-x [^Vec3r v] (:r v))") -(assert (= 5 (api/eval-string ctx "(vr-x (->Vec3r 5 6 7))")) "record field via ^Record hint") -# (get m :k) on assorted reps still matches core-get semantics (unhinted path) -(assert (= 2 (api/eval-string ctx "(get {:a 2} :a)")) "get struct present") -(assert (= nil (api/eval-string ctx "(get {:a 2} :z)")) "get struct miss") -(assert (= 1 (api/eval-string ctx "(get (hash-map :a 1 :x nil) :a)")) "get phm present") -(assert (= nil (api/eval-string ctx "(get (hash-map :a 1 :x nil) :x)")) "get phm nil value") -(assert (= 7 (api/eval-string ctx "(get (sorted-map :a 7) :a)")) "get sorted present") - -# --- checked mode: a lying hint throws (separate ctx with the flag on) ------- -(os/setenv "JOLT_CHECK_HINTS" "1") -(def cctx (api/init {:compile? true})) -(api/eval-string cctx "(ns ck)") -(api/eval-string cctx "(defn rd [^:struct m] (:a m))") -(assert (= 1 (api/eval-string cctx "(rd {:a 1 :b 2})")) "checked mode: accurate hint still works") -(let [r (protect (api/eval-string cctx "(rd (hash-map :a 1 :x nil))"))] - (assert (not (r 0)) "checked mode: lying ^:struct hint throws") - (assert (string/find "type hint violated" (string (r 1))) "checked-mode error is meaningful")) -(os/setenv "JOLT_CHECK_HINTS" nil) - -(print "Type hints passed!") diff --git a/test/integration/suite-worker.janet b/test/integration/suite-worker.janet deleted file mode 100644 index 63c7a36..0000000 --- a/test/integration/suite-worker.janet +++ /dev/null @@ -1,60 +0,0 @@ -# One-file worker for the clojure-test-suite battery. Loads the clojure.test -# shim, evaluates a single suite .cljc file, runs its deftests, and prints -# "pass fail error" to stdout. Used by the discovery pass to find files that -# hang under Jolt's eager evaluation (run under an external timeout). -(use ../../src/jolt/api) -(use ../../src/jolt/reader) -(use ../../src/jolt/evaluator) -(import ../../src/jolt/backend :as selfhost) - -(defn- parse-forms [src] - (var s src) (def fs @[]) (var go true) - (while (and go (> (length (string/trim s)) 0)) - (def r (protect (parse-next s))) - (if (not (r 0)) (set go false) - (let [p (r 1)] (set s (p 1)) (when (not (nil? (p 0))) (array/push fs (p 0)))))) - fs) - -# A helper, not a standalone test: it needs a .cljc path argument. When `jpm -# test` runs it with no args, no-op cleanly so it doesn't count as a failure. -(def path (get (dyn :args) 1)) - -(when path - # JOLT_COMPILE=1 runs the suite through the compile path (hybrid: hot forms - # compile, unsupported forms fall back to the interpreter) so the whole battery - # validates compile-mode correctness against the same baseline. - (def compile? (= "1" (os/getenv "JOLT_COMPILE"))) - # JOLT_SELFHOST=1 routes each form through the self-hosted pipeline (the - # portable Clojure analyzer + Janet back end, hybrid with interpreter fallback) - # so the whole battery validates the self-hosted compiler against the baseline. - (def selfhost? (= "1" (os/getenv "JOLT_SELFHOST"))) - (def ctx (init-cached (if compile? {:compile? true} {}))) - (defn run-form [f] - (cond - selfhost? (selfhost/compile-and-eval ctx f) - compile? (eval-one ctx f) - (eval-form ctx @{} f))) - (each f (parse-forms (slurp "test/support/clojure_test.clj")) (run-form f)) - - # Pre-load the suite's own clojure.core-test.number-range helper ns if present - # (35 files require it for r/max-int, r/max-double, … — its :default branches are - # plain numeric literals Jolt can read). Its `ns` form sets the namespace; the - # test file's own `ns` form switches back afterwards. - (let [dir (string/slice path 0 (- (length path) (length (last (string/split "/" path))))) - nr (string dir "number_range.cljc")] - (when (os/stat nr) - (each f (parse-forms (slurp nr)) (protect (run-form f))))) - - (eval-string ctx "(clojure.test/reset-report!)") - (each form (parse-forms (slurp path)) (protect (run-form form))) - (protect (eval-string ctx "(clojure.test/run-registered)")) - (def p (eval-string ctx "(clojure.test/n-pass)")) - (def f (eval-string ctx "(clojure.test/n-fail)")) - (def e (eval-string ctx "(clojure.test/n-error)")) - # A "dump" 2nd arg (or SUITE_DUMP env) also prints each failure/error message - # (one DUMP line each) for triage. - (when (or (os/getenv "SUITE_DUMP") (= "dump" (get (dyn :args) 2))) - (eval-string ctx "(doseq [m (clojure.test/failures)] (println (str \"DUMP \" m)))")) - # Counts on a sentinel line so parsers find it even if a test body printed to - # stdout (e.g. with-out-str / println-str tests). - (printf "@@COUNTS %d %d %d" (if (number? p) p 0) (if (number? f) f 0) (if (number? e) e 0))) diff --git a/test/integration/systematic-coverage-test.janet b/test/integration/systematic-coverage-test.janet deleted file mode 100644 index 0644430..0000000 --- a/test/integration/systematic-coverage-test.janet +++ /dev/null @@ -1,214 +0,0 @@ -# Systematic coverage tests for Clojure language features -(use ../../src/jolt/api) -(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) - -(print "Systematic Coverage Tests") - -# --- Type Predicates --- -(print "1: type predicates...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(integer? 0)")) "integer? 0") - (assert (= true (ct-eval ctx "(integer? 1)")) "integer? 1") - (assert (= true (ct-eval ctx "(integer? -5)")) "integer? negative") - (assert (= false (ct-eval ctx "(integer? 1.5)")) "integer? float") - (assert (= false (ct-eval ctx "(integer? nil)")) "integer? nil") - (assert (= false (ct-eval ctx "(integer? \"abc\")")) "integer? string") - (assert (= true (ct-eval ctx "(boolean? true)")) "boolean? true") - (assert (= true (ct-eval ctx "(boolean? false)")) "boolean? false") - (assert (= false (ct-eval ctx "(boolean? 1)")) "boolean? falsy") - (assert (= false (ct-eval ctx "(boolean? nil)")) "boolean? nil") - (assert (= true (ct-eval ctx "(nil? nil)")) "nil? nil") - (assert (= false (ct-eval ctx "(nil? false)")) "nil? false") - (assert (= false (ct-eval ctx "(nil? 0)")) "nil? 0") - (assert (= false (ct-eval ctx "(nil? [])")) "nil? empty vec") - (assert (= false (ct-eval ctx "(some? nil)")) "some? nil") - (assert (= true (ct-eval ctx "(some? false)")) "some? false") - (assert (= true (ct-eval ctx "(some? 0)")) "some? 0") - (assert (= true (ct-eval ctx "(some? [])")) "some? empty vec") - (assert (= true (ct-eval ctx "(string? \"hello\")")) "string?") - (assert (= false (ct-eval ctx "(string? 42)")) "string? false") - (assert (= true (ct-eval ctx "(string? \"\")")) "string? empty") - (assert (= true (ct-eval ctx "(number? 42)")) "number? int") - (assert (= true (ct-eval ctx "(number? 3.14)")) "number? float") - (assert (= false (ct-eval ctx "(number? \"42\")")) "number? string") - (assert (= true (ct-eval ctx "(fn? inc)")) "fn? builtin") - (assert (= false (ct-eval ctx "(fn? 42)")) "fn? false") - (assert (= true (ct-eval ctx "(keyword? :foo)")) "keyword?") - (assert (= false (ct-eval ctx "(keyword? \"foo\")")) "keyword? false") - (assert (= true (ct-eval ctx "(symbol? 'abc)")) "symbol?") - (assert (= false (ct-eval ctx "(symbol? :abc)")) "symbol? false") - (assert (= true (ct-eval ctx "(map? {:a 1})")) "map?") - (assert (= false (ct-eval ctx "(map? [1 2])")) "map? false") - (assert (= true (ct-eval ctx "(set? #{1 2})")) "set?") - (assert (= false (ct-eval ctx "(set? [1 2])")) "set? false") - (assert (= true (ct-eval ctx "(seq? '(1 2))")) "seq? list") - # vectors are not ISeq in Clojure — (seq? [1 2]) is false - (assert (= false (ct-eval ctx "(seq? [1 2])")) "seq? vector is false") - (assert (= true (ct-eval ctx "(coll? [1 2])")) "coll? vec") - (assert (= true (ct-eval ctx "(coll? '(1 2))")) "coll? list") - (assert (= true (ct-eval ctx "(coll? {})")) "coll? map") - (assert (= true (ct-eval ctx "(true? true)")) "true? true") - (assert (= false (ct-eval ctx "(true? 1)")) "true? 1") - (assert (= true (ct-eval ctx "(false? false)")) "false? false") - (assert (= false (ct-eval ctx "(false? nil)")) "false? nil") - (assert (= true (ct-eval ctx "(identical? 42 42)")) "identical? same value")) -(print " ok") - -# --- Number Predicates --- -(print "2: number predicates...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(zero? 0)")) "zero? 0") - (assert (= false (ct-eval ctx "(zero? 1)")) "zero? 1") - # zero?/pos?/neg? now reject non-numbers (Clojure-strict), like the JVM. - (assert (not ((protect (ct-eval ctx "(zero? nil)")) 0)) "zero? nil throws") - (assert (= true (ct-eval ctx "(pos? 1)")) "pos?") - (assert (= false (ct-eval ctx "(pos? 0)")) "pos? 0") - (assert (= false (ct-eval ctx "(pos? -1)")) "pos? -1") - (assert (= true (ct-eval ctx "(neg? -1)")) "neg?") - (assert (= false (ct-eval ctx "(neg? 0)")) "neg? 0") - (assert (= false (ct-eval ctx "(neg? 1)")) "neg? 1") - (assert (= true (ct-eval ctx "(even? 0)")) "even? 0") - (assert (= true (ct-eval ctx "(even? 2)")) "even? 2") - (assert (= false (ct-eval ctx "(even? 1)")) "even? 1") - (assert (= true (ct-eval ctx "(odd? 1)")) "odd? 1") - (assert (= true (ct-eval ctx "(odd? 3)")) "odd? 3") - (assert (= false (ct-eval ctx "(odd? 2)")) "odd? 2")) -(print " ok") - -# --- Math --- -(print "3: math operations...") -(let [ctx (init-cached)] - (assert (= 0 (ct-eval ctx "(+)")) "+ 0 args") - (assert (= 5 (ct-eval ctx "(+ 2 3)")) "+ 2 args") - (assert (= 10 (ct-eval ctx "(+ 1 2 3 4)")) "+ varargs") - (assert (= -5 (ct-eval ctx "(- 5)")) "- unary") - (assert (= 2 (ct-eval ctx "(- 5 3)")) "- binary") - (assert (= 1 (ct-eval ctx "(*)")) "* 0 args") - (assert (= 6 (ct-eval ctx "(* 2 3)")) "*") - (assert (= 0.5 (ct-eval ctx "(/ 2)")) "/ unary reciprocal") - (assert (= 2 (ct-eval ctx "(/ 4 2)")) "/ binary") - (assert (= 2 (ct-eval ctx "(quot 5 2)")) "quot") - (assert (= 1 (ct-eval ctx "(rem 5 2)")) "rem") - (assert (= 1 (ct-eval ctx "(mod 5 2)")) "mod") - (assert (= 43 (ct-eval ctx "(inc 42)")) "inc") - (assert (= 41 (ct-eval ctx "(dec 42)")) "dec") - (assert (= 3 (ct-eval ctx "(max 1 2 3)")) "max") - (assert (= 1 (ct-eval ctx "(min 1 2 3)")) "min") - (assert (= 5 (ct-eval ctx "(abs -5)")) "abs negative") - (assert (= 5 (ct-eval ctx "(abs 5)")) "abs positive") - (assert (= 0 (ct-eval ctx "(abs 0)")) "abs 0") - (assert (= 3.14 (ct-eval ctx "(abs -3.14)")) "abs float") - (assert (= true (ct-eval ctx "(< (rand) 1)")) "rand < 1") - (assert (= true (ct-eval ctx "(number? (rand-int 10))")) "rand-int type")) -(print " ok") - -# --- Comparison --- -(print "4: comparison...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= 1 1)")) "= same") - (assert (= true (ct-eval ctx "(= 1 1 1)")) "= multi same") - (assert (= false (ct-eval ctx "(= 1 2)")) "= different") - (assert (= true (ct-eval ctx "(not= 1 2)")) "not= different") - (assert (= false (ct-eval ctx "(not= 1 1)")) "not= same") - (assert (= true (ct-eval ctx "(< 1 2)")) "<") - (assert (= false (ct-eval ctx "(< 2 1)")) "< false") - (assert (= true (ct-eval ctx "(> 2 1)")) ">") - (assert (= true (ct-eval ctx "(<= 1 1)")) "<=") - (assert (= true (ct-eval ctx "(>= 2 2)")) ">=")) -(print " ok") - -# --- Boolean logic --- -(print "5: boolean logic...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(and)")) "and empty") - (assert (= true (ct-eval ctx "(and true)")) "and true") - (assert (= nil (ct-eval ctx "(and nil)")) "and nil") - (assert (= false (ct-eval ctx "(and false)")) "and false") - (assert (= 3 (ct-eval ctx "(and 1 2 3)")) "and last") - (assert (= nil (ct-eval ctx "(and 1 nil 3)")) "and short-circuit") - (assert (= nil (ct-eval ctx "(or)")) "or empty") - (assert (= true (ct-eval ctx "(or true)")) "or true") - (assert (= nil (ct-eval ctx "(or nil)")) "or nil") - (assert (= false (ct-eval ctx "(or false)")) "or false") - (assert (= 1 (ct-eval ctx "(or nil false 1 2)")) "or first truthy") - (assert (= false (ct-eval ctx "(or nil false)")) "or all falsy") - (assert (= false (ct-eval ctx "(not true)")) "not true") - (assert (= true (ct-eval ctx "(not nil)")) "not nil") - (assert (= true (ct-eval ctx "(not false)")) "not false")) -(print " ok") - -# --- Collections --- -(print "6: collections...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(empty? nil)")) "empty? nil") - (assert (= true (ct-eval ctx "(empty? [])")) "empty? []") - (assert (= true (ct-eval ctx "(empty? ())")) "empty? ()") - (assert (= true (ct-eval ctx "(empty? {})")) "empty? {}") - (assert (= true (ct-eval ctx "(empty? #{})")) "empty? #{}") - (assert (= true (ct-eval ctx "(empty? \"\")")) "empty? empty string") - (assert (= false (ct-eval ctx "(empty? [1])")) "empty? non-empty") - (assert (= true (ct-eval ctx "(every? even? [2 4 6])")) "every? true") - (assert (= false (ct-eval ctx "(every? even? [2 3 4])")) "every? false") - (assert (= 3 (ct-eval ctx "(count [1 2 3])")) "count vector") - (assert (= 2 (ct-eval ctx "(count {:a 1 :b 2})")) "count map") - (assert (= 3 (ct-eval ctx "(count #{1 2 3})")) "count set") - (assert (= 3 (ct-eval ctx "(count \"abc\")")) "count string")) -(print " ok") - -# --- Sequence Operations --- -(print "7: sequence operations...") -(let [ctx (init-cached)] - (assert (= 1 (ct-eval ctx "(first [1 2 3])")) "first") - (assert (= nil (ct-eval ctx "(first [])")) "first empty") - (assert (= nil (ct-eval ctx "(first nil)")) "first nil") - (assert (= :a (ct-eval ctx "(nth [:a :b :c] 0)")) "nth 0") - (assert (= :c (ct-eval ctx "(nth [:a :b :c] 2)")) "nth 2") - (assert (= :d (ct-eval ctx "(nth [:a :b :c] 3 :d)")) "nth default") - (assert (= nil (ct-eval ctx "(seq [])")) "seq empty -> nil") - (assert (= nil (ct-eval ctx "(seq nil)")) "seq nil -> nil") - (assert (= true (ct-eval ctx "(= [2 3 4] (map inc [1 2 3]))")) "map") - (assert (= true (ct-eval ctx "(= [2 4] (filter even? [1 2 3 4]))")) "filter") - (assert (= 6 (ct-eval ctx "(reduce + [1 2 3])")) "reduce") - (assert (= 10 (ct-eval ctx "(reduce + 4 [1 2 3])")) "reduce init") - (assert (= true (ct-eval ctx "(= [1 2] (take 2 [1 2 3 4]))")) "take") - (assert (= true (ct-eval ctx "(= [3 4] (drop 2 [1 2 3 4]))")) "drop") - (assert (= true (ct-eval ctx "(= [3 2 1] (reverse [1 2 3]))")) "reverse") - (assert (= true (ct-eval ctx "(= 3 (count (distinct [1 1 2 2 3 3])))")) "distinct")) -(print " ok") - -# --- Collections: conj, assoc, dissoc, get --- -(print "8: collection mutation...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= [1 2 3] (conj [1 2] 3))")) "conj vector") - (assert (= true (ct-eval ctx "(= (quote (0 1 2)) (conj (quote (1 2)) 0))")) "conj list prepend") - (assert (= true (ct-eval ctx "(= {:a 1 :b 2} (assoc {:a 1} :b 2))")) "assoc") - (assert (= true (ct-eval ctx "(= {:a 1} (dissoc {:a 1 :b 2} :b))")) "dissoc") - (assert (= 1 (ct-eval ctx "(get {:a 1} :a)")) "get") - (assert (= nil (ct-eval ctx "(get {:a 1} :z)")) "get missing") - (assert (= :d (ct-eval ctx "(get {:a 1} :z :d)")) "get default") - (assert (= true (ct-eval ctx "(contains? {:a 1} :a)")) "contains? map") - (assert (= false (ct-eval ctx "(contains? {:a 1} :z)")) "contains? missing") - (assert (= true (ct-eval ctx "(contains? [5 6 7] 1)")) "contains? vector") - (assert (= false (ct-eval ctx "(contains? [5 6 7] 3)")) "contains? vector oob")) -(print " ok") - -# --- Higher-order functions --- -(print "9: higher-order functions...") -(let [ctx (init-cached)] - (assert (= 3 (ct-eval ctx "((comp inc inc) 1)")) "comp") - (assert (= 42 (ct-eval ctx "(identity 42)")) "identity") - (assert (= 99 (ct-eval ctx "((constantly 99) :anything)")) "constantly") - (assert (= true (ct-eval ctx "(= 10 ((partial + 3 7)))")) "partial") - (assert (= true (ct-eval ctx "((every-pred even? pos?) 4)")) "every-pred true") - (assert (= false (ct-eval ctx "((every-pred even? pos?) -4)")) "every-pred false") - (assert (= false (ct-eval ctx "((complement even?) 2)")) "complement")) -(print " ok") - -# --- Destructuring --- -(print "10: destructuring...") -(let [ctx (init-cached)] - (assert (= 1 (ct-eval ctx "(let [[x] [1 2 3]] x)")) "seq destructure first") - (assert (= 2 (ct-eval ctx "(let [[_ y] [1 2 3]] y)")) "seq destructure second")) -(print " ok") - -(print "\nAll Systematic Coverage tests passed!") diff --git a/test/integration/type-check-test.janet b/test/integration/type-check-test.janet deleted file mode 100644 index 5580a24..0000000 --- a/test/integration/type-check-test.janet +++ /dev/null @@ -1,137 +0,0 @@ -# Success-type checking (RFC 0006, jolt-y3b). The structural inference of -# RFC 0005, reused as a loose checker: flag a core-fn call ONLY when an argument -# is PROVABLY the wrong type (concrete and in the op's throwing error domain). -# Ambiguous cases (:any, unions, :truthy) are accepted — no false positives. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/types :as types) -(import ../../src/jolt/reader :as reader) - -(print "Success-type checking (jolt-y3b)...") - -(os/setenv "JOLT_DIRECT_LINK" "1") -(reader/track-positions! true) # record form positions (jolt-fqy) -(def ctx (api/init {:compile? true})) -(def pns (types/ctx-find-ns ctx "jolt.passes")) -(def check (types/var-get (types/ns-find pns "check-form"))) - -# diagnostics (a Janet tuple of diag structs) for a source form -(defn diags [src] - (api/normalize-pvecs (check (backend/analyze-form ctx (reader/parse-string src))))) -(defn nd [src] (length (diags src))) -# strict mode (jolt-zo1): also report provably-wrong calls to user fns -(defn nds [src] - (length (api/normalize-pvecs - (check (backend/analyze-form ctx (reader/parse-string src)) true)))) - -# --- provably wrong: REPORTED ------------------------------------------------ -(assert (= 1 (nd "(inc \"x\")")) "inc on a string") -(assert (= 1 (nd "(+ 1 \"x\")")) "+ with a string arg") -(assert (= 1 (nd "(count :foo)")) "count of a keyword") -(assert (= 1 (nd "(count 5)")) "count of a number") -(assert (= 1 (nd "(first 42)")) "first of a number") -(assert (= 1 (nd "(nth :k 0)")) "nth of a keyword") -(assert (= 1 (nd "(let [n \"x\"] (inc n))")) "inc on a let-bound string") -(assert (= 1 (nd "(inc (count :k))")) "inner count of keyword reported (inc of :num is fine)") - -# --- ambiguous / lenient: ACCEPTED (no false positive) ----------------------- -(assert (= 0 (nd "(:k 5)")) "keyword lookup on a number returns nil, not an error") -(assert (= 0 (nd "(get 5 :k)")) "get on a number returns nil, not an error") -(assert (= 0 (nd "(fn [x] (inc x))")) "inc on an unknown (:any) param accepted") -(assert (= 0 (nd "(fn [c] (inc (if c 1 \"x\")))")) "inc on a {:num | :str} branch -> :any, accepted") -(assert (= 0 (nd "(count \"ab\")")) "count of a string is fine") -(assert (= 0 (nd "(count [1 2 3])")) "count of a vector is fine") -(assert (= 0 (nd "(first [1 2 3])")) "first of a vector is fine") -(assert (= 0 (nd "(inc (count [1 2 3]))")) "count of vector + inc of :num both fine") -(assert (= 0 (nd "(inc (first [1 2 3]))")) "first of vector -> :num, inc fine") - -# --- calling a non-function (jolt-wwy): :num and :str are not callable -------- -(assert (= 1 (nd "(5 1)")) "calling a number is reported") -(assert (= 1 (nd "(\"hi\" 0)")) "calling a string is reported") -(assert (= 1 (nd "((+ 1 2) :k)")) "calling an arithmetic result (a :num) is reported") -(assert (= 1 (nd "(let [n 5] (n 1))")) "calling a let-bound number is reported") -(assert (= 1 (nd "(let [s \"x\"] (s 0))")) "calling a let-bound string is reported") -# (a var holding a number, e.g. (def nn 5) (nn 1), is caught in direct-link -# mode via vtype-box; the standalone checker has no var value types) -# callable values: keyword/map/vector/set as IFn — NOT reported -(assert (= 0 (nd "(:k {:k 1})")) "keyword call is fine") -(assert (= 0 (nd "({:a 1} :a)")) "map call is fine") -(assert (= 0 (nd "([10 20] 1)")) "vector call is fine") -(assert (= 0 (nd "(#{1 2} 1)")) "set call is fine") -(assert (= 0 (nd "(fn [c] ((if c 1 :k) 0))")) "union {:num | :kw} callee accepted (:kw is callable)") -(assert (= 0 (nd "(fn [f] (f 1))")) "calling an unknown (:any) param accepted") -(assert (= 1 (nd "(fn [c] ((if c 1 \"x\") 0))")) "union {:num | :str} callee — both non-callable — reported") - -# --- bounded unions (jolt-pz5): report only when EVERY member is in the error -# domain; accept when any member is valid. Differing branches used to collapse -# to :any (accepted); now they form {:union #{...}} and are checked per-member. -(assert (= 1 (nd "(fn [c] (inc (if c \"a\" :k)))")) - "inc of {:str | :kw} — every member non-number — reported") -(assert (= 0 (nd "(fn [c] (inc (if c 1 \"x\")))")) - "inc of {:num | :str} — :num is fine — still accepted") -(assert (= 1 (nd "(fn [c] (count (if c :k 5)))")) - "count of {:kw | :num} — both non-seqable — reported") -(assert (= 0 (nd "(fn [c] (count (if c :k \"ab\")))")) - "count of {:kw | :str} — :str is seqable — accepted") -(assert (= 1 (nd "(fn [c] (inc (if c \"a\" (if c :k :j))))")) - "inc of nested all-non-number union reported") -(assert (= 0 (nd "(fn [c] (inc (if c \"a\" (if c :k 1))))")) - "inc of union with a buried :num member accepted") -# a union is opaque to structural specialization — it keeps the dynamic guard, -# exactly like :any, so a keyword lookup over it is never mis-specialized. -(assert (= 0 (nd "(fn [c] (:r (if c {:r 1} {:g 2})))")) - "keyword lookup over a struct union is accepted (no false positive)") - -# --- user-function error domains (jolt-zo1), opt-in strict mode -------------- -# A call passing a provably-wrong type to a user fn whose body requires -# otherwise is reported ONLY in strict mode; the default level never fires on -# user fns (closed-world soundness boundary). -(assert (= 0 (nd "(do (defn ufa [x] (+ x 1)) (ufa \"s\"))")) - "user-fn wrong call NOT reported at the default level") -(assert (= 1 (nds "(do (defn ufa [x] (+ x 1)) (ufa \"s\"))")) - "strict: arithmetic fn called with a string is reported") -(assert (= 0 (nds "(do (defn ufb [x] (+ x 1)) (ufb 5))")) - "strict: same fn called with a number is accepted") -(assert (= 0 (nds "(do (defn ufc [x] (:k x)) (ufc \"s\"))")) - "strict: a body that uses the param leniently is not reported") -# cross-form: a def registered by an earlier check is visible to a later call -(nds "(defn ufd [x] (count x))") -(assert (= 1 (nds "(ufd 42)")) - "strict: cross-form call to a seq-only fn with a number is reported") -(assert (= 0 (nds "(do (defn ^:redef ufe [x] (+ x 1)) (ufe \"s\"))")) - "strict: a ^:redef fn is not a stable requirement, not reported") -(assert (= 1 (nds "(do (defn ufrec [x] (ufrec (+ x 1))) (ufrec \"s\"))")) - "strict: self-recursion terminates (cycle guard) and the (+ x 1) on a string is reported once") -# wrong arity to a user fn (jolt-wwy), strict mode: the registered fixed arity -# makes a mismatched call provably throw, regardless of argument types -(assert (= 1 (nds "(do (defn uar [x y] (+ x y)) (uar 1))")) - "strict: 2-arg fn called with 1 arg is reported") -(assert (= 1 (nds "(do (defn uar2 [x] x) (uar2 1 2 3))")) - "strict: 1-arg fn called with 3 args is reported") -(assert (= 0 (nds "(do (defn uar3 [x y] (+ x y)) (uar3 1 2))")) - "strict: correct arity accepted") -(assert (= 0 (nd "(do (defn uar4 [x y] (+ x y)) (uar4 1))")) - "default level does NOT report user-fn arity (closed-world, opt-in)") -(assert (= 0 (nds "(do (defn ^:redef uar5 [x y] (+ x y)) (uar5 1))")) - "strict: ^:redef fn arity not checked (could be redefined)") - -# --- the diagnostic carries op + type + a message ---------------------------- -(def one (in (diags "(inc \"x\")") 0)) -(assert (= "inc" (get one :op)) "diagnostic names the op") -(assert (string/find "number" (get one :msg)) "message says a number is required") -# --- the diagnostic carries the offending form's source offset (jolt-fqy) ----- -(assert (= 0 (get one :pos)) "diagnostic carries :pos (offset 0 for a single form)") -(def nested (in (diags "(do 1 2 (inc :k))") 0)) -(assert (= 8 (get nested :pos)) - "the inner (inc :k) form is positioned at its own offset, not the do's") - -# --- end-to-end: strictness drives compilation (decoupled from :inline?) ----- -# error mode aborts a provably-wrong form's compilation; a correct form compiles. -(os/setenv "JOLT_TYPE_CHECK" "error") -(assert (not (first (protect (api/eval-string ctx "(count :nope)")))) - "error mode aborts a provably-wrong form") -(assert (first (protect (api/eval-string ctx "(count [1 2 3])"))) - "error mode accepts a correct form") -(os/setenv "JOLT_TYPE_CHECK" "off") - -(print "Success-type checking passed!") diff --git a/test/integration/type-infer-phase1-test.janet b/test/integration/type-infer-phase1-test.janet deleted file mode 100644 index 5d8fac7..0000000 --- a/test/integration/type-infer-phase1-test.janet +++ /dev/null @@ -1,55 +0,0 @@ -# Inter-procedural collection-type inference, Phase 1 (jolt-767): closed-world. -# A whole-unit fixpoint propagates collection types through the call graph — a -# fn's param types become the lub of its in-unit call-site arg types — so a -# param that always receives a struct map gets typed and its lookups specialize, -# with no hint. Fns whose var escapes as a value keep :any params (their callers -# aren't all visible). Sound under source distribution + whole-program compile. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/types :as types) -(import ../../src/jolt/reader :as reader) - -(print "Type inference Phase 1 (jolt-767)...") - -(os/setenv "JOLT_DIRECT_LINK" "1") -(def ctx (api/init-cached {:compile? true})) -(api/eval-string ctx "(ns p1)") -# closed-world unit. mk is small (inlined away). rd is RECURSIVE, so it survives -# inlining and is called via its var — exactly the shape (big/recursive fn with -# escaping-from-the-caller params) that inter-procedural inference targets. Its -# param v flows from mk's struct-map literal (after mk inlines into drv). -(each s ["(defn mk [a b] {:r a :g b})" - "(defn rd [v n] (if (< n 1) (:r v) (rd v (dec n))))" - "(defn drv [] (rd (mk 1 2) 3))" - # esc's var is used as a VALUE (passed to mapv) -> params must stay :any - "(defn esc [w] (:r w))" - "(defn use-esc [xs] (mapv esc xs))"] - (api/eval-string ctx s)) - -(def report (backend/infer-unit! ctx "p1")) - -# --- the fixpoint computed the right param types ----------------------------- -# rd's param v flows from mk's struct result (mk inlines to a struct literal in -# drv) and stays struct across the recursive self-call -> a {:struct ...} type -(defn struct-type? [t] (truthy? (get t :struct))) -(assert (struct-type? (in (get report "p1/rd") 0)) (string "rd param v: " (in (get report "p1/rd") 0))) -# esc escaped (passed to mapv) -> param stays unknown (:any / nil), NOT struct -(assert (not (struct-type? (in (get report "p1/esc") 0))) "escaping fn param not inferred struct") - -# --- the seeded re-inference drops the guard for a struct param -------------- -# (on a FRESH analysis, since infer-unit! re-stashes the already-specialized body) -(def pns (types/ctx-find-ns ctx "jolt.passes")) -(def reinfer (types/ns-find pns "reinfer-def")) -(def rd-def (backend/analyze-form ctx (reader/parse-string "(defn rdx [v n] (if (< n 1) (:r v) (rdx v (dec n))))"))) -(defn guards-seeded [ptmap] - (length (string/find-all ":jolt/type" (string/format "%p" (backend/emit-ir ctx ((types/var-get reinfer) rd-def ptmap)))))) -(assert (= 0 (guards-seeded @{"v" {:struct {}}})) "struct param -> bare lookup") -(assert (= 1 (guards-seeded @{})) "no param type -> guard kept") - -# --- correctness: recompiled unit still computes the same -------------------- -(assert (= 1 (api/eval-string ctx "(p1/drv)")) "drv correct after recompile") -(assert (= 7 (api/eval-string ctx "(p1/rd {:r 7 :g 8} 0)")) "rd correct on a struct") -(assert (= nil (api/eval-string ctx "(p1/rd (hash-map :r nil) 0)")) "rd correct on a phm (key present, nil)") -(assert (deep= [1 1] (api/normalize-pvecs (api/eval-string ctx "(p1/use-esc [{:r 1} {:r 1}])"))) "escaping fn still correct") - -(print "Type inference Phase 1 passed!") diff --git a/test/integration/type-infer-phase2-test.janet b/test/integration/type-infer-phase2-test.janet deleted file mode 100644 index 8ac347a..0000000 --- a/test/integration/type-infer-phase2-test.janet +++ /dev/null @@ -1,24 +0,0 @@ -# Vector op specialization, Phase 2 (jolt-d6u): a value the inference proved to -# be a vector ({:vec ...}) gets count -> pv-count (skip core-count's dispatch) -# and 3-arg nth -> pv-nth. 2-arg nth is NOT specialized: it errors on -# out-of-bounds where pv-nth returns nil. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/types :as types) -(import ../../src/jolt/reader :as reader) -(print "Type inference Phase 2 (vector ops)...") -(os/setenv "JOLT_DIRECT_LINK" "1") -(def ctx (api/init-cached {:compile? true})) -(api/eval-string ctx "(ns p2)") -(def reinfer (types/var-get (types/ns-find (types/ctx-find-ns ctx "jolt.passes") "reinfer-def"))) -(defn estr [src ptmap] - (string/format "%p" (backend/emit-ir ctx (reinfer (backend/analyze-form ctx (reader/parse-string src)) ptmap)))) -(assert (string/find "pv-count" (estr "(defn f [v] (count v))" @{"v" {:vec :any}})) "count on vector -> pv-count") -(assert (not (string/find "pv-count" (estr "(defn f [v] (count v))" @{}))) "count on unknown not specialized") -(assert (string/find "pv-nth" (estr "(defn f [v i] (nth v i 0))" @{"v" {:vec :any}})) "3-arg nth on vector -> pv-nth") -(assert (not (string/find "pv-nth" (estr "(defn f [v i] (nth v i))" @{"v" {:vec :any}}))) "2-arg nth NOT specialized") -# correctness -(assert (= 3 (api/eval-string ctx "(count [1 2 3])")) "count value") -(assert (= 2 (api/eval-string ctx "(nth [1 2 3] 1 9)")) "nth 3-arg in-bounds") -(assert (= 9 (api/eval-string ctx "(nth [1 2 3] 5 9)")) "nth 3-arg default") -(print "Type inference Phase 2 passed!") diff --git a/test/integration/type-infer-phase3-test.janet b/test/integration/type-infer-phase3-test.janet deleted file mode 100644 index 2160b04..0000000 --- a/test/integration/type-infer-phase3-test.janet +++ /dev/null @@ -1,41 +0,0 @@ -# Collection-element types + HOF awareness, Phase 3 (jolt-d6u). A vector carries -# its element type ({:vec ELEM}); a reduce/map/filter closure over it gets that -# element type on its element param. So a lookup inside a reduce closure over a -# vector-of-structs specializes — no hint — WHEN the element type is provable. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/types :as types) -(import ../../src/jolt/reader :as reader) - -(print "Type inference Phase 3 (jolt-d6u)...") - -(os/setenv "JOLT_DIRECT_LINK" "1") -(def ctx (api/init-cached {:compile? true})) -(api/eval-string ctx "(ns p3)") -(def pns (types/ctx-find-ns ctx "jolt.passes")) -(def reinfer (types/var-get (types/ns-find pns "reinfer-def"))) -# helper: analyze a defn, reinfer with seeded param types, count guards -(defn guards [src ptmap] - (def d (backend/analyze-form ctx (reader/parse-string src))) - (length (string/find-all ":jolt/type" (string/format "%p" (backend/emit-ir ctx (reinfer d ptmap)))))) - -# a reduce closure's element param gets the vector's element type -(def red "(defn f [coll] (reduce (fn [acc h] (+ acc (:r h))) 0 coll))") -(assert (= 0 (guards red @{"coll" {:vec {:struct {}}}})) "reduce element typed -> bare lookup in closure") -(assert (= 1 (guards red @{"coll" {:vec :any}})) "reduce over vector of unknown -> guard kept") -(assert (= 1 (guards red @{})) "untyped coll -> guard kept") - -# mapv over a vector-of-structs types the closure element too -(def mp "(defn g [coll] (mapv (fn [h] (:r h)) coll))") -(assert (= 0 (guards mp @{"coll" {:vec {:struct {}}}})) "mapv element typed -> bare lookup") -(assert (= 1 (guards mp @{"coll" {:vec :any}})) "mapv over unknown element -> guard") - -# element type is DERIVED, not just seeded: a vector literal of structs, reduced -(def derived "(defn h2 [] (reduce (fn [acc x] (+ acc (:r x))) 0 [{:r 1 :g 2} {:r 3 :g 4}]))") -(assert (= 0 (guards derived @{})) "vector literal of structs -> element struct -> bare lookup") - -# correctness: the specialized closures compute the same -(assert (= 4 (api/eval-string ctx "((fn [coll] (reduce (fn [acc h] (+ acc (:r h))) 0 coll)) [{:r 1} {:r 3}])")) "reduce value") -(assert (= 4 (api/eval-string ctx "(reduce (fn [acc x] (+ acc (:r x))) 0 [{:r 1 :g 2} {:r 3 :g 4}])")) "derived value") - -(print "Type inference Phase 3 passed!") diff --git a/test/integration/type-infer-test.janet b/test/integration/type-infer-test.janet deleted file mode 100644 index e010870..0000000 --- a/test/integration/type-infer-test.janet +++ /dev/null @@ -1,54 +0,0 @@ -# Static collection-type inference, Phase 0 (jolt-6sr): intra-procedural. -# The pass infers an expression's collection type from literals/arithmetic and -# flows it through let bindings and if-joins. Where a keyword-lookup subject is -# PROVEN to be a plain struct map it auto-drops the :jolt/type guard (the -# inference output is the same ^:struct channel as a manual hint); where the -# type is unknown it stays :any and keeps the dynamic guard (sound fallback). -# -# Note: Route 1 scalar-replacement already eliminates NON-escaping let-bound -# maps outright, so these cases force the map to ESCAPE (pass it to `sink`) to -# isolate what inference adds — typing a map that survives and is then looked up. -(import ../../src/jolt/api :as api) -(import ../../src/jolt/backend :as backend) -(import ../../src/jolt/reader :as reader) - -(print "Type inference Phase 0 (jolt-6sr)...") - -(os/setenv "JOLT_DIRECT_LINK" "1") -(def ctx (api/init-cached {:compile? true})) -(api/eval-string ctx "(ns ti)") - -(defn guards [src] - (length (string/find-all ":jolt/type" - (string/format "%p" (backend/emit-ir ctx (backend/analyze-form ctx (reader/parse-string src))))))) -(defn ev [src] (api/eval-string ctx src)) - -# --- guard auto-removal where the type is proven, no hint ------------------- -# escaping struct-map literal (scalar keys, truthy values) is proven struct -(assert (= 0 (guards "(fn [sink] (let [v {:r 1 :g 2 :b 3}] (sink v) (:r v)))")) "inferred struct-map literal -> bare lookup") -# arithmetic values are provably non-nil/non-false -> still a struct -(assert (= 0 (guards "(fn [sink a b] (let [v {:r (+ a 1) :g (* b 2) :b 7}] (sink v) (:r v)))")) "arithmetic-valued map inferred struct") -# the inferred type flows through a rebinding -(assert (= 0 (guards "(fn [sink] (let [v {:r 1 :g 2} w v] (sink w) (:r w)))")) "inferred type flows through a rebinding") -# both if-branches struct -> join is struct -(assert (= 0 (guards "(fn [sink c] (let [v (if c {:a 1} {:a 2})] (sink v) (:a v)))")) "if-join of two struct literals stays struct") - -# --- sound fallback to the guard where the type is NOT proven --------------- -# a param is unknown (Phase 1 handles params) -> guard kept, exactly as today -(assert (= 1 (guards "(fn [m] (:r m))")) "unknown param keeps the guard") -# a value that could be nil/false makes the literal maybe-phm -> :any -> guard -(assert (= 1 (guards "(fn [sink x] (let [v {:r x}] (sink v) (:r v)))")) "maybe-nil value -> not proven struct -> guard") -# join of a struct and a phm is :any -> guard -(assert (>= (guards "(fn [sink c] (let [v (if c {:a 1} (hash-map :a nil))] (sink v) (:a v)))") 1) "struct/phm join -> :any -> guard") - -# --- correctness: every shape evaluates to the same as the guarded path ----- -(def snk "(fn [_] nil)") -(assert (= 1 (ev (string "((fn [sink] (let [v {:r 1 :g 2 :b 3}] (sink v) (:r v))) " snk ")"))) "struct literal value") -(assert (= 6 (ev (string "((fn [sink a] (let [v {:r (+ a 1)}] (sink v) (:r v))) " snk " 5)"))) "arithmetic-valued struct") -(assert (= 2 (ev (string "((fn [sink] (let [v {:r 1 :g 2} w v] (sink w) (:g w))) " snk ")"))) "flowed type value") -(assert (= 1 (ev (string "((fn [sink c] (let [v (if c {:a 1} {:a 2})] (sink v) (:a v))) " snk " true)"))) "if-join value") -(assert (= nil (ev (string "((fn [sink x] (let [v {:r x}] (sink v) (:r v))) " snk " nil)"))) "maybe-nil map reads correctly (nil)") -(assert (= nil (ev (string "((fn [sink c] (let [v (if c {:a 1} (hash-map :a nil))] (sink v) (:a v))) " snk " false)"))) "phm branch reads nil correctly") -(assert (= 1 (ev (string "((fn [sink c] (let [v (if c {:a 1} (hash-map :a nil))] (sink v) (:a v))) " snk " true)"))) "struct branch reads correctly") - -(print "Type inference Phase 0 passed!") diff --git a/test/integration/uberscript-dce-test.janet b/test/integration/uberscript-dce-test.janet deleted file mode 100644 index 04a3a3b..0000000 --- a/test/integration/uberscript-dce-test.janet +++ /dev/null @@ -1,86 +0,0 @@ -# Dead-code elimination in `jolt uberscript` (jolt-atg): a bundle is closed- -# world (everything it needs is inlined, nothing is required later), so a user -# `defn` that is unreachable from the entry point's reference graph can be -# dropped. Sound + conservative: only plain defn/defn- are prunable; a defn is -# kept if its (bare or ns-qualified) name appears anywhere in a kept form, the -# closure iterates to a fixpoint, and any use of dynamic resolution -# (resolve/eval/...) keeps everything. Drives the BUILT binary (uberscript is a -# CLI command); skips cleanly if build/jolt is absent. -(def jolt "build/jolt") - -(defn- write-app [dir files] - (os/mkdir dir) - (each [name body] (partition 2 files) (spit (string dir "/" name) body))) - -(defn- uber [dir main-ns] - (def out (string dir "/out.clj")) - (def jbin (string (os/cwd) "/" jolt)) - (os/execute ["sh" "-c" (string "JOLT_PATH=" dir " " jbin " uberscript " out " -m " main-ns " 2>/dev/null")] :p) - (slurp out)) - -(defn- run-bundle [dir] - (def out2 (string dir "/run.txt")) - (def jbin (string (os/cwd) "/" jolt)) - (os/execute ["sh" "-c" (string jbin " " dir "/out.clj > " out2 " 2>&1")] :p) - (string/trimr (slurp out2))) - -(defn- has? [s needle] (not (nil? (string/find needle s)))) - -(if (not (os/stat jolt)) - (print "uberscript-dce: SKIP (no build/jolt — run from source)") - (do - # --- basic: an unreachable defn is dropped; reachable ones survive -------- - (def d1 (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-dce1")) - (write-app d1 - ["lib.clj" (string "(ns lib)\n" - "(defn used-helper [x] (* x 2))\n" - "(defn dead-never-called [x] (+ x 99999))\n" - "(defn also-used [x] (used-helper (inc x)))\n") - "app.clj" (string "(ns app (:require [lib]))\n" - "(defn -main [& _] (println \"result\" (lib/also-used 10)))\n")]) - (def b1 (uber d1 "app")) - (assert (not (has? b1 "dead-never-called")) "unreachable defn dropped from bundle") - (assert (has? b1 "used-helper") "transitively-reached defn kept") - (assert (has? b1 "also-used") "directly-reached defn kept") - (assert (= "result 22" (run-bundle d1)) "pruned bundle runs identically") - - # --- soundness: a fn reached ONLY through a macro template is kept -------- - (def d2 (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-dce2")) - (write-app d2 - ["mlib.clj" (string "(ns mlib)\n" - "(defn via-macro [x] (* x 3))\n" - "(defmacro tri [n] (list 'mlib/via-macro n))\n") - "app2.clj" (string "(ns app2 (:require [mlib]))\n" - "(defn -main [& _] (println \"m\" (mlib/tri 7)))\n")]) - (def b2 (uber d2 "app2")) - (assert (has? b2 "via-macro") "fn used only via a macro template is kept") - (assert (= "m 21" (run-bundle d2)) "macro-reached bundle runs identically") - - # --- soundness: dynamic resolution disables DCE (keeps everything) -------- - (def d3 (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-dce3")) - (write-app d3 - ["dlib.clj" (string "(ns dlib)\n" - "(defn looks-dead [x] (* x 5))\n") - "app3.clj" (string "(ns app3 (:require [dlib]))\n" - "(defn -main [& _]\n" - " (println \"d\" ((deref (resolve 'dlib/looks-dead)) 4)))\n")]) - (def b3 (uber d3 "app3")) - (assert (has? b3 "looks-dead") "resolve in bundle disables DCE (keeps all defns)") - (assert (= "d 20" (run-bundle d3)) "resolve bundle runs identically") - - # --- soundness: a fn reached only through a defmethod body is kept -------- - (def d4 (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-dce4")) - (write-app d4 - ["mmlib.clj" (string "(ns mmlib)\n" - "(defmulti shape-area :kind)\n" - "(defn rect-helper [w h] (* w h))\n" - "(defmethod shape-area :rect [s] (rect-helper (:w s) (:h s)))\n" - "(defn really-dead [x] (+ x 1))\n") - "app4.clj" (string "(ns app4 (:require [mmlib]))\n" - "(defn -main [& _] (println \"area\" (mmlib/shape-area {:kind :rect :w 3 :h 4})))\n")]) - (def b4 (uber d4 "app4")) - (assert (has? b4 "rect-helper") "fn reached only via a defmethod body is kept") - (assert (not (has? b4 "really-dead")) "truly-unreachable fn dropped alongside live multimethod code") - (assert (= "area 12" (run-bundle d4)) "multimethod bundle runs identically") - - (print "uberscript-dce: all cases passed"))) diff --git a/test/integration/uberscript-test.janet b/test/integration/uberscript-test.janet deleted file mode 100644 index 37ac08f..0000000 --- a/test/integration/uberscript-test.janet +++ /dev/null @@ -1,51 +0,0 @@ -# `jolt uberscript` bundles a namespace and everything it requires into one .clj -# that runs on a plain jolt with no JOLT_PATH / deps. Runs from source. - -(defn- run [env-jolt-path & args] - (if env-jolt-path (os/setenv "JOLT_PATH" env-jolt-path) (os/setenv "JOLT_PATH" nil)) - (def p (os/spawn ["janet" "src/jolt/main.janet" ;args] :p {:out :pipe :err :pipe})) - (def out (:read (p :out) :all)) - (os/proc-wait p) - (string (or out ""))) - -(defn- mkdirs [p] - (var acc nil) - (each seg (filter |(not= "" $) (string/split "/" p)) - (set acc (if (nil? acc) (if (string/has-prefix? "/" p) (string "/" seg) seg) (string acc "/" seg))) - (unless (os/stat acc) (os/mkdir acc)))) -(defn- rmrf [p] - (when (os/stat p) - (if (= :directory (os/stat p :mode)) - (do (each e (os/dir p) (rmrf (string p "/" e))) (os/rmdir p)) - (os/rm p)))) - -(def base (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-uber-" (os/time))) -(rmrf base) -(mkdirs (string base "/proj/src/app")) -(mkdirs (string base "/lib/src/greet")) -(spit (string base "/lib/src/greet/core.clj") - "(ns greet.core)\n(defn hello [n] (str \"Hello, \" n \"!\"))\n") -(spit (string base "/proj/src/app/core.clj") - "(ns app.core (:require [greet.core :as g]))\n(defn -main [& args] (println (g/hello (or (first args) \"world\"))))\n") - -(var fails 0) -(defn check [label got pred] - (if (pred got) (print " ok " label) - (do (++ fails) (printf " FAIL %s: got %q" label got)))) -(defn- has [s] (fn [x] (string/find s x))) - -(def roots (string base "/proj/src:" base "/lib/src")) -(def out (string base "/out.clj")) - -# build the uberscript with the dep roots on JOLT_PATH -(run roots "uberscript" out "-m" "app.core") -(check "uberscript written" (if (os/stat out) "yes" "no") (has "yes")) -(check "bundles the dep ns" (slurp out) (has "(ns greet.core)")) - -# run it standalone: no JOLT_PATH, so it only works if the dep was inlined -(check "runs standalone" (run nil out "Bob") (has "Hello, Bob!")) - -(rmrf base) -(if (> fails 0) - (error (string "uberscript-test: " fails " failing check(s)")) - (print "\nAll uberscript tests passed!")) diff --git a/test/integration/whole-program-test.janet b/test/integration/whole-program-test.janet deleted file mode 100644 index c711db8..0000000 --- a/test/integration/whole-program-test.janet +++ /dev/null @@ -1,51 +0,0 @@ -# Whole-program (Stalin) mode (jolt-t34, opt-in JOLT_WHOLE_PROGRAM): one closed- -# world inference fixpoint over ALL user namespaces, so param types propagate -# across ns boundaries (a non-inlined fn's record params get proven from its -# callers in another unit). This must be SOUND — same results as the per-ns -# pass — which is what this test guards, by running a cross-namespace record -# program both ways through the built binary and comparing output. Skips cleanly -# if build/jolt is absent (source-only test run). -(def jolt "build/jolt") - -(defn- run [env-extra] - (def dir (string (or (os/getenv "TMPDIR") "/tmp") "/jolt-wp-test")) - (os/mkdir dir) - (spit (string dir "/wputil.clj") - (string "(ns wputil)\n" - "(defrecord V [x y z])\n" - # const-link targets (jolt-rvt): a data def and a ^:redef fn are - # indirect (cell deref) per-ns but embedded as constants under - # whole-program. Soundness => both modes must give the same answer. - "(def scale 2.0)\n" - "(defn ^:redef bump [x] (+ x 1.0))\n" - # recursive => never inlined; params proven only whole-program - "(defn dot [a b n]\n" - " (if (<= n 0) 0.0\n" - " (+ (* (:x a) (:x b)) (* (:y a) (:y b)) (* (:z a) (:z b)) (bump (* scale (dot a b (dec n)))))))\n")) - (spit (string dir "/wpmain.clj") - (string "(ns wpmain (:require [wputil :as v]))\n" - "(defn -main []\n" - " (loop [i 0 acc 0.0]\n" - " (if (< i 1000)\n" - " (let [a (v/->V (double i) 2.0 3.0) b (v/->V 1.0 (double i) 0.5)]\n" - " (recur (inc i) (+ acc (v/dot a b 2))))\n" - " (println \"sum\" acc))))\n")) - (def out (string dir "/out.txt")) - (def jbin (string (os/cwd) "/" jolt)) - (def cmd (string env-extra "JOLT_DIRECT_LINK=1 JOLT_PATH=" dir " " jbin - " -m wpmain > " out " 2>&1")) - (os/execute ["sh" "-c" cmd] :p) - (string/trimr (slurp out))) - -(if (not (os/stat jolt)) - (print "whole-program: SKIP (no build/jolt — run from source)") - # -m now auto-enables whole-program under direct-linking, so the per-ns - # baseline must explicitly opt out to exercise the per-namespace path. - (let [per-ns (run "JOLT_NO_WHOLE_PROGRAM=1 ") - whole (run "JOLT_WHOLE_PROGRAM=1 ")] - (printf " per-ns: %s" per-ns) - (printf " whole-program: %s" whole) - (if (and (= per-ns whole) (string/has-prefix? "sum" per-ns)) - (print "whole-program: results match — sound") - (do (printf "whole-program: MISMATCH per-ns=%q whole=%q" per-ns whole) - (os/exit 1))))) diff --git a/test/spec/clojure-interop-fixes-spec.janet b/test/spec/clojure-interop-fixes-spec.janet deleted file mode 100644 index 3166dd5..0000000 --- a/test/spec/clojure-interop-fixes-spec.janet +++ /dev/null @@ -1,29 +0,0 @@ -# Specification: Clojure-compat fixes that landed with HTTP-client support -# (jolt-lang/http-client). All are general language behaviours, exercised here -# across interpret + compile modes by the harness. -(use ../support/harness) - -(defspec "interop-fixes / deprecated #^ metadata reader" - ["#^ type hint on a param" "\"x\"" - "(do (defn f1 [#^String s] s) (f1 \"x\"))"] - ["#^\"[B\" array hint" "[1 2]" - "(do (defn f2 [#^\"[B\" b] b) (f2 [1 2]))"] - ["#^ is equivalent to ^" "true" - "(= (meta (with-meta [] {:tag (quote String)})) {:tag (quote String)})"]) - -(defspec "interop-fixes / (str pattern) yields raw source" - ["str of a regex" "\"abc\"" "(str #\"abc\")"] - ["compose patterns via str" "true" - "(boolean (re-matches (re-pattern (str #\"<\" \"(.*)\" \">\")) \"\"))"]) - -(defspec "interop-fixes / into onto a map" - ["merges map items" "true" "(= {:a 1 :b 2} (into {} [{:a 1} {:b 2}]))"] - ["accepts [k v] pairs" "true" "(= {:a 1} (into {} [[:a 1]]))"] - ["map item onto empty {}" "true" "(= {:x 1} (into {} (list {:x 1})))"] - ["conj a map onto {}" "true" "(= {:a 1} (conj {} {:a 1}))"]) - -(defspec "interop-fixes / a var is callable as its value" - ["call a var directly" "42" - "(do (def vf (fn [x] (inc x))) ((var vf) 41))"] - ["var bound as a client fn" "\"ok\"" - "(do (def base (fn [_] \"ok\")) (def mw (fn [client] (fn [req] (client req)))) ((mw (var base)) {}))"]) diff --git a/test/spec/control-flow-spec.janet b/test/spec/control-flow-spec.janet deleted file mode 100644 index 59e3ccf..0000000 --- a/test/spec/control-flow-spec.janet +++ /dev/null @@ -1,108 +0,0 @@ -# Specification: control flow & binding forms. -(use ../support/harness) - -(defspec "control / conditionals" - ["if true" "1" "(if true 1 2)"] - ["if false" "2" "(if false 1 2)"] - ["if nil is false" "2" "(if nil 1 2)"] - ["if no else" "nil" "(if false 1)"] - ["when true" "3" "(when true 1 2 3)"] - ["when false" "nil" "(when false 1)"] - ["when-not" "1" "(when-not false 1)"] - ["cond" ":b" "(cond false :a true :b :else :c)"] - ["cond :else" ":c" "(cond false :a false :b :else :c)"] - ["cond no match" "nil" "(cond false :a)"] - ["condp" "\"two\"" "(condp = 2 1 \"one\" 2 \"two\" \"other\")"] - ["case" ":b" "(case 2 1 :a 2 :b :default)"] - ["case default" ":d" "(case 9 1 :a 2 :b :d)"] - ["case multi" ":ab" "(case 2 (1 2) :ab 3 :c)"] - ["case symbol const" ":s" "(case 'foo foo :s :default)"] - ["case vector const" ":v" "(case [1 2] [1 2] :v :default)"] - ["case map const" ":m" "(case {:a 1} {:a 1} :m :default)"] - ["case list const" ":l" "(case '(a b) (quote (a b)) :l :default)"] - ["case keyword" ":k" "(case :x :x :k :default)"]) - -(defspec "control / logic" - ["and all true" "3" "(and 1 2 3)"] - ["and short circuits" "nil" "(and 1 nil 3)"] - ["and empty" "true" "(and)"] - ["or first truthy" "1" "(or nil 1 2)"] - ["or all false" "false" "(or nil false)"] - ["or empty" "nil" "(or)"] - ["not" "false" "(not true)"]) - -(defspec "control / let & loop" - ["let" "3" "(let [a 1 b 2] (+ a b))"] - ["let sequential" "3" "(let [a 1 b (+ a 2)] b)"] - ["let shadowing" "2" "(let [a 1] (let [a 2] a))"] - ["letfn mutual" "true" "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 10))"] - ["loop/recur" "15" "(loop [i 1 acc 0] (if (> i 5) acc (recur (inc i) (+ acc i))))"] - ["when-let" "2" "(when-let [x 1] (inc x))"] - ["when-let nil" "nil" "(when-let [x nil] (inc x))"] - ["if-let" "2" "(if-let [x 1] (inc x) :none)"] - ["if-let else" ":none" "(if-let [x nil] (inc x) :none)"] - ["if-some zero" "1" "(if-some [x 0] (inc x) :none)"] - ["when-some nil" "nil" "(when-some [x nil] x)"]) - -# Regression: if-let/when-let/if-some/when-some bind the name ONLY in the -# then/body branch. The else branch (and a falsy when-let body, which there is -# none of) must see the surrounding scope, not the binding — so the else of -# (let [x 5] (if-let [x nil] ...)) sees x=5, like Clojure. (Previously the macros -# wrapped the whole `if` in the binding's let*, leaking it into the else.) -(defspec "control / conditional-binding scope" - ["if-let else sees outer" "5" "(let [x 5] (if-let [x nil] :then x))"] - ["if-let then binds" "7" "(let [x 5] (if-let [x 7] x :else))"] - ["if-some else sees outer" "5" "(let [x 5] (if-some [x nil] :then x))"] - ["if-some binds false" "false" "(if-some [x false] x :else)"] - ["when-let else via or" "5" "(let [x 5] (or (when-let [x nil] x) x))"] - ["when-let multi-form body" "14" "(when-let [x 7] (inc x) (* x 2))"] - ["if-let in fn param" "9" "((fn [xs] (if-let [xs nil] :then xs)) 9)"] - ["when-some binds zero" "1" "(when-some [x 0] (inc x))"] - ["if-let evals test once" "1" "(let [c (atom 0)] (if-let [v (do (swap! c inc) :v)] @c :none))"]) - -# Regression: loop/recur lowering (jolt-v28u). The backend lowers tail loop/recur -# to a Janet while + state vars with a fresh per-iteration `let` rebinding of the -# loop names. The let rebinding is load-bearing: a closure created in the body -# must capture THAT iteration's value (Clojure semantics), not a shared mutable -# var — Janet closures capture vars by reference, so a naive while+var would give -# [3 3 3]. recur reads the (immutable) iteration bindings and writes the state -# vars, so cross-referencing args don't clobber (swap, fib). -(defspec "control / loop lowering (jolt-v28u)" - ["closure captures per-iter binding" "[0 1 2]" - "(mapv (fn [g] (g)) (loop [i 0 fs []] (if (< i 3) (recur (inc i) (conj fs (fn [] i))) fs)))"] - ["fib via loop" "55" "(loop [a 0 b 1 i 0] (if (= i 10) a (recur b (+ a b) (inc i))))"] - ["recur args no clobber" "[2 1]" "(loop [a 1 b 2 n 0] (if (= n 1) [a b] (recur b a (inc n))))"] - ["nested loops" "9" "(loop [i 0 s 0] (if (= i 3) s (recur (inc i) (loop [j 0 t s] (if (= j 3) t (recur (inc j) (inc t)))))))"] - ["loop sequential init" "12" "(loop [a 1 b (+ a 10)] (+ a b))"] - ["recur through let" "6" "(loop [i 0 acc 0] (let [x (* i 2)] (if (< i 3) (recur (inc i) (+ acc x)) acc)))"] - ["fn-arity recur intact" "15" "((fn f [n acc] (if (zero? n) acc (recur (dec n) (+ acc n)))) 5 0)"]) - -(defspec "control / iteration" - ["dotimes side-effect" "5" "(let [a (atom 0)] (dotimes [i 5] (swap! a inc)) @a)"] - ["while" "5" "(let [a (atom 0)] (while (< @a 5) (swap! a inc)) @a)"] - ["for" "[0 1 2]" "(for [x (range 3)] x)"] - ["for nested" "[[0 :a] [0 :b] [1 :a] [1 :b]]" "(for [x (range 2) y [:a :b]] [x y])"] - ["for :when" "[0 2 4]" "(for [x (range 6) :when (even? x)] x)"] - ["for :while" "[0 1 2]" "(for [x (range 10) :while (< x 3)] x)"] - ["for :let" "[0 1 4]" "(for [x (range 3) :let [sq (* x x)]] sq)"] - ["for :let+:when" "[4 6 8]" "(for [x (range 5) :let [y (* x 2)] :when (> y 3)] y)"] - ["for multi :when" "[[1 :a] [1 :b]]" "(for [x [0 1] :when (odd? x) y [:a :b]] [x y])"] - ["for destructure" "[3 7]" "(for [[a b] [[1 2] [3 4]]] (+ a b))"] - ["doseq side-effect" "6" "(let [a (atom 0)] (doseq [x [1 2 3]] (swap! a (fn [v] (+ v x)))) @a)"] - ["doseq nested" "4" "(let [c (atom 0)] (doseq [x [1 2] y [10 20]] (swap! c inc)) @c)"] - ["doseq :when" "[1 3]" "(let [a (atom [])] (doseq [x [1 2 3] :when (odd? x)] (swap! a conj x)) @a)"] - ["doseq :while" "6" "(let [a (atom 0)] (doseq [x (range 10) :while (< x 4)] (swap! a + x)) @a)"] - ["doseq :let" "[0 1 4]" "(let [a (atom [])] (doseq [x (range 3) :let [sq (* x x)]] (swap! a conj sq)) @a)"] - ["doseq returns nil" "nil" "(doseq [x [1 2 3]] x)"]) - -(defspec "control / threading" - ["->" "6" "(-> 1 inc (+ 4))"] - ["-> with forms" "[1 2 3]" "(-> [] (conj 1) (conj 2) (conj 3))"] - ["->>" "9" "(->> [1 2 3] (map inc) (reduce +))"] - ["as->" "2" "(as-> [0 1] x (map inc x) (reverse x) (first x))"] - ["some->" "2" "(some-> 1 inc)"] - ["some-> nil stops" "nil" "(some-> nil inc)"] - ["some->>" "[2 3]" "(some->> [1 2] (map inc))"] - ["cond->" "2" "(cond-> 1 true inc false inc)"] - ["cond->>" "[1 2]" "(cond->> [2] true (cons 1))"] - ["doto returns subject" "5" "(let [a (doto (atom 0) (reset! 5))] @a)"]) diff --git a/test/spec/core-async-spec.janet b/test/spec/core-async-spec.janet deleted file mode 100644 index dfaec9f..0000000 --- a/test/spec/core-async-spec.janet +++ /dev/null @@ -1,98 +0,0 @@ -# Specification: clojure.core.async on Janet fibers (Phase 1 — API layer). -# Each case is self-contained: it requires the ns, sets up channels/go blocks, -# and ends with a take that pumps the event loop and yields the value compared. -(use ../support/harness) - -(def REQ - "(require '[clojure.core.async :refer [go go-loop chan ! close! alts! timeout put! take! chan? buffer dropping-buffer sliding-buffer]]) ") -(defn- a [body] (string "(do " REQ body ")")) - -(defspec "core.async / go & channels" - ["go produce, ! c (+ 40 2))) ( channel closes" - "nil" (a "(! x 10)) (go (>! y 32)) (! c 1) (>! c 2) (>! c 3) (close! c)) (! c :a) (close! c)) (! to a closed channel is false" - "false" (a "(def c (chan 1)) (close! c) (>! c 1)")] - ["take from closed empty channel is nil" - "nil" (a "(def c (chan)) (close! c) (! in 1) (>! in 2) (>! in 3) (close! in)) (! mid (inc (! out (* 10 (! in 4)) (! y :v)) (! c 7)) (! c 1) (>! c 2) (>! c 3) (close! c))")] - ["filter transducer" - "[0 2 4]" (drain "(def c (chan 10 (filter even?))) (go (doseq [x (range 6)] (>! c x)) (close! c))")] - ["mapcat expands" - "[1 1 2 2]" (drain "(def c (chan 10 (mapcat (fn [x] [x x])))) (go (>! c 1) (>! c 2) (close! c))")] - ["take closes early" - "[:a :b]" (drain "(def c (chan 10 (take 2))) (go (>! c :a) (>! c :b) (>! c :c) (>! c :d) (close! c))")] - ["comp of transducers" - "[10 30 50]" (drain "(def c (chan 10 (comp (filter odd?) (map (fn [x] (* x 10)))))) (go (doseq [x (range 6)] (>! c x)) (close! c))")]) - -# Buffers: fixed (default), dropping (drops new when full), sliding (drops oldest -# when full). Filled synchronously on this fiber (dropping/sliding never park). -(defn- fill [bufexpr] - (string "(do " REQ "(def c (chan " bufexpr ")) (doseq [x [1 2 3 4 5]] (>! c x)) (close! c)" - " (Foo \"hi\")))"] - ["str uses the method" "\"hi\"" - "(do (deftype Foo [s] Object (toString [_] s)) (str (->Foo \"hi\")))"] - ["str concatenation uses it" "\"\"" - "(do (deftype Foo [s] Object (toString [_] s)) (str \"<\" (->Foo \"hi\") \">\"))"] - ["computed toString" "\"v=7\"" - "(do (deftype Boxed [v] Object (toString [_] (str \"v=\" v))) (str (->Boxed 7)))"] - # a record WITHOUT a custom toString keeps the #Type{...} repr (regression guard) - ["defrecord without toString keeps repr" "true" - "(do (defrecord Bar [x]) (boolean (re-find #\"Bar\" (str (->Bar 1)))))"] - # pr-str of a defrecord is unaffected (still the data repr) - ["pr-str of a defrecord is the repr" "true" - "(do (defrecord Baz [x]) (boolean (re-find #\"\\{\" (pr-str (->Baz 1)))))"]) diff --git a/test/spec/destructuring-spec.janet b/test/spec/destructuring-spec.janet deleted file mode 100644 index 91525dd..0000000 --- a/test/spec/destructuring-spec.janet +++ /dev/null @@ -1,79 +0,0 @@ -# Specification: destructuring (in let, fn, loop, doseq, for). -(use ../support/harness) - -(defspec "destructure / sequential" - ["basic vector" "3" "(let [[a b] [1 2]] (+ a b))"] - ["skip with _" "3" "(let [[_ b] [1 2]] (+ b 1))"] - ["rest with &" "[3 4]" "(let [[a & more] [1 3 4]] more)"] - [":as whole" "[1 2]" "(let [[a :as v] [1 2]] v)"] - ["nested" "3" "(let [[[a b]] [[1 2]]] (+ a b))"] - ["fewer values nil" "nil" "(let [[a b c] [1 2]] c)"] - ["over a list" "1" "(let [[a] (list 1 2)] a)"] - ["over a seq" "2" "(let [[a b] (rest [9 1 2])] b)"] - ["string chars" "\\a" "(let [[a] (seq \"ab\")] a)"]) - -(defspec "destructure / associative" - ["keys" "3" "(let [{:keys [a b]} {:a 1 :b 2}] (+ a b))"] - [":as map" "{:a 1}" "(let [{:as m} {:a 1}] m)"] - [":or default" "9" "(let [{:keys [a] :or {a 9}} {}] a)"] - [":or present" "1" "(let [{:keys [a] :or {a 9}} {:a 1}] a)"] - ["explicit binding" "1" "(let [{x :a} {:a 1}] x)"] - ["nested map" "2" "(let [{{b :b} :a} {:a {:b 2}}] b)"] - ["keys + as" "[1 {:a 1}]" "(let [{:keys [a] :as m} {:a 1}] [a m])"] - ["map in vector" "1" "(let [[{:keys [a]}] [{:a 1}]] a)"]) - -(defspec "destructure / in forms" - ["fn params" "3" "((fn [[a b]] (+ a b)) [1 2])"] - ["fn map param" "1" "((fn [{:keys [a]}] a) {:a 1})"] - ["defn destructure" "3" "(do (defn f [[a b]] (+ a b)) (f [1 2]))"] - ["loop destructure" "3" "(loop [[a b] [1 2]] (+ a b))"] - ["doseq destructure" "12" "(let [s (atom 0)] (doseq [[k v] {:a 4 :b 8}] (swap! s (fn [x] (+ x v)))) @s)"] - ["for destructure" "[3 7]" "(for [[a b] [[1 2] [3 4]]] (+ a b))"] - ["& rest in fn" "[2 3]" "((fn [a & more] more) 1 2 3)"]) - -(defspec "destructure / associative extras" - [":strs" "7" "(let [{:strs [a]} {\"a\" 7}] a)"] - [":syms" "8" "(let [{:syms [a]} {(quote a) 8}] a)"] - ["namespaced :keys" "3" "(let [{:keys [x/y]} {:x/y 3}] y)"] - ["namespaced :syms" "4" "(let [{:syms [p/q]} {(quote p/q) 4}] q)"] - # :keys also accepts keyword elements ({:keys [:a :b]}), binding bare locals. - ["keyword :keys" "3" "(let [{:keys [:a :b]} {:a 1 :b 2}] (+ a b))"] - ["keyword :keys ns" "3" "(let [{:keys [:x/y]} {:x/y 3}] y)"]) - -(defspec "destructure / keyword args (& {:keys})" - ["fn kwargs" "[1 2]" "(do (defn f [& {:keys [a b]}] [a b]) (f :a 1 :b 2))"] - ["fn kwargs + fixed" "[0 5]" "(do (defn g [x & {:keys [a]}] [x a]) (g 0 :a 5))"] - ["fn kwargs :or" "9" "(do (defn h [& {:keys [a] :or {a 9}}] a) (h))"] - ["fn kwargs trailing map" "7" "(do (defn k [& {:keys [a]}] a) (k {:a 7}))"]) - -(defspec "destructure / fn params & loop" - ["fn vector param" "7" "((fn [[a b]] (+ a b)) [3 4])"] - ["fn map param" "30" "((fn [{:keys [x y]}] (* x y)) {:x 5 :y 6})"] - ["fn :or param" "7" "((fn [{:keys [x] :or {x 7}}] x) {})"] - ["fn multi-arity destr" "15" "((fn ([[a]] a) ([[a] b] (+ a b))) [10] 5)"] - ["loop vector binding" "[4 2]" "(loop [[a b] [1 2] n 0] (if (< n 3) (recur [(inc a) b] (inc n)) [a b]))"] - ["loop map binding" "4" "(loop [{:keys [v]} {:v 1} n 0] (if (< n 2) (recur {:v (* v 2)} (inc n)) v))"] - ["loop init sees destr" "[1 2 3]" "(loop [[a b] [1 2] c (+ a b)] [a b c])"]) - -# fn*/let*/loop* are PRIMITIVES: their binding forms must be plain symbols, exactly -# as in Clojure ("fn params must be Symbols" / "Bad binding form, expected symbol"). -# Destructuring lives in the fn/let/loop/defn MACROS, which desugar to plain -# primitives — so the interpreter and the self-hosted analyzer agree (neither -# destructures fn*), and nothing silently falls back to a lenient interpreter path. -(defspec "destructure / primitives reject patterns (jolt-f79)" - ["fn* fixed pattern" :throws "((fn* [[a b]] a) [1 2])"] - ["fn* rest pattern" :throws "((fn* [a & [b]] b) 1 2 3)"] - ["let* pattern" :throws "(let* [[a b] [1 2]] a)"] - ["loop* pattern" :throws "(loop* [[a b] [1 2]] a)"] - # the macros still desugar the same patterns to plain primitives: - ["fn desugars" "[1 2]" "((fn [[a b]] [a b]) [1 2])"] - ["let desugars" "[1 2]" "(let [[a b] [1 2]] [a b])"]) - -(defspec "destructure / macro params" - ["macro & [a & more :as all]" - "[1 [2 3] [1 2 3]]" - "(do (defmacro m [& [a & more :as all]] (list (quote quote) [a (vec more) (vec all)])) (m 1 2 3))"] - ["macro fixed destructure" "[2 1]" - "(do (defmacro mm [[a b]] (list (quote quote) [b a])) (mm [1 2]))"] - ["macro & {:keys}" "5" - "(do (defmacro mk [& {:keys [x]}] (list (quote quote) x)) (mk :x 5))"]) diff --git a/test/spec/exceptions-spec.janet b/test/spec/exceptions-spec.janet deleted file mode 100644 index ce89a14..0000000 --- a/test/spec/exceptions-spec.janet +++ /dev/null @@ -1,41 +0,0 @@ -# Specification: exceptions — try/catch/finally, throw, ex-info. -(use ../support/harness) - -(defspec "exceptions / try-catch" - ["catch :default" ":caught" - "(try (throw (ex-info \"boom\" {})) (catch :default e :caught))"] - ["catch by class" ":caught" - "(try (throw (ex-info \"boom\" {})) (catch Exception e :caught))"] - ["catch binds error" "\"boom\"" - "(try (throw (ex-info \"boom\" {})) (catch :default e (ex-message e)))"] - ["no throw -> body" "1" - "(try 1 (catch :default e :caught))"] - ["finally runs on ok" "2" - "(let [a (atom 0)] (try 2 (finally (reset! a 9))) )"] - ["finally runs on throw" "9" - "(let [a (atom 0)] (try (throw (ex-info \"x\" {})) (catch :default e nil) (finally (reset! a 9))) @a)"] - ["catch value of body" "5" - "(try (+ 2 3) (catch :default e 0))"]) - -(defspec "exceptions / assert" - ["assert true -> ok" ":ok" "(do (assert true) :ok)"] - ["assert expr -> ok" ":ok" "(do (assert (= 1 1)) :ok)"] - ["assert false throws" :throws "(assert false)"] - ["assert nil throws" :throws "(assert nil)"]) - -(defspec "exceptions / ex-info" - ["ex-message" "\"oops\"" "(ex-message (ex-info \"oops\" {}))"] - ["ex-data" "{:k 1}" "(ex-data (ex-info \"oops\" {:k 1}))"] - ["ex-data via catch" "{:code 42}" - "(try (throw (ex-info \"e\" {:code 42})) (catch :default e (ex-data e)))"] - ["ex-cause" "true" - "(let [c (ex-info \"root\" {})] (= c (ex-cause (ex-info \"outer\" {} c))))"] - ["propagates to outer" "\"inner\"" - "(try (try (throw (ex-info \"inner\" {})) (finally nil)) (catch :default e (ex-message e)))"] - ["catch binds thrown value" "42" - "(try (throw 42) (catch :default e e))"] - ["rethrow preserves ex" "\"inner\"" - "(try (try (throw (ex-info \"inner\" {})) (catch :default e (throw e))) (catch :default e (ex-message e)))"] - ["ex-data on non-ex" "nil" "(ex-data 42)"] - ["ex-cause on non-ex" "nil" "(ex-cause {:k 1})"] - ["ex-message of string" "\"hi\"" "(ex-message \"hi\")"]) diff --git a/test/spec/forms-spec.janet b/test/spec/forms-spec.janet deleted file mode 100644 index dab5fb8..0000000 --- a/test/spec/forms-spec.janet +++ /dev/null @@ -1,92 +0,0 @@ -# Specification: core special forms (case/fn/let/letfn/loop/if/do/def/call). -# -# Adapted from the jank test corpus (compiler+runtime/test/jank/form/**, /call) — -# we base our coverage on jank's to close gaps, but maintain our own copies since -# jank may diverge. jank-isms are translated to Jolt/Clojure: letfn* -> letfn, -# (catch jank.runtime.object_ref …) -> (catch :default …). Platform-specific cases -# (bigdecimal M, biginteger, ratios, unicode char edges) are intentionally omitted. -# -# Multi-form jank files (def + asserts, ending in :success) are wrapped in a single -# (do … :success) so they run as one expression and assert :success. -(use ../support/harness) - -(defspec "forms / case" - ["bool" ":yes" "(case true true :yes false :no :default)"] - ["keyword match" ":b" "(case :a :x :wrong :a :b :default)"] - ["number match" ":two" "(case 2 1 :one 2 :two :default)"] - ["string match" ":hit" "(case \"x\" \"y\" :miss \"x\" :hit :default)"] - ["nil match" ":nada" "(case nil nil :nada :default)"] - ["default" ":def" "(case 99 1 :one 2 :two :def)"] - ["list of consts" ":vowel" "(case \\a (\\a \\e \\i \\o \\u) :vowel :consonant)"] - ["no match no default" :throws "(case 5 1 :one)"] - ["duplicate keys" :throws "(case 1 1 :one 1 :dup :default)"] - ["duplicate in or-group" :throws "(case 2 (1 2) :a (2 3) :b :default)"]) - -(defspec "forms / fn" - ["named fn nil" "nil" "((fn* foo-bar []))"] - ["immediate call" "1" "((fn* [] 1))"] - ["args" "[:a :b]" "((fn* [a b] [a b]) :a :b)"] - ["multi-arity 0" "0" "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add))"] - ["multi-arity 1" "-500" "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add -500))"] - ["multi-arity 2" "-450" "(do (def add (fn* ([] 0) ([a] a) ([a b] (+ a b)))) (add -500 50))"] - ["variadic rest" "[3 4]" "(do (def v (fn* ([a b & args] args) ([] 0))) (v 1 2 3 4))"] - ["variadic empty" "0" "(do (def v (fn* ([a b & args] args) ([] 0))) (v))"] - ["variadic collect" "[{} nil :m]" "((fn* [a b & args] args) 'w 't {} nil :m)"] - ["closure capture" "8" "(do (def adder (fn* [n] (fn* [x] (+ x n)))) ((adder 5) 3))"] - ["recur countdown" "0" "(do (def cd (fn* [n] (if (< 0 n) (recur (+ n -1)) n))) (cd 10))"] - ["named self-recur" "120" "(do (def f (fn* fact [n] (if (= n 0) 1 (* n (fact (dec n)))))) (f 5))"] - ["no param vector" :throws "(fn* foo)"] - ["non-symbol param" :throws "(fn* [1] 1)"]) - -(defspec "forms / let" - ["literal" "1" "(let* [a 1] a)"] - ["multiple" "[1 2]" "(let* [a 1 b 2] [a b])"] - ["previous ref" ":bee" "(let* [a 1 b (if (= 1 a) :bee :uh-oh)] b)"] - ["nested let" "3" "(let* [a 5 b (let* [c -2] (+ a c))] b)"] - ["fn value bound" "\":foo\"" "(let* [kw->str (fn* [kw] (str kw))] (kw->str :foo))"] - ["shadowing" "2" "(let* [a 1 a 2] a)"]) - -(defspec "forms / letfn" - ["mutual top" "[1 2]" "(letfn [(a [] 1) (b [] 2)] [(a) (b)])"] - ["mutual recursion" ":done" "(letfn [(ev? [n] (if (= 0 n) :done (od? (dec n)))) (od? [n] (ev? n))] (ev? 4))"] - ["nested letfn" "3" "(letfn [(a [] 5) (b [] (letfn [(c [] -2)] (+ (a) (c))))] (b))"]) - -(defspec "forms / loop" - ["sum" "55" "(loop* [sum 0 cnt 10] (if (= cnt 0) sum (recur (+ cnt sum) (dec cnt))))"] - ["multi binding" "[4 2]" "(loop* [a 1 b 2 n 0] (if (< n 3) (recur (inc a) b (inc n)) [a b]))"] - ["init sees prior" "[1 2 3]" "(loop* [a 1 b (+ a 1) c (+ b 1)] [a b c])"]) - -(defspec "forms / try" - ["immediate throw caught" ":caught" "(try (throw :boom) (catch :default e :caught))"] - ["first throw wins" "\"a\"" "(try (throw (ex-info \"a\" {})) (throw (ex-info \"b\" {})) (catch :default e (ex-message e)))"] - ["catch ex-data" "7" "(try (throw (ex-info \"e\" {:v 7})) (catch :default e (:v (ex-data e))))"] - ["finally runs" "9" "(let [a (atom 0)] (try 1 (finally (reset! a 9))) @a)"] - ["body value w/ finally" "1" "(try 1 (finally 2))"] - ["catch value w/ finally" ":h" "(try (throw (ex-info \"x\" {})) (catch :default e :h) (finally :ignored))"] - ["no throw skips catch" "5" "(try 5 (catch :default e :nope))"]) - -(defspec "forms / if-do-def-call" - ["if truthy vec" ":fine" "(if [:ok] :fine :no)"] - ["if truthy str" ":fine" "(if \"good?\" :fine :no)"] - ["if nil = false" ":else" "(if nil :then :else)"] - ["if no else" "nil" "(if false 1)"] - ["do nested" "1" "(do (do (do (do 1))))"] - ["do returns last" "3" "(do 1 2 3)"] - ["def + deref var" "true" "(var? (def one 1))"] - ["def no init interns var" "true" "(var? (def no-init))"] - ["def no init keeps existing root" "7" "(do (def kept 7) (def kept) kept)"] - ["declare interns var" "true" "(do (declare fwd-declared) (var? (var fwd-declared)))"] - ["def redefine" "100" "(do (def one 1) (def one 100) one)"] - ["def in fn mutates" "[:default :meow]" "(do (def a :default) (def set-a (fn* [v] (def a v))) (let* [before a] (set-a :meow) [before a]))"] - ["call literal fn" "1" "((fn* [] 1))"] - ["call nested" "6" "(+ ((fn* [] 1)) ((fn* [] 2)) ((fn* [] 3)))"] - ["call nil" :throws "(nil)"]) - -# if takes two or three argument forms — anything else is a compile-time -# error (spec 03-special-forms X1). -(defspec "forms / if arity (X1)" - ["bare if throws" :throws "(if)"] - ["one-arg if throws" :throws "(if true)"] - ["four-arg if throws" :throws "(if true 1 2 3)"] - ["two-arg if ok" "nil" "(if false 1)"] - ["three-arg if ok" "2" "(if false 1 2)"]) diff --git a/test/spec/functions-spec.janet b/test/spec/functions-spec.janet deleted file mode 100644 index ba1f07c..0000000 --- a/test/spec/functions-spec.janet +++ /dev/null @@ -1,223 +0,0 @@ -# Specification: functions & higher-order combinators. -(use ../support/harness) - -(defspec "functions / definition" - ["fn literal" "3" "((fn [a b] (+ a b)) 1 2)"] - ["fn shorthand" "3" "(#(+ %1 %2) 1 2)"] - ["fn shorthand %" "2" "(#(inc %) 1)"] - ["defn" "5" "(do (defn f [x] (+ x 2)) (f 3))"] - ["multi-arity" "[1 5]" "(do (defn f ([x] x) ([x y] (+ x y))) [(f 1) (f 2 3)])"] - ["variadic" "[1 2 3]" "(do (defn f [& xs] xs) (f 1 2 3))"] - ["variadic with fixed" "[1 [2 3]]" "(do (defn f [a & xs] [a xs]) (f 1 2 3))"] - ["closure captures" "8" "(do (defn adder [n] (fn [x] (+ x n))) ((adder 5) 3))"] - ["recursion" "120" "(do (defn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) (fact 5))"] - ["named fn self-ref" "120" "((fn fact [n] (if (< n 2) 1 (* n (fact (dec n))))) 5)"] - # A param whose name collides with a Janet builtin the back end emits in - # generated code (here `in`, used to deref vars / index shape-recs) must not - # shadow it — malli's explainer binds `[value in acc]` (jolt-fjb1). - ["param named `in`" "1" "((fn [in] (first in)) [1 2 3])"] - ["param `in` via core fn" "3" "((fn [in] (count in)) [1 2 3])"] - ["local `in` in let body" "2" "(let [in [2 3]] (first in))"]) - -(defspec "functions / application" - ["apply" "6" "(apply + [1 2 3])"] - ["apply with leading" "10" "(apply + 1 2 [3 4])"] - ["apply keyword" "1" "(apply :a [{:a 1}])"] - ["partial" "7" "((partial + 5) 2)"] - ["partial multi" "10" "((partial + 1 2) 3 4)"] - ["comp" "4" "((comp inc inc) 2)"] - ["comp order" "5" "((comp inc (fn [x] (* x 2))) 2)"] - ["comp identity" "3" "((comp) 3)"] - ["complement" "true" "((complement even?) 3)"] - ["constantly" "5" "((constantly 5) 1 2 3)"] - ["identity" "7" "(identity 7)"]) - -(defspec "functions / combinators" - ["juxt" "[1 3]" "((juxt first last) [1 2 3])"] - ["fnil" "1" "((fnil inc 0) nil)"] - ["fnil passes value" "6" "((fnil inc 0) 5)"] - ["every-pred true" "true" "((every-pred pos? even?) 4)"] - ["every-pred false" "false" "((every-pred pos? even?) 3)"] - ["some-fn" "true" "((some-fn even? neg?) 3 4)"] - ["memoize" "2" "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) x))) (f 1) (f 1) (f 2) @c)"] - ["trampoline" "10" "(trampoline (fn f [n acc] (if (zero? n) acc (fn [] (f (dec n) (+ acc 2))))) 5 0)"]) - -# Phase 2 leaf batch (jolt-ded): moved from the Janet seed to 20-coll.clj. -(defspec "clojure.core / leaf batch (complement fnil munge etc.)" - ["complement true" "true" "((complement pos?) -1)"] - ["complement false" "false" "((complement pos?) 1)"] - ["complement multi" "true" "((complement <) 3 2)"] - ["fnil patches nil" "1" "((fnil inc 0) nil)"] - ["fnil passes non-nil" "6" "((fnil inc 0) 5)"] - ["fnil two defaults" "8" "((fnil + 1 2) nil nil 5)"] - ["fnil only first 3" "[:a :b :c nil]" "((fnil vector :a :b :c) nil nil nil nil)"] - ["fnil in update" "{:k 1}" "(update {} :k (fnil inc 0))"] - ["clojure-version" "true" "(string? (clojure-version))"] - ["bigdec" "3" "(bigdec 3)"] - ["numerator throws" :throws "(numerator 1)"] - ["denominator throws" :throws "(denominator 1)"] - ["supers empty set" "#{}" "(supers 1)"] - ["munge dashes" "\"a_b\"" "(munge \"a-b\")"] - ["munge symbol" "\"x_y\"" "(munge (quote x-y))"] - ["test no-test" ":no-test" "(test (quote foo))"]) - -# Phase 2 leaf batch 2 (jolt-ded): canonical ports of key/val/select-keys/ -# zipmap/merge/merge-with/get-in/memoize/partial/trampoline/some?/true?/false?/ -# max/min/reverse, plus find (previously missing entirely). -(defspec "clojure.core / leaf batch 2" - ["key" "1" "(key (first {1 :a}))"] - ["val" ":a" "(val (first {1 :a}))"] - ["key non-entry throws" :throws "(key 5)"] - ["find hit" "[:a 1]" "(find {:a 1} :a)"] - ["find miss" "nil" "(find {:a 1} :b)"] - ["find nil value" "[:a nil]" "(find {:a nil} :a)"] - ["find on vector" "[0 :x]" "(find [:x :y] 0)"] - ["select-keys" "{:a 1}" "(select-keys {:a 1 :b 2} [:a])"] - ["select-keys nil val" "{:a nil}" "(select-keys {:a nil :b 2} [:a])"] - ["select-keys missing" "{}" "(select-keys {:a 1} [:z])"] - ["zipmap" "{:a 1 :b 2}" "(zipmap [:a :b] [1 2])"] - ["zipmap uneven" "{:a 1}" "(zipmap [:a :b] [1])"] - ["zipmap nil val" "{:a nil}" "(zipmap [:a] [nil])"] - ["merge" "{:a 1 :b 2}" "(merge {:a 1} {:b 2})"] - ["merge later wins" "{:a 2}" "(merge {:a 1} {:a 2})"] - ["merge nil arg" "{:a 1}" "(merge {:a 1} nil)"] - ["merge nil first" "{:a 1}" "(merge nil {:a 1})"] - ["merge all nil" "nil" "(merge nil nil)"] - ["merge empty" "nil" "(merge)"] - ["merge entry pair" "{:a 1 :b 2}" "(merge {:a 1} [:b 2])"] - ["merge-with" "{:a 3}" "(merge-with + {:a 1} {:a 2})"] - ["merge-with disjoint" "{:a 1 :b 2}" "(merge-with + {:a 1} {:b 2})"] - ["merge-with nil-val present" "{:a 1}" "(merge-with (fn [a b] (or a b)) {:a nil} {:a 1})"] - ["get-in" "1" "(get-in {:a {:b 1}} [:a :b])"] - ["get-in missing" ":nf" "(get-in {:a 1} [:z :y] :nf)"] - ["get-in nil value present" "nil" "(get-in {:a {:b nil}} [:a :b] :nf)"] - ["get-in empty path" "{:a 1}" "(get-in {:a 1} [])"] - ["memoize" "2" "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) x))) (f 1) (f 1) (f 2) (deref c))"] - ["memoize caches nil" "1" "(do (def c (atom 0)) (def f (memoize (fn [x] (swap! c inc) nil))) (f 1) (f 1) (deref c))"] - ["partial" "6" "((partial + 1 2) 3)"] - ["partial no extra" "3" "((partial + 1 2))"] - ["partial many fixed" "15" "((partial + 1 2 3 4) 5)"] - ["trampoline" "10" "(trampoline (fn f [n acc] (if (zero? n) acc (fn [] (f (dec n) (+ acc 2))))) 5 0)"] - ["some? true" "true" "(some? 0)"] - ["some? false" "false" "(some? nil)"] - ["true?/false?" "[true false false]" "[(true? true) (true? 1) (false? nil)]"] - ["max" "3" "(max 1 3 2)"] - ["min" "1" "(min 3 1 2)"] - ["max single" "5" "(max 5)"] - ["max non-number throws" :throws "(max 1 :a)"] - ["reverse" "(quote (3 2 1))" "(reverse [1 2 3])"] - ["reverse empty" "()" "(reverse nil)"] - ["conj nil onto map" "{:a 1}" "(conj {:a 1} nil)"]) - -# Phase 2 leaf batch 3 (jolt-ded): empty/assoc-in/update-in (20-coll) and -# interpose/take-nth (40-lazy, with canonical transducer arities). keys/vals/ -# empty? are expander-coupled (00-syntax macros call them) and stay in the -# seed until the fast macro-expansion path lands. -(defspec "clojure.core / leaf batch 3" - ["empty vector" "[]" "(empty [1 2])"] - ["empty list" "()" "(empty (list 1))"] - ["empty map" "{}" "(empty {:a 1})"] - ["empty set" "#{}" "(empty #{1})"] - ["empty nil" "nil" "(empty nil)"] - ["empty string" "nil" "(empty \"abc\")"] - ["empty lazy is ()" "()" "(empty (map inc [1 2]))"] - ["empty sorted keeps cmp" "[3 1]" "(vec (seq (into (empty (sorted-set-by > 1 2)) [1 3])))"] - ["assoc-in" "{:a {:b 1}}" "(assoc-in {} [:a :b] 1)"] - ["assoc-in deep" "{:a {:b {:c 2}}}" "(assoc-in {:a {:b {:c 1}}} [:a :b :c] 2)"] - ["assoc-in keeps siblings" "{:a {:b 1 :c 2}}" "(assoc-in {:a {:b 1}} [:a :c] 2)"] - ["assoc-in vector idx" "[1 9]" "(assoc-in [1 2] [1] 9)"] - ["assoc-in nested vec" "[{:a 9}]" "(assoc-in [{:a 1}] [0 :a] 9)"] - ["update-in" "{:a {:b 2}}" "(update-in {:a {:b 1}} [:a :b] inc)"] - ["update-in extra args" "{:a {:b 111}}" "(update-in {:a {:b 1}} [:a :b] + 10 100)"] - ["update-in fnil" "{:a {:b 1}}" "(update-in {} [:a :b] (fnil inc 0))"] - ["update-in single key" "{:a 2}" "(update-in {:a 1} [:a] inc)"] - ["interpose" "(quote (1 :s 2 :s 3))" "(interpose :s [1 2 3])"] - ["interpose empty" "()" "(interpose :s [])"] - ["interpose one" "(quote (1))" "(interpose :s [1])"] - ["interpose is lazy" "(quote (0 :s 1))" "(take 3 (interpose :s (range)))"] - ["interpose xform" "[\"a\" \",\" \"b\"]" "(vec (sequence (interpose \",\") [\"a\" \"b\"]))"] - ["take-nth" "(quote (1 3 5))" "(take-nth 2 [1 2 3 4 5 6])"] - ["take-nth lazy" "(quote (0 3 6))" "(take 3 (take-nth 3 (range)))"] - ["take-nth xform" "[1 3 5]" "(vec (sequence (take-nth 2) [1 2 3 4 5 6]))"] - ["take-nth into" "[1 4]" "(into [] (take-nth 3) [1 2 3 4 5])"]) - -# Phase 2 leaf batch 4 (jolt-ded): sort-by (canonical: compare-defaulted, over -# the host sort seam), rand-int (canonical truncation via int), pure -# Fisher-Yates shuffle, random-uuid over parse-uuid, char tables as -# char-keyed Clojure maps. rand and sort stay: they ARE the host seams. -(defspec "clojure.core / leaf batch 4" - ["sort-by keyfn" "[[1 :b] [2 :a]]" "(sort-by first [[2 :a] [1 :b]])"] - ["sort-by string keys" "(quote (\"a\" \"bb\" \"ccc\"))" "(sort-by count [\"ccc\" \"a\" \"bb\"])"] - ["sort-by comparator" "[3 2 1]" "(sort-by identity > [1 3 2])"] - ["sort-by 3way cmp" "[3 2 1]" "(sort-by identity (fn [a b] (- b a)) [1 3 2])"] - ["sort-by mixed nil" "[nil 1 2]" "(sort-by identity [2 nil 1])"] - ["sort-by empty" "()" "(sort-by first [])"] - ["sort-by nil coll" "()" "(sort-by first nil)"] - ["rand-int range" "true" "(every? (fn [_] (let [r (rand-int 5)] (and (int? r) (<= 0 r 4)))) (range 50))"] - ["rand-int zero" "0" "(rand-int 1)"] - ["shuffle is permutation" "true" "(= (sort (shuffle [5 3 1 4 2])) [1 2 3 4 5])"] - ["shuffle returns vector" "true" "(vector? (shuffle [1 2 3]))"] - ["shuffle empty" "[]" "(shuffle [])"] - ["shuffle non-coll throws" :throws "(shuffle 5)"] - ["random-uuid is uuid" "true" "(uuid? (random-uuid))"] - ["random-uuid v4 shape" "true" "(boolean (re-matches #\"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\" (str (random-uuid))))"] - ["random-uuid distinct" "true" "(not= (random-uuid) (random-uuid))"] - ["char-escape newline" "\"\\\\n\"" "(char-escape-string \\newline)"] - ["char-escape quote" "true" "(= 2 (count (char-escape-string \\\")))"] - ["char-escape none" "nil" "(char-escape-string \\a)"] - ["char-name space" "\"space\"" "(char-name-string \\space)"] - ["char-name newline" "\"newline\"" "(char-name-string \\newline)"] - ["char-name none" "nil" "(char-name-string \\a)"]) - -# recur into a VARIADIC fn arity binds the LAST recur arg directly as the -# rest seq (Clojure: recur to a variadic head takes n-fixed + 1 args, no -# re-collection). The interpreter used to re-enter through the varargs -# collector, wrapping the seq in a fresh 1-element rest list — xs never -# emptied and the loop hung (jolt-4df). -(defspec "functions / recur into variadic arity" - ["counts rest via recur" "3" - "((fn cnt [acc & xs] (if (seq xs) (recur (inc acc) (rest xs)) acc)) 0 :a :b :c)"] - ["zero-fixed variadic" "4" - "((fn f [& xs] (if (< (count xs) 4) (recur (cons :x xs)) (count xs))) :a)"] - ["rest empties to nil" "(quote (:done))" - "((fn f [& xs] (if xs (recur (next xs)) (list :done))) 1 2)"] - ["multi-arity variadic recur" "6" - "((fn ma ([a] a) ([a & xs] (if (seq xs) (recur (+ a (first xs)) (rest xs)) a))) 1 2 3)"] - ["recur passes nil rest" ":empty" - "((fn f [acc & xs] (if (seq xs) (recur acc (rest xs)) :empty)) 0 1)"] - ["fixed-arity recur untouched" "10" - "((fn f [n acc] (if (pos? n) (recur (dec n) (+ acc 2)) acc)) 5 0)"]) - -# An EMPTY rest arg binds nil, never () — Clojure semantics. (f) with [& r] -# giving a truthy () sent yogthos/config's (or (.exists f) required) down the -# wrong branch and broke its load. -(defspec "functions / empty rest arg is nil" - ["no args" ":nil" "((fn [& r] (if r :truthy :nil)))"] - ["after fixed" ":nil" "((fn [a & r] (if r :truthy :nil)) 1)"] - ["via apply" ":nil" "(apply (fn [& r] (if r :truthy :nil)) [])"] - ["defn no args" ":nil" "(do (defn er-f [& r] (if r :truthy :nil)) (er-f))"] - ["non-empty unchanged" "'(1 2)" "((fn [& r] r) 1 2)"] - ["one extra" "'(2)" "((fn [a & r] r) 1 2)"] - ["rest destructure with no args" ":nil" - "((fn [& [a]] (if a :truthy :nil)))"]) - -# Arity enforcement (jolt-6xn): fixed arities throw on any mismatch, variadic -# arities on fewer than the fixed params — Clojure's ArityException, in both -# the interpreter and the compiled path. -(defspec "functions / arity enforcement" - ["fixed extra args" :throws "((fn [x] x) 1 2)"] - ["fixed missing args" :throws "((fn [x y] x) 1)"] - ["fixed zero of one" :throws "((fn [x] x))"] - ["named defn extra" :throws "(do (defn af1 [x] x) (af1 1 2))"] - ["overlay fn extra" :throws "(identity 1 2)"] - ["through apply" :throws "(apply (fn [x] x) [1 2])"] - ["through update" :throws "(update {:k 1} :k identity 1 2 3 4)"] - ["variadic below min" :throws "((fn [x & r] x))"] - ["variadic at min" "nil" "((fn [x & r] r) 1)"] - ["variadic above min" "(quote (2 3))" "((fn [x & r] r) 1 2 3)"] - ["multi-arity no match" :throws "((fn ([x] x) ([x y] y)) 1 2 3)"] - ["multi-arity variadic below min" :throws "((fn ([x] x) ([x y & r] r)))"] - ["destructured param counts as one" "3" "((fn [[a b] c] c) [1 2] 3)"] - ["destructured extra throws" :throws "((fn [[a b]] a) [1 2] [3 4])"] - ["hof exact arity ok" "[2 4]" "(mapv (fn [x] (* 2 x)) [1 2])"] - ["zero-arity fn ok" "7" "((fn [] 7))"]) diff --git a/test/spec/futures-spec.janet b/test/spec/futures-spec.janet deleted file mode 100644 index 82e5996..0000000 --- a/test/spec/futures-spec.janet +++ /dev/null @@ -1,64 +0,0 @@ -# Specification: clojure.core futures on Janet OS threads (ev/thread). -# -# A `future` runs its body on a *real* OS thread (ev/thread), so it can use a -# second core for CPU-bound work — unlike the cooperatively-scheduled go blocks. -# Because Janet threads have separate heaps, the body and its captured state are -# MARSHALLED (copied) to the worker thread and the result is marshalled back: a -# future sees a snapshot of captured state and communicates only via its return -# value (mutations to captured atoms do NOT propagate back). `deref`/`@` blocks -# (parks) until the worker finishes; the result is cached for later derefs. -(use ../support/harness) - -(defspec "clojure.core / futures — deref" - ["future + deref" "3" "(deref (future (+ 1 2)))"] - ["@ reader macro derefs" "42" "@(future (* 6 7))"] - ["future returns collection" "[2 3 4]" "(deref (future (mapv inc [1 2 3])))"] - ["future returns a map" "{:a 1}" "(deref (future {:a 1}))"] - ["deref is cached/idempotent" "[2 2]" "(let [f (future (+ 1 1))] [(deref f) (deref f)])"] - ["timed deref of ready future" "42" "(let [f (future 42)] (deref f) (deref f 1000 :nope))"] - ["body error re-raised on deref" :throws "(deref (future (throw \"boom\")))"] - # Thread/sleep parks the WORKER's own event loop (each future thread has one), - # so a sleeping future doesn't block the parent — and timed deref can fire. - ["timed deref times out" ":timed-out" "(deref (future (do (Thread/sleep 300) :late)) 10 :timed-out)"] - ["Thread/sleep in body" ":slept" "(deref (future (do (Thread/sleep 5) :slept)))"] - ["timed-out future still completes" ":late" - "(let [f (future (do (Thread/sleep 30) :late))] (deref f 5 :early) (deref f))"]) - -(defspec "clojure.core / futures — predicates" - ["future? true" "true" "(future? (future 1))"] - ["future? false" "false" "(future? 42)"] - ["future-done? after deref" "true" "(let [f (future 1)] (deref f) (future-done? f))"] - ["realized? after deref" "true" "(let [f (future 1)] (deref f) (realized? f))"] - # Cancel marks the future done (the worker can't be interrupted, but the - # future object reflects the cancellation: deref raises, predicates flip). - ["cancel an in-flight future returns true" "true" - "(let [f (future 1)] (future-cancel f))"] - ["future-cancelled? after cancel" "true" - "(let [f (future 1)] (future-cancel f) (future-cancelled? f))"] - ["future-done? after cancel" "true" - "(let [f (future 1)] (future-cancel f) (future-done? f))"] - ["cancel an already-completed future returns false" "false" - "(let [f (future 1)] (deref f) (future-cancel f))"] - ["future-cancelled? fresh is false" "false" - "(future-cancelled? (future 1))"]) - -(defspec "clojure.core / futures — snapshot (copy) semantics" - # The worker thread swaps its *copy* of the atom; the parent's atom is untouched. - ["captured atom is snapshotted, not shared" - "0" "(let [a (atom 0)] (deref (future (swap! a inc))) @a)"] - # The future's own return value still reflects the swap on its copy. - ["future sees its own mutation" - "1" "(let [a (atom 0)] (deref (future (swap! a inc))))"]) - -# pmap/pcalls/pvalues over the real-thread futures: spawn-all-then-deref, so -# independent work overlaps; snapshot semantics (pure fns only). The wall-time -# row uses generous margins (4 x 150ms in parallel vs 600ms serial). -(defspec "clojure.core / pmap family" - ["pmap values in order" "[2 3 4]" "(vec (pmap inc [1 2 3]))"] - ["pmap multi-coll" "[5 7 9]" "(vec (pmap + [1 2 3] [4 5 6]))"] - ["pmap empty" "()" "(pmap inc [])"] - ["pmap is parallel" "true" - "(do (deref (future :warmup)) (let [t0 (System/currentTimeMillis)] (dorun (pmap (fn [_] (Thread/sleep 200)) [1 2 3 4])) (< (- (System/currentTimeMillis) t0) 700)))"] - ["pcalls" "[1 2]" "(vec (pcalls (fn [] 1) (fn [] 2)))"] - ["pvalues" "[3 7]" "(vec (pvalues (+ 1 2) (+ 3 4)))"] - ["snapshot semantics" "0" "(let [a (atom 0)] (dorun (pmap (fn [_] (swap! a inc)) [1 2])) (deref a))"]) diff --git a/test/spec/hierarchy-spec.janet b/test/spec/hierarchy-spec.janet deleted file mode 100644 index e6de89a..0000000 --- a/test/spec/hierarchy-spec.janet +++ /dev/null @@ -1,48 +0,0 @@ -# Specification: ad-hoc hierarchies (make-hierarchy/derive/underive/isa?/ -# parents/ancestors/descendants) — ported to pure Clojure (stage 3). The -# 3-arity forms are PURE (derive returns a new hierarchy); the 1/2-arity forms -# use the global hierarchy. Multi-parent derive, transitive ancestors AND -# descendants, and vector-pair isa? match Clojure (the old Janet kernel had -# single-parent :parents and direct-only descendants). -(use ../support/harness) - -(defspec "hierarchy / pure 3-arity" - ["derive returns new h" "true" - "(let [h (derive (make-hierarchy) :rect :shape)] (and (map? h) (isa? h :rect :shape)))"] - ["original unchanged" "false" - "(let [h0 (make-hierarchy) h1 (derive h0 :rect :shape)] (isa? h0 :rect :shape))"] - ["isa? self" "true" "(isa? (make-hierarchy) :a :a)"] - ["isa? transitive" "true" - "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (isa? h :square :shape))"] - ["multi-parent" "[true true]" - "(let [h (-> (make-hierarchy) (derive :sq :rect) (derive :sq :rhombus))] [(isa? h :sq :rect) (isa? h :sq :rhombus)])"] - ["parents set" "true" - "(let [h (-> (make-hierarchy) (derive :sq :rect) (derive :sq :rhombus))] (= #{:rect :rhombus} (parents h :sq)))"] - ["ancestors transitive" "true" - "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (= #{:rect :shape} (ancestors h :square)))"] - ["descendants transitive" "true" - "(let [h (-> (make-hierarchy) (derive :square :rect) (derive :rect :shape))] (= #{:rect :square} (descendants h :shape)))"] - ["underive removes" "false" - "(let [h (-> (make-hierarchy) (derive :a :b) (underive :a :b))] (isa? h :a :b))"] - ["vector isa?" "true" - "(let [h (-> (make-hierarchy) (derive :rect :shape))] (isa? h [:rect :rect] [:shape :shape]))"] - ["vector isa? length" "false" - "(isa? (make-hierarchy) [:a] [:a :a])"] - ["cyclic derive throws" :throws - "(-> (make-hierarchy) (derive :a :b) (derive :b :a))"] - ["duplicate derive ok" "true" - "(let [h (-> (make-hierarchy) (derive :a :b) (derive :a :b))] (isa? h :a :b))"] - ["parents nil when none" "nil" "(parents (make-hierarchy) :x)"]) - -(defspec "hierarchy / global + multimethod dispatch" - ["global derive + isa?" "true" "(do (derive :gsq :grect) (isa? :gsq :grect))"] - ["global ancestors" "true" - "(do (derive :ga :gb) (derive :gb :gc) (contains? (ancestors :ga) :gc))"] - ["global underive" "false" - "(do (derive :gu :gv) (underive :gu :gv) (isa? :gu :gv))"] - ["dispatch via hierarchy" ":is-shape" - "(do (derive :hsq :hshape) (defmulti hmm identity) (defmethod hmm :hshape [_] :is-shape) (hmm :hsq))"] - ["dispatch custom hierarchy" ":parent" - "(do (def hh (atom (derive (make-hierarchy) :c :p))) (defmulti cmm identity :hierarchy hh) (defmethod cmm :p [_] :parent) (cmm :c))"] - ["dispatch exact beats isa" ":exact" - "(do (derive :de1 :de2) (defmulti emm identity) (defmethod emm :de2 [_] :parent) (defmethod emm :de1 [_] :exact) (emm :de1))"]) diff --git a/test/spec/host-interop-spec.janet b/test/spec/host-interop-spec.janet deleted file mode 100644 index 17e1b55..0000000 --- a/test/spec/host-interop-spec.janet +++ /dev/null @@ -1,314 +0,0 @@ -# Specification: host (Janet) interop — the `.` forms and jolt.interop. -(use ../support/harness) - -(defspec "interop / dot forms" - ["method call" "\"v=41\"" - "(. {:value 41 :describe (fn [self] (str \"v=\" (:value self)))} describe)"] - ["method with args" "\"Hello Alice\"" - "(. {:greet (fn [self n] (str \"Hello \" n))} greet \"Alice\")"] - ["field access .-" "41" "(.-value {:value 41})"] - ["dot field keyword" "41" "(. {:value 41} :value)"]) - -# Both `.` arms share one dispatch-member helper (jolt-eos3). These rows lock the -# behaviors where the call form (args) and the bare form (zero-arg) diverge in -# their tails: zero-arg coll-interop vs with-arg coll-interop, and record/deftype -# zero-arg methods vs methods-with-args vs `-field` field access. -(defspec "interop / dot dispatch arms" - ["zero-arg coll-interop .count" "3" "(.count [1 2 3])"] - ["zero-arg coll-interop .seq" "[1 2]" "(.seq [1 2])"] - ["explicit dot zero-arg interop" "3" "(. [1 2 3] count)"] - ["with-arg coll-interop .nth" "2" "(.nth [1 2 3] 1)"] - ["record zero-arg method" "10" - "(do (defprotocol Pd (gm [this])) (defrecord Rd [x] Pd (gm [this] (* 2 x))) (.gm (->Rd 5)))"] - ["record method with args" "15" - "(do (defprotocol Pa (am [this y])) (defrecord Ra [x] Pa (am [this y] (+ x y))) (.am (->Ra 5) 10))"] - ["deftype method with args" "7" - "(do (defprotocol Pq (qq [this y])) (deftype Tq [x] Pq (qq [this y] (+ x y))) (.qq (Tq. 3) 4))"] - ["record -field is field access" "7" - "(do (defrecord Rf [x]) (.-x (->Rf 7)))"] - ["object-method with args .equals" "true" "(.equals \"a\" \"a\")"]) - -# The `janet` namespace segment is the explicit Janet-stdlib bridge added for -# the networking layer (and used by jolt.nrepl). `janet/` resolves a Janet -# root binding; `janet./` resolves a module binding. The boundary -# is explicit so it's visible where host semantics take over. -(defspec "interop / janet bridge" - ["root builtin janet/" "\"123\"" "(janet/string 1 2 3)"] - ["root builtin janet/type" ":string" "(janet/type \"x\")"] - ["module fn janet./" "4" "(janet.math/sqrt 16)"] - ["janet.string module fn" "\"HI\"" "(janet.string/ascii-upper \"hi\")"] - ["janet.os/clock is a number" "true" "(number? (janet.os/clock))"] - # crossing the boundary uses Janet representations: a Jolt vector is a table - ["jolt vector crosses as a janet table" ":table" "(janet/type [1 2])"] - # interop is explicit-only: an unprefixed Janet module is not auto-exposed - ["unprefixed janet module not exposed" :throws "net/server"] - ["unknown janet symbol throws" :throws "(janet.os/definitely-not-a-real-fn)"]) - -(defspec "interop / jolt.interop" - ["janet-type quoted list" ":array" "(do (require (quote [jolt.interop :as j])) (j/janet-type (quote (1 2))))"] - ["janet-type list" ":array" "(do (require (quote [jolt.interop :as j])) (j/janet-type (list 1 2)))"] - ["janet-type string" ":string" "(do (require (quote [jolt.interop :as j])) (j/janet-type \"x\"))"] - ["janet-type number" ":number" "(do (require (quote [jolt.interop :as j])) (j/janet-type 1))"] - ["janet-type keyword" ":keyword" "(do (require (quote [jolt.interop :as j])) (j/janet-type :a))"]) - -(defspec "interop / arrays (aget/aset/alength)" - ["alength" "3" "(alength (object-array [1 2 3]))"] - ["aget" "20" "(aget (object-array [10 20 30]) 1)"] - ["aset returns val" "9" "(aset (object-array [1 2 3]) 1 9)"] - ["aset mutates" "[7 2 3]" "(let [a (object-array [1 2 3])] (aset a 0 7) (vec a))"] - ["aget 2d" "4" "(aget (to-array-2d [[1 2] [3 4]]) 1 1)"]) - -# java.lang.String surface + .method sugar (clj-compat: what portable cljc -# libraries call — landed for the cuerdas acceptance run). ASCII case mapping. -(defspec "interop / String methods" - [".toLowerCase" "\"hi\"" "(.toLowerCase \"HI\")"] - [".toUpperCase" "\"HI\"" "(.toUpperCase \"hi\")"] - ["dot-form" "\"hi\"" "(. \"HI\" toLowerCase)"] - [".trim" "\"x\"" "(.trim \" x \")"] - [".length" "3" "(.length \"abc\")"] - [".isEmpty" "[true false]" "[(.isEmpty \"\") (.isEmpty \"a\")]"] - [".indexOf hit" "1" "(.indexOf \"abc\" \"b\")"] - [".indexOf miss is -1" "-1" "(.indexOf \"abc\" \"z\")"] - [".lastIndexOf" "3" "(.lastIndexOf \"abab\" \"b\")"] - [".substring" "\"bc\"" "(.substring \"abc\" 1)"] - [".substring end" "\"b\"" "(.substring \"abc\" 1 2)"] - [".startsWith" "true" "(.startsWith \"abc\" \"ab\")"] - [".endsWith" "true" "(.endsWith \"abc\" \"bc\")"] - [".contains" "true" "(.contains \"abc\" \"b\")"] - [".replace" "\"axc\"" "(.replace \"abc\" \"b\" \"x\")"] - [".charAt" "\\b" "(.charAt \"abc\" 1)"] - [".equalsIgnoreCase" "true" "(.equalsIgnoreCase \"AbC\" \"aBc\")"] - ["Long/MAX_VALUE" "true" "(pos? Long/MAX_VALUE)"] - # String/valueOf static (jolt-nkx): hiccup stringifies attribute values with it. - ["String/valueOf num" "\"42\"" "(String/valueOf 42)"] - ["String/valueOf str" "\"hi\"" "(String/valueOf \"hi\")"] - ["String/valueOf kw" "\":k\"" "(String/valueOf :k)"] - ["String/valueOf nil" "\"null\"" "(String/valueOf nil)"] - # String implements CharSequence (malli's :re gates on it, jolt-ltwk). - ["instance? CharSequence" "true" "(instance? CharSequence \"aaa\")"] - ["instance? CharSequence non-str" "false" "(instance? CharSequence 42)"] - ["unsupported method throws" :throws "(.frobnicate \"abc\")"]) - -# java.time shims (jolt-ea7): epoch-ms backed values + a DateTimeFormatter -# pattern subset — the surface Selmer's date filters drive. Formatting uses -# the HOST's local timezone, so rows assert structure, not wall-clock values. -(defspec "interop / java.time shims" - ["ofPattern formats #inst" "true" - "(string? (.format (DateTimeFormatter/ofPattern \"yyyy-MM-dd\") #inst \"2020-03-05T13:45:30Z\"))"] - ["pattern shape" "true" - "(boolean (re-matches #\"\\d{4}-\\d{2}-\\d{2}\" (.format (DateTimeFormatter/ofPattern \"yyyy-MM-dd\") #inst \"2020-03-05T13:45:30Z\")))"] - ["month name + ampm" "true" - "(boolean (re-matches #\"[A-Z][a-z]{2} \\d{1,2}, 2020 \\d{1,2}:\\d{2} [AP]M\" (.format (DateTimeFormatter/ofPattern \"MMM d, yyyy h:mm a\") #inst \"2020-03-05T13:45:30Z\")))"] - ["quoted literal" "true" - "(boolean (re-matches #\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\" (.format DateTimeFormatter/ISO_LOCAL_DATE_TIME #inst \"2020-03-05T13:45:30Z\")))"] - ["localized style" "true" - "(string? (.format (DateTimeFormatter/ofLocalizedDate FormatStyle/MEDIUM) #inst \"2020-03-05T13:45:30Z\"))"] - ["withLocale chain" "true" - "(string? (.format (.withLocale (DateTimeFormatter/ofPattern \"yyyy\") (java.util.Locale. \"en\")) #inst \"2020-01-01T00:00:00Z\"))"] - ["fix-date chain" "true" - "(instance? LocalDateTime (-> #inst \"2020-03-05T13:45:30Z\" (.toInstant) (.atZone (ZoneId/systemDefault)) (.toLocalDateTime)))"] - ["inst is java.util.Date" "true" "(instance? java.util.Date #inst \"2020-01-01T00:00:00Z\")"] - ["Instant instance" "true" "(instance? java.time.Instant (Instant/ofEpochMilli 0))"] - ["getTime epoch ms" "0" "(.getTime #inst \"1970-01-01T00:00:00Z\")"] - ["toEpochMilli round trip" "1234" "(.toEpochMilli (Instant/ofEpochMilli 1234))"] - ["Instant/now is current" "true" "(> (.toEpochMilli (Instant/now)) 1500000000000)"] - ["sql types are not" "false" "(instance? java.sql.Timestamp #inst \"2020-01-01T00:00:00Z\")"]) - -# java.io / java.lang shims that carry Selmer's char-by-char template reader. -(defspec "interop / StringReader & StringBuilder" - ["StringReader read" "[97 98 -1]" - "(let [r (java.io.StringReader. \"ab\")] [(.read r) (.read r) (.read r)])"] - ["mark/reset" "[97 97]" - "(let [r (StringReader. \"ab\")] (.mark r 1) [(.read r) (do (.reset r) (.read r))])"] - ["StringBuilder append" "\"ab1\"" - "(.toString (-> (StringBuilder.) (.append \"a\") (.append \\b) (.append 1)))"] - ["capacity arg is not content" "\"x\"" - "(.toString (.append (StringBuilder. 16) \"x\"))"] - ["setLength truncates" "\"ab\"" - "(let [sb (StringBuilder.)] (.append sb \"abcd\") (.setLength sb 2) (.toString sb))"] - ["char-array of string" "true" - "(instance? (Class/forName \"[C\") (char-array \"ab\"))"] - ["reader over char[]" "97" - "(do (require (quote clojure.java.io)) (.read (clojure.java.io/reader (char-array \"abc\"))))"] - ["line-seq over file reader" "[\"a\" \"b\"]" - "(do (require (quote clojure.java.io)) (janet/spit \"/tmp/jolt-lineseq-spec.txt\" \"a\\nb\\n\") (vec (line-seq (clojure.java.io/reader \"/tmp/jolt-lineseq-spec.txt\"))))"] - ["with-open closes shim" "97" - "(with-open [r (StringReader. \"a\")] (.read r))"] - ["File.toURL methods read it back" "\"file:/tmp/x\"" - "(do (require (quote clojure.java.io)) (.toString (.toURL (clojure.java.io/file \"/tmp/x\"))))"] - ["vector :import shares deftype ctor" "\"hi!\"" - "(do (ns spec.nodea) (defprotocol SpecP (spec-pm [this])) (deftype SpecTN [t] SpecP (spec-pm [this] (str t \"!\"))) (ns spec.nodeb (:import [spec.nodea SpecTN])) (.spec-pm (SpecTN. \"hi\")))"]) - -# Shims for yogthos/config: PushbackReader, numeric/boolean parse statics, -# System/getenv + getProperties as iterable maps, edn/read from a reader. -(defspec "interop / PushbackReader & parse statics" - ["PushbackReader read" "[97 98]" - "(let [r (java.io.PushbackReader. (java.io.StringReader. \"ab\"))] [(.read r) (.read r)])"] - ["unread pushes back" "[97 97 98]" - "(let [r (PushbackReader. (StringReader. \"ab\")) a (.read r)] (.unread r a) [a (.read r) (.read r)])"] - ["unread accepts a char" "[120 97]" - "(let [r (PushbackReader. (StringReader. \"a\"))] (.unread r \\x) [(.read r) (.read r)])"] - ["edn/read from reader" "5432" - "(do (require (quote clojure.edn)) (clojure.edn/read (java.io.PushbackReader. (java.io.StringReader. \"{:db {:port 5432}}\\nrest\"))) (get-in (clojure.edn/read-string \"{:db {:port 5432}}\") [:db :port]))"] - ["edn/read multi-line" "true" - "(do (require (quote clojure.edn)) (= {:a 1 :b 2} (clojure.edn/read (PushbackReader. (StringReader. \"{:a 1\\n :b 2}\")))))"] - ["Long/parseLong" "42" "(Long/parseLong \"42\")"] - ["parseLong rejects non-numeric" :throws "(Long/parseLong \"4x\")"] - ["BigInteger." "123" "(BigInteger. \"123\")"] - ["Boolean/parseBoolean" "[true false false]" - "[(Boolean/parseBoolean \"true\") (Boolean/parseBoolean \"false\") (Boolean/parseBoolean \"yes\")]"] - ["System/getenv is a map" "true" - "(string? (get (System/getenv) \"HOME\"))"] - # registered, so (System/exit n) resolves; actual exit verified via subprocess - ["System/exit resolves" "true" "(fn? System/exit)"] - # NOT every? alone — it held vacuously while seq over a raw host table - # yielded nothing, hiding that read-system-env came back empty - ["getenv entries destructure (non-empty)" "true" - "(let [es (map (fn [[k v]] [k v]) (System/getenv))] (and (pos? (count es)) (every? vector? es)))"] - ["seq over a raw host table" "true" - "(pos? (count (seq (System/getenv))))"] - ["into {} from host table" "true" - "(string? (get (into {} (map (fn [[k v]] [k v]) (System/getenv))) \"HOME\"))"] - ["System/getProperties" "true" - "(string? (get (System/getProperties) \"os.name\"))"]) - -# ring-core enablement (host shims + protocol/reduce fixes): the java.net / -# java.util surface ring.util.codec needs, extend-protocol on Map and nil, -# and reduce over a reified clojure.lang.IReduceInit. -(defspec "host-interop / ring-codec surface" - ["URLEncoder www form" "\"a+b%3Dc\"" "(URLEncoder/encode \"a b=c\")"] - ["URLDecoder www form" "\"a b=c\"" "(URLDecoder/decode \"a+b%3Dc\" (Charset/forName \"UTF-8\"))"] - ["url round trip" "\"x &=%?\"" "(URLDecoder/decode (URLEncoder/encode \"x &=%?\"))"] - ["Base64 encode" "\"aGVsbG8=\"" "(String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))"] - ["Base64 round trip" "\"hello\"" "(String. (.decode (Base64/getDecoder) (String. (.encode (Base64/getEncoder) (.getBytes \"hello\")))))"] - ["Integer radix + byteValue" "-1" "(.byteValue (Integer/valueOf \"ff\" 16))"] - ["Integer parseInt" "255" "(Integer/parseInt \"ff\" 16)"] - ["StringTokenizer" "[\"a=1\" \"b=2\"]" "(let [t (StringTokenizer. \"a=1&b=2\" \"&\")] [(.nextToken t) (.nextToken t)])"] - ["MapEntry key/val" "[:a 1]" "(let [e (MapEntry. :a 1)] [(key e) (val e)])"] - ["String ctor from bytes" "\"hi\"" "(String. (.getBytes \"hi\"))"] - ["extend-protocol Map" ":map" - "(do (defprotocol Pe (pe [x])) (extend-protocol Pe Map (pe [m] :map) Object (pe [o] :obj)) (pe {:a 1}))"] - ["extend-protocol nil" ":nil" - "(do (defprotocol Pn (pn [x])) (extend-protocol Pn nil (pn [n] :nil) Object (pn [o] :obj)) (pn nil))"] - ["extend-protocol Map covers sorted" ":map" - "(do (defprotocol Ps (ps [x])) (extend-protocol Ps Map (ps [m] :map) Object (ps [o] :obj)) (ps (sorted-map 1 2)))"] - ["reduce over reified IReduceInit" "42" - "(reduce + 0 (reify clojure.lang.IReduceInit (reduce [_ f init] (f (f init 40) 2))))"]) - -# ring-core enablement, part 2: class-name symbols evaluate to canonical -# class-name strings (so class-dispatch defmultis match), ctor sugar still -# constructs, type-hinted param vectors parse, slurp drains reader shims, -# str/replace takes fn replacements, and int needles are char codes. -(defspec "host-interop / class tokens & readers" - ["class name evaluates to canonical string" "\"java.lang.String\"" "String"] - ["dispatch-only class name" "\"java.io.InputStream\"" "InputStream"] - ["(class x) matches the token" "true" "(= String (class \"abc\"))"] - ["defmulti on class dispatches" ":str" - "(do (defmulti cm (fn [x] (class x))) (defmethod cm String [x] :str) (cm \"a\"))"] - ["defmethod on nil dispatch value" ":nil" - "(do (defmulti cn (fn [x] (class x))) (defmethod cn nil [x] :nil) (defmethod cn String [x] :str) (cn nil))"] - ["ctor sugar still constructs" "\"x\"" "(.toString (StringBuilder. \"x\"))"] - ["return-hinted defn parses" "7" "(do (defn- hb ^bytes [b] b) (hb 7))"] - ["hinted multi-arity parses" ":two" "((fn ([x] :one) (^String [x y] :two)) 1 2)"] - ["slurp drains a StringReader" "\"a=1\"" "(slurp (StringReader. \"a=1\"))"] - ["slurp accepts :encoding opts" "\"b\"" "(slurp (StringReader. \"b\") :encoding \"UTF-8\")"] - ["replace with fn replacement is literal" "\"$0\"" - "(do (require (quote [clojure.string :as s9])) (s9/replace \"x\" #\".\" (fn [m] \"$0\")))"] - ["replace fn gets group vector" "\"v=k\"" - "(do (require (quote [clojure.string :as s9])) (s9/replace \"k=v\" #\"(\\w+)=(\\w+)\" (fn [[_ k v]] (str v \"=\" k))))"] - ["indexOf int needle is a char code" "1" "(.indexOf \"a=b\" 61)"]) - -# JOLT_BAKE_ENV_ALLOWLIST (jolt-s3j): with the allowlist set, System/getenv -# serves only the listed names — so an image bake can't marshal the builder's -# secrets into the binary. Unset, reads are live and unfiltered. -(defspec "host-interop / bake env scrub" - ["unlisted name reads nil under the allowlist" "nil" - "(do (janet.os/setenv \"JOLT_BAKE_ENV_ALLOWLIST\" \"PATH\") (let [r (System/getenv \"HOME\")] (janet.os/setenv \"JOLT_BAKE_ENV_ALLOWLIST\" nil) r))"] - ["listed name still reads" "true" - "(do (janet.os/setenv \"JOLT_BAKE_ENV_ALLOWLIST\" \"HOME\") (let [r (System/getenv \"HOME\")] (janet.os/setenv \"JOLT_BAKE_ENV_ALLOWLIST\" nil) (string? r)))"] - ["full snapshot filtered to the allowlist" "true" - "(do (janet.os/setenv \"JOLT_BAKE_ENV_ALLOWLIST\" \"HOME\") (let [e (System/getenv)] (janet.os/setenv \"JOLT_BAKE_ENV_ALLOWLIST\" nil) (and (contains? (set (keys e)) \"HOME\") (= 1 (count (keys e))))))"] - ["no allowlist: unfiltered live reads" "true" - "(string? (System/getenv \"HOME\"))"]) - -# Host-class shim registration exposed to Clojure (reitit.Trie mirror, etc.): -# statics resolve as (Class/method ...), ctors as (Class. ...), and registered -# tag methods dispatch. Also: .getMessage on an exception/string, HashMap. -(defspec "host-interop / exception + HashMap shims" - ["getMessage on a thrown string" "\"boom\"" - "(try (throw \"boom\") (catch Throwable e (.getMessage e)))"] - ["getMessage on ex-info" "\"bad\"" - "(try (throw (ex-info \"bad\" {})) (catch Throwable e (.getMessage e)))"] - ["HashMap get" "2" - "(let [m (HashMap. {:a 1 :b 2})] (.get m :b))"] - ["HashMap put + size" "2" - "(let [m (HashMap. {})] (.put m :x 1) (.put m :y 2) (.size m))"]) - -# Reader-feature toggle exposed to Clojure (scoped clj-lib loading): a -# namespace can load a clj-targeted library under :clj without forcing the -# whole process — set features, require, restore. -(defspec "host-interop / reader-feature toggle" - ["features default to jolt+default" "true" - "(contains? (set (__reader-features)) \"jolt\")"] - ["set + read back" "true" - "(do (def prev (__reader-features)) (__reader-features-set! [\"clj\" \"jolt\" \"default\"]) (def r (contains? (set (__reader-features)) \"clj\")) (__reader-features-set! prev) r)"] - ["restore returns to default" "false" - "(do (def prev (__reader-features)) (__reader-features-set! [\"clj\"]) (__reader-features-set! prev) (contains? (set (__reader-features)) \"clj\"))"]) - -# JVM class shims migratus relies on. Exception constructors resolve as bare -# class symbols (jolt-6xk) and carry a message; Character/Thread/Long statics; -# java.sql.Timestamp is the millis number; SimpleDateFormat formats UTC. -(defspec "host-interop / migratus class shims" - ["Exception. message" "\"boom\"" - "(try (throw (Exception. \"boom\")) (catch Throwable e (.getMessage e)))"] - ["IllegalArgumentException." "\"bad\"" - "(try (throw (IllegalArgumentException. \"bad\")) (catch Exception e (.getMessage e)))"] - ["InterruptedException." "\"stop\"" - "(try (throw (InterruptedException. \"stop\")) (catch Throwable e (.getMessage e)))"] - ["Character/isUpperCase" "true" "(Character/isUpperCase \\A)"] - ["Character/isLowerCase" "true" "(Character/isLowerCase \\a)"] - ["Character/isUpperCase neg" "false" "(Character/isUpperCase \\a)"] - ["Thread/interrupted" "false" "(Thread/interrupted)"] - ["Long/valueOf" "42" "(Long/valueOf \"42\")"] - ["Timestamp is millis" "1000" "(.getTime (java.util.Date. (java.sql.Timestamp. 1000)))"] - ["SimpleDateFormat UTC" "\"19700101000000\"" - "(let [f (doto (java.text.SimpleDateFormat. \"yyyyMMddHHmmss\") (.setTimeZone (java.util.TimeZone/getTimeZone \"UTC\")))] (.format f (java.util.Date. 0)))"]) - -# java.io.File model (jolt-hjw): io/file builds a value that answers -# (instance? File _) so migratus's File-vs-jar branch takes the filesystem path; -# the method surface and a File-aware file-seq back it; str/slurp coerce to path. -(defspec "host-interop / java.io.File" - ["instance? File" "true" "(do (require '[clojure.java.io :as io]) (instance? java.io.File (io/file \"/a/b\")))"] - ["str is the path" "\"/a/b\"" "(do (require '[clojure.java.io :as io]) (str (io/file \"/a/b\")))"] - ["getName" "\"c.txt\"" "(do (require '[clojure.java.io :as io]) (.getName (io/file \"/a/b/c.txt\")))"] - ["getPath joins" "\"/a/b\"" "(do (require '[clojure.java.io :as io]) (.getPath (io/file \"/a\" \"b\")))"] - ["isDirectory of repo dir" "true" "(do (require '[clojure.java.io :as io]) (.isDirectory (io/file \"docs\")))"] - ["isFile of repo file" "true" "(do (require '[clojure.java.io :as io]) (.isFile (io/file \"project.janet\")))"] - ["exists is false off-disk" "false" "(do (require '[clojure.java.io :as io]) (.exists (io/file \"/no/such/path/xyz\")))"] - ["file-seq yields File values" "true" - "(do (require '[clojure.java.io :as io]) (every? (fn [f] (instance? java.io.File f)) (file-seq (io/file \"docs\"))))"] - ["file-seq finds files" "true" - "(do (require '[clojure.java.io :as io]) (pos? (count (filter (fn [f] (.isFile f)) (file-seq (io/file \"docs\"))))))"]) - -# Host shims that let libraries like clojure.tools.logging load: no STM (a -# transaction is never running) and a minimal clojure.pprint (used by spy). -(defspec "host-interop / logging host shims" - ["LockingTransaction/isRunning" "false" "(clojure.lang.LockingTransaction/isRunning)"] - ["pprint writes value" "\"[1 2 3]\\n\"" - "(do (require '[clojure.pprint :as pp]) (with-out-str (pp/pprint [1 2 3])))"] - ["with-pprint-dispatch runs body" "42" - "(do (require '[clojure.pprint :as pp]) (pp/with-pprint-dispatch pp/code-dispatch 42))"]) - -# Language capabilities that real-world macros like clojure.tools.logging exercise: -# multi-arity defmacro dispatch, conditional-eval macros (short-circuit like -# debug), and macros that eval+print+return (like spy). Self-contained — no -# external library needed. -(defspec "host-interop / macro dispatch & short-circuit patterns" - ["conditional-eval suppresses" "0" - "(do (def ^:dynamic *enabled* false) (defmacro when-on [& body] `(when *enabled* ~@body)) (let [a (atom 0)] (when-on (reset! a 9)) @a))"] - ["conditional-eval fires" "9" - "(do (def ^:dynamic *enabled* true) (defmacro when-on [& body] `(when *enabled* ~@body)) (let [a (atom 0)] (when-on (reset! a 9)) @a))"] - ["spy-like eval+print+return" "3" - "(do (defmacro spylog [expr] `(let [v# ~expr] (println v#) v#)) (spylog (+ 1 2)))"] - ["multi-arity 4 dispatch" "[:single :double :triple :quad]" - "(do (defmacro ml ([a] :single) ([a b] :double) ([a b c] :triple) ([a b c d] :quad)) [(ml 1) (ml 1 2) (ml 1 2 3) (ml 1 2 3 4)])"]) diff --git a/test/spec/inst-spec.janet b/test/spec/inst-spec.janet deleted file mode 100644 index 8edddd3..0000000 --- a/test/spec/inst-spec.janet +++ /dev/null @@ -1,30 +0,0 @@ -# Specification: #inst literals — instants as values (spec 02-reader S20). -# An instant is an immutable tagged struct {:jolt/type :jolt/inst :ms }: -# value equality by instant (offset-normalized), usable as map keys. -# The reader accepts RFC3339 with Clojure's partial-timestamp defaults -# (#inst "2020" == #inst "2020-01-01T00:00:00.000-00:00"). -(use ../support/harness) - -(defspec "inst / reading & identity" - ["reads to inst" "true" "(inst? #inst \"2020-01-01T00:00:00Z\")"] - ["inst? false on string" "false" "(inst? \"2020-01-01\")"] - ["epoch zero" "0" "(inst-ms #inst \"1970-01-01T00:00:00Z\")"] - ["one second" "1000" "(inst-ms #inst \"1970-01-01T00:00:01Z\")"] - ["millis" "123" "(inst-ms #inst \"1970-01-01T00:00:00.123Z\")"] - ["a real date" "1577836800000" "(inst-ms #inst \"2020-01-01T00:00:00Z\")"] - ["inst-ms throws on non-inst" :throws "(inst-ms 42)"]) - -(defspec "inst / partial timestamps & offsets" - ["year only" "true" "(= #inst \"2020\" #inst \"2020-01-01T00:00:00.000Z\")"] - ["year-month" "true" "(= #inst \"2020-03\" #inst \"2020-03-01T00:00:00Z\")"] - ["date only" "true" "(= #inst \"2020-03-15\" #inst \"2020-03-15T00:00:00Z\")"] - ["positive offset" "true" "(= #inst \"2020-01-01T01:00:00+01:00\" #inst \"2020-01-01T00:00:00Z\")"] - ["negative offset" "true" "(= #inst \"2019-12-31T23:00:00-01:00\" #inst \"2020-01-01T00:00:00Z\")"] - ["-00:00 offset" "true" "(= #inst \"2020-01-01T00:00:00-00:00\" #inst \"2020-01-01T00:00:00Z\")"] - ["bad timestamp throws" :throws "#inst \"garbage\""]) - -(defspec "inst / value semantics & printing" - ["equal by instant" "true" "(= #inst \"2020-01-01T00:00:00Z\" #inst \"2020-01-01T00:00:00.000Z\")"] - ["unequal instants" "false" "(= #inst \"2020-01-01T00:00:00Z\" #inst \"2020-01-01T00:00:01Z\")"] - ["works as map key" ":v" "(get {#inst \"2020-01-01T00:00:00Z\" :v} #inst \"2020-01-01T00:00:00.000Z\")"] - ["pr-str round-trips" "\"#inst \\\"2020-01-01T00:00:00.000-00:00\\\"\"" "(pr-str #inst \"2020-01-01T00:00:00Z\")"]) diff --git a/test/spec/io-spec.janet b/test/spec/io-spec.janet deleted file mode 100644 index 6a2b138..0000000 --- a/test/spec/io-spec.janet +++ /dev/null @@ -1,114 +0,0 @@ -# Specification: printing / output (print/println/pr/prn, *-str, format, str). -# Output is captured with with-out-str (jolt-rfw); the *-str fns return strings. -(use ../support/harness) - -(defspec "io / with-out-str captures" - ["println" "\"hi\\n\"" "(with-out-str (println \"hi\"))"] - ["print spaces" "\"a b\"" "(with-out-str (print \"a\" \"b\"))"] - ["prn quotes" "\"[1 2]\\n\"" "(with-out-str (prn [1 2]))"] - ["pr no newline" "\"5\"" "(with-out-str (pr 5))"] - ["multiple writes" "\"12\"" "(with-out-str (print 1) (print 2))"] - ["no output" "\"\"" "(with-out-str 42)"] - ["println no args" "\"\\n\"" "(with-out-str (println))"]) - -(defspec "io / *-str builders" - ["print-str" "\"a b\"" "(print-str \"a\" \"b\")"] - ["println-str" "\"x\\n\"" "(println-str \"x\")"] - ["prn-str" "\"[1 2]\\n\"" "(prn-str [1 2])"] - ["pr-str quotes" "\"\\\"s\\\"\"" "(pr-str \"s\")"] - ["pr-str keyword" "\":a\"" "(pr-str :a)"]) - -(defspec "io / str & format" - ["str concat" "\"1:ab\"" "(str 1 :a \"b\")"] - ["str nil" "\"\"" "(str nil)"] - ["str of coll" "\"[1 2]\"" "(str [1 2])"] - ["format d/s" "\"5-x\"" "(format \"%d-%s\" 5 \"x\")"] - ["format float" "\"3.14\"" "(format \"%.2f\" 3.14159)"]) - -# The *in* reader family (jolt-0d9): *in* is a dynamic var holding a reader; -# with-in-str rebinds it to a string reader over one shared buffer, so read -# (consumes exactly one form) and read-line (rest of that line) interleave -# correctly, as in Clojure. -(defspec "io / *in* + with-in-str + read-line" - ["read-line one line" "\"hello\"" "(with-in-str \"hello\" (read-line))"] - ["read-line strips nl" "\"a\"" "(with-in-str \"a\\nb\" (read-line))"] - ["read-line sequential" "[\"a\" \"b\"]" "(with-in-str \"a\\nb\" [(read-line) (read-line)])"] - ["read-line EOF nil" "nil" "(with-in-str \"\" (read-line))"] - ["read-line after last" "[\"x\" nil]" "(with-in-str \"x\" [(read-line) (read-line)])"] - ["empty line" "[\"\" \"y\"]" "(with-in-str \"\\ny\" [(read-line) (read-line)])"] - ["*in* is bound" "true" "(with-in-str \"\" (map? *in*))"]) - -(defspec "io / read" - ["read a form" "42" "(with-in-str \"42\" (read))"] - ["read a list form" "(quote (+ 1 2))" "(with-in-str \"(+ 1 2)\" (read))"] - ["read two forms" "[1 2]" "(with-in-str \"1 2\" [(read) (read)])"] - ["read then read-line" "[1 \" rest\"]" "(with-in-str \"1 rest\\nnext\" [(read) (read-line)])"] - ["read vector" "[1 2]" "(with-in-str \"[1 2]\" (read))"] - ["read nil literal" "nil" "(with-in-str \"nil\" (read))"] - ["read EOF throws" :throws "(with-in-str \"\" (read))"] - ["read EOF value" ":done" "(with-in-str \"\" (read *in* false :done))"] - ["read eval data" "3" "(with-in-str \"(+ 1 2)\" (eval (read)))"]) - -(defspec "io / line-seq" - ["line-seq" "[\"a\" \"b\" \"c\"]" "(with-in-str \"a\\nb\\nc\" (vec (line-seq *in*)))"] - ["line-seq empty" "nil" "(with-in-str \"\" (seq (line-seq *in*)))"] - ["line-seq is lazy seq" "true" "(with-in-str \"a\\nb\" (seq? (line-seq *in*)))"] - ["line-seq count" "3" "(with-in-str \"1\\n2\\n3\" (count (line-seq *in*)))"]) - -# The print family is overlay now (seed-shrink round 6), over the __write / -# __pr-str1 host seams: pr is readable, print is str semantics, *-ln appends. -(defspec "io / print family (overlay)" - ["pr-str multi-arg spacing" "\"\\\"a\\\" [1 2] :k\"" "(pr-str \"a\" [1 2] :k)"] - ["pr-str zero args" "\"\"" "(pr-str)"] - ["pr-str escapes" "\"\\\"a\\\\\\\"b\\\"\"" "(pr-str \"a\\\"b\")"] - ["print is unreadable" "\"a b\"" "(with-out-str (print \"a\" \"b\"))"] - ["println appends newline" "\"x 1\\n\"" "(with-out-str (println \"x\" 1))"] - ["prn is readable + newline" "\"[1 \\\"s\\\"]\\n\"" "(with-out-str (prn [1 \"s\"]))"] - ["pr writes no newline" "\"\\\\a\"" "(with-out-str (pr \\a))"] - ["print nil arg" "\"\"" "(with-out-str (print nil))"] - ["prn keyword" "\":k\\n\"" "(with-out-str (prn :k))"]) - -# print-method is a real multimethod (jolt-g1r): canonical dispatch on -# (:type meta) keyword else (type x); records print as #ns.Type{...} by -# default, and a user (defmethod print-method 'ns.Type ...) overrides record -# rendering everywhere — top level AND nested, through pr/prn/pr-str — via -# the host renderer's callback. Builtin overrides apply only on direct -# print-method calls (documented divergence; pr keeps the native fast path). -(defspec "io / print-method multimethod" - ["records print canonically" "\"#user.Pt{:x 1, :y 2}\"" - "(do (defrecord Pt [x y]) (pr-str (->Pt 1 2)))"] - ["records nested in colls" "\"[#user.Pt{:x 1, :y 2}]\"" - "(do (defrecord Pt [x y]) (pr-str [(->Pt 1 2)]))"] - ["defmethod overrides a record, top level" "\"<3,4>\"" - "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (pr-str (->Pt 3 4)))"] - ["defmethod fires nested in a map" "\"{:p <5,6>}\"" - "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (pr-str {:p (->Pt 5 6)}))"] - ["defmethod fires through prn" "\"[<1,2>]\\n\"" - "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] (.write w (str \"<\" (:x r) \",\" (:y r) \">\"))) (with-out-str (prn [(->Pt 1 2)])))"] - ["direct call uses :default" "\"42\"" - "(let [w (StringWriter.)] (print-method 42 w) (.toString w))"] - ["direct builtin override" "\"#42#\"" - "(do (defmethod print-method :number [n w] (.write w (str \"#\" n \"#\"))) (let [w (StringWriter.)] (print-method 42 w) (.toString w)))"] - ["print-dup routes to print-method" "\"[1 2]\"" - "(let [w (StringWriter.)] (print-dup [1 2] w) (.toString w))"] - ["StringWriter accumulates" "\"ab\"" - "(let [w (StringWriter.)] (.write w \"a\") (.append w \\b) (.toString w))"] - ["methods table inspectable" "true" - "(do (defrecord Pt [x y]) (defmethod print-method (quote user.Pt) [r w] r) (contains? (methods print-method) (quote user.Pt)))"]) - -# Cold tagged-type printing now lives in io-tier defmethods (the host -# renderer dispatches any remaining :jolt/* tagged value through the -# print-method hook). Outputs unchanged from the old host branches; any -# tagged type is now user-overridable, atoms included. -(defspec "io / cold tagged types via print-method" - ["uuid" "\"#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"\"" - "(pr-str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"] - ["uuid nested" "\"[#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"]\"" - "(pr-str [(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")])"] - ["regex" "\"#\\\"a+b\\\"\"" "(pr-str #\"a+b\")"] - ["transient vector" "\"#\"" "(pr-str (transient [1]))"] - ["transient map" "\"#\"" "(pr-str (transient {:a 1}))"] - ["atom override fires nested" "\"{:a #atom[7]}\"" - "(do (defmethod print-method :jolt/atom [a w] (.write w (str \"#atom[\" (deref a) \"]\"))) (pr-str {:a (atom 7)}))"] - ["uuid through str unchanged" "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" - "(str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"]) diff --git a/test/spec/iseq-call-spec.janet b/test/spec/iseq-call-spec.janet deleted file mode 100644 index b1aeaa4..0000000 --- a/test/spec/iseq-call-spec.janet +++ /dev/null @@ -1,19 +0,0 @@ -# Specification: a non-array ISeq (plist/lazy-seq, e.g. from cons/concat/list or -# ~@) used as a FORM is evaluated as a call, not returned as self-evaluating data -# (jolt-2rx). The interpreter only treated a reader LIST (Janet array) as a call; -# a runtime-built list (a plist/lazy-seq table) fell through to self-eval, so -# (eval (cons '+ '(1 2))) returned the list instead of 3. The analyzer already -# punts such forms to the interpreter, so the fix lives in eval-form. -(use ../support/harness) - -(defspec "ISeq call forms (jolt-2rx)" - ["eval a cons'd call" "3" "(eval (cons (quote +) (quote (1 2))))"] - ["eval a list-built call" "6" "(eval (list (quote +) 1 2 3))"] - ["eval a concat'd call" "10" "(eval (concat (list (quote +)) (list 1 2 3 4)))"] - ["nested cons'd subform" "7" "(eval (list (quote +) 3 (cons (quote +) (quote (1 3)))))"] - ["empty list self-evals" "()" "(eval (list))"] - ["macro output via cons" "3" "(do (defmacro mc [] (cons (quote +) (quote (1 2)))) (mc))"] - ["macro output via concat" "6" "(do (defmacro mk [] (concat (list (quote +)) (list 1 2 3))) (mk))"] - # regressions: vectors/quoted-data are NOT calls - ["vector value self-evals" "[1 2 3]" "(eval (vec [1 2 3]))"] - ["quoted list of data" "(quote (1 2 3))" "(quote (1 2 3))"]) diff --git a/test/spec/lazy-seqs-spec.janet b/test/spec/lazy-seqs-spec.janet deleted file mode 100644 index 0c9c99d..0000000 --- a/test/spec/lazy-seqs-spec.janet +++ /dev/null @@ -1,44 +0,0 @@ -# Specification: lazy sequences. -(use ../support/harness) - -(defspec "lazy / construction & laziness" - ["lazy-seq value" "[1 2 3]" "(take 3 (lazy-seq (cons 1 (lazy-seq (cons 2 (lazy-seq (cons 3 nil)))))))"] - ["not eagerly evaluated" "0" "(let [c (atom 0)] (lazy-seq (swap! c inc) nil) @c)"] - ["realized on demand" "1" "(let [c (atom 0) s (lazy-seq (swap! c inc) [1])] (first s) @c)"] - ["lazy-cat" "[0 1 2 3]" "(lazy-cat [0 1] [2 3])"] - ["doall forces" "[2 3 4]" "(doall (map inc [1 2 3]))"] - ["dorun returns nil" "nil" "(dorun (map inc [1 2 3]))"]) - -(defspec "lazy / infinite" - ["take from repeat" "[7 7 7]" "(take 3 (repeat 7))"] - ["take from iterate" "[1 2 4 8]" "(take 4 (iterate (fn [x] (* 2 x)) 1))"] - ["take from cycle" "[1 2 1 2]" "(take 4 (cycle [1 2]))"] - ["take from range" "[0 1 2]" "(take 3 (range))"] - ["drop then take" "[5 6 7]" "(take 3 (drop 5 (range)))"] - ["filter infinite" "[0 2 4]" "(take 3 (filter even? (range)))"] - ["map infinite" "[0 1 4]" "(take 3 (map (fn [x] (* x x)) (range)))"] - ["nth of infinite" "100" "(nth (range) 100)"]) - -(defspec "lazy / self-referential" - ["self-ref ones" "[1 1 1 1 1]" "(do (def ones (lazy-seq (cons 1 ones))) (take 5 ones))"] - ["self-ref nats" "[0 1 2 3 4]" "(do (def nats (lazy-cat [0] (map inc nats))) (take 5 nats))"] - ["self-ref fib" "[0 1 1 2 3 5 8 13 21 34]" - "(do (def fib (lazy-cat [0 1] (map + (rest fib) fib))) (take 10 fib))"]) - -(defspec "lazy / realized?" - ["unrealized" "false" "(realized? (lazy-seq (cons 1 nil)))"] - ["realized after" "true" "(let [s (lazy-seq (cons 1 nil))] (first s) (realized? s))"] - ["body runs once" "1" "(let [c (atom 0) s (lazy-seq (do (swap! c inc) [1 2 3]))] (seq s) (seq s) @c)"]) - -# Independent walks over the SAME lazy seq share realization: each node's rest -# wrapper is memoized (ls-rest-cached), so the shared rest-thunks run exactly -# once. Pre-fix, every walk after the first re-ran the thunks — duplicating -# side effects, and a doall'd seq of futures re-spawned them serially on the -# deref walk (which is how it surfaced, via pmap). -(defspec "lazy-seq / realization is shared across walks" - ["effects run once across three walks" "3" - "(let [a (atom 0) s (map (fn [x] (swap! a inc) x) [1 2 3])] (doall s) (dorun s) (vec s) (deref a))"] - ["values stable across walks" "true" - "(let [s (map inc [1 2 3])] (= (vec s) (vec s) [2 3 4]))"] - ["filter effects once" "4" - "(let [a (atom 0) s (filter (fn [x] (swap! a inc) (odd? x)) [1 2 3 4])] (dorun s) (count s) (deref a))"]) diff --git a/test/spec/lists-spec.janet b/test/spec/lists-spec.janet deleted file mode 100644 index 7a35f70..0000000 --- a/test/spec/lists-spec.janet +++ /dev/null @@ -1,28 +0,0 @@ -# Specification: lists (persistent singly-linked). -(use ../support/harness) - -(defspec "list / construct & predicate" - ["list" "[1 2 3]" "(list 1 2 3)"] - ["empty list" "[]" "(list)"] - ["quoted list" "[1 2 3]" "(quote (1 2 3))"] - ["list? true" "true" "(list? (list 1 2))"] - ["list? on conj result" "true" "(list? (conj (list 1) 0))"] - ["count" "3" "(count (list 1 2 3))"] - ["empty? true" "true" "(empty? (list))"] - ["list = vector elts" "true" "(= (list 1 2 3) [1 2 3])"]) - -(defspec "list / access & update" - ["first" "1" "(first (list 1 2 3))"] - ["rest" "[2 3]" "(rest (list 1 2 3))"] - ["peek is first" "1" "(peek (list 1 2 3))"] - ["pop drops first" "[2 3]" "(pop (list 1 2 3))"] - ["conj prepends" "[0 1 2]" "(conj (list 1 2) 0)"] - ["conj many prepends" "[4 3 1 2]" "(conj (list 1 2) 3 4)"] - ["cons prepends" "[0 1 2]" "(cons 0 (list 1 2))"] - ["nth" "20" "(nth (list 10 20 30) 1)"]) - -(defspec "list / immutability & performance" - ["conj does not mutate" "true" "(let [l (list 1 2 3) m (conj l 0)] (and (= l [1 2 3]) (= m [0 1 2 3])))"] - ["reduce conj builds" "[2 1 0]" "(reduce conj (list) (range 3))"] - ["O(1) conj at scale" "200000" "(count (reduce conj (list) (range 200000)))"] - ["scale head correct" "199999" "(first (reduce conj (list) (range 200000)))"]) diff --git a/test/spec/macros-spec.janet b/test/spec/macros-spec.janet deleted file mode 100644 index 5dd1fbd..0000000 --- a/test/spec/macros-spec.janet +++ /dev/null @@ -1,115 +0,0 @@ -# Specification: macros, quoting and syntax-quote. -(use ../support/harness) - -(defspec "macros / quoting" - ["quote symbol" "(quote a)" "(quote a)"] - ["quote list" "[1 2 3]" "(quote (1 2 3))"] - ["quote nested" "[1 [2 3]]" "(quote (1 (2 3)))"] - ["quote sugar" "'a" "'a"] - ["syntax-quote literal" "[1 2]" "`[1 2]"] - ["unquote" "[1 2 3]" "(let [x 2] `[1 ~x 3])"] - ["unquote-splicing" "[1 2 3 4]" "(let [xs [2 3]] `[1 ~@xs 4])"] - ["unquote in list" "[3]" "(let [x 3] `(~x))"] - ["syntax-quote symbol qualifies" "true" "(symbol? `foo)"]) - -(defspec "macros / defmacro" - ["simple macro" "3" - "(do (defmacro m [a b] `(+ ~a ~b)) (m 1 2))"] - ["macro unless" "1" - "(do (defmacro unless [c body] `(if ~c nil ~body)) (unless false 1))"] - ["macro with body splice" "6" - "(do (defmacro msum [& xs] `(+ ~@xs)) (msum 1 2 3))"] - ["macroexpand-1" "true" - "(do (defmacro m [x] `(inc ~x)) (list? (macroexpand-1 '(m 5))))"] - ["gensym unique" "false" - "(= (gensym) (gensym))"] - ["gensym# in template" "true" - "(do (defmacro m [] `(let [x# 1] x#)) (= 1 (m)))"] - # An #() lambda written inside a syntax-quote: its generated params must not be - # qualified to the ns (a qualified symbol is not a valid param). hiccup's - # compiler emits `(let [sb# ..] (run! #(.append sb# %) ..)) (jolt-nkx). - ["#() inside syntax-quote" "[2 4 6]" - "(do (defmacro m [] `(mapv #(* % 2) [1 2 3])) (m))"] - ["#() + auto-gensym share in template" "\"ab\"" - "(do (defmacro m [] `(let [sb# (StringBuilder.)] (mapv #(.append sb# %) [\"a\" \"b\"]) (.toString sb#))) (m))"]) - -# Core macros ported from Janet to the Clojure overlay (jolt-1j0 phase 3, -# jolt-core/clojure/core/30-macros.clj). -(defspec "macros / core-overlay" - ["if-not true branch" ":then" "(if-not false :then :else)"] - ["if-not else branch" ":else" "(if-not true :then :else)"] - ["if-not no else" "nil" "(if-not true :then)"] - ["if-not no else hit" ":then" "(if-not false :then)"] - ["comment -> nil" "nil" "(comment a b c)"] - ["comment in do" "42" "(do (comment ignored) 42)"] - ["if-let then" "6" "(if-let [x 5] (inc x) :none)"] - ["if-let else" ":none" "(if-let [x nil] (inc x) :none)"] - ["if-let else scope" "9" "(let [x 9] (if-let [x nil] :t x))"] - ["if-some zero" "1" "(if-some [x 0] (inc x) :none)"] - ["if-some nil" ":none" "(if-some [x nil] x :none)"] - ["when-some multi" "14" "(when-some [x 7] (inc x) (* x 2))"] - ["when-some nil" "nil" "(when-some [x nil] x)"] - ["while loop" "3" "(let [a (atom 0)] (while (< @a 3) (swap! a inc)) @a)"] - ["dotimes sum" "10" "(let [a (atom 0)] (dotimes [i 5] (swap! a + i)) @a)"] - ["as-> threads" "12" "(as-> 5 x (+ x 1) (* x 2))"] - ["as-> no forms" "5" "(as-> 5 x)"] - ["some-> through" "6" "(some-> {:a {:b 5}} :a :b inc)"] - ["some-> short-circuit" "nil" "(some-> {:a nil} :a :b)"] - ["some->> through" "9" "(some->> [1 2 3] (map inc) (reduce +))"] - ["some->> nil" "nil" "(some->> nil (map inc))"] - ["doto returns obj" "[1 2]" "(deref (doto (atom []) (swap! conj 1) (swap! conj 2)))"] - ["when-first" "20" "(when-first [x [10 20 30]] (* x 2))"] - ["when-first empty" "nil" "(when-first [x []] :body)"] - ["when-first nil coll" "nil" "(when-first [x nil] :body)"] - ["when-first range" "0" "(when-first [x (range 5)] x)"] - ["cond->> threads" "12" "(cond->> 5 true (+ 1) false (* 100) true (* 2))"] - ["cond->> skip" "10" "(cond->> 10 false (+ 1))"] - ["assert pass" ":ok" "(do (assert (= 1 1)) :ok)"] - ["assert throws" ":threw" "(try (assert (= 1 2)) (catch :default e :threw))"] - ["assert message" "\"nope\"" "(try (assert false \"nope\") (catch :default e (ex-message e)))"] - ["delay value" "42" "(deref (delay 42))"] - ["delay forces once" "1" "(let [c (atom 0) d (delay (swap! c inc))] @d @d @c)"] - ["future deref" "9" "(deref (future (* 3 3)))"] - ["letfn simple" "25" "(letfn [(sq [x] (* x x))] (sq 5))"] - ["letfn mutual" "true" "(letfn [(ev? [n] (if (zero? n) true (od? (dec n)))) (od? [n] (if (zero? n) false (ev? (dec n))))] (ev? 8))"] - ["condp match" ":two" "(condp = 2 1 :one 2 :two 3 :three)"] - ["condp default" ":else" "(condp = 9 1 :one 2 :two :else)"] - ["condp :>> form" "\"got 2\"" "(condp some [1 2 3] #{0 9} :>> (fn [x] (str \"got \" x)) #{2 6} :>> (fn [x] (str \"got \" x)))"] - ["condp no match" ":threw" "(try (condp = 9 1 :one) (catch :default e :threw))"] - ["binding rebinds" "99" "(do (def ^:dynamic *bx* 10) (binding [*bx* 99] *bx*))"] - ["binding restores" "10" "(do (def ^:dynamic *by* 10) (binding [*by* 99] *by*) *by*)"] - ["binding seen by fn" "7" "(do (def ^:dynamic *bz* 0) (defn rdz [] *bz*) (binding [*bz* 7] (rdz)))"]) - -# time returns the body value (the timing line goes to *out*); with-redefs -# temporarily rebinds var roots and restores on exit (even on throw); -# macroexpand expands repeatedly until the head is no longer a macro. -(defspec "macros / time, with-redefs, macroexpand" - ["time returns value" "3" "(time (+ 1 2))"] - ["with-redefs rebinds" "42" "(do (defn wr-f [] 1) (with-redefs [wr-f (fn [] 42)] (wr-f)))"] - ["with-redefs restores" "1" "(do (defn wr-g [] 1) (with-redefs [wr-g (fn [] 42)]) (wr-g))"] - ["with-redefs restores on throw" "1" - "(do (defn wr-h [] 1) (try (with-redefs [wr-h (fn [] 42)] (throw (ex-info \"x\" {}))) (catch :default e nil)) (wr-h))"] - ["with-redefs-fn" "42" "(do (defn wr-i [] 1) (with-redefs-fn {(var wr-i) (fn [] 42)} (fn [] (wr-i))))"] - ["macroexpand full" "true" "(let [e (macroexpand (quote (when-not false 1)))] (= (quote if) (first e)))"] - ["macroexpand non-macro" "[1 2]" "(macroexpand (quote [1 2]))"]) - -# defmacro accepts the arity-clause form (defmacro name ([params] body...)), a -# leading docstring, and ^{:map} metadata on the name (jolt-whp, jolt-8w2). -(defspec "macros / defmacro arity-clause & name metadata" - ["arity-clause form" "10" "(do (defmacro tw ([x] (list (quote *) x 2))) (tw 5))"] - ["docstring + arity" "15" "(do (defmacro th \"triple\" ([x] (list (quote *) x 3))) (th 5))"] - ["^{:map} name meta" "7" "(do (defmacro ^{:private true} pm [] 7) (pm))"] - ["multi-form body" "6" "(do (defmacro mb ([a b] (list (quote +) a b))) (mb 2 4))"]) - -# Multi-arity defmacro (dispatch on arg count) and the docstring + attr-map + -# params form — both needed to run real Clojure macros, e.g. -# clojure.tools.logging/log (4 arities) and its level macros (jolt-q8l, jolt-qnr). -(defspec "macros / defmacro multi-arity & attr-map" - ["multi-arity 1" "6" "(do (defmacro ma ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b))) (ma 5))"] - ["multi-arity 2" "5" "(do (defmacro ma ([a] (list (quote +) a 1)) ([a b] (list (quote +) a b))) (ma 2 3))"] - ["arity delegates" "[:d nil 9]" - "(do (defmacro lg ([m] `(lg :d nil ~m)) ([l t m] (list (quote vector) l t m))) (lg 9))"] - ["doc + attr-map + params" "10" - "(do (defmacro am \"doc\" {:arglists (quote ([x]))} [x] (list (quote inc) x)) (am 9))"] - ["doc + attr-map + variadic" "6" - "(do (defmacro vg \"d\" {:arglists (quote ([& a]))} [& xs] `(+ ~@xs)) (vg 1 2 3))"]) diff --git a/test/spec/map-fastpath-spec.janet b/test/spec/map-fastpath-spec.janet deleted file mode 100644 index cc4d3f7..0000000 --- a/test/spec/map-fastpath-spec.janet +++ /dev/null @@ -1,74 +0,0 @@ -# Specification: keyword-invoke and map-literal semantics that the compiled -# fast paths (jolt-4vr: inlined keyword lookup, inlined struct construction) -# must preserve. Written BEFORE the optimization; every row passes on the -# generic jolt-call/build-map-literal paths and must keep passing on the -# inlined ones. -(use ../support/harness) - -(defspec "maps / keyword invoke" - ["hit" "1" "(:a {:a 1 :b 2})"] - ["miss" "nil" "(:z {:a 1})"] - ["miss with default" ":d" "(:z {:a 1} :d)"] - ["hit with default" "1" "(:a {:a 1} :d)"] - ["on nil" "nil" "(:a nil)"] - ["on nil with default" ":d" "(:a nil :d)"] - ["nil value is present" "nil" "(:a {:a nil} :d)"] - ["false value is present" "false" "(:a {:a false} :d)"] - ["on a vector" "nil" "(:a [1 2 3])"] - ["on a number" "nil" "(:a 42)"] - ["on a sorted map" "2" "(:b (sorted-map :a 1 :b 2))"] - ["on assoc result" "3" "(:c (assoc {:a 1} :c 3))"] - ["on a record field" "5" "(do (defrecord KFP [x]) (:x (->KFP 5)))"] - ["qualified keyword" "1" "(:n/a {:n/a 1})"] - ["nested in expr" "6" "(+ (:a {:a 1}) (:b {:b 2}) (:c {:c 3}))"] - ["evaluates map expr once" "[2 1]" - "(do (def cnt (atom 0)) (let [v (:a (do (swap! cnt inc) {:a 2}))] [v @cnt]))"]) - -(defspec "maps / literal construction" - ["basic" "{:a 1, :b 2}" "{:a 1 :b 2}"] - ["empty" "{}" "{}"] - ["computed values" "{:a 3}" "{:a (+ 1 2)}"] - ["nil value kept" "true" "(contains? {:a nil} :a)"] - ["nil value lookup" "nil" "(get {:a nil} :a :d)"] - ["string key" "1" "(get {\"k\" 1} \"k\")"] - ["number key" ":one" "(get {1 :one} 1)"] - ["collection key" ":v" "(get {[1 2] :v} [1 2])"] - ["collection value-equal key" ":v" "(get {[1 2] :v} (vector 1 2))"] - ["computed key" "1" "(get {(keyword \"a\") 1} :a)"] - # jolt-p3c: literal entries evaluate left to right in SOURCE order (the - # reader carries [k v ...] order on a struct prototype / phm field) - ["values evaluate in source order" "[1 2 3]" - "(do (def log (atom [])) {:a (swap! log conj 1) :b (swap! log conj 2) :c (swap! log conj 3)} (deref log))"] - ["keys evaluate before their values, pairwise" "[:k1 :v1 :k2 :v2]" - "(do (def log (atom [])) {(do (swap! log conj :k1) :a) (do (swap! log conj :v1) 1) (do (swap! log conj :k2) :b) (do (swap! log conj :v2) 2)} (deref log))"] - ["source order with a nil value (phm form)" "[1 2 3]" - "(do (def log (atom [])) {:a (do (swap! log conj 1) nil) :b (swap! log conj 2) :c (swap! log conj 3)} (deref log))"] - ["source order through syntax-quote" "[1 2]" - "(do (def log (atom [])) (defmacro m-p3c [] `{:a ~(list 'swap! 'log 'conj 1) :b ~(list 'swap! 'log 'conj 2)}) (m-p3c) (deref log))"] - ["count" "3" "(count {:a 1 :b 2 :c 3})"] - ["equality with phm" "true" "(= {:a 1 :b 2} (assoc {:a 1} :b 2))"] - ["keys work after assoc" "2" "(:b (assoc {:a 1 :b 2} :c 3))"] - ["literal in fn body" "12" "(do (defn mfp-mk [x] {:v (* x 2)}) (:v (mfp-mk 6)))"]) - -(defspec "clojure.math (jolt-h79)" - ["sqrt" "true" "(< 1.4142 (clojure.math/sqrt 2) 1.4143)"] - ["pow" "1024" "(long (clojure.math/pow 2 10))"] - ["tan of 0" "0" "(long (clojure.math/tan 0))"] - ["round" "3" "(clojure.math/round 2.6)"] - ["floor" "2" "(clojure.math/floor 2.9)"] - ["signum" "-1" "(clojure.math/signum -7.2)"] - ["to-radians" "true" "(< 3.14 (clojure.math/to-radians 180) 3.15)"] - ["PI" "true" "(< 3.14 clojure.math/PI 3.15)"] - ["require + alias" "5" "(do (require '[clojure.math :as m]) (long (m/hypot 3 4)))"] - ["as a value" "[1 2]" "(mapv (comp long clojure.math/sqrt) [1 4])"]) - -# jolt-507: a jolt local in janet CALL-HEAD position must not resolve as a -# janet core macro of the same name (repeat/seq/loop are janet macros). The -# emitter rebinds local callees to reserved _fp$ symbols. -(defspec "calls / locals named like janet macros" - ["local fn named repeat" "[1 1]" "(let [repeat (fn [x] [x x])] (repeat 1))"] - ["local fn named seq" ":end" "((fn seq [n] (if (pos? n) (seq (dec n)) :end)) 2)"] - ["local fn named loop2" "[2 1]" "(let [with (fn [a b] [b a])] (with 1 2))"] - ["overlay repeat self-call (regression)" "(quote (0 0 0))" "(take 3 (repeat 0))"] - ["closure param called" "42" "((fn [f] (f 41)) inc)"] - ["param holding a keyword (IFn leftover)" "1" "((fn [f] (f {:a 1})) :a)"]) diff --git a/test/spec/maps-spec.janet b/test/spec/maps-spec.janet deleted file mode 100644 index 9ebd5e2..0000000 --- a/test/spec/maps-spec.janet +++ /dev/null @@ -1,240 +0,0 @@ -# Specification: maps (associative). -(use ../support/harness) - -(defspec "map / construct & predicate" - ["literal" "{:a 1}" "{:a 1}"] - ["hash-map" "{:a 1, :b 2}" "(hash-map :a 1 :b 2)"] - ["empty" "{}" "{}"] - ["map? true" "true" "(map? {:a 1})"] - ["map? false on vector" "false" "(map? [1 2])"] - ["count" "2" "(count {:a 1 :b 2})"] - ["empty? true" "true" "(empty? {})"] - ["equality order-indep" "true" "(= {:a 1 :b 2} {:b 2 :a 1})"]) - -(defspec "map / access" - ["get" "1" "(get {:a 1} :a)"] - ["get missing nil" "nil" "(get {:a 1} :z)"] - ["get default" ":x" "(get {:a 1} :z :x)"] - ["keyword as fn" "1" "(:a {:a 1})"] - ["keyword fn default" ":x" "(:z {:a 1} :x)"] - ["map as fn" "1" "({:a 1} :a)"] - ["get-in" "2" "(get-in {:a {:b 2}} [:a :b])"] - ["get-in missing" "nil" "(get-in {:a {}} [:a :b])"] - ["contains? key" "true" "(contains? {:a 1} :a)"] - ["contains? missing" "false" "(contains? {:a 1} :z)"] - ["find returns entry" "[:a 1]" "(find {:a 1} :a)"] - ["keys" "true" "(= #{:a :b} (set (keys {:a 1 :b 2})))"] - ["vals" "true" "(= #{1 2} (set (vals {:a 1 :b 2})))"]) - -(defspec "map / update" - ["assoc adds" "{:a 1, :b 2}" "(assoc {:a 1} :b 2)"] - ["assoc overwrites" "{:a 9}" "(assoc {:a 1} :a 9)"] - ["assoc many" "{:a 1, :b 2}" "(assoc {} :a 1 :b 2)"] - ["dissoc" "{:a 1}" "(dissoc {:a 1 :b 2} :b)"] - ["dissoc many" "{:a 1}" "(dissoc {:a 1 :b 2 :c 3} :b :c)"] - ["merge" "{:a 1, :b 2}" "(merge {:a 1} {:b 2})"] - ["merge overwrites" "{:a 2}" "(merge {:a 1} {:a 2})"] - ["merge lattermost wins" "{:a 3}" "(merge {:a 1} {:a 2} {:a 3})"] - ["merge no args -> nil" "nil" "(merge)"] - ["merge all nil -> nil" "nil" "(merge nil nil)"] - ["merge nil arg no-op" "{:a 1}" "(merge {:a 1} nil)"] - ["merge nil then map" "{:a 1}" "(merge nil {:a 1})"] - ["merge empty + nil" "{}" "(merge {} nil)"] - ["merge map-entry (conj)" "{:a 1}" "(merge {} (first {:a 1}))"] - ["merge [k v] vector" "{:foo 1}" "(merge {} [:foo 1])"] - ["merge collection key" "true" "(= {[2 3] :foo} (merge {[2 3] :foo} nil {}))"] - ["merge-with" "{:a 3}" "(merge-with + {:a 1} {:a 2})"] - ["update" "{:a 2}" "(update {:a 1} :a inc)"] - ["update missing w/ fnil" "{:a 1}" "(update {} :a (fnil inc 0))"] - ["update-in" "{:a {:b 2}}" "(update-in {:a {:b 1}} [:a :b] inc)"] - ["assoc-in" "{:a {:b 1}}" "(assoc-in {} [:a :b] 1)"] - ["select-keys" "{:a 1}" "(select-keys {:a 1 :b 2} [:a])"] - ["into onto map" "{:a 1, :b 2}" "(into {:a 1} [[:b 2]])"] - ["zipmap" "{:a 1, :b 2}" "(zipmap [:a :b] [1 2])"]) - -(defspec "map / iteration & entries" - ["map over entries" "true" "(= #{1 2} (set (map val {:a 1 :b 2})))"] - ["map keys" "true" "(= #{:a :b} (set (map key {:a 1 :b 2})))"] - ["reduce over entries" "6" "(reduce (fn [a e] (+ a (val e))) 0 {:a 1 :b 2 :c 3})"] - ["reduce-kv" "6" "(reduce-kv (fn [a k v] (+ a v)) 0 {:a 1 :b 2 :c 3})"] - ["destructure entry" "true" "(= [[:a 2]] (into [] (map (fn [[k v]] [k (inc v)]) {:a 1})))"] - ["first of map is entry" "true" "(let [e (first {:a 1})] (and (= (key e) :a) (= (val e) 1)))"] - ["map-entry?" "true" "(map-entry? (first {:a 1}))"] - ["count of nil map" "0" "(count nil)"] - ["get from nil" "nil" "(get nil :a)"] - ["immutability" "true" "(let [m {:a 1} n (assoc m :b 2)] (and (= m {:a 1}) (= n {:a 1 :b 2})))"]) - -(defspec "map / collection keys (by value)" - ["vector key literal" ":v" "(get {[1 2] :v} [1 2])"] - ["map key literal" ":v" "(get {(hash-map :a 1) :v} {:a 1})"] - ["assoc vector key" ":v" "(get (assoc {} [1 2] :v) [1 2])"] - ["key across repr" ":v" "(get (assoc {} (vec [1 2]) :v) [1 2])"] - ["frequencies of maps" "2" "(get (frequencies [{:a 1} (hash-map :a 1)]) {:a 1})"] - ["group-by collection key" "1" "(count (group-by identity [{:a 1} (hash-map :a 1)]))"]) - -# A nil element/key/value INSIDE a collection used as a map key must survive key -# canonicalization — it used to be dropped, so the nil-containing collection -# collided with the nil-free one (jolt-zcm9). -(defspec "map / nil inside a collection key (jolt-zcm9)" - ["set key w/ nil distinct" "2" "(count {#{nil 1} :a, #{1} :b})"] - ["set key w/ nil neg lookup" "nil" "(get {#{nil 1} :a} #{1})"] - ["set key w/ nil pos lookup" ":a" "(get {#{nil 1} :a} #{nil 1})"] - ["set key just nil distinct" "false" "(= {#{nil} :x} {#{} :x})"] - ["map nil-value key distinct" "2" "(count {{:a nil} 1, {} 2})"] - ["map nil-value key neg" "nil" "(get {{:a nil} 1} {})"] - ["map nil-value key pos" "1" "(get {{:a nil} 1} {:a nil})"] - ["map nil-key key distinct" "2" "(count {{nil :a} 1, {} 2})"] - ["map nil-key key pos" "1" "(get {{nil :a} 1} {nil :a})"]) - -# Strictness: assoc bounds-checks vector indices; dissoc requires a map; -# count rejects scalars; numerator/denominator have no ratio type. -(defspec "map / strictness (throws like Clojure)" - ["assoc vec out of bounds" :throws "(assoc [0 1 2] 4 4)"] - ["assoc vec negative" :throws "(assoc [] -1 0)"] - ["assoc vec at count ok" "[1 2 3]" "(assoc [1 2] 2 3)"] - ["dissoc on number" :throws "(dissoc 42 :a)"] - ["dissoc on vector" :throws "(dissoc [1 2] 0)"] - ["dissoc on set" :throws "(dissoc #{:a} :a)"] - ["dissoc nil ok" "nil" "(dissoc nil :a)"] - ["count on number" :throws "(count 1)"] - ["count on keyword" :throws "(count :a)"] - ["count string ok" "3" "(count \"abc\")"] - ["numerator throws" :throws "(numerator 1)"] - ["denominator throws" :throws "(denominator 2)"] - ["subvec out of range" :throws "(subvec [0 1 2 3] 1 5)"] - ["subvec start>end" :throws "(subvec [0 1 2 3] 3 2)"] - ["subvec ok" "[1 2]" "(subvec [0 1 2 3] 1 3)"] - ["min-key empty" :throws "(apply min-key identity [])"] - ["merge empty vector" :throws "(merge {} [])"] - ["merge 1-elem vector" :throws "(merge {} [:foo])"] - ["merge atomic arg" :throws "(merge {} :foo)"] - ["merge [k v] ok" "{:foo 1}" "(merge {} [:foo 1])"] - ["merge maps ok" "{:a 1, :b 2}" "(merge {:a 1} {:b 2})"]) - -# Map entries are distinct from plain vectors (key/val/map-entry? reject a -# vector); min-key/max-key follow Clojure's NaN-aware ordering; subvec coerces -# float/NaN indices like (int ...). -(defspec "map / map-entry & key ordering" - ["key of entry" ":a" "(key (first {:a 1}))"] - ["val of entry" "1" "(val (first {:a 1}))"] - ["key rejects vector" :throws "(key [:a 1])"] - ["val rejects vector" :throws "(val [:a 1])"] - ["map-entry? entry" "true" "(map-entry? (first {:a 1}))"] - ["map-entry? vector" "false" "(map-entry? [:a 1])"] - ["min-key NaN first" "1" "(min-key identity ##NaN 1)"] - ["min-key NaN last" "true" "(NaN? (min-key identity 1 ##NaN))"] - ["min-key NaN three" "true" "(infinite? (min-key identity ##NaN ##-Inf 1))"] - ["min-key keys nonnum" :throws "(min-key identity \"x\" \"y\")"] - ["max-key picks max" "[1 2 3]" "(max-key count [1] [1 2 3] [1 2])"] - ["subvec float trunc" "[0]" "(subvec [0 1 2] 0.5 1.33)"] - ["subvec NaN start" "[0 1 2]" "(subvec [0 1 2] ##NaN 3)"] - ["subvec NaN end" "[]" "(subvec [0 1 2] 0 ##NaN)"]) - -# A nil value is a PRESENT key in Clojure (distinct from a missing key); Janet -# structs drop nil, so jolt builds these maps as a phm. Tested via literals (the -# reader path) and the construction/op surface, in every spec mode. -(defspec "map / nil values preserved" - ["literal contains" "true" "(contains? {:b nil} :b)"] - ["literal not= empty" "false" "(= {:b nil} {})"] - ["literal get nil" "nil" "(get {:b nil} :b :x)"] - ["literal keys incl nil" "true" "(= #{:a :b} (set (keys {:a nil :b 1})))"] - ["literal count" "2" "(count {:a nil :b 1})"] - ["literal vals incl nil" "2" "(count (vals {:a nil :b 1}))"] - ["eval values w/ nil" "3" "(:a {:a (+ 1 2) :b nil})"] - ["nil key present" "true" "(contains? {nil :v} nil)"] - ["assoc nil present" "true" "(contains? (assoc {:a 1} :b nil) :b)"] - ["assoc nil get" "nil" "(get (assoc {:a 1} :b nil) :b :x)"] - ["assoc overwrite nil" "nil" "(get (assoc {:a 1} :a nil) :a :x)"] - ["hash-map nil" "true" "(contains? (hash-map :b nil) :b)"] - ["merge new nil" "true" "(contains? (merge {:a 1} {:b nil}) :b)"] - ["merge overwrite nil" "nil" "(get (merge {:a 1} {:a nil}) :a :x)"] - ["merge-with present nil" "true" "(= [nil 1] (get (merge-with (fn [a b] [a b]) {:a nil} {:a 1}) :a))"] - ["into nil val" "true" "(contains? (into {} [[:a nil]]) :a)"] - ["conj map nil" "true" "(contains? (conj {:x 1} {:a nil}) :a)"] - ["zipmap nil" "true" "(contains? (zipmap [:a] [nil]) :a)"] - ["select-keys nil" "true" "(contains? (select-keys {:a nil} [:a]) :a)"] - ["get-in present nil" "nil" "(get-in {:a nil} [:a] :x)"] - ["get-in through nil" ":x" "(get-in {:a nil} [:a :b] :x)"] - ["dissoc keeps nil" "true" "(contains? (dissoc {:a nil :b 1} :b) :a)"] - ["reduce-kv sees nil" "true" "(= #{:a :b} (reduce-kv (fn [acc k v] (conj acc k)) #{} {:a nil :b 2}))"] - ["nil-free stays fast" "true" "(= {:a 1 :b 2} {:b 2 :a 1})"]) - -# Clojure 1.11 map transformers. -(defspec "map / update-keys & update-vals (1.11)" - ["update-keys" "{\"a\" 1, \"b\" 2}" "(update-keys {:a 1 :b 2} name)"] - ["update-keys empty" "{}" "(update-keys {} inc)"] - ["update-keys nil" "{}" "(update-keys nil str)"] - ["update-keys collide last wins" "1" "(count (update-keys {:a 1 :b 2} (fn [_] :k)))"] - ["update-vals" "{:a 2, :b 3}" "(update-vals {:a 1 :b 2} inc)"] - ["update-vals empty" "{}" "(update-vals {} inc)"] - ["update-vals nil" "{}" "(update-vals nil inc)"] - ["update-vals keeps keys" "[:a :b]" "(sort (keys (update-vals {:a 1 :b 2} inc)))"]) - -# keys/vals/empty? are 00-syntax overlay fns now (jolt-4j3) — expander-called, -# so they live in the first tier and get the staged defn recompile. -(defspec "maps / keys-vals-empty? as overlay fns" - ["keys" "(quote (:a))" "(keys {:a 1})"] - ["keys empty map" "nil" "(keys {})"] - ["keys nil" "nil" "(keys nil)"] - ["vals" "(quote (1))" "(vals {:a 1})"] - ["vals empty" "nil" "(vals {})"] - ["keys sorted order" "[1 2 3]" "(vec (keys (sorted-map 2 :b 1 :a 3 :c)))"] - ["vals sorted order" "[:a :b :c]" "(vec (vals (sorted-map 2 :b 1 :a 3 :c)))"] - ["keys/vals zip" "{:a 1 :b 2}" "(zipmap (keys {:a 1 :b 2}) (vals {:a 1 :b 2}))"] - ["empty? map" "true" "(empty? {})"] - ["empty? vec" "[true false]" "[(empty? []) (empty? [1])]"] - ["empty? list" "[true false]" "[(empty? ()) (empty? (list 1))]"] - ["empty? string" "[true false]" "[(empty? \"\") (empty? \"a\")]"] - ["empty? nil" "true" "(empty? nil)"] - ["empty? set" "[true false]" "[(empty? #{}) (empty? #{1})]"] - ["empty? lazy" "[true false]" "[(empty? (filter pos? [-1])) (empty? (map inc [1]))]"] - ["empty? lazy nil elem" "false" "(empty? (cons nil nil))"] - ["empty? sorted" "[true false]" "[(empty? (sorted-map)) (empty? (sorted-set 1))]"] - ["empty? number throws" :throws "(empty? 5)"]) - -# (assoc nil k v) yields a real immutable map, not a raw host table, so -# assoc-in into absent keys nests countable/seqable maps (jolt-w4s). -(defspec "map / assoc on nil" - ["assoc nil is a map" "{:a 1}" "(assoc nil :a 1)"] - ["count of assoc nil" "1" "(count (assoc nil :a 1))"] - ["assoc-in nested countable" "1" "(count (:a (assoc-in {} [:a :b] 1)))"] - ["assoc-in deep get" "9" "(get-in (assoc-in {} [:a :b :c] 9) [:a :b :c])"] - ["seq over assoc-nil map" ":a" "(ffirst (seq (assoc nil :a 1)))"] - ["keys of assoc-nil map" "[:a]" "(vec (keys (assoc nil :a 1)))"]) - -# into {} / frequencies / group-by bulk-build the HAMT in one pass from a native -# pairs/table accumulator (phm-from-pairs), instead of an assoc per element -# (jolt-5vsp collections). Cross the bin(<=16)/array-node(>=17) promotion and a -# size that grows the trie a level; check dedup (last-wins), nil keys, and that -# assoc/dissoc after a bulk build still land. The structure is identical to the -# incremental builder (validated in the PR), so reads agree. -(defspec "map / bulk build boundaries" - ["into = incr at 17" "true" "(= (into {} (map (fn [i] [i (* i 2)]) (range 17))) (reduce (fn [m p] (assoc m (first p) (second p))) {} (map (fn [i] [i (* i 2)]) (range 17))))"] - ["into = incr at 1000" "true" "(= (into {} (map (fn [i] [i (* i 2)]) (range 1000))) (reduce (fn [m p] (assoc m (first p) (second p))) {} (map (fn [i] [i (* i 2)]) (range 1000))))"] - ["into count 1000" "1000" "(count (into {} (map (fn [i] [i i]) (range 1000))))"] - ["into reads back" "999" "(get (into {} (map (fn [i] [i (* i 3)]) (range 1000))) 333)"] - ["into onto non-empty" "9" "(get (into {:a 1} [[:a 9] [:b 2]]) :a)"] - ["into dup last wins" "9" "(get (into {} [[:k 1] [:k 9]]) :k)"] - ["into nil key" ":x" "(get (into {} [[nil :x] [:a 1]]) nil)"] - ["assoc after bulk" "7" "(get (assoc (into {} (map (fn [i] [i i]) (range 100))) :new 7) :new)"] - ["dissoc after bulk" "nil" "(get (dissoc (into {} (map (fn [i] [i i]) (range 100))) 50) 50)"] - ["frequencies count" "3" "(get (frequencies [1 2 2 1 2 1]) 1)"] - ["frequencies coll-key" "2" "(get (frequencies [[1 2] [1 2] [3 4]]) [1 2])"] - # nil is a legal map key, but a Janet table drops a nil key — the transient - # map (canon-keyed table) used to silently lose the nil-key entry, so - # group-by/frequencies/assoc dropped the whole nil bucket. tbl-key routes nil - # to a sentinel; phm keeps its own has-nil slot. - ["frequencies nil key" "2" "(get (frequencies [nil nil 1]) nil)"] - ["group-by nil key" "[nil nil]" "(get (group-by identity [nil nil 1]) nil)"] - ["group-by nil count" "2" "(count (group-by identity [nil nil 1]))"] - ["transient nil key" ":x" "(let [t (transient {})] (assoc! t nil :x) (get (persistent! t) nil))"] - ["transient nil get" "true" "(let [t (transient {})] (assoc! t nil :x) (contains? t nil))"] - ["transient nil dissoc" ":gone" "(let [t (transient {})] (assoc! t nil :x) (dissoc! t nil) (get (persistent! t) nil :gone))"] - # group-by buckets are built on transient vectors (O(1) push) and frozen once, - # rather than an O(log n) persistent conj per element. Result is identical: - # bucket contents and order match the persistent build across a coarse - # grouping (few large buckets — the case bound on the per-bucket conj). - ["group-by bucket" "[1 3 5]" "(get (group-by odd? (range 1 6)) true)"] - ["group-by big bucket" "true" "(= (group-by even? (range 200)) {true (vec (filter even? (range 200))) false (vec (filter odd? (range 200)))})"] - ["group-by order" "[0 3 6 9]" "(get (group-by (fn [x] (mod x 3)) (range 10)) 0)"] - ["hash-map bulk = incr" "true" "(= (apply hash-map (mapcat (fn [i] [i i]) (range 50))) (reduce (fn [m i] (assoc m i i)) {} (range 50)))"]) diff --git a/test/spec/metadata-spec.janet b/test/spec/metadata-spec.janet deleted file mode 100644 index aa1b4b5..0000000 --- a/test/spec/metadata-spec.janet +++ /dev/null @@ -1,31 +0,0 @@ -# Specification: metadata. -(use ../support/harness) - -(defspec "metadata / with-meta & meta" - ["meta of bare value" "nil" "(meta [1 2 3])"] - ["with-meta then meta" "{:a 1}" "(meta (with-meta [1 2 3] {:a 1}))"] - ["with-meta preserves value" "true" "(= [1 2 3] (with-meta [1 2 3] {:a 1}))"] - ["with-meta on map" "{:doc \"x\"}" "(meta (with-meta {:k 1} {:doc \"x\"}))"] - ["vary-meta" "{:a 2}" "(meta (vary-meta (with-meta [1] {:a 1}) update :a inc))"] - ["vary-meta extra args" "{:a 1 :b 2}" "(meta (vary-meta (with-meta [1] {:a 1}) assoc :b 2))"] - ["meta reader ^" "{:tag :int}" "(meta ^{:tag :int} [1 2])"] - ["with-meta on fn ok" "true" "(fn? (with-meta inc {:a 1}))"] - ["with-meta nil clears" "nil" "(meta (with-meta [1 2 3] nil))"]) - -(defspec "metadata / type hints" - # ^Type / ^:kw / ^"str" on a symbol attach as metadata and are otherwise inert: - # the symbol stays a symbol so hints are transparent in every position. - ["type hint on param" "\"hi\"" "(do (defn f [^String s] s) (f \"hi\"))"] - ["type hint, extra params" "[1 2]" "(do (defn g [^String x y] [x y]) (g 1 2))"] - ["type hint in let" "6" "(let [^long x 5] (inc x))"] - ["type hint in body" "2" "(let [s \"ab\"] (count ^String s))"] - ["type hint in destructure" "3" "(let [{:keys [^long a]} {:a 3}] a)"] - ["symbol hint -> :tag" "\"String\"" "(:tag (meta (read-string \"^String x\")))"] - ["keyword hint -> true" "true" "(:foo (meta (read-string \"^:foo x\")))"]) - -(defspec "metadata / def metadata" - ["^:dynamic var binds" "9" "(do (def ^:dynamic *d* 1) (binding [*d* 9] *d*))"] - ["^:private on var" "true" "(do (def ^:private pv 1) (:private (meta (var pv))))"] - ["^Type tag on var" "\"String\"" "(do (def ^String tv \"a\") (:tag (meta (var tv))))"] - ["^{:doc} on var" "\"hi\"" "(do (def ^{:doc \"hi\"} dv 1) (:doc (meta (var dv))))"] - ["(def name doc val) doc" "\"d\"" "(do (def dd \"d\" 5) (:doc (meta (var dd))))"]) diff --git a/test/spec/missing-vars-spec.janet b/test/spec/missing-vars-spec.janet deleted file mode 100644 index 0690976..0000000 --- a/test/spec/missing-vars-spec.janet +++ /dev/null @@ -1,53 +0,0 @@ -# Specification: the last missing-portable core vars (jolt-brh): -# extenders, find-keyword, inst-ms*, read+string, with-local-vars, with-open, -# with-precision. Documented jolt divergences: find-keyword always finds (jolt -# keywords have no intern table — babashka does the same); with-precision -# evaluates its body with the precision ignored (numbers are doubles, no -# BigDecimal context); with-open closes via the value's :close fn or a host -# file (no .close interop on the Janet host). -(use ../support/harness) - -(defspec "core / find-keyword + inst-ms*" - ["find-keyword" ":a" "(find-keyword \"a\")"] - ["find-keyword 2-arity" ":n/a" "(find-keyword \"n\" \"a\")"] - ["find-keyword = keyword" "true" "(= (find-keyword \"x\") :x)"] - ["inst-ms*" "true" "(= (inst-ms* #inst \"2020-01-01T00:00:00Z\") (inst-ms #inst \"2020-01-01T00:00:00Z\"))"] - ["inst-ms* value" "0" "(inst-ms* #inst \"1970-01-01T00:00:00Z\")"]) - -(defspec "core / with-local-vars" - ["var-get initial" "1" "(with-local-vars [x 1] (var-get x))"] - ["var-set" "2" "(with-local-vars [x 1] (var-set x 2) (var-get x))"] - ["two vars" "[1 2]" "(with-local-vars [a 1 b 2] [(var-get a) (var-get b)])"] - ["vars are values" "5" "(with-local-vars [x 0] (let [bump (fn [v] (var-set v (+ 5 (var-get v))))] (bump x) (var-get x)))"] - ["init sees outer" "3" "(let [y 3] (with-local-vars [x y] (var-get x)))"] - ["body result" ":done" "(with-local-vars [x 1] :done)"]) - -(defspec "core / with-open" - ["body result" ":r" "(let [log (atom [])] (with-open [c {:close (fn [] (swap! log conj :closed))}] :r))"] - ["close runs" "[:closed]" "(let [log (atom [])] (with-open [c {:close (fn [] (swap! log conj :closed))}] :r) (deref log))"] - ["close on throw" "[:closed]" "(let [log (atom [])] (try (with-open [c {:close (fn [] (swap! log conj :closed))}] (throw (ex-info \"boom\" {}))) (catch Exception e nil)) (deref log))"] - ["nested close order" "[:inner :outer]" "(let [log (atom [])] (with-open [a {:close (fn [] (swap! log conj :outer))} b {:close (fn [] (swap! log conj :inner))}] :r) (deref log))"] - ["zero bindings" ":r" "(with-open [] :r)"] - ["binding visible" "5" "(with-open [c {:close (fn [] nil) :v 5}] (:v c))"]) - -(defspec "core / with-precision" - ["body evaluates" "3.14" "(with-precision 3 3.14)"] - ["multiple body forms" "2" "(with-precision 10 1 2)"] - ["rounding arg accepted" "1.5" "(with-precision 4 :rounding :half-up 1.5)"] - ["arithmetic" "2" "(with-precision 5 (+ 1 1))"]) - -(defspec "core / read+string" - ["form and text" "true" "(let [[v s] (with-in-str \"42 rest\" (read+string))] (and (= v 42) (string? s)))"] - ["form value" "(quote (+ 1 2))" "(first (with-in-str \"(+ 1 2)\" (read+string)))"] - ["text covers the form" "true" "(let [[v s] (with-in-str \" [1 2] tail\" (read+string))] (and (= v [1 2]) (> (count s) 3)))"] - ["advances the stream" "[1 2]" "(with-in-str \"1 2\" [(first (read+string)) (first (read+string))])"] - ["EOF throws" :throws "(with-in-str \"\" (read+string))"] - ["eof-value arity" ":done" "(first (with-in-str \"\" (read+string *in* false :done)))"]) - -(defspec "core / extenders" - ["lists extended type" "[\"user.Rx\"]" - "(do (defprotocol Px (pm [x])) (defrecord Rx [] Px (pm [x] 1)) (mapv str (extenders Px)))"] - ["nil when none" "nil" - "(do (defprotocol Py (pn [x])) (extenders Py))"] - ["seq of tags" "true" - "(do (defprotocol Pz (pz [x])) (defrecord Rz [] Pz (pz [x] 1)) (and (seq (extenders Pz)) (= 1 (count (extenders Pz)))))"]) diff --git a/test/spec/multimethods-spec.janet b/test/spec/multimethods-spec.janet deleted file mode 100644 index 1dd8acb..0000000 --- a/test/spec/multimethods-spec.janet +++ /dev/null @@ -1,70 +0,0 @@ -# Specification: multimethods & hierarchies. -(use ../support/harness) - -(defspec "multimethods / dispatch" - ["dispatch on value" "\"two\"" - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (f 2))"] - ["dispatch on keyword fn" "\"circle\"" - "(do (defmulti area :shape) (defmethod area :circle [_] \"circle\") (area {:shape :circle}))"] - [":default method" "\"other\"" - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f :default [_] \"other\") (f 99))"] - ["no match throws" :throws - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (f 99))"] - ["multiple args" "5" - "(do (defmulti g (fn [a b] a)) (defmethod g :add [_ b] b) (g :add 5))"] - ["get-method" "\"one\"" - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") ((get-method f 1) 1))"] - ["remove-method" :throws - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (remove-method f 1) (f 1))"] - ["methods" "\"one\"" - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") ((get (methods f) 1) 1))"] - ["methods count" "2" - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (count (methods f)))"] - ["remove-all-methods" :throws - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (defmethod f 2 [_] \"two\") (remove-all-methods f) (f 1))"] - ["remove-all-methods empties the table" "0" - "(do (defmulti f identity) (defmethod f 1 [_] \"one\") (remove-all-methods f) (count (methods f)))"]) - -(defspec "multimethods / hierarchies" - ["derive + isa?" "true" "(do (derive ::child ::parent) (isa? ::child ::parent))"] - ["isa? reflexive" "true" "(isa? ::x ::x)"] - ["isa? unrelated" "false" "(do (derive ::a ::b) (isa? ::a ::c))"] - ["parents" "true" "(do (derive ::c ::p) (contains? (parents ::c) ::p))"] - ["ancestors" "true" "(do (derive ::c ::p) (derive ::p ::g) (contains? (ancestors ::c) ::g))"] - ["descendants" "true" "(do (derive ::c ::p) (contains? (descendants ::p) ::c))"] - ["dispatch via hierarchy" "\"animal\"" - "(do (derive ::dog ::animal) (defmulti speak identity) (defmethod speak ::animal [_] \"animal\") (speak ::dog))"] - ["custom :default key" ":unknown" - "(do (defmulti classify :type :default :other) (defmethod classify :a [_] :alpha) (defmethod classify :other [_] :unknown) (classify {:type :zzz}))"] - ["explicit :hierarchy" "\"a\"" - "(do (def h (derive (make-hierarchy) ::dog ::animal)) (defmulti snd identity :hierarchy h) (defmethod snd ::animal [_] \"a\") (snd ::dog))"]) - -# prefer-method breaks isa-dispatch ties; ambiguity without a preference is -# an ERROR (jolt-heo — this used to silently take an arbitrary method). -(defspec "multimethods / prefer-method" - ["preference picks the winner" ":rect" - "(do (derive :p/sq :p/rect) (derive :p/sq :p/shape) (defmulti pm1 identity) (defmethod pm1 :p/rect [x] :rect) (defmethod pm1 :p/shape [x] :shape) (prefer-method pm1 :p/rect :p/shape) (pm1 :p/sq))"] - ["reverse preference" ":shape" - "(do (derive :q/sq :q/rect) (derive :q/sq :q/shape) (defmulti pm2 identity) (defmethod pm2 :q/rect [x] :rect) (defmethod pm2 :q/shape [x] :shape) (prefer-method pm2 :q/shape :q/rect) (pm2 :q/sq))"] - ["ambiguity throws" :throws - "(do (derive :r/sq :r/rect) (derive :r/sq :r/shape) (defmulti pm3 identity) (defmethod pm3 :r/rect [x] :rect) (defmethod pm3 :r/shape [x] :shape) (pm3 :r/sq))"] - ["isa dominance needs no preference" ":child" - "(do (derive :s/c :s/p) (defmulti pm4 identity) (defmethod pm4 :s/c [x] :child) (defmethod pm4 :s/p [x] :parent) (pm4 :s/c))"] - ["prefers map shape" "true" - "(do (defmulti pm5 identity) (defmethod pm5 :a [x] 1) (defmethod pm5 :b [x] 2) (prefer-method pm5 :a :b) (contains? (get (prefers pm5) :a) :b))"] - ["exact match needs no preference" ":exact" - "(do (derive :t/sq :t/rect) (defmulti pm6 identity) (defmethod pm6 :t/sq [x] :exact) (defmethod pm6 :t/rect [x] :parent) (pm6 :t/sq))"]) - -# defmulti drops a leading docstring/attr-map (jolt-es4 — it used to be taken as -# the dispatch fn). methods/get-method take the multimethod VALUE and recover -# the table, so a bare multifn ref works even when defmethods live elsewhere -# (jolt-9pu). -(defspec "multimethods / docstring & value-based table ops" - ["defmulti docstring" "\"A\"" - "(do (defmulti gd \"the dispatcher\" identity) (defmethod gd :a [_] \"A\") (gd :a))"] - ["defmulti doc+default" "\"d\"" - "(do (defmulti gx \"doc\" identity) (defmethod gx :default [_] \"d\") (gx :anything))"] - ["methods on value" "2" - "(do (defmulti gm identity) (defmethod gm 1 [_] :one) (defmethod gm 2 [_] :two) (count (methods gm)))"] - ["get-method on value" "true" - "(do (defmulti gg identity) (defmethod gg :a [_] :x) (fn? (get-method gg :a)))"]) diff --git a/test/spec/namespaces-spec.janet b/test/spec/namespaces-spec.janet deleted file mode 100644 index 2e332d4..0000000 --- a/test/spec/namespaces-spec.janet +++ /dev/null @@ -1,80 +0,0 @@ -# Specification: namespaces, vars and require. -(use ../support/harness) - -(defspec "namespaces / def & vars" - ["def + deref" "5" "(do (def x 5) x)"] - ["def returns var" "true" "(var? (def y 1))"] - ["declare then def" "2" "(do (declare z) (def z 2) z)"] - ["var special form" "true" "(var? (var +))"] - ["var sugar #'" "true" "(var? #'+)"] - ["var-get" "5" "(do (def w 5) (var-get #'w))"] - ["defn defines fn" "3" "(do (defn f [x] (inc x)) (f 2))"] - ["def with docstring" "7" "(do (def d \"a doc\" 7) d)"] - ["dynamic var binding" "2" "(do (def ^:dynamic *x* 1) (binding [*x* 2] *x*))"] - ["binding restores" "1" "(do (def ^:dynamic *y* 1) (binding [*y* 9] nil) *y*)"] - ["var-set in binding" "5" "(do (def ^:dynamic *z* 1) (binding [*z* 0] (var-set (var *z*) 5) *z*))"]) - -(defspec "namespaces / ns operations" - ["in-ns switches" "true" "(do (in-ns 'my.ns) (symbol? 'x))"] - # ns is a macro over in-ns/require/use/import (Stage 2 jolt-eaa): the form sets - # the current ns and processes its clauses. - ["ns form + alias" "\"HI\"" "(do (ns my.app (:require [clojure.string :as s])) (s/upper-case \"hi\"))"] - ["ns :use refers all" "9" "(do (ns src.lib) (def helper 9) (ns dst.app (:use [src.lib])) helper)"] - ["standalone use" "7" "(do (ns src.l2) (def k 7) (in-ns 'dst.a2) (use '[src.l2]) k)"] - ["ns-name" "true" "(do (require (quote [clojure.string])) (= 'clojure.string (ns-name (find-ns 'clojure.string))))"] - ["find-ns existing" "true" "(some? (find-ns 'clojure.core))"] - ["find-ns missing" "nil" "(find-ns 'does.not.exist)"] - ["resolve var" "true" "(var? (resolve '+))"] - ["resolve missing" "nil" "(resolve 'totally-undefined-xyz)"]) - -(defspec "namespaces / require & refer" - ["require :as" "\"AB\"" "(do (require '[clojure.string :as s]) (s/upper-case \"ab\"))"] - ["require :refer" "true" "(do (require '[clojure.string :refer [blank?]]) (blank? \"\"))"] - ["require :as + :refer" "true" "(do (require '[clojure.string :as s :refer [blank?]]) (and (blank? \"\") (= \"X\" (s/upper-case \"x\"))))"] - ["require clojure.set" "#{1 2 3}" "(do (require '[clojure.set :as set]) (set/union #{1 2} #{3}))"] - ["require clojure.walk" "{:a 2}" "(do (require '[clojure.walk :as w]) (w/postwalk (fn [x] (if (number? x) (inc x) x)) {:a 1}))"] - ["walk keywordize-keys" "{:a 1}" "(do (require '[clojure.walk :as w]) (w/keywordize-keys {\"a\" 1}))"] - ["walk stringify-keys" "true" "(do (require '[clojure.walk :as w]) (= {\"a\" 1} (w/stringify-keys {:a 1})))"] - # Clojure throws FileNotFoundException; silently succeeding masks typos and - # missing roots until the first unresolved-symbol error far from the cause. - ["require missing lib throws" :throws "(require '[no.such.lib])"] - ["use missing lib throws" :throws "(use 'no.such.lib)"] - # …but an ns created in-session is in *loaded-libs* (the ns macro puts it - # there), so require/use of it must NOT hit the loader. - ["require of in-session ns ok" "1" "(do (ns made.here) (def x 1) (require '[made.here]) made.here/x)"]) - -(defspec "namespaces / alias, ns-unalias, ns-publics" - ["alias + use" "\"1,2\"" "(do (require (quote clojure.string)) (alias (quote st) (quote clojure.string)) (st/join \",\" [1 2]))"] - ["ns-unalias removes" "true" - "(do (require (quote clojure.string)) (alias (quote st2) (quote clojure.string)) (ns-unalias (quote user) (quote st2)) (nil? (get (ns-aliases (quote user)) (quote st2))))"] - ["ns-publics has var" "true" "(do (def npv 1) (some? (get (ns-publics (quote user)) (quote npv))))"] - ["newline returns nil" "nil" "(newline)"]) - -# A throw inside an interpreted fn body (or macro expander) must restore the -# caller's current-ns: the body runs with current-ns rebound to the fn's -# DEFINING ns, and an unwind that skipped the restore left the ctx stuck -# there — every later alias-qualified lookup in the REPL ns then failed -# ("Unable to resolve symbol: alias/...", seen via sci + clojure.edn). -(defspec "namespaces / error inside a fn must not leak its defining ns" - ["alias survives a throwing stdlib call" "\"A\"" - "(do (require (quote [clojure.string :as s9])) (try (s9/join nil nil nil) (catch Exception e nil)) (s9/upper-case \"a\"))"] - ["*ns* restored after throw" "\"user\"" - "(do (require (quote [clojure.walk :as w9])) (try (w9/postwalk nil nil nil) (catch Exception e nil)) (str *ns*))"]) - -# Alias bookkeeping is unified (jolt-ark): one string-keyed :aliases store, -# read by resolution AND ns-aliases (which presents Clojure's -# {alias-symbol -> namespace} shape); :imports holds class imports only. -(defspec "namespaces / unified alias store" - ["require :as registers the alias" "1" - "(do (require (quote [clojure.string :as st1])) (count (filter (fn [[a n]] (= (str a) \"st1\")) (ns-aliases))))"] - ["aliased call resolves" "\"A\"" - "(do (require (quote [clojure.string :as st2])) (st2/upper-case \"a\"))"] - ["alias fn registers + resolves" "\"B\"" - "(do (require (quote [clojure.string])) (alias (quote st3) (quote clojure.string)) (st3/upper-case \"b\"))"] - ["alias fn visible to ns-aliases" "true" - "(do (require (quote [clojure.string])) (alias (quote st4) (quote clojure.string)) (pos? (count (filter (fn [[a n]] (= (str a) \"st4\")) (ns-aliases)))))"] - ["ns-unalias removes both views" "[0 false]" - "(do (require (quote [clojure.string :as st5])) (ns-unalias (quote user) (quote st5)) [(count (filter (fn [[a n]] (= (str a) \"st5\")) (ns-aliases))) (boolean (resolve (quote st5/upper-case)))])"] - ["ns-resolve through alias" "true" - "(do (require (quote [clojure.string :as st6])) (var? (ns-resolve (quote user) (quote st6/upper-case))))"] - ["empty ns-aliases is a map" "true" "(map? (ns-aliases (quote clojure.core)))"]) diff --git a/test/spec/nrepl-spec.janet b/test/spec/nrepl-spec.janet deleted file mode 100644 index 2d635c0..0000000 --- a/test/spec/nrepl-spec.janet +++ /dev/null @@ -1,27 +0,0 @@ -# Specification: jolt.nrepl bencode codec (pure, no networking). -# The server/client wire behavior is covered by test/integration/nrepl-test.janet. -(use ../support/harness) - -(defn- b [body] - (string "(do (require '[jolt.nrepl :as nr]) " body ")")) -(defn- rt [body] - # round-trip a value through encode -> decode - (b (string "(nr/decode (nr/reader nil (nr/encode " body ")))"))) - -(defspec "jolt.nrepl / bencode round-trip" - ["integer" "42" (rt "42")] - ["negative" "-7" (rt "-7")] - ["string" "\"hello\"" (rt "\"hello\"")] - ["empty string" "\"\"" (rt "\"\"")] - ["list" "[\"a\" 1 \"b\"]" (rt "[\"a\" 1 \"b\"]")] - ["nested list" "[1 [2 3]]" (rt "[1 [2 3]]")] - ["dict" "{\"op\" \"eval\" \"id\" \"7\"}" (rt "{\"op\" \"eval\" \"id\" \"7\"}")] - ["dict with list" "{\"status\" [\"done\"]}" (rt "{\"status\" [\"done\"]}")] - ["nested dict" "{\"a\" {\"b\" 1}}" (rt "{\"a\" {\"b\" 1}}")]) - -(defspec "jolt.nrepl / bencode encode shape" - ["int" "\"i42e\"" (b "(nr/encode 42)")] - ["string" "\"5:hello\"" (b "(nr/encode \"hello\")")] - ["list" "\"li1ei2ee\"" (b "(nr/encode [1 2])")] - # dict keys are sorted lexicographically - ["dict sorted keys" "\"d1:ai1e1:bi2ee\"" (b "(nr/encode {\"b\" 2 \"a\" 1})")]) diff --git a/test/spec/ns-var-spec.janet b/test/spec/ns-var-spec.janet deleted file mode 100644 index aa44480..0000000 --- a/test/spec/ns-var-spec.janet +++ /dev/null @@ -1,16 +0,0 @@ -# Specification: *ns* — the current-namespace dynamic var (stage 3). -# *ns* holds the current NAMESPACE OBJECT; (str *ns*) is its name; it tracks -# in-ns at the top level and works with the ns-introspection fns. -(use ../support/harness) - -(defspec "*ns* / identity & printing" - ["str of *ns*" "\"user\"" "(str *ns*)"] - ["ns-name of *ns*" "(quote user)" "(ns-name *ns*)"] - ["*ns* is find-ns" "true" "(= (ns-name *ns*) (ns-name (find-ns (quote user))))"] - ["*ns* not a map" "false" "(map? *ns*)"] - ["tracks in-ns" "\"jolt.test-ns-a\"" "(do (in-ns (quote jolt.test-ns-a)) (str *ns*))"] - ["in-ns returns ns" "\"jolt.test-ns-b\"" "(str (in-ns (quote jolt.test-ns-b)))"] - ["usable with ns fns" "true" - "(do (require (quote clojure.string)) (alias (quote nsv) (quote clojure.string)) (some? (get (ns-aliases *ns*) (quote nsv))))"] - ["ns-unalias via *ns*" "true" - "(do (require (quote clojure.string)) (alias (quote nsw) (quote clojure.string)) (ns-unalias *ns* (quote nsw)) (nil? (get (ns-aliases *ns*) (quote nsw))))"]) diff --git a/test/spec/numbers-spec.janet b/test/spec/numbers-spec.janet deleted file mode 100644 index 8cf89b2..0000000 --- a/test/spec/numbers-spec.janet +++ /dev/null @@ -1,220 +0,0 @@ -# Specification: numbers & arithmetic. -(use ../support/harness) - -(defspec "numbers / arithmetic" - ["add" "6" "(+ 1 2 3)"] - ["add zero args" "0" "(+)"] - ["subtract" "5" "(- 10 3 2)"] - ["negate" "-5" "(- 5)"] - ["multiply" "24" "(* 2 3 4)"] - ["multiply zero args" "1" "(*)"] - ["divide" "2" "(/ 10 5)"] - ["divide to fraction" "0.5" "(/ 1 2)"] - ["inc" "6" "(inc 5)"] - ["dec" "4" "(dec 5)"] - ["quot" "3" "(quot 10 3)"] - ["rem" "1" "(rem 10 3)"] - ["mod" "2" "(mod -1 3)"] - ["rem negative" "-1" "(rem -1 3)"] - ["max" "9" "(max 3 9 1)"] - ["min" "1" "(min 3 9 1)"] - ["abs" "5" "(abs -5)"] - ["promoting + alias" "3" "(+' 1 2)"] - ["inc' alias" "6" "(inc' 5)"]) - -(defspec "numbers / comparison" - ["less than" "true" "(< 1 2 3)"] - ["less than false" "false" "(< 1 3 2)"] - ["greater than" "true" "(> 3 2 1)"] - ["<=" "true" "(<= 1 1 2)"] - [">=" "true" "(>= 3 3 2)"] - ["= numbers" "true" "(= 2 2)"] - ["= different" "false" "(= 2 3)"] - ["== numeric" "true" "(== 2 2)"] - ["not=" "true" "(not= 1 2)"] - ["compare less" "-1" "(compare 1 2)"] - ["compare equal" "0" "(compare 1 1)"] - ["compare greater" "1" "(compare 2 1)"]) - -(defspec "numbers / predicates" - ["zero?" "true" "(zero? 0)"] - ["pos?" "true" "(pos? 5)"] - ["neg?" "true" "(neg? -5)"] - ["even?" "true" "(even? 4)"] - ["odd?" "true" "(odd? 3)"] - ["number?" "true" "(number? 5)"] - ["number? false" "false" "(number? :a)"] - ["int?" "true" "(int? 5)"] - ["pos-int?" "true" "(pos-int? 5)"] - ["neg-int?" "true" "(neg-int? -5)"] - ["nat-int? zero" "true" "(nat-int? 0)"] - ["nat-int? neg" "false" "(nat-int? -1)"] - ["ratio? false" "false" "(ratio? 5)"]) - -# Symbolic float values and float/double predicates. NOTE: Janet represents -# integers and integer-valued doubles identically, so (float? 1.0) is false -# (1.0 is indistinguishable from 1) — a documented divergence. Fractional and -# non-finite values ARE recognized as floats. -(defspec "numbers / floats & symbolic values" - ["read ##Inf" "true" "(= ##Inf (/ 1.0 0.0))"] - ["read ##-Inf" "true" "(< ##-Inf 0)"] - ["##NaN not= itself" "true" "(not (== ##NaN ##NaN))"] - ["float? fractional" "true" "(float? 1.5)"] - ["double? fractional" "true" "(double? 0.25)"] - ["float? integer" "false" "(float? 3)"] - ["float? ##Inf" "true" "(float? ##Inf)"] - ["double? ##NaN" "true" "(double? ##NaN)"] - ["infinite? ##Inf" "true" "(infinite? ##Inf)"] - ["infinite? ##-Inf" "true" "(infinite? ##-Inf)"] - ["infinite? finite" "false" "(infinite? 1.5)"] - ["NaN? ##NaN" "true" "(NaN? ##NaN)"] - ["NaN? number" "false" "(NaN? 1.0)"] - ["int? ##Inf false" "false" "(int? ##Inf)"] - ["pos-int? ##Inf" "false" "(pos-int? ##Inf)"]) - -# Numeric literal syntaxes. Jolt has no true bignum/ratio/bigdec types, so the -# N (bigint) and M (bigdec) suffixes read as the plain number, ratios as the -# double quotient; radix integers (NrDDD) are parsed by base. -(defspec "numbers / literal syntax" - ["bigint suffix N" "42" "42N"] - ["bigint zero" "0" "0N"] - ["bigdec suffix M" "1.5" "1.5M"] - ["bigdec int M" "0" "0.0M"] - ["ratio -> double" "0.5" "1/2"] - ["ratio 3/4" "0.75" "3/4"] - ["neg ratio" "-0.5" "-1/2"] - ["radix binary" "10" "2r1010"] - ["radix hex-ish" "255" "16rFF"] - ["radix base36" "35" "36rZ"] - ["hex" "255" "0xFF"] - ["exponent" "1000.0" "1e3"] - ["exponent neg" "0.015" "1.5e-2"]) - -# Strictness: numeric ops reject non-numbers like Clojure; the integer -# predicates reject non-integers; quot/rem/mod reject zero/non-finite. -(defspec "numbers / strictness (throws like Clojure)" - ["odd? nil" :throws "(odd? nil)"] - ["odd? fractional" :throws "(odd? 1.5)"] - ["even? inf" :throws "(even? ##Inf)"] - ["zero? nil" :throws "(zero? nil)"] - ["pos? false" :throws "(pos? false)"] - ["neg? keyword" :throws "(neg? :a)"] - ["< nil" :throws "(< nil 1)"] - ["> with nil" :throws "(> 1 nil)"] - ["max non-number" :throws "(max 1 nil)"] - ["quot by zero" :throws "(quot 10 0)"] - ["quot inf" :throws "(quot ##Inf 1)"] - ["< arity-1 any" "true" "(< :anything)"] - ["odd? ok" "true" "(odd? 3)"] - ["< ok" "true" "(< 1 2 3)"] - ["quot ok" "3" "(quot 10 3)"]) - -(defspec "numbers / printing of inf & nan" - ["str Infinity" "\"Infinity\"" "(str ##Inf)"] - ["str -Infinity" "\"-Infinity\"" "(str ##-Inf)"] - ["str NaN" "\"NaN\"" "(str ##NaN)"] - ["pr-str Infinity" "\"Infinity\"" "(pr-str ##Inf)"] - ["inf inside coll" "\"[Infinity]\"" "(str [##Inf])"]) - -(defspec "numbers / bit-ops & math" - ["bit-and" "4" "(bit-and 12 6)"] - ["bit-or" "14" "(bit-or 12 6)"] - ["bit-xor" "10" "(bit-xor 12 6)"] - ["bit-shift-left" "8" "(bit-shift-left 1 3)"] - ["bit-shift-right" "2" "(bit-shift-right 8 2)"] - ["bit-set" "8" "(bit-set 0 3)"] - ["bit-clear" "13" "(bit-clear 15 1)"] - ["bit-test true" "true" "(bit-test 4 2)"] - ["bigint 64-bit" "\"9000000000\"" "(str (bigint 9000000000))"]) - -(defspec "numbers / random (invariants — non-deterministic)" - ["rand-int in range" "true" "(let [r (rand-int 5)] (and (integer? r) (>= r 0) (< r 5)))"] - ["rand-int zero" "0" "(rand-int 1)"] - ["rand in [0,1)" "true" "(let [r (rand)] (and (>= r 0) (< r 1)))"] - ["rand n in [0,n)" "true" "(let [r (rand 10)] (and (>= r 0) (< r 10)))"] - ["rand-nth member" "true" "(contains? #{:a :b :c} (rand-nth [:a :b :c]))"] - ["rand-nth single" ":x" "(rand-nth [:x])"]) - -# Clojure 1.11 string->scalar parsers: nil on malformed, throw on non-string. -(defspec "numbers / parse fns (1.11)" - ["parse-long" "42" "(parse-long \"42\")"] - ["parse-long negative" "-7" "(parse-long \"-7\")"] - ["parse-long plus" "7" "(parse-long \"+7\")"] - ["parse-long float nil" "nil" "(parse-long \"1.5\")"] - ["parse-long hex nil" "nil" "(parse-long \"0x10\")"] - ["parse-long empty nil" "nil" "(parse-long \"\")"] - ["parse-long junk nil" "nil" "(parse-long \"12ab\")"] - ["parse-long throws" :throws "(parse-long 42)"] - ["parse-double" "1.5" "(parse-double \"1.5\")"] - ["parse-double int" "4.0" "(parse-double \"4\")"] - ["parse-double sci" "1500.0" "(parse-double \"1.5e3\")"] - ["parse-double neg" "-0.5" "(parse-double \"-0.5\")"] - ["parse-double junk" "nil" "(parse-double \"abc\")"] - ["parse-double trail" "nil" "(parse-double \"1.5x\")"] - ["parse-double throws" :throws "(parse-double :k)"] - ["parse-boolean true" "true" "(parse-boolean \"true\")"] - ["parse-boolean false" "false" "(parse-boolean \"false\")"] - ["parse-boolean case" "nil" "(parse-boolean \"True\")"] - ["parse-boolean junk" "nil" "(parse-boolean \"yes\")"] - ["parse-boolean throws" :throws "(parse-boolean true)"]) - -# Jolt numbers don't overflow, so the auto-promoting (') and unchecked -# variants are aliases of the checked ops (overlay defs, core/20-coll.clj). -(defspec "numbers / promoting & unchecked aliases" - ["+'" "3" "(+' 1 2)"] - ["-'" "3" "(-' 5 2)"] - ["*'" "12" "(*' 3 4)"] - ["inc'" "6" "(inc' 5)"] - ["dec'" "4" "(dec' 5)"] - ["unchecked-add" "5" "(unchecked-add 2 3)"] - ["unchecked-add-int" "5" "(unchecked-add-int 2 3)"] - ["unchecked-subtract" "3" "(unchecked-subtract 5 2)"] - ["unchecked-subtract-int" "3" "(unchecked-subtract-int 5 2)"] - ["unchecked-multiply" "12" "(unchecked-multiply 3 4)"] - ["unchecked-multiply-int" "12" "(unchecked-multiply-int 3 4)"] - ["unchecked-negate" "-5" "(unchecked-negate 5)"] - ["unchecked-negate-int" "-5" "(unchecked-negate-int 5)"] - ["unchecked-inc" "2" "(unchecked-inc 1)"] - ["unchecked-inc-int" "2" "(unchecked-inc-int 1)"] - ["unchecked-dec" "0" "(unchecked-dec 1)"] - ["unchecked-dec-int" "0" "(unchecked-dec-int 1)"] - ["unchecked-divide-int" "3" "(unchecked-divide-int 7 2)"] - ["unchecked-divide-int negative truncates toward zero" "-3" "(unchecked-divide-int -7 2)"] - ["unchecked-divide-int by zero throws" :throws "(unchecked-divide-int 1 0)"] - ["unchecked-remainder-int" "1" "(unchecked-remainder-int 7 2)"] - ["unchecked-remainder-int negative" "-1" "(unchecked-remainder-int -7 2)"] - ["unchecked-int truncates" "3" "(unchecked-int 3.7)"] - ["unchecked-int negative" "-3" "(unchecked-int -3.7)"] - ["unchecked-long" "3" "(unchecked-long 3.7)"] - ["int? on integer" "true" "(int? 5)"] - ["int? on double" "false" "(int? 5.5)"] - ["int? on non-number" "false" "(int? \"5\")"] - ["num passes a number through" "5" "(num 5)"] - ["num on a double" "5.5" "(num 5.5)"] - ["num throws on non-number" :throws "(num \"x\")"]) - -# == is numeric equality: single arg is trivially true (Clojure's 1-arity -# never inspects the value); 2+ args must be numbers. -(defspec "numbers / == numeric equality" - ["== single arg" "true" "(== :a)"] - ["== equal" "true" "(== 2 2)"] - ["== unequal" "false" "(== 2 3)"] - ["== chained" "true" "(== 2 2 2)"] - ["== chained unequal" "false" "(== 2 2 3)"] - ["== int and double" "true" "(== 1 1.0)"] - ["== throws on non-number" :throws "(== 1 :a)"] - ["== throws on two keywords" :throws "(== :a :a)"]) - -# Variadic bit ops (canonical Clojure arities: binary host op folded over the -# rest). Shift/clear/set/flip/test stay 2-arg, as in Clojure. -(defspec "numbers / variadic bit ops" - ["bit-and 2" "4" "(bit-and 12 6)"] - ["bit-and 3" "4" "(bit-and 12 6 7)"] - ["bit-and 4" "0" "(bit-and 12 6 7 3)"] - ["bit-or 3" "7" "(bit-or 1 2 4)"] - ["bit-xor 3" "7" "(bit-xor 1 2 4)"] - ["bit-xor folds left" "1" "(bit-xor 5 6 2)"] - ["bit-and-not 2" "8" "(bit-and-not 12 6)"] - ["bit-and-not 3" "8" "(bit-and-not 12 6 3)"] - ["bit-and single arg throws" :throws "(bit-and 5)"] - ["bit-or keeps binary fast path" "3" "(bit-or 1 2)"]) diff --git a/test/spec/predicates-spec.janet b/test/spec/predicates-spec.janet deleted file mode 100644 index fd77d90..0000000 --- a/test/spec/predicates-spec.janet +++ /dev/null @@ -1,229 +0,0 @@ -# Specification: type & value predicates. -(use ../support/harness) - -(defspec "predicates / nil & boolean" - ["nil? true" "true" "(nil? nil)"] - ["nil? false" "false" "(nil? 0)"] - ["some? true" "true" "(some? 0)"] - ["some? on nil" "false" "(some? nil)"] - ["true?" "true" "(true? true)"] - ["false?" "true" "(false? false)"] - ["boolean? true" "true" "(boolean? false)"] - ["not nil" "true" "(not nil)"] - ["not 0 is false" "false" "(not 0)"] - ["boolean of nil" "false" "(boolean nil)"] - ["boolean of value" "true" "(boolean 5)"]) - -(defspec "predicates / types" - ["string?" "true" "(string? \"x\")"] - ["number?" "true" "(number? 1)"] - ["keyword?" "true" "(keyword? :a)"] - ["symbol?" "true" "(symbol? (quote a))"] - ["char?" "true" "(char? \\a)"] - ["fn? on fn" "true" "(fn? inc)"] - ["ifn? on keyword" "true" "(ifn? :a)"] - ["vector?" "true" "(vector? [1])"] - ["list?" "true" "(list? (list 1))"] - ["map?" "true" "(map? {:a 1})"] - ["set?" "true" "(set? #{1})"] - ["coll? vector" "true" "(coll? [1])"] - ["coll? map" "true" "(coll? {:a 1})"] - ["coll? on number" "false" "(coll? 1)"] - ["seq? list" "true" "(seq? (list 1))"] - ["seq? vector" "false" "(seq? [1])"] - ["sequential? vector" "true" "(sequential? [1])"] - ["associative? map" "true" "(associative? {:a 1})"] - ["associative? vec" "true" "(associative? [1])"] - ["associative? list" "false" "(associative? '(1 2))"] - ["associative? set" "false" "(associative? #{1})"] - ["reversible? vec" "true" "(reversible? [1 2])"] - ["reversible? list" "false" "(reversible? '(1 2))"] - ["reversible? smap" "true" "(reversible? (sorted-map :a 1))"] - ["reversible? hmap" "false" "(reversible? (hash-map :a 1))"] - ["indexed? vector" "true" "(indexed? [1])"] - ["counted? vector" "true" "(counted? [1])"]) - -(defspec "predicates / idents" - ["ident? keyword" "true" "(ident? :a)"] - ["ident? symbol" "true" "(ident? (quote a))"] - ["simple-keyword?" "true" "(simple-keyword? :a)"] - ["qualified-keyword?" "true" "(qualified-keyword? :a/b)"] - ["simple-symbol?" "true" "(simple-symbol? (quote a))"] - ["qualified-symbol?" "true" "(qualified-symbol? (quote a/b))"] - ["name of keyword" "\"a\"" "(name :a)"] - ["name of qualified" "\"b\"" "(name :a/b)"] - ["namespace" "\"a\"" "(namespace :a/b)"] - ["namespace simple" "nil" "(namespace :a)"] - ["keyword constructor" ":foo" "(keyword \"foo\")"] - ["keyword ns + name" ":a/b" "(keyword \"a\" \"b\")"] - ["symbol constructor" "(quote x)" "(symbol \"x\")"] - ["name of string" "\"s\"" "(name \"s\")"]) - -# Predicates moved from Janet to the Clojure overlay (jolt-1j0). Jolt has no -# ratio/bigdecimal types (so ratio?/decimal? are always false, rational?=int?), -# and no distinct host object/undefined types (object?/undefined? always false). -(defspec "predicates / overlay-migrated" - ["not-any? true" "true" "(not-any? even? [1 3 5])"] - ["not-any? false" "false" "(not-any? even? [1 2 3])"] - ["not-every? true" "true" "(not-every? even? [2 4 5])"] - ["not-every? false" "false" "(not-every? even? [2 4 6])"] - ["ident? number" "false" "(ident? 1)"] - ["qualified-ident?" "true" "(qualified-ident? :a/b)"] - ["qualified-ident? no" "false" "(qualified-ident? :a)"] - ["simple-ident?" "true" "(simple-ident? :a)"] - ["ratio?" "false" "(ratio? 3)"] - ["decimal?" "false" "(decimal? 3)"] - # No first-class Class objects on this host (class names are symbols handled - # in instance?/new positions), so class? is always false — like Clojure's - # class? of a symbol. Selmer's `exception` macro calls it at expansion time. - ["class? of value" "false" "(class? \"s\")"] - ["class? of symbol" "false" "(class? 'java.lang.String)"] - ["rational? int" "true" "(rational? 3)"] - ["rational? float" "false" "(rational? 3.5)"] - ["nat-int? zero" "true" "(nat-int? 0)"] - ["nat-int? neg" "false" "(nat-int? -1)"] - ["pos-int?" "true" "(pos-int? 5)"] - ["neg-int?" "true" "(neg-int? -3)"] - ["NaN? on nan" "true" "(NaN? (/ 0.0 0.0))"] - ["NaN? on number" "false" "(NaN? 5)"] - ["abs negative" "3" "(abs -3)"] - ["abs positive" "2.5" "(abs 2.5)"] - ["object?" "false" "(object? 1)"] - ["undefined?" "false" "(undefined? 1)"] - ["keyword-identical?" "true" "(keyword-identical? :a :a)"] - ["keyword-identical? no" "false" "(keyword-identical? :a :b)"]) - -# Tagged-value predicates moved to the overlay in Phase 4 (read the value's -# :jolt/type via get). The constructors stay native. -# map?/coll? are STRICT (jolt-6s2 cleanup): tagged structs (symbols, chars, -# uuids) are values, not collections; sorted maps/sets and records ARE -# collections (and sorted-map/record are map?), matching Clojure. -(defspec "predicates / map? & coll? strictness" - ["map? symbol" "false" "(map? (quote sym))"] - ["map? char" "false" "(map? \\a)"] - ["map? uuid" "false" "(map? (random-uuid))"] - ["map? literal" "true" "(map? {:a 1})"] - ["map? hash-map" "true" "(map? (hash-map :a 1))"] - ["map? sorted-map" "true" "(map? (sorted-map :a 1))"] - ["map? record" "true" "(do (defrecord Mr [a]) (map? (->Mr 1)))"] - ["map? sorted-set" "false" "(map? (sorted-set 1))"] - ["map? vector" "false" "(map? [1])"] - ["coll? symbol" "false" "(coll? (quote sym))"] - ["coll? char" "false" "(coll? \\a)"] - ["coll? uuid" "false" "(coll? (random-uuid))"] - ["coll? keyword" "false" "(coll? :k)"] - ["coll? string" "false" "(coll? \"s\")"] - ["coll? map literal" "true" "(coll? {:a 1})"] - ["coll? sorted-map" "true" "(coll? (sorted-map :a 1))"] - ["coll? sorted-set" "true" "(coll? (sorted-set 1))"] - ["coll? record" "true" "(do (defrecord Cr [a]) (coll? (->Cr 1)))"] - ["coll? vector" "true" "(coll? [1])"] - ["coll? list" "true" "(coll? (list 1))"] - ["coll? set" "true" "(coll? #{1})"] - ["coll? lazy seq" "true" "(coll? (map inc [1]))"]) - -(defspec "predicates / tagged-value (Phase 4)" - ["atom? yes" "true" "(atom? (atom 1))"] - ["atom? no" "false" "(atom? 1)"] - ["volatile? yes" "true" "(volatile? (volatile! 1))"] - ["volatile? no" "false" "(volatile? (atom 1))"] - ["record? yes" "true" "(do (defrecord Rp [a]) (record? (->Rp 1)))"] - ["record? no map" "false" "(record? {:a 1})"] - ["record? no nil" "false" "(record? nil)"] - ["tagged-literal? yes" "true" "(tagged-literal? (tagged-literal (quote inst) \"2020\"))"] - ["tagged-literal? no" "false" "(tagged-literal? 1)"] - ["reader-conditional? no" "false" "(reader-conditional? 1)"] - ["chunked-seq? always false" "false" "(chunked-seq? (seq [1 2 3]))"]) - -(defspec "predicates / equality & identity" - ["= same" "true" "(= 1 1)"] - ["= vectors" "true" "(= [1 2] [1 2])"] - ["= vector & list" "true" "(= [1 2] (list 1 2))"] - ["= maps" "true" "(= {:a 1} {:a 1})"] - ["= sets" "true" "(= #{1 2} #{2 1})"] - ["= nested" "true" "(= {:a [1 2]} {:a [1 2]})"] - ["not= differs" "true" "(not= [1 2] [1 3])"] - ["identical? same kw" "true" "(identical? :a :a)"] - ["compare strings" "-1" "(compare \"a\" \"b\")"]) - -(defspec "predicates / seqable, reduced & emptiness" - ["seqable? vector" "true" "(seqable? [1])"] - ["seqable? map" "true" "(seqable? {:a 1})"] - ["seqable? string" "true" "(seqable? \"s\")"] - ["seqable? nil" "true" "(seqable? nil)"] - ["seqable? number" "false" "(seqable? 5)"] - ["integer? int" "true" "(integer? 5)"] - ["integer? fraction" "false" "(integer? 5.5)"] - ["reduced? wrapped" "true" "(reduced? (reduced 1))"] - ["reduced? plain" "false" "(reduced? 1)"] - ["deref reduced" "9" "(deref (reduced 9))"] - ["unreduced wrapped" "9" "(unreduced (reduced 9))"] - ["unreduced plain" "9" "(unreduced 9)"] - ["not-empty full" "[1]" "(not-empty [1])"] - ["not-empty empty" "nil" "(not-empty [])"] - ["not-empty string" "nil" "(not-empty \"\")"]) - -# Stage 3 turn 2a: the implicit Janet root-env fallback is GONE — these are now -# proper interned clojure.core vars with Clojure semantics (compare's total -# order, meta-aware type, any?, gensym returning jolt symbols). -(defspec "predicates / compare, type, any? (stage 3)" - ["compare =" "0" "(compare 1 1)"] - ["compare <" "-1" "(compare 1 2)"] - ["compare nil first" "-1" "(compare nil 1)"] - ["compare nil nil" "0" "(compare nil nil)"] - ["compare strings" "-1" "(compare \"a\" \"b\")"] - ["compare keywords" "-1" "(compare :a :b)"] - ["compare symbols" "-1" "(compare (quote a) (quote b))"] - ["compare bools" "-1" "(compare false true)"] - ["compare vec length" "-1" "(compare [1 2] [1 2 3])"] - ["compare vec elems" "-1" "(compare [1 2] [1 3])"] - ["compare cross-type throws" :throws "(compare 1 \"a\")"] - ["sort with compare" "[nil 1 3]" "(sort compare [3 nil 1])"] - ["type meta override" ":custom" "(type (with-meta [1] {:type :custom}))"] - ["type of record" "true" "(do (defrecord TyR [a]) (= (symbol (str (type (->TyR 1)))) (type (->TyR 1))))"] - ["any? value" "true" "(any? 5)"] - ["any? nil" "true" "(any? nil)"] - ["gensym is symbol" "true" "(symbol? (gensym))"] - ["gensym prefix" "true" "(do (require (quote [clojure.string :as s])) (s/starts-with? (str (gensym \"p_\")) \"p_\"))"] - ["gensym distinct" "false" "(= (gensym) (gensym))"] - ["int? Inf false" "false" "(int? ##Inf)"] - ["integer? Inf false" "false" "(integer? ##Inf)"] - ["integer? NaN false" "false" "(integer? ##NaN)"]) - -# ifn? is the canonical IFn set (jolt-1vx): lists are NOT IFn. -(defspec "predicates / ifn?" - ["fn" "true" "(ifn? inc)"] - ["keyword" "true" "(ifn? :k)"] - ["symbol" "true" "(ifn? (quote s))"] - ["map" "true" "(ifn? {})"] - ["sorted map" "true" "(ifn? (sorted-map))"] - ["set" "true" "(ifn? #{1})"] - ["vector" "true" "(ifn? [1])"] - ["var" "true" "(ifn? (var first))"] - ["list NOT" "false" "(ifn? (list 1 2))"] - ["lazy NOT" "false" "(ifn? (map inc [1]))"] - ["string NOT" "false" "(ifn? \"s\")"] - ["number NOT" "false" "(ifn? 5)"] - ["nil NOT" "false" "(ifn? nil)"]) - -# zero?/pos? throw on non-numbers (Numbers.isZero/isPos), as in Clojure; -# every? short-circuits on the first falsey pred result, so an infinite seq -# with an early counterexample terminates. char? is the tagged-value check. -(defspec "predicates / numeric guards & every? (overlay moves)" - ["zero? zero" "true" "(zero? 0)"] - ["zero? nonzero" "false" "(zero? 3)"] - ["zero? throws" :throws "(zero? :a)"] - ["zero? throws on nil" :throws "(zero? nil)"] - ["pos? positive" "true" "(pos? 2)"] - ["pos? zero" "false" "(pos? 0)"] - ["pos? throws" :throws "(pos? \"x\")"] - ["neg? throws" :throws "(neg? \"x\")"] - ["every? all pass" "true" "(every? odd? [1 3 5])"] - ["every? one fails" "false" "(every? odd? [1 2 5])"] - ["every? vacuous" "true" "(every? odd? [])"] - ["every? nil coll" "true" "(every? odd? nil)"] - ["every? infinite short-circuit" "false" "(every? pos? (range))"] - ["char? char" "true" "(char? \\x)"] - ["char? string" "false" "(char? \"x\")"] - ["char? number" "false" "(char? 97)"] - ["char? nil" "false" "(char? nil)"]) diff --git a/test/spec/protocols-spec.janet b/test/spec/protocols-spec.janet deleted file mode 100644 index b14a723..0000000 --- a/test/spec/protocols-spec.janet +++ /dev/null @@ -1,64 +0,0 @@ -# Specification: protocols, types and records. -(use ../support/harness) - -(defspec "protocols / defprotocol & dispatch" - ["protocol on record" "16" - "(do (defprotocol Shape (area [s])) (defrecord Sq [side] Shape (area [_] (* side side))) (area (->Sq 4)))"] - ["protocol on deftype" "16" - "(do (defprotocol Shape (area [s])) (deftype Sq [side] Shape (area [_] (* side side))) (area (->Sq 4)))"] - ["multiple methods" "[1 2]" - "(do (defprotocol P (m [s]) (n [s])) (defrecord R [a b] P (m [_] a) (n [_] b)) [(m (->R 1 2)) (n (->R 1 2))])"] - ["multiple protocols" "[:a :b]" - "(do (defprotocol P1 (p1 [s])) (defprotocol P2 (p2 [s])) (deftype T [] P1 (p1 [_] :a) P2 (p2 [_] :b)) [(p1 (->T)) (p2 (->T))])"] - ["method args" "7" - "(do (defprotocol P (add [s x])) (defrecord R [n] P (add [_ x] (+ n x))) (add (->R 5) 2))"] - ["extend-type" "10" - "(do (defprotocol P (twice [s])) (extend-type Number P (twice [n] (* n 2))) (twice 5))"] - ["extend-protocol" "[2 4]" - "(do (defprotocol P (dbl [s])) (extend-protocol P Number (dbl [n] (* n 2))) [(dbl 1) (dbl 2)])"]) - -(defspec "protocols / records" - ["record field access" "1" - "(do (defrecord R [a b]) (:a (->R 1 2)))"] - ["record map access" "2" - "(do (defrecord R [a b]) (get (->R 1 2) :b))"] - ["record equality" "true" - "(do (defrecord R [a b]) (= (->R 1 2) (->R 1 2)))"] - ["record inequality" "false" - "(do (defrecord R [a b]) (= (->R 1 2) (->R 3 4)))"] - ["map-> factory" "1" - "(do (defrecord R [a b]) (:a (map->R {:a 1 :b 2})))"] - ["record? true" "true" - "(do (defrecord R [a]) (record? (->R 1)))"] - ["assoc on record" "9" - "(do (defrecord R [a]) (:a (assoc (->R 1) :a 9)))"]) - -(defspec "protocols / reify & satisfies" - ["reify dispatch" "42" - "(do (defprotocol P (m [_])) (m (reify P (m [_] 42))))"] - ["reify multi-method" "[1 2]" - "(do (defprotocol P (a [_]) (b [_])) (let [r (reify P (a [_] 1) (b [_] 2))] [(a r) (b r)]))"] - ["satisfies? true" "true" - "(do (defprotocol P (m [_])) (defrecord R [] P (m [_] 1)) (satisfies? P (->R)))"] - ["satisfies? false" "false" - "(do (defprotocol P (m [_])) (defrecord R []) (satisfies? P (->R)))"] - ["satisfies? reify" "true" - "(do (defprotocol P (m [_])) (satisfies? P (reify P (m [_] 1))))"] - ["satisfies? reify multi-protocol" "[true true]" - "(do (defprotocol P (m [_])) (defprotocol Q (n [_])) (let [r (reify P (m [_] 1) Q (n [_] 2))] [(satisfies? P r) (satisfies? Q r)]))"] - ["satisfies? reify other proto" "false" - "(do (defprotocol P (m [_])) (defprotocol Q (n [_])) (satisfies? Q (reify P (m [_] 1))))"] - ["instance? record" "true" - "(do (defrecord R [a]) (instance? R (->R 1)))"] - ["dot constructor" "5" - "(do (deftype P [n]) (.-n (P. 5)))"] - ["dot ctor + method" "5" - "(do (defprotocol G (val-of [_])) (deftype P [n] G (val-of [_] n)) (val-of (P. 5)))"]) - -# defprotocol accepts Clojure's optional docstring + leading keyword options -# before the signatures (honeysql: :extend-via-metadata true). -(defspec "protocols / defprotocol options" - ["docstring + option + method" ":hi" - "(do (defprotocol Pdoc \"docs\" :extend-via-metadata true (greet [x])) (extend-protocol Pdoc String (greet [s] :hi)) (greet \"x\"))"] - ["option only" "3" - "(do (defprotocol Popt :extend-via-metadata true (plus2 [x])) (extend-protocol Popt Long (plus2 [n] (+ n 2))) (plus2 1))"]) diff --git a/test/spec/reader-forms-spec.janet b/test/spec/reader-forms-spec.janet deleted file mode 100644 index 08e4d59..0000000 --- a/test/spec/reader-forms-spec.janet +++ /dev/null @@ -1,80 +0,0 @@ -# Specification: reader forms + syntax-quote + metadata. -# -# Adapted from the jank test corpus (test/jank/{syntax-quote,metadata,reader-macro, -# call}); we keep our own copies since jank may diverge. Syntax-quoted symbols are -# qualified to clojure.core (matching jank/Clojure). Platform-specific reader forms -# (#uuid, #inst, ##Inf/##NaN, bigdecimal/biginteger/ratio) are omitted. -(use ../support/harness) - -(defspec "reader / anonymous fn #()" - ["no args" "3" "(#(+ 1 2))"] - ["one arg %" "6" "(#(* % 2) 3)"] - ["positional %1 %2" "[1 2]" "(#(do [%1 %2]) 1 2)"] - ["rest %&" "[1 2 3]" "(#(do %&) 1 2 3)"] - ["fixed + rest" "[2 3]" "(#(do % %&) 1 2 3)"] - ["%2 + rest" "[3]" "(#(do %2 %&) 1 2 3)"] - ["%2 only (placeholder p1)" "20" "(#(* %2 2) 1 10)"] - ["% and %1 same" "10" "(#(+ % %1) 5)"]) - -(defspec "reader / var-quote #'" - ["var-quote = var" "true" "(= (var str) #'str)"] - ["is a var" "true" "(var? #'str)"] - ["deref var-quote" "5" "(do (def w 5) (deref #'w))"]) - -(defspec "reader / metadata ^" - ["meta on map" "true" "(:foo (meta ^:foo {}))"] - ["meta on vector" "true" "(:foo (meta ^:foo [1 2]))"] - ["meta on set" "true" "(:foo (meta ^:foo #{}))"] - ["meta map form" "1" "(:a (meta ^{:a 1} {}))"] - ["meta on quoted sym" "true" "(:foo (meta (quote ^:foo bar)))"] - ["with-meta map" "true" "(:k (meta (with-meta {} {:k true})))"] - ["with-meta vector" "true" "(:k (meta (with-meta [] {:k true})))"] - ["non-metadatable num" "nil" "(meta 100)"] - ["non-metadatable str" "nil" "(meta \"\")"] - ["non-metadatable bool" "nil" "(meta true)"]) - -(defspec "reader / syntax-quote" - ["plain literal" "[1 2 3]" "`[1 2 3]"] - ["gensym distinct" "true" "(not= `meow# `meow#)"] - ["gensym stable" "true" "(let [s `[meow# meow#]] (= (first s) (second s)))"] - ["qualifies unresolved" "(quote user/foo)" "`foo"] - # jolt-265 (fixed): resolved core symbols fully-qualify to clojure.core/. - ["qualifies core sym" "(quote clojure.core/str)" "`str"] - ["unquote value" "[1 2 3]" "(let [a [1 2 3]] `~a)"] - ["unquote in call" "(quote (clojure.core/str [1 2 3]))" "(let [a [1 2 3]] `(str ~a))"] - ["splice empty" "(quote (clojure.core/str))" "(let [e []] `(str ~@e))"] - ["splice values" "(quote (clojure.core/str 1 2 3))" "(let [a [1 2 3]] `(str ~@a))"] - ["splice in vector" "[1 2 3 0 1 2 3]" "(let [b [0] a [1 2 3] e []] `[~@e ~@a ~@b ~@a ~@e])"] - # jolt-edb (fixed): ~/~@ inside set literals. - ["splice in set" "#{0 1 2 3}" "(let [b [0] a [1 2 3] e []] `#{~@e ~@a ~@b})"] - ["unquote in set" "#{5 9}" "(let [x 5] `#{~x 9})"]) - -# Spec 02-reader S17/S19/S18/S13a/S22: discard, symbolic values, conditionals, -# var-quote identity, gensym stability (jank corpus derived). -(defspec "reader / discard, symbolic values, conditionals (spec 2.3)" - ["discard simple" "2" "(do #_1 2)"] - ["discard in vector" "[1 3]" "[1 #_2 3]"] - ["discard stacks" "3" "(do #_ #_ 1 2 3)"] - ["##Inf" "true" "(= ##Inf (/ 1.0 0.0))"] - ["##-Inf" "true" "(= ##-Inf (/ -1.0 0.0))"] - ["##NaN not self-equal" "false" "(= ##NaN ##NaN)"] - ["##NaN is NaN?" "true" "(NaN? ##NaN)"] - ["conditional :default reachable" "2" "#?(:no-such-dialect 1 :default 2)"] - ["var-quote qualified" "true" "(= (var clojure.core/str) #'clojure.core/str)"] - ["gensym stable in template" "true" "(let [syms `[meow# meow#]] (= (first syms) (second syms)))"] - ["gensym fresh across templates" "false" "(= `meow# `meow#)"]) - -# Spec 02-reader S25: syntax-quote of a self-evaluating literal is the literal -# (read-time collapse), so adjacent/nested backticks over literals are inert. -(defspec "reader / syntax-quote literal collapse (spec 2.4 S25)" - ["string once" "true" "(= \"meow\" `\"meow\")"] - ["string nested" "true" "(= \"meow\" ``\"meow\")"] - ["string triple" "true" "(= \"meow\" ```\"meow\")"] - ["number nested" "true" "(= 42 ``42)"] - ["keyword nested" "true" "(= :k ``:k)"] - ["nil nested" "true" "(nil? ``nil)"] - ["char nested" "true" "(= \\a ``\\a)"] - ["bool nested" "true" "(= true ``true)"] - # collapse must NOT apply to symbols (they qualify) or collections (templates) - ["symbol still qualifies" "true" "(= (quote clojure.core/map) `map)"] - ["vector still templates" "true" "(= [1 2] `[1 ~(inc 1)])"]) diff --git a/test/spec/reader-syntax-spec.janet b/test/spec/reader-syntax-spec.janet deleted file mode 100644 index 7e39eae..0000000 --- a/test/spec/reader-syntax-spec.janet +++ /dev/null @@ -1,72 +0,0 @@ -# Specification: reader syntax & literals. -(use ../support/harness) - -(defspec "reader / scalar literals" - ["integer" "42" "42"] - ["negative" "-7" "-7"] - ["float" "1.5" "1.5"] - ["string" "\"hi\"" "\"hi\""] - ["boolean true" "true" "true"] - ["nil" "nil" "nil"] - ["keyword" ":a" ":a"] - ["namespaced keyword" "true" "(= :a/b :a/b)"] - ["char" "\\a" "\\a"] - ["char newline" "true" "(= \\newline (first \"\\n\"))"] - # single non-symbol chars are one-char literals (\{ \( \, \% etc.) - ["char open-brace" "123" "(int \\{)"] - ["char open-paren" "40" "(int \\()"] - ["char comma" "44" "(int \\,)"] - ["char percent" "37" "(int \\%)"] - ["char unicode" "65" "(int \\u0041)"] - ["hex literal" "255" "0xff"] - ["hex uppercase" "31" "0X1F"] - ["bigint suffix N" "42" "42N"] - ["bigdec suffix M" "1.5" "1.5M"] - ["ratio -> double" "0.75" "3/4"] - ["radix integer" "255" "16rFF"] - ["exponent" "1500.0" "1.5e3"] - ["symbolic Infinity" "true" "(infinite? ##Inf)"] - ["symbolic NaN" "true" "(NaN? ##NaN)"] - ["symbol via quote" "'foo" "'foo"]) - -(defspec "reader / collection literals" - ["vector" "[1 2 3]" "[1 2 3]"] - ["list quoted" "[1 2 3]" "'(1 2 3)"] - ["map" "{:a 1}" "{:a 1}"] - ["set" "#{1 2 3}" "#{1 2 3}"] - ["nested" "{:a [1 {:b 2}]}" "{:a [1 {:b 2}]}"] - ["empty vector" "[]" "[]"] - ["empty map" "{}" "{}"] - ["empty set" "#{}" "#{}"]) - -(defspec "reader / dispatch & sugar" - ["anon fn #()" "3" "(#(+ %1 %2) 1 2)"] - ["anon fn single %" "2" "(#(inc %) 1)"] - ["anon fn %&" "[2 3]" "(#(vec %&) 2 3)"] - ["discard #_" "[1 3]" "[1 #_2 3]"] - ["regex literal" "true" "(= \"abc\" (re-find #\"abc\" \"xabcx\"))"] - # Feature set is #{:jolt :default} (spec 02-reader S18; RFC 0002) — :clj - # branches are NOT taken; matching is by clause order. - ["reader conditional" "3" "#?(:clj 1 :cljs 2 :default 3)"] - ["reader cond :jolt" "4" "#?(:clj 1 :jolt 4 :default 3)"] - ["reader cond clause order" "5" "#?(:default 5 :jolt 6)"] - ["reader cond no match" "[]" "[#?(:clj 1 :cljs 2)]"] - ["reader cond splice" "[1 2 3]" "[#?@(:jolt [1 2 3] :cljs [4 5])]"] - ["reader cond splice no match" "[]" "[#?@(:clj [1 2 3] :cljs [4 5])]"] - ["inst literal reads" "true" "(some? #inst \"2020-01-01T00:00:00Z\")"] - ["uuid literal" "\"550e8400-e29b-41d4-a716-446655440000\"" "(str #uuid \"550e8400-e29b-41d4-a716-446655440000\")"] - ["tagged literal var" "true" "(var? #'+)"] - ["deref sugar" "5" "(let [a (atom 5)] @a)"] - ["meta sugar" "{:t 1}" "(meta ^{:t 1} [])"]) - -# Comments and #_ discards in a map's VALUE slot keep the pending key -# (jolt-ou8: dropping both desynced kv pairing — Selmer's deps.edn, with a -# "; for development (REPL, etc)" comment between key and value, read its -# closing brace in value position: 'Unmatched closing brace'). -(defspec "reader / comments inside maps" - ["comment in value slot" "{:a 1}" "{:a ; note\n 1}"] - ["comment before key" "{:a 1}" "{; lead\n :a 1}"] - ["comment between entries" "{:a 1 :b 2}" "{:a 1 ; mid\n :b 2}"] - ["discard in value slot" "{:a 1}" "{:a #_9 1}"] - ["comment with parens" "{:a {:b 1}}" "{:a ; dev (REPL, etc)\n {:b 1}}"] - ["nested with comments" "{:x {:y 2}}" "{:x ; outer\n {:y ; inner\n 2}}"]) diff --git a/test/spec/regex-spec.janet b/test/spec/regex-spec.janet deleted file mode 100644 index 78de377..0000000 --- a/test/spec/regex-spec.janet +++ /dev/null @@ -1,83 +0,0 @@ -# Specification: regular expressions — #"…" literals and the re-* fns. -# (Whole area previously unspecced; some cases adapted from jank reader-macro/regex.) -(use ../support/harness) - -(defspec "regex / literals & predicate" - ["regex? literal" "true" "(regex? #\"\\d+\")"] - ["regex? non-regex" "false" "(regex? \"\\d+\")"] - ["escaped digits" "\"42\"" "(re-find #\"\\d+\" \"x42y\")"] - ["escaped ws/non-ws" "\"x a\"" "(re-find #\"\\S\\s\\S\" \"x a b y\")"]) - -(defspec "regex / re-find" - ["match" "\"123\"" "(re-find #\"\\d+\" \"abc123def\")"] - ["no match nil" "nil" "(re-find #\"\\d+\" \"abc\")"] - ["with groups" "[\"a1\" \"a\" \"1\"]" "(re-find #\"([a-z])(\\d)\" \"--a1--\")"] - ["first match only" "\"1\"" "(re-find #\"\\d\" \"1 2 3\")"]) - -(defspec "regex / re-matches" - ["full match" "\"123\"" "(re-matches #\"\\d+\" \"123\")"] - ["partial = nil" "nil" "(re-matches #\"\\d+\" \"123abc\")"] - ["groups" "[\"12\" \"1\" \"2\"]" "(re-matches #\"(\\d)(\\d)\" \"12\")"] - ["no match nil" "nil" "(re-matches #\"x+\" \"yyy\")"]) - -(defspec "regex / re-seq" - ["all matches" "(quote (\"1\" \"22\" \"333\"))" "(re-seq #\"\\d+\" \"a1b22c333\")"] - ["empty when none" "nil" "(seq (re-seq #\"z\" \"abc\"))"] - ["words" "(quote (\"foo\" \"bar\"))" "(re-seq #\"\\w+\" \"foo bar\")"]) - -(defspec "regex / re-pattern & string ops" - ["re-pattern build" "\"hi\"" "(re-find (re-pattern \"\\\\w+\") \"hi!\")"] - ["re-pattern is regex?" "true" "(regex? (re-pattern \"a\"))"] - ["split on regex" "[\"a\" \"b\" \"c\"]" "(do (require '[clojure.string :as s]) (s/split \"a1b2c\" #\"\\d\"))"] - ["replace regex" "\"X-X\"" "(do (require '[clojure.string :as s]) (s/replace \"a-b\" #\"[a-z]\" \"X\"))"] - ["replace $1" "\"[a][b]\"" "(do (require '[clojure.string :as s]) (s/replace \"ab\" #\"([a-z])\" \"[$1]\"))"]) - -# Unicode property classes (jolt-xlp), byte-PEG approximation: ASCII exact, -# any high byte (inside a UTF-8 sequence) counts as a LETTER for \p{L}. -# Acceptance target was cuerdas (kebab/snake/capital now pass conformance). -(defspec "regex / \\p property classes" - ["p{L} ascii" "\"hello\"" `(re-matches #"^\p{L}+$" "hello")`] - ["p{L} utf-8" "true" `(boolean (re-matches #"^\p{L}+$" "héllo"))`] - ["p{L} rejects digits" "false" `(boolean (re-matches #"^\p{L}+$" "ab1"))`] - ["p{N}" "(quote (\"12\" \"345\"))" `(re-seq #"\p{N}+" "a12b345")`] - ["P{N} negation" "\"abc\"" `(re-matches #"^\P{N}+$" "abc")`] - ["inside class" "\"a-1_b\"" `(re-matches #"^[\p{N}\p{L}_-]+$" "a-1_b")`] - ["p{Lu}/p{Ll}" "\"aB\"" `(re-matches #"^\p{Ll}\p{Lu}$" "aB")`] - ["p{Z} space" "\" \"" `(re-matches #"(?u)^[\s\p{Z}]+$" " ")`] - ["p{Ps}/p{Pe}" "\"(x)\"" `(re-matches #"^\p{Ps}x\p{Pe}$" "(x)")`] - ["(?u) accepted" "\"hi\"" `(re-matches #"(?u)^hi$" "hi")`] - ["unknown class throws" :throws `(re-pattern "\p{Greek}")`]) - -# java.util.regex.Pattern statics (jolt-47b): compile returns jolt's native -# regex value (so .split / str-ops accept it), MULTILINE maps to (?m), quote -# escapes metachars. Plus the regex String methods migratus uses. -(defspec "regex / Pattern statics & String regex methods" - ["Pattern/compile is a regex" "true" "(regex? (Pattern/compile \"a.c\"))"] - ["compiled .split" "[\"a\" \"b\" \"c\"]" "(.split (Pattern/compile \",\") \"a,b,c\")"] - ["str/replace w/ Pattern" "\"ab\"" "(do (require '[clojure.string :as s]) (s/replace \"a1b2\" (Pattern/compile \"[0-9]\") \"\"))"] - ["Pattern/MULTILINE ^" "true" "(boolean (re-find (Pattern/compile \"^x\" Pattern/MULTILINE) \"y\\nx\"))"] - ["Pattern/quote literal" "true" "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"za.cy\"))"] - ["Pattern/quote not meta" "false" "(boolean (re-find (re-pattern (Pattern/quote \"a.c\")) \"zabcy\"))"] - [".matches whole string" "true" "(.matches \"abc\" \"a.c\")"] - [".matches partial -> false" "false" "(.matches \"abcd\" \"a.c\")"] - [".replaceAll regex" "\"a-b-c\"" "(.replaceAll \"a_b_c\" \"_\" \"-\")"] - [".replaceFirst regex" "\"a-b_c\"" "(.replaceFirst \"a_b_c\" \"_\" \"-\")"]) - -(defspec "regex / bounded quantifiers (jolt-3xur)" - ["exact {n}" "\"aaa\"" "(re-matches #\"a{3}\" \"aaa\")"] - ["range {n,m} max" "\"aaaa\"" "(re-find #\"a{2,4}\" \"aaaaa\")"] - ["zero lower {0,n}" "\"aa\"" "(re-find #\"a{0,3}\" \"aa\")"] - ["{n,} unbounded" "\"aaaa\"" "(re-find #\"a{2,}\" \"aaaa\")"] - # nested bounded quantifiers must not blow up the PEG compiler — this used to - # expand to ~2^61 nodes and hang at compile time. - ["nested bounds compile" "true" - "(boolean (re-matches #\"[a-z](?:[a-z]{0,61}[a-z])?(?:-[a-z]{0,61}[a-z])*\" \"abc-def\"))"]) - -(defspec "regex / backreferences (jolt-xtss)" - ["repeated char" "true" "(boolean (re-find #\"(.)\\1\" \"abba\"))"] - ["no repeat = nil" "nil" "(re-find #\"(.)\\1\" \"abc\")"] - ["thematic-break run" "true" "(boolean (re-matches #\"([-*_])\\1\\1\" \"---\"))"] - ["mismatched run" "nil" "(re-matches #\"([-*_])\\1\\1\" \"-*_\")"] - ["repeated word" "[\"the the\" \"the\"]" "(re-find #\"(\\w+) \\1\" \"say the the word\")"] - ["group still captures" "[\"x=x\" \"x\"]" "(re-matches #\"(\\w+)=\\1\" \"x=x\")"] - ["html tag pair" "true" "(boolean (re-matches #\"<(\\w+)>.*\" \"hi\"))"]) diff --git a/test/spec/sequences-spec.janet b/test/spec/sequences-spec.janet deleted file mode 100644 index 2c9f3a8..0000000 --- a/test/spec/sequences-spec.janet +++ /dev/null @@ -1,309 +0,0 @@ -# Specification: the sequence abstraction (clojure.core). -# Sequential expecteds use vector literals — Jolt's `=` treats vectors and lists -# with the same elements as equal, so [2 3 4] matches a (2 3 4) seq result. -(use ../support/harness) - -(defspec "seq / access" - ["first of vector" "1" "(first [1 2 3])"] - ["first of list" "1" "(first (list 1 2 3))"] - ["first of empty is nil" "nil" "(first [])"] - ["first of nil is nil" "nil" "(first nil)"] - ["second" "2" "(second [1 2 3])"] - ["last" "3" "(last [1 2 3])"] - ["rest of vector" "[2 3]" "(rest [1 2 3])"] - ["rest of single" "[]" "(rest [1])"] - ["rest of empty" "[]" "(rest [])"] - ["next of single is nil" "nil" "(next [1])"] - ["next of empty is nil" "nil" "(next [])"] - ["nth" "30" "(nth [10 20 30] 2)"] - ["nth with default" "99" "(nth [10] 5 99)"] - ["nth out of range" :throws "(nth [10] 5)"] - ["ffirst" "1" "(ffirst [[1 2] [3 4]])"] - ["fnext" "2" "(fnext [1 2 3])"] - ["nnext" "[3 4]" "(nnext [1 2 3 4])"]) - -(defspec "seq / construction" - ["cons onto list" "[0 1 2]" "(cons 0 (list 1 2))"] - ["cons onto vector" "[0 1 2]" "(cons 0 [1 2])"] - ["cons onto nil" "[0]" "(cons 0 nil)"] - ["conj vector appends" "[1 2 3]" "(conj [1 2] 3)"] - ["conj list prepends" "[0 1 2]" "(conj (list 1 2) 0)"] - ["conj multiple on vec" "[1 2 3 4]" "(conj [1 2] 3 4)"] - ["conj multiple on list" "[4 3 1 2]" "(conj (list 1 2) 3 4)"] - ["seq of empty is nil" "nil" "(seq [])"] - ["seq of nil is nil" "nil" "(seq nil)"] - ["seq of string" "[\\a \\b]" "(seq \"ab\")"] - ["empty?" "true" "(empty? [])"] - ["not empty?" "false" "(empty? [1])"] - ["count" "3" "(count [1 2 3])"] - ["count of nil" "0" "(count nil)"] - ["count of string" "3" "(count \"abc\")"]) - -(defspec "seq / map filter reduce" - ["map" "[2 3 4]" "(map inc [1 2 3])"] - ["map two colls" "[5 7 9]" "(map + [1 2 3] [4 5 6])"] - ["map stops at shortest" "[5 7]" "(map + [1 2] [4 5 6])"] - # nil elements are values, not end-of-seq: multi-coll map must not truncate. - ["map keeps nil elements" "[[1 :a] [nil :b] [3 nil]]" "(map vector [1 nil 3] [:a :b nil])"] - ["map 3 colls" "[12 15 18]" "(map + [1 2 3] [4 5 6] [7 8 9])"] - ["map 3 colls shortest" "[12 15]" "(map + [1 2] [4 5 6] [7 8 9])"] - ["map 4 colls" "[16 20]" "(map + [1 2] [3 4] [5 6] [7 8])"] - ["map 3 colls nils" "[[1 :a 10] [nil :b 20] [3 nil 30]]" "(map vector [1 nil 3] [:a :b nil] [10 20 30])"] - ["map empty coll" "()" "(map + [] [1 2 3] [4 5 6])"] - ["map lazy+concrete" "[11 22 33]" "(map + (map identity [1 2 3]) [10 20 30])"] - ["map-indexed" "[[0 :a] [1 :b]]" "(map-indexed vector [:a :b])"] - ["mapv" "[2 3 4]" "(mapv inc [1 2 3])"] - ["filter" "[2 4]" "(filter even? [1 2 3 4])"] - ["filterv" "[2 4]" "(filterv even? [1 2 3 4])"] - ["remove" "[1 3]" "(remove even? [1 2 3 4])"] - ["reduce" "10" "(reduce + [1 2 3 4])"] - ["reduce with init" "20" "(reduce + 10 [1 2 3 4])"] - ["reduce empty with init" "0" "(reduce + 0 [])"] - ["reduce single no init" "5" "(reduce + [5])"] - ["reduced short-circuits" "3" "(reduce (fn [a x] (if (> a 2) (reduced a) (+ a x))) 0 [1 2 3 4 5])"] - ["reduce-kv" "6" "(reduce-kv (fn [a k v] (+ a v)) 0 {:a 1 :b 2 :c 3})"] - ["reduce-kv on vector" "[[0 :a] [1 :b]]" "(reduce-kv (fn [a i v] (conj a [i v])) [] [:a :b])"] - ["reduce-kv honors reduced" "[:a]" "(reduce-kv (fn [a i v] (if (= i 1) (reduced a) (conj a v))) [] [:a :b :c])"] - ["reduce-kv on nil" "0" "(reduce-kv (fn [a k v] (+ a v)) 0 nil)"] - ["reductions" "[1 3 6]" "(reductions + [1 2 3])"] - ["mapcat" "[1 1 2 2]" "(mapcat (fn [x] [x x]) [1 2])"] - ["mapcat two colls" "[1 3 2 4]" "(mapcat vector [1 2] [3 4])"] - ["mapcat three colls" "[1 2 3]" "(mapcat vector [1] [2] [3])"] - ["mapcat empty coll" "()" "(mapcat vector [] [1 2] [3 4])"] - ["mapcat seqs" "[1 2 3 4]" "(mapcat identity [[1 2] [3 4]])"] - ["keep" "[1 3]" "(keep (fn [x] (if (odd? x) x nil)) [1 2 3 4])"] - ["some truthy" "true" "(some even? [1 2 3])"] - ["some nil" "nil" "(some even? [1 3 5])"] - ["every? true" "true" "(every? pos? [1 2 3])"] - ["every? false" "false" "(every? pos? [1 -2 3])"]) - -(defspec "seq / take drop slice" - ["take" "[1 2 3]" "(take 3 [1 2 3 4 5])"] - ["take more than size" "[1 2]" "(take 5 [1 2])"] - ["drop" "[4 5]" "(drop 3 [1 2 3 4 5])"] - ["take-while" "[1 2]" "(take-while (fn [x] (< x 3)) [1 2 3 1])"] - ["drop-while" "[3 1]" "(drop-while (fn [x] (< x 3)) [1 2 3 1])"] - ["take-last" "[4 5]" "(take-last 2 [1 2 3 4 5])"] - ["drop-last" "[1 2 3]" "(drop-last [1 2 3 4])"] - ["take-nth" "[1 3 5]" "(take-nth 2 [1 2 3 4 5])"] - ["partition" "[[1 2] [3 4]]" "(partition 2 [1 2 3 4 5])"] - ["partition-all" "[[1 2] [3]]" "(partition-all 2 [1 2 3])"] - ["split-at" "[[1 2] [3 4]]" "(split-at 2 [1 2 3 4])"]) - -(defspec "seq / transform" - ["reverse" "[3 2 1]" "(reverse [1 2 3])"] - ["sort" "[1 2 3]" "(sort [3 1 2])"] - ["sort with comparator" "[3 2 1]" "(sort > [1 3 2])"] - ["sort-by" "[[1] [2 2]]" "(sort-by count [[2 2] [1]])"] - ["distinct" "[1 2 3]" "(distinct [1 1 2 3 3])"] - ["dedupe" "[1 2 1]" "(dedupe [1 1 2 1])"] - ["interpose" "[1 0 2 0 3]" "(interpose 0 [1 2 3])"] - ["interleave" "[1 :a 2 :b]" "(interleave [1 2] [:a :b])"] - ["flatten" "[1 2 3 4]" "(flatten [1 [2 [3 [4]]]])"] - ["concat" "[1 2 3 4]" "(concat [1 2] [3 4])"] - ["into vector" "[1 2 3 4]" "(into [1 2] [3 4])"] - ["into list" "[3 2 1]" "(into (list) [1 2 3])"] - ["frequencies" "{1 2, 2 1}" "(frequencies [1 1 2])"] - ["group-by" "{false [1 3], true [2 4]}" "(group-by even? [1 2 3 4])"] - ["zipmap" "{:a 1, :b 2}" "(zipmap [:a :b] [1 2])"] - ["mapcat seqs" "[1 2 3 4]" "(mapcat identity [[1 2] [3 4]])"]) - -(defspec "seq / generators" - ["range n" "[0 1 2 3]" "(range 4)"] - ["range from to" "[2 3 4]" "(range 2 5)"] - ["range with step" "[0 2 4]" "(range 0 6 2)"] - ["take repeat" "[:x :x :x]" "(take 3 (repeat :x))"] - ["repeat n" "[5 5]" "(repeat 2 5)"] - ["take iterate" "[1 2 4 8]" "(take 4 (iterate (fn [x] (* x 2)) 1))"] - ["take cycle" "[1 2 1 2 1]" "(take 5 (cycle [1 2]))"] - ["take repeatedly" "3" "(count (take 3 (repeatedly (fn [] 1))))"] - ["take-last of range" "[8 9]" "(take-last 2 (range 10))"]) - -# Clojure IFn values used as the function arg to higher-order fns: a keyword or -# symbol looks up a key, a set tests membership, a map looks up a key. -(defspec "seq / IFn values as functions" - ["map keyword" "[1 2 3]" "(map :a [{:a 1} {:a 2} {:a 3}])"] - ["filter keyword" "[{:ok true}]" "(filter :ok [{:ok true} {:ok false}])"] - ["remove keyword" "[{:ok false}]" "(remove :ok [{:ok true} {:ok false}])"] - ["sort-by keyword" "[{:a 1} {:a 2} {:a 3}]" "(sort-by :a [{:a 3} {:a 1} {:a 2}])"] - ["sort-by key + cmp" "[{:a 3} {:a 2} {:a 1}]" "(sort-by :a > [{:a 3} {:a 1} {:a 2}])"] - ["filter set" "[2 4]" "(filter #{2 4} [1 2 3 4 5])"] - ["remove set" "[1 3 5]" "(remove #{2 4} [1 2 3 4 5])"] - ["group-by keyword" "{1 [{:n 1}], 2 [{:n 2}]}" "(group-by :n [{:n 1} {:n 2}])"] - ["map a map" "[1 nil 2]" "(map {:a 1 :b 2} [:a :z :b])"] - ["take-nth transducer" "[0 2 4 6 8]" "(into [] (take-nth 2) (range 10))"] - ["interpose transducer" "[1 :x 2]" "(into [] (interpose :x) [1 2])"]) - -# conj edge cases: 0-arg, conj onto nil (builds a list), conj a map into a map. -(defspec "seq / conj edge cases" - ["conj no args" "[]" "(conj)"] - ["conj nil one" "[3]" "(conj nil 3)"] - ["conj nil many" "[2 1]" "(conj nil 1 2)"] - ["conj vector" "[1 2 3]" "(conj [1 2] 3)"] - ["conj list prepend" "[0 1 2]" "(conj '(1 2) 0)"] - ["conj map + map" "{:a 0, :b 1}" "(conj {:a 0} {:b 1})"] - ["conj map + pair" "{:a 0, :b 1}" "(conj {:a 0} [:b 1])"] - ["conj map merge wins" "{:a 2}" "(conj {:a 0} {:a 1} {:a 2})"]) - -# Strictness: these reject malformed arguments like Clojure. -(defspec "seq / strictness (throws like Clojure)" - ["cons non-seqable num" :throws "(cons 1 42)"] - ["cons non-seqable kw" :throws "(cons 1 :k)"] - ["cons onto nil ok" "[1]" "(cons 1 nil)"] - ["cons onto seq ok" "[0 1 2]" "(cons 0 [1 2])"] - ["num non-number" :throws "(num \"x\")"] - ["num ok" "5" "(num 5)"] - ["realized? on number" :throws "(realized? 1)"] - ["realized? on nil" :throws "(realized? nil)"] - ["symbol from nil" :throws "(symbol nil)"] - ["symbol bad 2-arg" :throws "(symbol :a \"b\")"] - ["symbol from keyword" "\"x\"" "(name (symbol :x))"] - ["keyword bad 2-arg" :throws "(keyword \"abc\" nil)"] - ["keyword from symbol" "\"x\"" "(name (keyword 'x))"]) - -# Stack/accessor strictness: peek/pop are stack-only; vec needs a seqable; -# key/val need a map entry. -(defspec "seq / accessor strictness" - ["peek vector" "3" "(peek [1 2 3])"] - ["peek list" "1" "(peek '(1 2 3))"] - ["peek empty vec" "nil" "(peek [])"] - ["peek on set" :throws "(peek #{1 2})"] - ["peek on number" :throws "(peek 42)"] - ["pop empty vec" :throws "(pop [])"] - ["pop on number" :throws "(pop 0)"] - ["pop vector" "[1 2]" "(pop [1 2 3])"] - ["vec on number" :throws "(vec 42)"] - ["vec on keyword" :throws "(vec :a)"] - ["vec ok" "[1 2]" "(vec '(1 2))"] - ["key on nil" :throws "(key nil)"] - ["key on map" :throws "(key {})"] - ["val on number" :throws "(val 0)"] - ["key of entry" ":a" "(key (first {:a 1}))"] - ["val of entry" "1" "(val (first {:a 1}))"]) - -# More strictness: first/rseq on the right shapes, assoc even-arg requirement. -(defspec "seq / more strictness" - ["first on number" :throws "(first 42)"] - ["first on keyword" :throws "(first :a)"] - ["first ok vec" "1" "(first [1 2])"] - ["first ok nil" "nil" "(first nil)"] - ["rseq vector" "[3 2 1]" "(rseq [1 2 3])"] - ["rseq on string" :throws "(rseq \"ab\")"] - ["rseq on map" :throws "(rseq {:a 1})"] - ["rseq on number" :throws "(rseq 0)"] - ["assoc odd args" :throws "(assoc {:a 1} :b)"] - ["assoc on number" :throws "(assoc 5 :a 1)"] - ["assoc on set" :throws "(assoc #{} :a 1)"]) - -# Strictness on more core fns: seq/shuffle need seqables, NaN? needs a number, -# nthrest/nthnext need a numeric count (and clamp negatives / accept nil coll). -(defspec "seq / strictness round 3" - ["seq on number" :throws "(seq 1)"] - ["seq on fn" :throws "(seq (fn [] 1))"] - ["seq vector ok" "[1 2]" "(seq [1 2])"] - ["NaN? on nil" :throws "(NaN? nil)"] - ["NaN? on number ok" "false" "(NaN? 1.0)"] - ["shuffle on number" :throws "(shuffle 1)"] - ["shuffle on string" :throws "(shuffle \"abc\")"] - ["shuffle vec ok" "3" "(count (shuffle [1 2 3]))"] - ["nthrest nil count" :throws "(nthrest [0 1 2] nil)"] - ["nthrest negative" "[0 1 2]" "(nthrest [0 1 2] -1)"] - ["nthrest nil coll" "nil" "(nthrest nil 0)"] - ["nthnext nil count" :throws "(nthnext [0 1 2] nil)"] - ["update vec oob" :throws "(update [] 1 identity)"] - ["update vec kw key" :throws "(update [1 2 3] :k identity)"]) - -# Regression cases for clojure.core fns moved from Janet to the Clojure overlay -# (jolt-1j0), plus two bugs fixed in the process: nthrest returns () (not nil) -# for an exhausted n>0 walk, and distinct? compares by VALUE (equal collections -# are not distinct). -(defspec "seq / overlay-migrated fns" - ["nthrest exhausted -> ()" "()" "(nthrest nil 100)"] - ["nthrest vec exhausted" "()" "(nthrest [1 2 3] 100)"] - ["nthrest n<=0 keeps coll" "[1 2 3]" "(nthrest [1 2 3] 0)"] - ["nthrest drops n" "[3 4 5]" "(nthrest [1 2 3 4 5] 2)"] - ["nthnext exhausted -> nil" "nil" "(nthnext [1 2] 5)"] - ["nthnext surprising nil" "nil" "(nthnext nil nil)"] - ["nthnext drops n" "[3 4]" "(nthnext [1 2 3 4] 2)"] - ["distinct? distinct" "true" "(distinct? 1 2 3)"] - ["distinct? dup" "false" "(distinct? 1 2 1)"] - ["distinct? equal colls" "false" "(distinct? [1 2] [1 2])"] - ["distinct? single" "true" "(distinct? 5)"] - ["replace maps elements" "[:a 2 :c 2]" "(replace {1 :a 3 :c} [1 2 3 2])"] - ["replace preserves nil val" "[1 nil 3]" "(replace {2 nil} [1 2 3])"] - ["take-last" "[3 4]" "(take-last 2 [1 2 3 4])"] - ["take-last empty -> nil" "nil" "(take-last 2 [])"] - ["take-last n>len" "[1 2]" "(take-last 9 [1 2])"] - ["drop-last default 1" "[1 2]" "(drop-last [1 2 3])"] - ["drop-last n" "[1 2]" "(drop-last 2 [1 2 3 4])"] - ["split-with" "[[2 4] [5 6]]" "(split-with even? [2 4 5 6])"] - ["replicate" "[:x :x :x]" "(replicate 3 :x)"] - ["bounded-count" "3" "(bounded-count 3 [1 2 3 4 5])"] - ["run! side effects" "6" "(let [a (atom 0)] (run! (fn [x] (swap! a + x)) [1 2 3]) @a)"] - ["completing wraps rf" "3" "((completing +) 1 2)"] - ["comparator <" "[1 2 3]" "(sort (comparator <) [3 1 2])"] - ["comparator >" "[3 2 1]" "(sort (comparator >) [3 1 2])"] - ["reductions" "[1 3 6 10]" "(reductions + [1 2 3 4])"] - ["reductions with init" "[10 11 13 16]" "(reductions + 10 [1 2 3])"] - ["reductions empty calls f" "[0]" "(reductions + [])"] - ["reductions empty + init" "[5]" "(reductions + 5 [])"] - ["tree-seq pre-order" "[[1 [2] 3] 1 [2] 2 3]" "(tree-seq sequential? seq [1 [2] 3])"] - ["some found" "true" "(some even? [1 3 4])"] - ["some none -> nil" "nil" "(some even? [1 3 5])"] - ["some keyword pred" "7" "(some :a [{:b 1} {:a 7}])"] - ["some returns value" "4" "(some (fn [x] (when (even? x) x)) [1 3 4 5])"] - ["flatten nested" "[1 2 3 4 5]" "(flatten [1 [2 [3 4]] 5])"] - ["flatten lists too" "[1 2 3]" "(flatten [1 (list 2 3)])"] - ["flatten scalar -> empty" "[]" "(flatten 5)"] - ["interleave" "[1 :a 2 :b]" "(interleave [1 2 3] [:a :b])"] - ["interleave empty" "[]" "(interleave)"] - ["rationalize identity" "5" "(rationalize 5)"] - ["dedupe consecutive" "[1 2 3 1]" "(dedupe [1 1 2 2 3 1 1])"] - ["dedupe empty" "[]" "(dedupe [])"] - ["dedupe no dups" "[1 2 3]" "(dedupe [1 2 3])"]) - -# Clojure 1.11 vector-returning partition/split variants. -(defspec "seq / partitionv & splitv-at (1.11)" - ["partitionv" "[[1 2] [3 4]]" "(partitionv 2 [1 2 3 4 5])"] - ["partitionv elems are vectors" "true" "(every? vector? (partitionv 2 [1 2 3 4]))"] - ["partitionv step" "[[1 2] [3 4]]" "(partitionv 2 2 [1 2 3 4 5])"] - ["partitionv pad" "[[1 2] [3 :p]]" "(partitionv 2 2 [:p] [1 2 3])"] - ["partitionv-all" "[[1 2] [3]]" "(partitionv-all 2 [1 2 3])"] - ["partitionv-all vectors" "true" "(every? vector? (partitionv-all 2 [1 2 3]))"] - ["splitv-at" "[[1 2] [3 4]]" "(splitv-at 2 [1 2 3 4])"] - ["splitv-at first is vector" "true" "(vector? (first (splitv-at 2 [1 2 3])))"] - ["splitv-at past end" "[[1 2] []]" "(splitv-at 5 [1 2])"]) - -# Linear seq walks (flatiron review find): cell chains over concrete -# collections walk by INDEX. Slicing the remainder per step made every full -# walk O(n^2) — mapv over 40k elements took ten seconds, a 20k first/rest -# loop took two. rest/next of an indexed collection is an O(1) lazy view — -# and therefore a SEQ, as in Clojure (it was a vector-typed slice). -(defspec "sequences / linear walks over concrete collections" - ["rest of vector is a seq" "true" "(seq? (rest [1 2 3]))"] - ["rest of vector not vector" "false" "(vector? (rest [1 2 3]))"] - ["rest values" "(quote (2 3))" "(rest [1 2 3])"] - ["next of vector" "(quote (2 3))" "(next [1 2 3])"] - ["next exhausts to nil" "nil" "(next [1])"] - ["rest exhausts to ()" "()" "(rest [1])"] - ["rest-loop scales (20k linear)" "20000" - "(loop [xs (seq (vec (range 20000))) n 0] (if xs (recur (next xs) (inc n)) n))"] - ["mapv scales (50k linear)" "50000" "(count (mapv inc (vec (range 50000))))"] - ["nested walk" "[2 3]" "(vec (rest (mapv inc [0 1 2])))"]) - -# rest/next over sets, maps, and sorted colls used to fall into the indexed -# fall-through and walk the wrapper table's internal fields ((next #{1 2}) -# was (nil nil)) — exposed when the canonical every? started seq-walking. -(defspec "sequences / rest & next over set-like colls" - ["next of set" "true" "(let [n (next #{1 2})] (and (= 1 (count n)) (contains? #{1 2} (first n))))"] - ["rest of set count" "1" "(count (rest #{1 2}))"] - ["next of singleton set" "nil" "(next #{1})"] - ["rest of empty set" "0" "(count (rest #{}))"] - ["next of map" "true" "(let [n (next {:a 1 :b 2})] (and (= 1 (count n)) (map-entry? (first n))))"] - ["next of singleton map" "nil" "(next {:a 1})"] - ["rest of sorted-set" "(quote (2 3))" "(rest (sorted-set 3 1 2))"] - ["next of sorted-map" "(quote ([2 :b]))" "(next (sorted-map 1 :a 2 :b))"] - ["every? over set" "true" "(every? pos? #{1 2 3})"] - ["every? over set false" "false" "(every? odd? #{1 2})"] - ["every? over sorted-set" "true" "(every? pos? (sorted-set 1 2 3))"] - ["every? over map entries" "true" "(every? map-entry? (seq {:a 1 :b 2}))"]) diff --git a/test/spec/sets-spec.janet b/test/spec/sets-spec.janet deleted file mode 100644 index e041010..0000000 --- a/test/spec/sets-spec.janet +++ /dev/null @@ -1,94 +0,0 @@ -# Specification: sets, including clojure.set. -(use ../support/harness) - -(defspec "set / construct & predicate" - ["literal" "#{1 2 3}" "#{1 2 3}"] - ["hash-set" "#{1 2 3}" "(hash-set 1 2 3)"] - ["set from vector" "#{1 2 3}" "(set [1 2 3 1])"] - ["empty" "#{}" "#{}"] - ["set? true" "true" "(set? #{1})"] - ["set? false on vector" "false" "(set? [1])"] - ["count dedups" "3" "(count (set [1 1 2 3]))"] - ["equality order-indep" "true" "(= #{1 2 3} #{3 2 1})"] - # jolt-h86: into-conj had no set branch and returned the set unchanged - ["into set" "#{:a :b}" "(into #{} [:a :b])"] - ["into non-empty set" "#{1 2 3}" "(into #{1} [2 3 2])"]) - -(defspec "set / operations" - ["conj adds" "#{1 2 3}" "(conj #{1 2} 3)"] - ["conj dup no-op" "#{1 2}" "(conj #{1 2} 1)"] - ["disj removes" "#{1 2}" "(disj #{1 2 3} 3)"] - ["disj missing no-op" "#{1 2}" "(disj #{1 2} 9)"] - ["contains?" "true" "(contains? #{1 2} 1)"] - ["contains? missing" "false" "(contains? #{1 2} 9)"] - ["get present" "1" "(get #{1 2} 1)"] - ["get missing nil" "nil" "(get #{1 2} 9)"] - ["set as fn present" "2" "(#{1 2 3} 2)"] - ["set as fn missing" "nil" "(#{1 2 3} 9)"]) - -(defspec "set / literals & value elements" - ["literal evaluates elements" "#{2 4}" "#{(inc 1) (* 2 2)}"] - ["map elements by value" "true" "(= #{{:a 1}} #{(hash-map :a 1)})"] - ["contains? map by value" "true" "(contains? #{(hash-map :x 1)} {:x 1})"] - ["dedup equal maps" "1" "(count (set [{:a 1} (hash-map :a 1)]))"] - ["vector elements" "true" "(contains? #{[1 2]} (vec [1 2]))"]) - -(defspec "set / nil element (jolt-bn2p)" - # canon-key returns nil for nil and Janet tables drop a nil key, so a nil - # member used to be silently lost while count/contains? disagreed. - ["set keeps nil" "2" "(count (set [nil 1 nil]))"] - ["contains? nil true" "true" "(contains? (set [nil 1]) nil)"] - ["contains? nil false" "false" "(contains? #{1} nil)"] - ["seq includes nil" "true" "(some nil? (seq (set [nil 1])))"] - ["disj nil" "#{1}" "(disj (set [nil 1]) nil)"] - ["disj nil count" "1" "(count (disj (set [nil 1]) nil))"] - ["conj nil count" "2" "(count (conj #{1} nil))"] - ["conj nil contains?" "true" "(contains? (conj #{1} nil) nil)"] - ["into #{} keeps nil" "2" "(count (into #{} [nil 1]))"] - ["into #{} contains? nil" "true" "(contains? (into #{} [nil 1]) nil)"] - ["into keeps existing nil" "true" "(contains? (into #{nil} [1]) nil)"] - # transient set path: tr-conj!/persistent!/disj!/contains? - ["transient conj! nil" "2" "(count (persistent! (conj! (transient #{}) nil 1)))"] - ["transient contains? nil" "true" "(contains? (persistent! (conj! (transient #{}) nil 1)) nil)"] - ["transient disj! nil cnt" "1" "(count (persistent! (disj! (conj! (transient #{}) nil 1) nil)))"] - ["transient disj! removes" "false" "(contains? (persistent! (disj! (conj! (transient #{}) nil 1) nil)) nil)"] - ["transient of set w/ nil" "true" "(contains? (persistent! (transient (set [nil 1]))) nil)"]) - -(defspec "clojure.set" - ["union" "#{1 2 3 4}" "(do (require (quote [clojure.set :as s])) (s/union #{1 2} #{3 4}))"] - ["intersection" "#{2}" "(do (require (quote [clojure.set :as s])) (s/intersection #{1 2} #{2 3}))"] - ["difference" "#{1}" "(do (require (quote [clojure.set :as s])) (s/difference #{1 2} #{2 3}))"] - ["subset? true" "true" "(do (require (quote [clojure.set :as s])) (s/subset? #{1} #{1 2}))"] - ["superset? true" "true" "(do (require (quote [clojure.set :as s])) (s/superset? #{1 2} #{1}))"] - ["select" "#{2 4}" "(do (require (quote [clojure.set :as s])) (s/select even? #{1 2 3 4}))"] - ["join" "#{{:a 1, :b 2, :c 3}}" "(do (require (quote [clojure.set :as s])) (s/join #{{:a 1 :b 2}} #{{:b 2 :c 3}}))"] - ["map-invert" "{1 :a}" "(do (require (quote [clojure.set :as s])) (s/map-invert {:a 1}))"] - ["rename-keys" "{:b 1}" "(do (require (quote [clojure.set :as s])) (s/rename-keys {:a 1} {:a :b}))"]) - -# set? recognizes every set representation (jolt-dpn: sorted sets are tagged -# tables the host set? predicate missed). -(defspec "set / set? across representations" - ["literal" "true" "(set? #{1})"] - ["empty literal" "true" "(set? #{})"] - ["sorted-set" "true" "(set? (sorted-set 1 2))"] - ["sorted-set-by" "true" "(set? (sorted-set-by > 1 2))"] - ["empty sorted" "true" "(set? (sorted-set))"] - ["map is not" "false" "(set? {})"] - ["vector is not" "false" "(set? [1])"] - ["coll? still true" "true" "(coll? (sorted-set 1))"] - ["ifn? sorted-set" "true" "(ifn? (sorted-set 1))"]) - -# set / into #{} bulk-build the backing HAMT in one pass (phs-from-seq), instead -# of a phs-conj per element (jolt-5vsp collections). Cross the promotion -# boundary, check dedup, collection members, and conj after a bulk build. -(defspec "set / bulk build boundaries" - ["set dedup count" "3" "(count (set [1 1 2 3 3 2]))"] - ["set big count" "1000" "(count (set (range 1000)))"] - ["into #{} count" "500" "(count (into #{} (range 500)))"] - ["into #{} onto base" "3" "(count (into #{:a} [:a :b :c]))"] - ["set contains" "true" "(contains? (set (range 1000)) 777)"] - ["set missing" "false" "(contains? (set (range 1000)) 5000)"] - ["set coll members" "true" "(contains? (set [[1 2] [3 4]]) [1 2])"] - ["conj after bulk" "true" "(contains? (conj (set (range 100)) :x) :x)"] - ["disj after bulk" "false" "(contains? (disj (set (range 100)) 50) 50)"] - ["set = literal" "true" "(= #{0 1 2} (set (range 3)))"]) diff --git a/test/spec/sorted-spec.janet b/test/spec/sorted-spec.janet deleted file mode 100644 index d7fdc6d..0000000 --- a/test/spec/sorted-spec.janet +++ /dev/null @@ -1,120 +0,0 @@ -# Specification: sorted collections (sorted-map / sorted-set, subseq/rsubseq). -# -# Sorted collections are pure Clojure (stage 3, jolt-0lj): the entries live in -# a comparator-ordered vector, all ops are overlay Clojure attached to the -# value, and the Janet seed only dispatches to them. Semantics match Clojure: -# lookup/membership go through the COMPARATOR ((contains? (sorted-set 1) 1.0) -# is true), equality is representation-agnostic ((= (sorted-map :a 1) {:a 1})), -# empty?/empty see the collection (not the host wrapper) and (empty sc) keeps -# the comparator. (vec coerces a seq to a vector so expecteds are vector -# literals, not quoted lists.) -(use ../support/harness) - -(defspec "sorted / construction & ordering" - ["sorted-set orders" "[1 2 3]" "(vec (seq (sorted-set 3 1 2)))"] - ["sorted-set dedupes" "[1 2 3]" "(vec (seq (sorted-set 3 1 2 1 3)))"] - ["sorted-set numeric" "[1 2 10]" "(vec (seq (sorted-set 10 1 2)))"] - ["sorted-map ordered entries" "[[:a 1] [:b 2] [:c 3]]" "(vec (seq (sorted-map :c 3 :a 1 :b 2)))"] - ["first is min" "1" "(first (sorted-set 5 3 9 1))"]) - -(defspec "sorted / sorted?" - ["sorted-set" "true" "(sorted? (sorted-set 1))"] - ["sorted-map" "true" "(sorted? (sorted-map :a 1))"] - ["plain set" "false" "(sorted? #{1})"] - ["plain map" "false" "(sorted? {:a 1})"] - ["vector" "false" "(sorted? [1 2])"]) - -(defspec "sorted / map ops" - ["get hit" "2" "(get (sorted-map :a 1 :b 2) :b)"] - ["get miss default" ":none" "(get (sorted-map :a 1) :z :none)"] - ["contains? yes" "true" "(contains? (sorted-map :a 1) :a)"] - ["contains? no" "false" "(contains? (sorted-map :a 1) :z)"] - ["assoc keeps order" "[[:a 1] [:b 2] [:c 3]]" "(vec (seq (assoc (sorted-map :c 3 :a 1) :b 2)))"] - ["dissoc" "[[:a 1] [:c 3]]" "(vec (seq (dissoc (sorted-map :a 1 :b 2 :c 3) :b)))"] - ["conj entry" "[[:a 1] [:z 9]]" "(vec (seq (conj (sorted-map :a 1) [:z 9])))"] - ["keys sorted" "[:a :b :c]" "(vec (keys (sorted-map :c 3 :a 1 :b 2)))"] - ["vals by key" "[1 2 3]" "(vec (vals (sorted-map :c 3 :a 1 :b 2)))"] - ["map as fn" "2" "((sorted-map :a 1 :b 2) :b)"] - ["map as fn miss" ":d" "((sorted-map :a 1) :z :d)"]) - -(defspec "sorted / set ops" - ["get present" "2" "(get (sorted-set 1 2 3) 2)"] - ["get absent" ":none" "(get (sorted-set 1 2 3) 9 :none)"] - ["contains? yes" "true" "(contains? (sorted-set 1 2 3) 2)"] - ["contains? no" "false" "(contains? (sorted-set 1 2 3) 9)"] - ["conj keeps order" "[0 1 2 3 5]" "(vec (seq (conj (sorted-set 1 2 3) 5 0)))"] - ["disj" "[1 3]" "(vec (seq (disj (sorted-set 1 2 3) 2)))"] - ["set as fn" "3" "((sorted-set 1 2 3) 3)"] - ["set as fn miss" "nil" "((sorted-set 1 2 3) 9)"]) - -(defspec "sorted / by comparator" - ["sorted-set-by desc" "[10 3 2 1]" "(vec (seq (sorted-set-by > 1 3 2 10)))"] - ["sorted-map-by desc" "[[3 :c] [2 :b] [1 :a]]" "(vec (seq (sorted-map-by > 1 :a 3 :c 2 :b)))"] - ["conj keeps comparator" "[5 3 2 1 0]" "(vec (seq (conj (sorted-set-by > 1 3 2) 5 0)))"] - ["assoc keeps comparator" "[3 2 1]" "(vec (keys (assoc (sorted-map-by > 1 :a 3 :c) 2 :b)))"] - ["disj keeps comparator" "[3 1]" "(vec (seq (disj (sorted-set-by > 1 2 3) 2)))"] - ["by-comparator is sorted?" "true" "(sorted? (sorted-set-by > 1 2))"]) - -(defspec "sorted / subseq & rsubseq" - ["subseq >=" "[3 4 5]" "(vec (subseq (sorted-set 1 2 3 4 5) >= 3))"] - ["subseq <" "[1 2]" "(vec (subseq (sorted-set 1 2 3 4 5) < 3))"] - ["subseq range" "[2 3 4]" "(vec (subseq (sorted-set 1 2 3 4 5) > 1 < 5))"] - ["rsubseq <=" "[3 2 1]" "(vec (rsubseq (sorted-set 1 2 3 4 5) <= 3))"] - ["subseq on map" "[[2 :b] [3 :c]]" "(vec (subseq (sorted-map 1 :a 2 :b 3 :c) > 1))"] - ["subseq empty result" "nil" "(subseq (sorted-set 1 2) > 5)"] - ["rsubseq on map" "[[2 :b] [1 :a]]" "(vec (rsubseq (sorted-map 1 :a 2 :b 3 :c) < 3))"]) - -(defspec "sorted / predicates" - ["sorted-map? true" "true" "(sorted-map? (sorted-map 1 :a))"] - ["sorted-map? false" "false" "(sorted-map? {:a 1})"] - ["sorted-set? true" "true" "(sorted-set? (sorted-set 1))"] - ["sorted-set? false" "false" "(sorted-set? #{1})"] - ["map? sorted-map" "true" "(map? (sorted-map 1 :a))"] - ["coll? sorted-set" "true" "(coll? (sorted-set 1))"]) - -(defspec "sorted / lookup + membership use the comparator" - ["get cross-numeric" ":a" "(get (sorted-map 1 :a) 1.0)"] - ["contains? cross-numeric" "true" "(contains? (sorted-set 1) 1.0)"] - ["conj equal elem no-op" "1" "(count (conj (sorted-set 1) 1.0))"] - ["assoc equal key replaces" "[[1 :z]]" "(vec (seq (assoc (sorted-map 1 :a) 1.0 :z)))"] - ["first sorted-map" "[1 :a]" "(first (sorted-map 2 :b 1 :a))"] - ["dissoc missing no-op" "2" "(count (dissoc (sorted-map 1 :a 2 :b) 9))"] - ["conj map merges" "3" "(count (conj (sorted-map 1 :a) {2 :b 3 :c}))"] - ["conj nil no-op" "1" "(count (conj (sorted-map 1 :a) nil))"] - ["into sorted-map" "[[1 :a] [2 :b]]" "(vec (seq (into (sorted-map) [[2 :b] [1 :a]])))"] - ["source unchanged" "[1 2]" "(let [s (sorted-set 1 2)] (conj s 9) (vec (seq s)))"] - ["sorted-map odd kvs throws" :throws "(sorted-map 1 :a 2)"]) - -(defspec "sorted / equality is representation-agnostic" - ["sorted-map = literal" "true" "(= (sorted-map :a 1 :b 2) {:a 1 :b 2})"] - ["literal = sorted-map" "true" "(= {:a 1 :b 2} (sorted-map :a 1 :b 2))"] - ["sorted-map = hash-map" "true" "(= (sorted-map :a 1) (hash-map :a 1))"] - ["sorted-map != more keys" "false" "(= (sorted-map :a 1) {:a 1 :b 2})"] - ["sorted-set = literal" "true" "(= (sorted-set 1 2) #{1 2})"] - ["literal = sorted-set" "true" "(= #{1 2} (sorted-set 2 1))"] - ["sorted-set != diff" "false" "(= (sorted-set 1 2) #{1 3})"] - ["two sorted-maps" "true" "(= (sorted-map 1 :a 2 :b) (sorted-map 2 :b 1 :a))"] - ["cmp irrelevant to =" "true" "(= (sorted-map-by > 1 :a 2 :b) (sorted-map 1 :a 2 :b))"] - ["sorted-map as map key" ":hit" "(get {(sorted-map :a 1) :hit} {:a 1})"] - ["sorted-set as map key" ":hit" "(get {(sorted-set 1 2) :hit} #{2 1})"]) - -(defspec "sorted / empty + empty? + rseq + printing" - ["empty? empty map" "true" "(empty? (sorted-map))"] - ["empty? non-empty" "false" "(empty? (sorted-map 1 :a))"] - ["empty? empty set" "true" "(empty? (sorted-set))"] - ["empty keeps sortedness" "true" "(sorted? (empty (sorted-map 1 :a)))"] - ["empty keeps cmp" "[3 1]" "(vec (seq (into (empty (sorted-set-by > 1 2)) [1 3])))"] - ["empty set kind" "true" "(sorted-set? (empty (sorted-set 1)))"] - ["rseq map" "[[2 :b] [1 :a]]" "(vec (rseq (sorted-map 1 :a 2 :b)))"] - ["rseq set" "[3 2 1]" "(vec (rseq (sorted-set 1 2 3)))"] - ["pr-str sorted-map" "\"{1 :a, 2 :b}\"" "(pr-str (sorted-map 2 :b 1 :a))"] - ["pr-str sorted-set" "\"#{1 2 3}\"" "(pr-str (sorted-set 3 1 2))"]) - -(defspec "sorted / seq fn interop" - ["map over sorted-map" "[1 2 3]" "(vec (map first (sorted-map 2 :b 1 :a 3 :c)))"] - ["map over sorted-set" "[2 3 4]" "(vec (map inc (sorted-set 3 1 2)))"] - ["filter entries" "[[2 :b]]" "(vec (filter (fn [[k v]] (even? k)) (sorted-map 1 :a 2 :b)))"] - ["reduce over set" "6" "(reduce + (sorted-set 1 2 3))"] - ["vec of sorted-set" "[1 2 3]" "(vec (sorted-set 3 1 2))"] - ["into vec" "[[1 :a] [2 :b]]" "(into [] (sorted-map 2 :b 1 :a))"] - ["sorted-map-by 3way cmp" "[3 2 1]" "(vec (keys (sorted-map-by (fn [a b] (- b a)) 1 :a 2 :b 3 :c)))"]) diff --git a/test/spec/stage3-io-ns-spec.janet b/test/spec/stage3-io-ns-spec.janet deleted file mode 100644 index 386ce64..0000000 --- a/test/spec/stage3-io-ns-spec.janet +++ /dev/null @@ -1,52 +0,0 @@ -# Specification: Stage 3 turn 2b — host-classified IO fns, ns introspection, -# the thread-binding family, and load-string/eval as values. These were -# previously either missing or silently leaked from Janet's root environment. -(use ../support/harness) - -(defspec "io / slurp, spit, printf, flush (host-classified)" - ["slurp returns string" "true" "(string? (slurp \"project.janet\"))"] - ["slurp content" "true" "(do (require (quote [clojure.string :as s])) (s/includes? (slurp \"project.janet\") \"jolt\"))"] - ["spit + slurp round" "\"hello\"" "(do (spit \"/tmp/jolt-spit-test.txt\" \"hello\") (slurp \"/tmp/jolt-spit-test.txt\"))"] - ["spit append" "\"ab\"" "(do (spit \"/tmp/jolt-spit-test.txt\" \"a\") (spit \"/tmp/jolt-spit-test.txt\" \"b\" :append true) (slurp \"/tmp/jolt-spit-test.txt\"))"] - ["printf formats" "\"x=1 y=a\"" "(with-out-str (printf \"x=%d y=%s\" 1 \"a\"))"] - ["printf no newline" "false" "(do (require (quote [clojure.string :as s])) (s/includes? (with-out-str (printf \"%d\" 1)) \"\\n\"))"] - ["flush returns nil" "nil" "(flush)"] - ["file-seq finds files" "true" "(do (require (quote [clojure.string :as s])) (boolean (some (fn [p] (s/ends-with? p \"project.janet\")) (file-seq \".\"))))"]) - -(defspec "ns / ns-map, ns-unmap, ns-refers" - ["ns-map has var" "true" "(do (def nmv 1) (some? (get (ns-map (quote user)) (quote nmv))))"] - ["ns-unmap removes" "nil" "(do (def nuv 1) (ns-unmap (quote user) (quote nuv)) (resolve (quote nuv)))"] - ["ns-refers sees refer" "true" "(do (require (quote clojure.string)) (refer (quote clojure.string)) (some? (get (ns-refers (quote user)) (quote join))))"]) - -(defspec "vars / thread-binding family" - ["bound? on def" "true" "(do (def bvv 1) (bound? (var bvv)))"] - ["with-bindings* binds" "5" - "(do (def ^:dynamic dynv 1) (with-bindings* (array-map (var dynv) 5) (fn [] dynv)))"] - ["with-bindings* restores" "1" - "(do (def ^:dynamic dynw 1) (with-bindings* (array-map (var dynw) 5) (fn [] nil)) dynw)"] - ["with-bindings macro" "7" - "(do (def ^:dynamic dynx 1) (with-bindings (array-map (var dynx) 7) dynx))"] - ["thread-bound? inside" "[true false]" - "(do (def ^:dynamic dyny 1) [(with-bindings* (array-map (var dyny) 2) (fn [] (thread-bound? (var dyny)))) (thread-bound? (var dyny))])"] - ["bound-fn* conveys" "9" - "(do (def ^:dynamic dynz 1) (def f (with-bindings* (array-map (var dynz) 9) (fn [] (bound-fn* (fn [] dynz))))) (f))"] - ["get-thread-bindings" "3" - "(do (def ^:dynamic dyng 1) (with-bindings* (array-map (var dyng) 3) (fn [] (get (get-thread-bindings) (var dyng)))))"]) - -(defspec "eval & load-string as values" - ["load-string evals all" "3" "(load-string \"(def lsv 1) (+ lsv 2)\")"] - ["eval as value" "[2 3]" "(mapv eval [(quote (+ 1 1)) (quote (+ 1 2))])"] - ["eval special still works" "3" "(eval (quote (+ 1 2)))"]) - -# clojure.edn is complete (jolt-b7y / jolt-0mb): sets, #uuid/#inst, :eof, -# and the :readers / :default opts (tag normalized from the reader's :#name -# keyword to the symbol Clojure keys :readers with). -(defspec "clojure.edn / opts" - ["set literal" "#{1 2}" "(do (require (quote [clojure.edn :as e0])) (e0/read-string \"#{1 2}\"))"] - ["uuid tag" "true" "(do (require (quote [clojure.edn :as e0])) (uuid? (e0/read-string \"#uuid \\\"550e8400-e29b-41d4-a716-446655440000\\\"\")))"] - ["inst tag" "true" "(do (require (quote [clojure.edn :as e0])) (inst? (e0/read-string \"#inst \\\"2020-01-01T00:00:00Z\\\"\")))"] - [":eof on empty" ":end" "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:eof :end} \"\"))"] - [":readers custom tag" "[:custom 5]" "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:readers {(quote custom) (fn [v] [:custom v])}} \"#custom 5\"))"] - [":readers nested" "[6 8]" "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:readers {(quote w) (fn [v] (* 2 v))}} \"[#w 3 #w 4]\"))"] - [":default fn" "[:dflt 7]" "(do (require (quote [clojure.edn :as e0])) (e0/read-string {:default (fn [t v] [:dflt v])} \"#unknown 7\"))"] - ["unknown tag throws" :throws "(do (require (quote [clojure.edn :as e0])) (e0/read-string \"#nope 1\"))"]) diff --git a/test/spec/state-spec.janet b/test/spec/state-spec.janet deleted file mode 100644 index b35944c..0000000 --- a/test/spec/state-spec.janet +++ /dev/null @@ -1,48 +0,0 @@ -# Specification: stateful reference types (atoms, volatiles, delays, promises). -(use ../support/harness) - -(defspec "state / atoms" - ["deref @" "0" "(let [a (atom 0)] @a)"] - ["deref fn" "0" "(deref (atom 0))"] - ["reset!" "5" "(let [a (atom 0)] (reset! a 5) @a)"] - ["reset! returns new" "5" "(let [a (atom 0)] (reset! a 5))"] - ["swap!" "1" "(let [a (atom 0)] (swap! a inc) @a)"] - ["swap! with args" "10" "(let [a (atom 1)] (swap! a + 2 3 4) @a)"] - ["swap! returns new" "1" "(let [a (atom 0)] (swap! a inc))"] - ["swap-vals!" "[0 1]" "(let [a (atom 0)] (swap-vals! a inc))"] - ["reset-vals!" "[0 9]" "(let [a (atom 0)] (reset-vals! a 9))"] - ["compare-and-set! ok" "true" "(let [a (atom 0)] (compare-and-set! a 0 1))"] - ["compare-and-set! no" "false" "(let [a (atom 0)] (compare-and-set! a 9 1))"] - ["atom?" "true" "(do (require (quote [clojure.core])) (instance? clojure.lang.Atom (atom 0)))"] - ["atom? predicate" "true" "(atom? (atom 0))"] - ["atom? on non-atom" "false" "(atom? 5)"]) - -(defspec "state / watches & validators" - ["add-watch fires" "1" "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (reset! seen 1))) (reset! a 5) @seen)"] - ["remove-watch" "0" "(let [a (atom 0) seen (atom 0)] (add-watch a :k (fn [k r o n] (swap! seen inc))) (remove-watch a :k) (reset! a 5) @seen)"] - ["set-validator! ok" "5" "(let [a (atom 0)] (set-validator! a number?) (reset! a 5) @a)"] - ["set-validator! rejects" :throws "(let [a (atom 0)] (set-validator! a pos?) (reset! a -1))"] - ["get-validator" "true" "(let [a (atom 0)] (set-validator! a number?) (fn? (get-validator a)))"]) - -(defspec "state / volatiles & delays" - ["volatile! deref" "0" "(let [v (volatile! 0)] @v)"] - ["vreset!" "5" "(let [v (volatile! 0)] (vreset! v 5) @v)"] - ["vswap!" "1" "(let [v (volatile! 0)] (vswap! v inc) @v)"] - ["delay not forced" "0" "(let [c (atom 0) d (delay (swap! c inc))] @c)"] - ["delay force once" "1" "(let [c (atom 0) d (delay (swap! c inc))] (force d) (force d) @c)"] - ["delay value" "5" "(let [d (delay 5)] @d)"] - ["realized? before" "false" "(let [d (delay 5)] (realized? d))"] - ["realized? after" "true" "(let [d (delay 5)] (force d) (realized? d))"]) - -(defspec "state / promises" - ["promise deliver" "5" "(let [p (promise)] (deliver p 5) @p)"] - ["promise undelivered" "nil" "(let [p (promise)] @p)"]) - -# Minimal synchronous agent shim (jolt has no thread pool/STM) — enough for -# libraries that hold an agent without depending on async dispatch. -(defspec "state / agents (synchronous shim)" - ["agent deref" "0" "(deref (agent 0))"] - ["agent with opts" "0" "(deref (agent 0 :error-mode :continue))"] - ["send-off applies" "5" "(let [a (agent 0)] (send-off a + 5) (deref a))"] - ["send applies" "7" "(let [a (agent 1)] (send a + 6) (deref a))"] - ["agent-error nil" "nil" "(agent-error (agent 0))"]) diff --git a/test/spec/strings-spec.janet b/test/spec/strings-spec.janet deleted file mode 100644 index 731734c..0000000 --- a/test/spec/strings-spec.janet +++ /dev/null @@ -1,88 +0,0 @@ -# Specification: strings (str + clojure.string). -(use ../support/harness) - -(defspec "string / str & basics" - ["str concat" "\"abc\"" "(str \"a\" \"b\" \"c\")"] - ["str of numbers" "\"12\"" "(str 1 2)"] - ["str nil is empty" "\"\"" "(str nil)"] - ["str mixed" "\"a1:b\"" "(str \"a\" 1 :b)"] - ["str of coll" "\"[1 2]\"" "(str [1 2])"] - ["count" "3" "(count \"abc\")"] - ["subs from" "\"bc\"" "(subs \"abc\" 1)"] - ["subs range" "\"b\"" "(subs \"abc\" 1 2)"] - ["string? true" "true" "(string? \"x\")"] - ["pr-str vector" "\"[1 2 3]\"" "(pr-str [1 2 3])"] - ["pr-str quotes str" "\"\\\"hi\\\"\"" "(pr-str \"hi\")"] - # a var's :meta/:ns refs are cyclic — pr-str/str render it as #'ns/name - # rather than recursing into (and looping on) the var's fields. - ["pr-str of a var" "\"#'user/vv\"" "(pr-str (def vv 1))"] - ["str of a var" "\"#'user/ww\"" "(str (def ww 2))"] - ["pr-str of a defn" "\"#'user/gg\"" "(pr-str (defn gg [x] x))"] - ["seq of string" "[\\a \\b]" "(seq \"ab\")"]) - -(defspec "string as a seqable of chars (jolt-dl4s)" - ["vec of string" "[\\a \\b]" "(vec \"ab\")"] - ["into [] of string" "[\\a \\b]" "(into [] \"ab\")"] - ["set of string" "true" "(= #{\\a \\b} (set \"ab\"))"] - ["into #{} of string" "true" "(= #{\\a \\b} (into #{} \"ab\"))"] - ["set dedups chars" "2" "(count (set \"aab\"))"] - ["mapv over string" "[\\a \\b]" "(mapv identity \"ab\")"]) - -(defspec "clojure.string / split limit (jolt-ik3a)" - ["neg keeps trailing" "[\"a\" \"\" \"\"]" "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\" -1))"] - ["zero trims trailing" "[\"a\"]" "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\" 0))"] - ["omitted trims" "[\"a\"]" "(do (require (quote [clojure.string :as s])) (s/split \"a,,\" #\",\"))"] - ["positive caps parts" "[\"a\" \"b,c\"]" "(do (require (quote [clojure.string :as s])) (s/split \"a,b,c\" #\",\" 2))"] - ["empty string" "[\"\"]" "(do (require (quote [clojure.string :as s])) (s/split \"\" #\",\"))"] - ["interior empties kept" "[\"a\" \"\" \"b\"]" "(do (require (quote [clojure.string :as s])) (s/split \"a,,b\" #\",\"))"]) - -(defspec "clojure.string" - ["join" "\"a,b,c\"" "(do (require (quote [clojure.string :as s])) (s/join \",\" [\"a\" \"b\" \"c\"]))"] - ["join no sep" "\"abc\"" "(do (require (quote [clojure.string :as s])) (s/join [\"a\" \"b\" \"c\"]))"] - ["split" "[\"a\" \"b\"]" "(do (require (quote [clojure.string :as s])) (s/split \"a,b\" #\",\"))"] - ["split-lines" "[\"a\" \"b\"]" "(do (require (quote [clojure.string :as s])) (s/split-lines \"a\\nb\"))"] - ["upper-case" "\"ABC\"" "(do (require (quote [clojure.string :as s])) (s/upper-case \"abc\"))"] - ["lower-case" "\"abc\"" "(do (require (quote [clojure.string :as s])) (s/lower-case \"ABC\"))"] - ["capitalize" "\"Abc\"" "(do (require (quote [clojure.string :as s])) (s/capitalize \"abc\"))"] - ["trim" "\"x\"" "(do (require (quote [clojure.string :as s])) (s/trim \" x \"))"] - ["triml" "\"x \"" "(do (require (quote [clojure.string :as s])) (s/triml \" x \"))"] - ["blank? true" "true" "(do (require (quote [clojure.string :as s])) (s/blank? \" \"))"] - ["blank? false" "false" "(do (require (quote [clojure.string :as s])) (s/blank? \"x\"))"] - ["includes?" "true" "(do (require (quote [clojure.string :as s])) (s/includes? \"hello\" \"ell\"))"] - ["starts-with?" "true" "(do (require (quote [clojure.string :as s])) (s/starts-with? \"hello\" \"he\"))"] - ["ends-with?" "true" "(do (require (quote [clojure.string :as s])) (s/ends-with? \"hello\" \"lo\"))"] - ["replace" "\"hexxo\"" "(do (require (quote [clojure.string :as s])) (s/replace \"hello\" \"l\" \"x\"))"] - ["reverse" "\"cba\"" "(do (require (quote [clojure.string :as s])) (s/reverse \"abc\"))"] - ["index-of" "2" "(do (require (quote [clojure.string :as s])) (s/index-of \"hello\" \"l\"))"]) - -# subs validates bounds like Clojure (no Janet from-end/clamping). -(defspec "string / subs strictness" - ["subs basic" "\"bcd\"" "(subs \"abcde\" 1 4)"] - ["subs to end" "\"cde\"" "(subs \"abcde\" 2)"] - ["subs start>end" :throws "(subs \"abcde\" 2 1)"] - ["subs negative" :throws "(subs \"abcde\" -1)"] - ["subs end past len" :throws "(subs \"abcde\" 1 6)"] - ["subs nil start" :throws "(subs \"abcde\" nil 2)"] - ["subs on nil" :throws "(subs nil 1 2)"]) - -(defspec "string / namespace-munge" - ["hyphens to underscores" "\"a_b_c\"" "(namespace-munge \"a-b-c\")"] - ["from a symbol" "\"foo_bar\"" "(namespace-munge (quote foo-bar))"] - ["no hyphens unchanged" "\"ok\"" "(namespace-munge \"ok\")"]) - -# (get s i) indexes a string and returns the char, like Clojure (nth already -# did; get did not — reitit's path parser relies on it). -(defspec "strings / get indexes a string" - ["get returns the char" "true" "(= (get \"a:b\" 1) \\:)"] - ["get first char" "\\a" "(get \"abc\" 0)"] - ["get out of range nil" "nil" "(get \"abc\" 9)"] - ["get negative nil" "nil" "(get \"abc\" -1)"] - ["get default honored" ":none" "(get \"abc\" 9 :none)"]) - -# clojure.string/trim-newline (ported from clojure.string): strips trailing \n/\r. -(defspec "clojure.string / trim-newline" - ["trailing newline" "\"x\"" "(do (require (quote [clojure.string :as s])) (s/trim-newline \"x\\n\"))"] - ["trailing \\r\\n" "\"x\"" "(do (require (quote [clojure.string :as s])) (s/trim-newline \"x\\r\\n\"))"] - ["no trailing" "\"ab\"" "(do (require (quote [clojure.string :as s])) (s/trim-newline \"ab\"))"] - ["only newlines" "\"\"" "(do (require (quote [clojure.string :as s])) (s/trim-newline \"\\n\\n\"))"] - ["interior kept" "\"a\\nb\"" "(do (require (quote [clojure.string :as s])) (s/trim-newline \"a\\nb\\n\"))"]) diff --git a/test/spec/transducers-spec.janet b/test/spec/transducers-spec.janet deleted file mode 100644 index be21ca1..0000000 --- a/test/spec/transducers-spec.janet +++ /dev/null @@ -1,77 +0,0 @@ -# Specification: transducers. -(use ../support/harness) - -(defspec "transducers / into" - ["map xform" "[2 3 4]" "(into [] (map inc) [1 2 3])"] - ["filter xform" "[2 4]" "(into [] (filter even?) [1 2 3 4])"] - ["remove xform" "[1 3]" "(into [] (remove even?) [1 2 3 4])"] - ["take xform" "[1 2]" "(into [] (take 2) [1 2 3 4])"] - ["drop xform" "[3 4]" "(into [] (drop 2) [1 2 3 4])"] - ["take-while xform" "[1 2]" "(into [] (take-while (fn [x] (< x 3))) [1 2 3 1])"] - ["keep xform" "[1 3]" "(into [] (keep (fn [x] (if (odd? x) x nil))) [1 2 3 4])"] - ["map-indexed xform" "[[0 :a] [1 :b]]" "(into [] (map-indexed vector) [:a :b])"] - ["mapcat xform" "[1 1 2 2]" "(into [] (mapcat (fn [x] [x x])) [1 2])"] - ["cat xform" "[1 2 3 4]" "(into [] cat [[1 2] [3 4]])"] - ["into a set" "#{2 3 4}" "(into #{} (map inc) [1 2 3])"]) - -# transducer comp applies left-to-right: (comp (map a) (filter b)) maps then filters -(defspec "transducers / compose" - ["comp map+filter" "[2 4 6 8]" "(into [] (comp (map (fn [x] (* x 2))) (filter even?)) [1 2 3 4])"] - ["comp filter+map" "[2 4]" "(into [] (comp (filter odd?) (map inc)) [1 2 3 4])"] - ["comp three" "[2]" "(into [] (comp (map inc) (filter even?) (take 1)) [1 2 3 4])"]) - -(defspec "transducers / transduce & sequence" - ["transduce sum" "9" "(transduce (map inc) + [1 2 3])"] - ["transduce init" "19" "(transduce (map inc) + 10 [1 2 3])"] - ["transduce filter" "6" "(transduce (filter even?) + [1 2 3 4])"] - ["sequence xform" "[2 3 4]" "(sequence (map inc) [1 2 3])"] - ["eduction" "[2 3 4]" "(into [] (eduction (map inc) [1 2 3]))"] - ["completing" "9" "(transduce (map inc) (completing +) 0 [1 2 3])"]) - -# halt-when replaces the WHOLE reduction result with the halting input (or -# with (retf acc input)) — Clojure's ::halt map protocol, unwrapped by the -# transducer's completion arity. -(defspec "transducers / halt-when" - ["halt returns the halting input" "7" - "(transduce (halt-when (fn [x] (> x 5))) conj [1 2 7 3])"] - ["no halt is a plain reduction" "[1 2 3]" - "(transduce (halt-when (fn [x] (> x 5))) conj [1 2 3])"] - ["retf combines acc and input" "[[1 2] 7]" - "(transduce (halt-when (fn [x] (> x 5)) (fn [r i] [r i])) conj [1 2 7 3])"] - ["halt-when through into" "3" - "(into [] (halt-when odd?) [2 4 3 6])"]) - -# A `take`/`take-while` transducer returns `reduced`, which must short-circuit -# the reduction so transducing over an INFINITE seq terminates rather than -# realizing it eagerly. -(defspec "transducers / short-circuit over infinite seqs" - ["into take (range)" "[0 1 2 3 4]" "(into [] (take 5) (range))"] - ["transduce take (range)" "3" "(transduce (take 3) + 0 (range))"] - ["sequence take (range)" "[0 1 2 3 4]" "(sequence (take 5) (range))"] - ["take-while over (range)" "[0 1 2]" "(into [] (take-while (fn [x] (< x 3))) (range))"] - ["comp take over (range)" "[1 3 5]" "(into [] (comp (filter odd?) (take 3)) (range))"] - ["into take iterate" "[0 1 2 3 4]" "(into [] (take 5) (iterate inc 0))"]) - -# `reduce` itself honors `reduced`, so a reducing fn that returns `reduced` -# terminates even over an infinite seq. -(defspec "reduce / honors reduced" - ["reduced short-circuits inf" "105" - "(reduce (fn [a x] (if (> a 100) (reduced a) (+ a x))) 0 (range))"] - ["reduce take inf" "10" "(reduce + (take 5 (range)))"] - ["reduce no-init first elem" "6" "(reduce + [1 2 3])"] - ["reduce no-init single" "42" "(reduce + [42])"] - ["reduce empty calls f" "0" "(reduce + [])"] - ["reduce with-init" "16" "(reduce + 10 [1 2 3])"] - ["reduce reduced immediate" ":x" "(reduce (fn [a x] (reduced :x)) :init [1 2 3])"]) - -# into/transduce/eduction are overlay fns now (seed-shrink round 5): into -# takes a transient fast path for vectors and preserves metadata; eduction -# stays eager (documented divergence). -(defspec "transducers / into & eduction (overlay)" - ["into list prepends" "(quote (4 3 1 2))" "(into (quote (1 2)) [3 4])"] - ["into sorted-map" "{1 :a, 2 :b}" "(into (sorted-map) [[2 :b] [1 :a]])"] - ["into from map entry" "[:a 1]" "(into [] (first {:a 1}))"] - ["into xform on map" "{:a 2}" "(into {} (map (fn [e] [(key e) (inc (val e))])) {:a 1})"] - ["eduction multiple xforms" "[4]" "(into [] (eduction (filter odd?) (map inc) [2 3 4]))"] - ["->Eduction" "[2 3]" "(->Eduction (map inc) [1 2])"] - ["transduce no init uses (f)" "5" "(transduce (map inc) + [1 2])"]) diff --git a/test/spec/transients-spec.janet b/test/spec/transients-spec.janet deleted file mode 100644 index be67284..0000000 --- a/test/spec/transients-spec.janet +++ /dev/null @@ -1,98 +0,0 @@ -# Specification: transients (mutable scratch collections frozen by persistent!). -(use ../support/harness) - -(defspec "transient / vector" - ["conj! then persistent!" "[1 2]" "(persistent! (conj! (conj! (transient []) 1) 2))"] - ["reduce conj!" "[0 1 2 3 4]" "(persistent! (reduce conj! (transient []) (range 5)))"] - ["conj! many args" "[1 2 3]" "(persistent! (conj! (transient [1]) 2 3))"] - ["assoc! existing" "[1 9 3]" "(persistent! (assoc! (transient [1 2 3]) 1 9))"] - ["assoc! at count grows" "[1 2 3]" "(persistent! (assoc! (transient [1 2]) 2 3))"] - ["pop!" "[1 2]" "(persistent! (pop! (transient [1 2 3])))"] - ["from existing vector" "[1 2 3 4]" "(persistent! (conj! (transient [1 2 3]) 4))"] - ["count" "3" "(count (transient [1 2 3]))"] - ["nth" "2" "(nth (transient [1 2 3]) 1)"] - ["get" "2" "(get (transient [1 2 3]) 1)"] - ["persistent! is a vector" "true" "(vector? (persistent! (transient [1])))"] - ["transient? true" "true" "(transient? (transient []))"] - ["transient? false" "false" "(transient? [1 2])"]) - -(defspec "transient / map" - ["assoc! then persistent!" "{:a 1, :b 2}" "(persistent! (assoc! (assoc! (transient {}) :a 1) :b 2))"] - ["assoc! many" "{:a 1, :b 2}" "(persistent! (assoc! (transient {}) :a 1 :b 2))"] - ["dissoc!" "{:b 2}" "(persistent! (dissoc! (transient {:a 1 :b 2}) :a))"] - ["conj! map entry" "{:a 1}" "(persistent! (conj! (transient {}) [:a 1]))"] - ["from existing map" "{:a 1, :b 2}" "(persistent! (assoc! (transient {:a 1}) :b 2))"] - ["get" "1" "(get (transient {:a 1}) :a)"] - ["get missing default" ":x" "(get (transient {:a 1}) :z :x)"] - ["contains?" "true" "(contains? (transient {:a 1}) :a)"] - ["count" "2" "(count (transient {:a 1 :b 2}))"] - ["collection key by value" ":v" "(get (persistent! (assoc! (transient {}) [1 2] :v)) [1 2])"] - ["persistent! is a map" "true" "(map? (persistent! (transient {:a 1})))"] - ["reduce build" "{0 0, 1 1, 2 2}" "(persistent! (reduce (fn [t i] (assoc! t i i)) (transient {}) (range 3)))"]) - -(defspec "transient / set" - ["conj! dedups" "#{1 2 3}" "(persistent! (conj! (transient #{}) 1 2 2 3))"] - ["disj!" "#{1 3}" "(persistent! (disj! (transient #{1 2 3}) 2))"] - ["from existing set" "#{1 2 3}" "(persistent! (conj! (transient #{1 2}) 3))"] - ["contains?" "true" "(contains? (transient #{1 2}) 1)"] - ["count" "2" "(count (transient #{1 2}))"] - ["persistent! is a set" "true" "(set? (persistent! (transient #{1})))"] - ["map elements by value" "1" "(count (persistent! (conj! (transient #{}) {:a 1} (hash-map :a 1))))"]) - -(defspec "transient / immutability of source" - ["source vector unchanged" "true" - "(let [v [1 2 3] _ (persistent! (conj! (transient v) 4))] (= v [1 2 3]))"] - ["source map unchanged" "true" - "(let [m {:a 1} _ (persistent! (assoc! (transient m) :b 2))] (= m {:a 1}))"]) - -# Transients are invokable for read-only lookup, like their persistent forms. -(defspec "transient / invokable lookup" - ["vector index" "20" "((transient [10 20 30]) 1)"] - ["map key as fn" "7" "((transient {:x 7}) :x)"] - ["map key default" "99" "((transient {:x 7}) :z 99)"] - ["keyword on transient" "7" "(:x (transient {:x 7}))"] - ["set membership" "2" "((transient #{1 2 3}) 2)"] - ["set miss default" ":no" "((transient #{1 2 3}) 42 :no)"] - ["collection key" ":v" "((transient {[1 2] :v}) [1 2])"]) - -# assoc! (unlike assoc) accepts an odd arg count — a missing final value is nil. -# (A struct literal can't express an explicit nil value, so assert via contains?.) -(defspec "transient / assoc! odd args" - ["odd arg key present" "true" - "(contains? (persistent! (assoc! (transient {}) :a 1 :b)) :b)"] - ["odd arg value is nil" "true" - "(nil? (get (persistent! (assoc! (transient {}) :a 1 :b)) :b))"] - ["odd arg keeps prior" "1" - "(get (persistent! (assoc! (transient {}) :a 1 :b)) :a)"] - ["vector odd arg" "[9 nil]" - "(persistent! (apply assoc! (transient []) [0 9 1]))"]) - -# Using a transient after persistent! (or popping an empty one) throws. -(defspec "transient / invalidation" - ["conj! after persistent!" :throws - "(let [t (transient [])] (persistent! t) (conj! t 1))"] - ["assoc! after persistent!" :throws - "(let [t (transient {})] (persistent! t) (assoc! t :a 1))"] - ["persistent! twice" :throws - "(let [t (transient [])] (persistent! t) (persistent! t))"] - ["pop! empty" :throws "(pop! (transient []))"]) - -# The bang ops require an appropriate transient (Clojure throws otherwise); -# conj! has the special 0-/1-arg identity arities. -(defspec "transient / strictness" - ["conj! on persistent" :throws "(conj! [1 2] 3)"] - ["assoc! on persistent" :throws "(assoc! {:a 1} :b 2)"] - ["persistent! on vector" :throws "(persistent! [1 2])"] - ["persistent! on nil" :throws "(persistent! nil)"] - ["pop! on transient map" :throws "(pop! (transient {:a 1}))"] - ["dissoc! on tset" :throws "(dissoc! (transient #{1}) 1)"] - ["conj! map bad item" :throws "(conj! (transient {}) #{:a 1})"] - ["conj! no args" "[]" "(persistent! (conj!))"] - ["conj! identity" "[1 2]" "(conj! [1 2])"] - ["conj! map merges map" "{:a 1, :b 2}" "(persistent! (conj! (transient {:a 1}) {:b 2}))"]) - -(defspec "transient / assoc! bounds" - ["assoc! existing idx" "[1 9 3]" "(persistent! (assoc! (transient [1 2 3]) 1 9))"] - ["assoc! at count grows" "[1 2 3]" "(persistent! (assoc! (transient [1 2]) 2 3))"] - ["assoc! out of bounds" :throws "(assoc! (transient [0 1 2]) 4 4)"] - ["assoc! negative" :throws "(assoc! (transient []) -1 0)"]) diff --git a/test/spec/truthiness-spec.janet b/test/spec/truthiness-spec.janet deleted file mode 100644 index a119e7a..0000000 --- a/test/spec/truthiness-spec.janet +++ /dev/null @@ -1,61 +0,0 @@ -# Specification: truthiness & boolean logic. -# The core Clojure rule: ONLY nil and false are logically false; every other -# value — including 0, 0.0, "", and empty collections — is logically true. -(use ../support/harness) - -(defspec "truthiness / if (only nil & false are falsy)" - ["nil is falsy" ":f" "(if nil :t :f)"] - ["false is falsy" ":f" "(if false :t :f)"] - ["zero is truthy" ":t" "(if 0 :t :f)"] - ["zero float truthy" ":t" "(if 0.0 :t :f)"] - ["empty string truthy" ":t" "(if \"\" :t :f)"] - ["empty list truthy" ":t" "(if (list) :t :f)"] - ["empty vector truthy" ":t" "(if [] :t :f)"] - ["empty map truthy" ":t" "(if {} :t :f)"] - ["empty set truthy" ":t" "(if #{} :t :f)"] - ["number truthy" ":t" "(if 42 :t :f)"] - ["string truthy" ":t" "(if \"x\" :t :f)"] - ["keyword truthy" ":t" "(if :kw :t :f)"] - ["symbol truthy" ":t" "(if (quote abc) :t :f)"] - ["coll truthy" ":t" "(if [1 2] :t :f)"] - ["map truthy" ":t" "(if {:a 1} :t :f)"] - ["if no else -> nil" "nil" "(if false :t)"]) - -(defspec "truthiness / not" - ["not nil" "true" "(not nil)"] - ["not false" "true" "(not false)"] - ["not zero" "false" "(not 0)"] - ["not empty vector" "false" "(not [])"] - ["not empty string" "false" "(not \"\")"] - ["not number" "false" "(not 42)"] - ["not true" "false" "(not true)"]) - -(defspec "truthiness / and" - ["empty is true" "true" "(and)"] - ["single value" "5" "(and 5)"] - ["all truthy -> last" "3" "(and 1 2 3)"] - ["stops at false" "false" "(and 1 false 3)"] - ["stops at nil" "nil" "(and 1 nil 3)"] - ["false alone" "false" "(and false)"] - ["nil alone" "nil" "(and nil)"] - ["zero is truthy" "0" "(and 1 0)"]) - -(defspec "truthiness / or" - ["empty is nil" "nil" "(or)"] - ["first truthy" "1" "(or 1 2)"] - ["skips nil/false" "5" "(or nil false 5)"] - ["all falsy -> last" "false" "(or nil false)"] - ["nil chain -> false" "false" "(or nil nil nil false)"] - ["zero is truthy" "0" "(or 0 1)"] - ["false alone" "false" "(or false)"]) - -(defspec "truthiness / if-not & boolean" - ["if-not false" ":yes" "(if-not false :yes :no)"] - ["if-not truthy" ":no" "(if-not 0 :yes :no)"] - ["when-not nil" "1" "(when-not nil 1)"] - ["when-not truthy" "nil" "(when-not 5 1)"] - ["boolean of nil" "false" "(boolean nil)"] - ["boolean of false" "false" "(boolean false)"] - ["boolean of 0" "true" "(boolean 0)"] - ["boolean of value" "true" "(boolean :x)"] - ["true?/false?" "true" "(and (true? true) (false? false) (not (true? 1)))"]) diff --git a/test/spec/untested-vars-spec.janet b/test/spec/untested-vars-spec.janet deleted file mode 100644 index b5da2ed..0000000 --- a/test/spec/untested-vars-spec.janet +++ /dev/null @@ -1,185 +0,0 @@ -# Specification: spec rows for every previously-untested implemented var -# (jolt-brh follow-up — promotes the dashboard's implemented-untested category). -# Rows assert jolt's ACTUAL documented behavior, including the stub families: -# arrays are vectors/host buffers, proxies/JVM reflection are resolve-only, -# unchecked-* are plain double ops, chunks are eager equivalents. -(use ../support/harness) - -(defspec "untested / primed + division + bit ops" - ["+'" "3" "(+' 1 2)"] - ["-'" "3" "(-' 5 2)"] - ["*'" "12" "(*' 3 4)"] - ["inc'" "2.5" "(inc' 1.5)"] - ["dec'" "1.5" "(dec' 2.5)"] - ["/" "2" "(/ 6 3)"] - ["/ ratio-as-double" "0.5" "(/ 1 2)"] - ["bit-not" "-6" "(bit-not 5)"] - ["bit-and-not" "4" "(bit-and-not 12 10)"] - ["bit-flip" "3" "(bit-flip 2 0)"] - ["unsigned-bit-shift-right" "2" "(unsigned-bit-shift-right 8 2)"]) - -(defspec "untested / hash family" - ["hash stable" "true" "(= (hash :a) (hash :a))"] - ["hash int" "true" "(int? (hash [1 2]))"] - ["hash-combine" "true" "(int? (hash-combine 1 2))"] - ["hash-ordered-coll" "true" "(int? (hash-ordered-coll [1 2]))"] - ["hash-unordered-coll" "true" "(int? (hash-unordered-coll #{1}))"]) - -(defspec "untested / array stubs (vectors + host buffers)" - ["make-array" "(quote (nil nil nil))" "(make-array 3)"] - ["into-array" "(quote (1 2))" "(into-array [1 2])"] - ["to-array" "(quote (1 2))" "(to-array [1 2])"] - ["aclone vec" "(quote (1 2))" "(aclone [1 2])"] - ["aclone independent" "(quote (9 2))" "(let [a (aclone (to-array [1 2]))] (aset a 0 9) (seq a))"] - ["aset/aget" "9" "(let [a (to-array [1 2 3])] (aset a 0 9) (aget a 0))"] - ["aset-int" "7" "(let [a (to-array [1 2])] (aset-int a 0 7) (aget a 0))"] - ["aset-boolean" "true" "(let [a (to-array [1])] (aset-boolean a 0 true) (aget a 0))"] - ["aset-byte" "9" "(let [a (to-array [0])] (aset-byte a 0 9) (aget a 0))"] - ["aset-char" "\\a" "(let [a (to-array [0])] (aset-char a 0 \\a) (aget a 0))"] - ["aset-double" "1.5" "(let [a (to-array [0])] (aset-double a 0 1.5) (aget a 0))"] - ["aset-float" "2.5" "(let [a (to-array [0])] (aset-float a 0 2.5) (aget a 0))"] - ["aset-long" "3" "(let [a (to-array [0])] (aset-long a 0 3) (aget a 0))"] - ["aset-short" "4" "(let [a (to-array [0])] (aset-short a 0 4) (aget a 0))"] - ["boolean-array" "(quote (false false))" "(boolean-array 2)"] - ["int-array" "(quote (1 2))" "(int-array [1 2])"] - ["long-array" "(quote (0 0))" "(long-array 2)"] - ["double-array" "(quote (0 0))" "(double-array 2)"] - ["float-array" "(quote (0 0))" "(float-array 2)"] - ["short-array" "(quote (0 0))" "(short-array 2)"] - ["char-array count" "2" "(count (char-array 2))"] - ["byte-array bytes?" "true" "(bytes? (byte-array 2))"] - ["bytes? not vec" "false" "(bytes? [1])"]) - -(defspec "untested / typed coercion views" - ["booleans" "(quote (true))" "(booleans [true])"] - ["doubles" "(quote (1))" "(doubles [1.0])"] - ["floats" "(quote (1))" "(floats [1.0])"] - ["ints" "(quote (1))" "(ints [1])"] - ["longs" "(quote (1))" "(longs [1])"] - ["shorts" "(quote (1))" "(shorts [1])"] - ["chars first" "\\a" "(first (chars [\\a]))"] - ["bytes view" "true" "(bytes? (bytes [65]))"] - ["byte" "65" "(byte 65)"] - ["short" "1" "(short 1)"] - ["long truncates" "1" "(long 1.7)"] - ["double" "3" "(double 3)"] - ["float" "3" "(float 3)"]) - -(defspec "untested / unchecked-* are plain ops" - ["unchecked-add" "3" "(unchecked-add 1 2)"] - ["unchecked-add-int" "3" "(unchecked-add-int 1 2)"] - ["unchecked-subtract" "3" "(unchecked-subtract 5 2)"] - ["unchecked-subtract-int" "3" "(unchecked-subtract-int 5 2)"] - ["unchecked-multiply" "6" "(unchecked-multiply 2 3)"] - ["unchecked-multiply-int" "6" "(unchecked-multiply-int 2 3)"] - ["unchecked-inc" "2" "(unchecked-inc 1)"] - ["unchecked-inc-int" "2" "(unchecked-inc-int 1)"] - ["unchecked-dec" "2" "(unchecked-dec 3)"] - ["unchecked-dec-int" "2" "(unchecked-dec-int 3)"] - ["unchecked-negate" "-4" "(unchecked-negate 4)"] - ["unchecked-negate-int" "-4" "(unchecked-negate-int 4)"] - ["unchecked-divide-int" "3" "(unchecked-divide-int 7 2)"] - ["unchecked-remainder-int" "1" "(unchecked-remainder-int 7 2)"] - ["unchecked-int" "3" "(unchecked-int 3.7)"] - ["unchecked-long" "3" "(unchecked-long 3.7)"] - ["unchecked-double" "3" "(unchecked-double 3)"] - ["unchecked-float" "3" "(unchecked-float 3)"] - ["unchecked-byte" "65" "(unchecked-byte 65)"] - ["unchecked-char" "97" "(unchecked-char 97)"] - ["unchecked-short" "5" "(unchecked-short 5)"]) - -(defspec "untested / chunk family (eager equivalents) + cat" - ["chunk round-trip" "1" - "(let [cb (chunk-buffer 4)] (chunk-append cb 1) (chunk-first (chunk-cons (chunk cb) nil)))"] - ["cat transducer" "[1 2 3]" "(into [] cat [[1] [2 3]])"] - ["ensure-reduced wraps" "true" "(reduced? (ensure-reduced 5))"] - ["ensure-reduced keeps reduced" "true" "(reduced? (ensure-reduced (reduced 5)))"] - ["halt-when" "4" "(transduce (halt-when even?) conj [] [1 3 4 5])"] - ["chunk-next exhausted" "nil" - "(let [cb (chunk-buffer 2)] (chunk-append cb 1) (chunk-next (chunk-cons (chunk cb) nil)))"] - ["chunk-rest seqable" "()" - "(let [cb (chunk-buffer 2)] (chunk-append cb 1) (vec (chunk-rest (chunk-cons (chunk cb) nil))))"]) - -(defspec "untested / JVM-shape stubs (documented jolt behavior)" - ["class number" "\"java.lang.Number\"" "(class 1)"] - ["class string" "\"java.lang.String\"" "(class \"s\")"] - ["class keyword" "\"clojure.lang.Keyword\"" "(class :k)"] - ["class nil" "nil" "(class nil)"] - ["bean is the map" "{:a 1}" "(bean {:a 1})"] - ["biginteger" "\"5\"" "(str (biginteger 5))"] - ["proxy resolves nil" "nil" "(proxy [Object] [] (toString [] \"x\"))"] - ["construct-proxy throws" :throws "(construct-proxy nil)"] - ["get-proxy-class throws" :throws "(get-proxy-class)"] - ["init-proxy" "nil" "(init-proxy nil {})"] - ["update-proxy" "nil" "(update-proxy nil {})"] - ["proxy-mappings" "{}" "(proxy-mappings nil)"] - ["proxy-call-with-super calls" "1" "(proxy-call-with-super (fn [] 1) nil \"m\")"] - ["memfn upper" "\"ABC\"" "((memfn toUpperCase) \"abc\")"] - ["memfn with args" "2" "((memfn indexOf needle) \"hello\" \"l\")"] - ["memfn length" "3" "((memfn length) \"abc\")"] - ["array-seq" "(quote (1 2 3))" "(array-seq (to-array [1 2 3]))"] - ["array-seq empty" "nil" "(array-seq (to-array []))"] - ["proxy-super throws" :throws "(proxy-super count [1])"] - ["re-groups throws" :throws "(re-groups (re-matcher #\"a\" \"b\"))"] - ["re-matcher builds" "false" "(nil? (re-matcher #\"a\" \"abc\"))"] - ["print-dup nil writer throws" :throws "(print-dup 1 nil)"] - ["print-method nil writer throws" :throws "(print-method 1 nil)"] - ["uri? string" "false" "(uri? \"http://x\")"] - ["uri? nil" "false" "(uri? nil)"] - ["definterface defines" "true" "(var? (definterface IFoo (foo [x])))"] - ["enumeration-seq" "(quote (1 2))" "(enumeration-seq [1 2])"] - ["iterator-seq" "(quote (1 2))" "(iterator-seq [1 2])"] - ["seque passthrough" "(quote (1 2))" "(seque [1 2])"] - ["delay? true" "true" "(delay? (delay 1))"] - ["delay? false" "false" "(delay? 1)"] - ["future-call" "42" "(deref (future-call (fn [] 42)))"] - [". calls String surface" "3" "(. \"abc\" length)"] - [".. threads members" "\"ABC\"" "(.. \"abc\" toUpperCase)"] - ["unknown String member throws" :throws "(. \"abc\" frobnicate)"]) - -(defspec "untested / protocols: extend + extends?" - ["extend registers" ":str" - "(do (defprotocol Pe (pe [x])) (extend (quote String) Pe {:pe (fn [x] :str)}) (pe \"s\"))"] - ["extend two methods" "[1 2]" - "(do (defprotocol P3 (pa [x]) (pb [x])) (extend (quote Long) P3 {:pa (fn [x] 1) :pb (fn [x] 2)}) [(pa 0) (pb 0)])"] - ["extends? after extend" "true" - "(do (defprotocol P4 (pc [x])) (extend (quote Long) P4 {:pc (fn [x] 1)}) (extends? P4 (quote Long)))"] - ["extends? without" "false" "(do (defprotocol P5 (pd [x])) (extends? P5 (quote Long)))"]) - -(defspec "untested / ns + REPL machinery" - ["all-ns non-empty" "true" "(pos? (count (all-ns)))"] - ["ns-interns sees def" "true" "(do (def zz 1) (pos? (count (ns-interns (quote user)))))"] - ["ns-interns countable" "true" "(map? (ns-interns (quote user)))"] - ["ns-imports empty user" "0" "(count (ns-imports (quote user)))"] - ["reset-meta!" "{:doc \"d\"}" "(do (def vv 1) (reset-meta! (var vv) {:doc \"d\"}))"] - ["prefers empty" "{}" "(do (defmulti mm identity) (prefers mm))"] - ["refer-clojure" "nil" "(refer-clojure)"] - ["special-symbol? if" "true" "(special-symbol? (quote if))"] - ["special-symbol? fn name" "false" "(special-symbol? (quote foo))"] - ["destructure expands" "true" "(pos? (count (destructure (quote [[a b] x]))))"] - ["seq-to-map-for-destructuring" "{:a 1}" "(seq-to-map-for-destructuring (quote (:a 1)))"] - ["s2m trailing map passes through" "{:b 2}" "(seq-to-map-for-destructuring (list {:b 2}))"] - ["s2m unpaired key throws" :throws "(seq-to-map-for-destructuring (quote (:a 1 :b)))"] - ["s2m kwargs trailing map call" "2" "((fn [& {:keys [b]}] b) {:b 2})"] - ["*clojure-version* major" "1" "(:major *clojure-version*)"] - ["*ns* user" "\"user\"" "(str *ns*)"] - ["*1 nil outside repl" "nil" "*1"] - ["*2 nil" "nil" "*2"] - ["*3 nil" "nil" "*3"] - ["*e nil" "nil" "*e"] - ["*unchecked-math*" "false" "*unchecked-math*"] - ["*in* bound" "true" "(map? *in*)"]) - -(defspec "untested / misc seqs + binding machinery" - ["nfirst" "(quote (2))" "(nfirst [[1 2] [3]])"] - ["xml-seq root" "1" "(count (xml-seq {:tag :a :content []}))"] - ["xml-seq walks" "2" "(count (xml-seq {:tag :a :content [{:tag :b :content []}]}))"] - # regression: comp with a keyword stage must use jolt IFn dispatch - ["comp keyword stage" "(quote (1 2))" "((comp seq :content) {:content [1 2]})"] - ["comp three stages" "4" "((comp inc inc :n) {:n 2})"] - ["random-sample all" "(quote (1 2))" "(random-sample 1.0 [1 2])"] - ["random-sample none" "()" "(random-sample 0.0 [1 2])"] - ["reader-conditional builds" "true" "(reader-conditional? (reader-conditional (quote (:clj 1)) false))"] - ["->Eduction" "[2 3]" "(vec (->Eduction (map inc) [1 2]))"] - ["bound-fn calls" "42" "((bound-fn [] 42))"] - ["push/pop-thread-bindings" ":ok" "(do (push-thread-bindings {}) (pop-thread-bindings) :ok)"]) diff --git a/test/spec/uuid-spec.janet b/test/spec/uuid-spec.janet deleted file mode 100644 index a9c8e7f..0000000 --- a/test/spec/uuid-spec.janet +++ /dev/null @@ -1,51 +0,0 @@ -# Specification: UUID support — random-uuid, parse-uuid, uuid?, #uuid literal. -# UUIDs are immutable tagged structs {:jolt/type :jolt/uuid :str ""}: -# value equality, usable as map keys, case-normalized at construction. -(use ../support/harness) - -(defspec "uuid / random-uuid" - ["returns a uuid" "true" "(uuid? (random-uuid))"] - ["str is 36 chars" "36" "(count (str (random-uuid)))"] - ["8-4-4-4-12 shape" "[8 4 4 4 12]" "(do (require (quote [clojure.string :as s])) (mapv count (s/split (str (random-uuid)) #\"-\")))"] - ["version nibble is 4" "\\4" "(nth (str (random-uuid)) 14)"] - ["variant nibble 8-b" "true" "(contains? #{\\8 \\9 \\a \\b} (nth (seq (str (random-uuid))) 19))"] - ["distinct" "10" "(count (set (repeatedly 10 random-uuid)))"] - ["all hex digits" "true" "(every? (fn [c] (contains? (set (seq \"0123456789abcdef-\")) c)) (seq (str (random-uuid))))"]) - -(defspec "uuid / parse-uuid" - ["valid round-trips" "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" - "(str (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"] - ["parses to uuid" "true" "(uuid? (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"] - ["case-insensitive =" "true" - "(= (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\") (parse-uuid \"B6883C0A-0342-4007-9966-BC2DFA6B109E\"))"] - ["empty -> nil" "nil" "(parse-uuid \"\")"] - ["short -> nil" "nil" "(parse-uuid \"0\")"] - ["garbage -> nil" "nil" "(parse-uuid \"df0993\")"] - ["too long -> nil" "nil" "(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109eb\")"] - ["leading extra -> nil" "nil" "(parse-uuid \"ab6883c0a-0342-4007-9966-bc2dfa6b109e\")"] - ["non-hex -> nil" "nil" "(parse-uuid \"g6883c0a-0342-4007-9966-bc2dfa6b109e\")"] - ["bad dashes -> nil" "nil" "(parse-uuid \"b6883c0a00342-4007-9966-bc2dfa6b109e\")"] - ["non-string throws" :throws "(parse-uuid 1000)"] - ["keyword throws" :throws "(parse-uuid :key)"] - ["map throws" :throws "(parse-uuid {})"]) - -(defspec "uuid / value semantics" - ["equal by value" "true" - "(= (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\") (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"] - ["unequal differs" "false" - "(= (random-uuid) (random-uuid))"] - ["works as map key" ":v" - "(let [u (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")] (get {u :v} (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")))"] - ["works in a set" "true" - "(contains? #{(parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")} (parse-uuid \"B6883C0A-0342-4007-9966-BC2DFA6B109E\"))"] - ["uuid? false on string" "false" "(uuid? \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")"] - ["uuid? false on nil" "false" "(uuid? nil)"]) - -(defspec "uuid / #uuid reader literal" - ["reads to uuid" "true" "(uuid? #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")"] - ["= parse-uuid" "true" - "(= #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\" (parse-uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\"))"] - ["str of literal" "\"b6883c0a-0342-4007-9966-bc2dfa6b109e\"" - "(str #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")"] - ["pr-str round-trips" "\"#uuid \\\"b6883c0a-0342-4007-9966-bc2dfa6b109e\\\"\"" - "(pr-str #uuid \"b6883c0a-0342-4007-9966-bc2dfa6b109e\")"]) diff --git a/test/spec/vectors-spec.janet b/test/spec/vectors-spec.janet deleted file mode 100644 index 136752d..0000000 --- a/test/spec/vectors-spec.janet +++ /dev/null @@ -1,69 +0,0 @@ -# Specification: vectors (persistent, indexed). -(use ../support/harness) - -(defspec "vector / construct & predicate" - ["literal" "[1 2 3]" "[1 2 3]"] - ["vector" "[1 2 3]" "(vector 1 2 3)"] - ["vector zero args" "[]" "(vector)"] - ["vec from list" "[1 2 3]" "(vec (list 1 2 3))"] - ["vec from range" "[0 1 2]" "(vec (range 3))"] - ["vec of map yields entries" "[[:a 1]]" "(vec {:a 1})"] - ["vector? true" "true" "(vector? [1])"] - ["vector? false on list" "false" "(vector? (list 1))"] - ["vector = list elts" "true" "(= [1 2 3] (list 1 2 3))"]) - -(defspec "vector / access" - ["nth" ":b" "(nth [:a :b :c] 1)"] - ["nth default" ":x" "(nth [:a] 5 :x)"] - ["get by index" ":b" "(get [:a :b] 1)"] - ["get out of range nil" "nil" "(get [:a] 5)"] - ["get default" ":x" "(get [:a] 5 :x)"] - ["first" "1" "(first [1 2 3])"] - ["last" "3" "(last [1 2 3])"] - ["peek is last" "3" "(peek [1 2 3])"] - ["count" "3" "(count [1 2 3])"] - ["contains? index" "true" "(contains? [:a :b] 1)"] - ["contains? past end" "false" "(contains? [:a] 3)"] - ["vector as fn" ":b" "([:a :b :c] 1)"] - # An IFn collection held in a binding (not just a literal) must dispatch as IFn, - # not as a host call: applies to vectors, keywords, and meta-bearing vectors. - ["vector-in-local as fn" "20" "(let [v [10 20 30]] (v 1))"] - ["keyword-in-local as fn" "7" "(let [k :a] (k {:a 7}))"] - ["meta vector as fn" "10" "((with-meta [10 20] {:k 1}) 0)"]) - -(defspec "vector / update (persistent)" - ["conj appends" "[1 2 3]" "(conj [1 2] 3)"] - ["conj many" "[1 2 3 4]" "(conj [1 2] 3 4)"] - ["assoc index" "[1 9 3]" "(assoc [1 2 3] 1 9)"] - ["assoc at count appends" "[1 2 3]" "(assoc [1 2] 2 3)"] - ["update" "[1 3 3]" "(update [1 2 3] 1 inc)"] - ["pop drops last" "[1 2]" "(pop [1 2 3])"] - ["subvec start end" "[2 3]" "(subvec [1 2 3 4] 1 3)"] - ["subvec to end" "[3 4]" "(subvec [1 2 3 4] 2)"] - ["mapv" "[2 3 4]" "(mapv inc [1 2 3])"] - ["filterv" "[2 4]" "(filterv even? [1 2 3 4])"]) - -(defspec "vector / immutability & nesting" - ["conj does not mutate" "true" "(let [v [1 2] w (conj v 3)] (and (= v [1 2]) (= w [1 2 3])))"] - ["assoc does not mutate" "true" "(let [v [1 2 3] w (assoc v 0 9)] (and (= v [1 2 3]) (= w [9 2 3])))"] - ["get-in" "2" "(get-in [[1 2] [3 4]] [0 1])"] - ["assoc-in" "[[1 9]]" "(assoc-in [[1 2]] [0 1] 9)"] - ["update-in" "[[1 3]]" "(update-in [[1 2]] [0 1] inc)"] - ["large vector nth" "1500" "(nth (vec (range 2000)) 1500)"] - ["large vector count" "2000" "(count (vec (range 2000)))"] - ["large conj immutable" "true" "(let [v (vec (range 1000)) w (conj v :end)] (and (= 1000 (count v)) (= 1001 (count w))))"]) - -# vec/into build the pvec trie BOTTOM-UP in one pass (pv-from-indexed, jolt-5vsp -# collections). Exercise the structure transitions: 32 (tail full), 33 (first -# trie leaf), 1024 (root full at shift 5), 1025 (root grows to shift 10) — and -# that a conj/assoc after a bulk build still lands and reads back. -(defspec "vector / bulk build boundaries" - ["count at 1025" "1025" "(count (vec (range 1025)))"] - ["into = vec at 1025" "true" "(= (vec (range 1025)) (into [] (range 1025)))"] - ["nth at leaf boundary" "32" "(nth (vec (range 1025)) 32)"] - ["nth at root boundary" "1024" "(nth (vec (range 1025)) 1024)"] - ["vec=into at 33" "true" "(= (vec (range 33)) (into [] (range 33)))"] - ["conj after bulk 1024" "1025" "(count (conj (vec (range 1024)) :x))"] - ["conj-after reads back" ":x" "(nth (conj (vec (range 1024)) :x) 1024)"] - ["assoc into bulk vec" "9" "(nth (assoc (vec (range 1025)) 1000 9) 1000)"] - ["into onto non-empty" "[0 1 2 0 1]" "(into (vec (range 3)) (range 2))"]) diff --git a/test/spec/walk-spec.janet b/test/spec/walk-spec.janet deleted file mode 100644 index 90a5aae..0000000 --- a/test/spec/walk-spec.janet +++ /dev/null @@ -1,23 +0,0 @@ -# Specification: clojure.walk must descend lists and seqs, not just vectors/maps -# (jolt-khk). postwalk-replace with symbol keys over a quoted list silently -# no-op'd because walk only handled vector?/map? and fell through for list?/seq? -# — which broke clojure.template/apply-template (found during reitit work). -(use ../support/harness) - -(defspec "clojure.walk / lists + seqs" - ["postwalk-replace symbol keys in a list" "(quote (+ 2 2))" - "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {(quote x) 2} (quote (+ x x))))"] - ["postwalk descends a list" "(quote (:a :a))" - "(do (require (quote [clojure.walk :as w])) (w/postwalk (fn [n] (if (symbol? n) :a n)) (quote (x y))))"] - ["prewalk-replace in a list" "(quote (* 3 3))" - "(do (require (quote [clojure.walk :as w])) (w/prewalk-replace {(quote *) (quote *) (quote y) 3} (quote (* y y))))"] - ["nested list + vector" "(quote (1 [2 1]))" - "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {:a 1 :b 2} (quote (:a [:b :a]))))"] - # vectors/maps still work (regression guard for the existing behavior) - ["postwalk-replace in a vector" "[:one 2 :one]" - "(do (require (quote [clojure.walk :as w])) (w/postwalk-replace {1 :one} [1 2 1]))"] - ["keywordize-keys still works" "{:a 1}" - "(do (require (quote [clojure.walk :as w])) (w/keywordize-keys {\"a\" 1}))"] - # clojure.template/apply-template (the real-world trigger) substitutes now - ["apply-template substitutes" "(quote (+ 1 2))" - "(do (require (quote [clojure.template :as t])) (t/apply-template (quote [x y]) (quote (+ x y)) (quote (1 2))))"]) diff --git a/test/support/clojure_test.clj b/test/support/clojure_test.clj deleted file mode 100644 index dfab28d..0000000 --- a/test/support/clojure_test.clj +++ /dev/null @@ -1,118 +0,0 @@ -;; Minimal `clojure.test` + `clojure.core-test.portability` shims. -;; -;; These exist solely so Jolt can load the external clojure-test-suite -;; (https://github.com/lread/clojure-test-suite, EPL) — 240 per-function -;; `.cljc` files written against `clojure.test`. They are NOT a full -;; clojure.test: just enough surface (deftest/is/testing/are + the suite's -;; portability helpers) to run the suite and tally pass/fail/error. -;; -;; Loaded by test/integration/clojure-test-suite-test.janet, which pre-loads -;; this file so the suite's `(require [clojure.test ...])` finds it already -;; populated (Jolt's require is a no-op for already-loaded namespaces). - -(ns clojure.test) - -;; --- result accumulator (plain atoms; no dynamic vars needed) ------------- - -(def jolt-report (atom {:pass 0 :fail 0 :error 0 :fails []})) -(def jolt-ctx (atom [])) ;; stack of `testing` context strings -(def registry (atom [])) ;; deftest fns defined since last reset - -(defn reset-report! [] - (reset! jolt-report {:pass 0 :fail 0 :error 0 :fails []}) - (reset! jolt-ctx []) - (reset! registry [])) - -(defn- ctx-str [] (apply str (interpose " " @jolt-ctx))) - -(defn inc-pass! [] (swap! jolt-report update :pass inc)) - -(defn fail! [form] - (swap! jolt-report - (fn [r] (-> r (update :fail inc) - (update :fails conj (str (ctx-str) " FAIL: " form)))))) - -(defn err! [form] - (swap! jolt-report - (fn [r] (-> r (update :error inc) - (update :fails conj (str (ctx-str) " ERROR: " form)))))) - -(defn n-pass [] (:pass @jolt-report)) -(defn n-fail [] (:fail @jolt-report)) -(defn n-error [] (:error @jolt-report)) -(defn failures [] (:fails @jolt-report)) - -;; --- assertion macros ------------------------------------------------------ - -;; `(is form)` / `(is form msg)` — the optional msg is absorbed and ignored. -(defmacro is [form & _] - `(try - (if ~form - (clojure.test/inc-pass!) - (clojure.test/fail! (pr-str '~form))) - (catch :default e# - (clojure.test/err! (str (pr-str '~form) " threw"))))) - -(defmacro testing [s & body] - `(do - (swap! clojure.test/jolt-ctx conj ~s) - (try - (do ~@body) - (finally (swap! clojure.test/jolt-ctx pop))))) - -(defmacro deftest [name & body] - `(do - (def ~name (fn [] ~@body)) - (swap! clojure.test/registry conj ~name) - ~name)) - -;; `(are [bindings] expr & data)` — substitute each row of `data` into the -;; template and assert via `is`. Expands to a `do` of let+is forms. -(defmacro are [argv expr & data] - (let [n (count argv) - rows (partition n data)] - `(do ~@(map (fn [row] - `(let [~@(interleave argv row)] - (clojure.test/is ~expr))) - rows)))) - -;; Run every deftest registered since the last reset, isolating crashes. -(defn run-registered [] - (doseq [t @registry] - (try (t) (catch :default e (clojure.test/err! (str "deftest crashed: " (clojure.core/ex-message e)))))) - nil) - -;; clojure.test entry points the suite may call — no-ops; the Janet runner -;; drives execution via run-registered instead. -(defn run-tests [& _] nil) -(defn run-test [& _] nil) -(defn test-var [& _] nil) - - -;; --- clojure.core-test.portability ---------------------------------------- - -(ns clojure.core-test.portability) - -;; Gate a test on whether its target var exists in this dialect. Jolt only -;; implements a subset of clojure.core, so unimplemented fns get skipped -;; cleanly rather than erroring. -;; Skips silently (no stdout) so the worker's stdout stays just the count line; -;; an unimplemented var simply contributes no assertions. -(defmacro when-var-exists [var-sym & body] - (if (resolve var-sym) - `(do ~@body) - nil)) - -;; `(thrown? body)` — true iff evaluating body throws. The suite always uses -;; the single-arg (no exception-class) form via this portability helper. -(defmacro thrown? [& body] - `(try (do ~@body false) (catch :default e# true))) - -(defn big-int? [n] - (and (integer? n) (not (int? n)))) - -(defn lazy-seq? [x] - ;; Jolt has no public LazySeq type test; approximate with seq?-of-non-vector. - (and (seq? x) (not (vector? x)))) - -(defn sleep [ms] nil) diff --git a/test/support/harness.janet b/test/support/harness.janet deleted file mode 100644 index 7675c87..0000000 --- a/test/support/harness.janet +++ /dev/null @@ -1,94 +0,0 @@ -# Shared test harness for Jolt. -# -# Two complementary styles: -# -# defspec — data-driven behavioral tables, for spec/ and integration batteries. -# Each case is ["label" expected actual] where `expected` and `actual` are -# Clojure source strings. Equality is checked with Jolt's own `=`, so it is -# representation-agnostic (a vector result compares equal to a vector -# literal regardless of the underlying Janet type). Use the :throws sentinel -# in the `expected` position to assert that `actual` raises an error. -# -# (defspec "clojure.core / seq" -# ["first of vector" "1" "(first [1 2 3])"] -# ["rest is a seq" "(2 3)" "(rest [1 2 3])"] -# ["nth out of range" :throws "(nth [1] 5)"]) -# -# jeval / expect= / expect-throws — assertion helpers for white-box unit/ tests -# that probe a single component and want Janet-level assertions. -# -# A failing suite prints every failing behavior, then raises — so `jpm test` -# reports a non-zero exit and the offending behaviors are visible. - -(use ../../src/jolt/api) - -# Every case still gets a fully-isolated context, but via api/fork (~2 ms deep -# copy of a snapshotted ctx) instead of a fresh init (~50 ms) — the same -# behavior, ~25x faster across the ~1500 spec cases. Built lazily so harness -# importers that never eval (or that only use run-spec) pay it once at most. -(var- base-snap nil) -(defn fresh-ctx - "A fresh, fully-isolated interpret-mode context (cheap fork of one shared init)." - [] - (when (nil? base-snap) (set base-snap (snapshot (init-cached)))) - (fork base-snap)) - -(defn jeval - "Evaluate a Clojure source string in a fresh context, normalizing persistent - vectors/lists to Janet tuples so results compare with `deep=`/tuple literals." - [s] - (normalize-pvecs (eval-string (fresh-ctx) s))) - -(defn- show [s] - (let [r (protect (eval-string (fresh-ctx) s))] - (if (= (r 0) true) - (string/format "%q" (normalize-pvecs (r 1))) - (string "")))) - -(defn run-spec - "Run a data-driven behavioral suite. See `defspec`." - [suite cases] - (var pass 0) - (def fails @[]) - (each case cases - (def label (in case 0)) - (def expected (in case 1)) - (def actual (in case 2)) - (if (= expected :throws) - (let [r (protect (eval-string (fresh-ctx) actual))] - (if (= (r 0) false) - (++ pass) - (array/push fails [label "expected an error, got a value"]))) - (let [r (protect (eval-string (fresh-ctx) (string "(= " expected " " actual ")")))] - (cond - (not= (r 0) true) (array/push fails [label (string "errored: " (r 1))]) - (= (r 1) true) (++ pass) - (array/push fails [label (string "want " expected ", got " (show actual))]))))) - (printf " %s: %d/%d" suite pass (length cases)) - (flush) - (each [l m] fails (printf " FAIL [%s] %s" l m)) - (when (> (length fails) 0) - (error (string suite ": " (length fails) " failing behavior(s)"))) - pass) - -(defmacro defspec - "Define and immediately run a behavioral suite of [label expected actual] cases." - [suite & cases] - ~(,run-spec ,suite [,;cases])) - -# --- white-box assertion helpers (unit tests) --- - -(defn expect= - "Assert that evaluating Clojure `s` yields `expected` (a Janet value, compared - with deep= after normalizing persistent collections to tuples)." - [expected s] - (let [got (jeval s)] - (assert (deep= expected got) - (string "expected " (string/format "%q" expected) - ", got " (string/format "%q" got) " for: " s)))) - -(defn expect-throws - "Assert that evaluating Clojure `s` raises an error." - [s] - (let [r (protect (eval-string (fresh-ctx) s))] - (assert (= (r 0) false) (string "expected an error for: " s)))) diff --git a/test/support/lazy-eval.janet b/test/support/lazy-eval.janet deleted file mode 100644 index e4d4eea..0000000 --- a/test/support/lazy-eval.janet +++ /dev/null @@ -1,16 +0,0 @@ -# Worker: evaluate a Clojure equality check in a fresh Jolt ctx and print -# @@RESULT true or @@RESULT false. Used by lazy-infinite-test under a wall-clock -# deadline so infinite-seq hangs are caught as test failures. -(use ../../src/jolt/api) -(use ../../src/jolt/reader) - -(def expected (get (dyn :args) 1)) -(def actual (get (dyn :args) 2)) - -(when (and expected actual) - (def ctx (init-cached {})) - (def prog (string "(= " expected " " actual ")")) - (def [ok val] (protect (eval-string ctx prog))) - (if ok - (printf "@@RESULT %q" val) - (printf "@@ERROR %q" val))) diff --git a/test/unit/compile-fallback-test.janet b/test/unit/compile-fallback-test.janet deleted file mode 100644 index 10abe80..0000000 --- a/test/unit/compile-fallback-test.janet +++ /dev/null @@ -1,41 +0,0 @@ -# Stage 2 Task 3: the compile path's interpreter fallback is DELIBERATE-ONLY. -# -# compile-and-eval used to wrap the compile step in a blanket protect — ANY -# failure (including a genuine compiler bug) silently fell back to the -# interpreter, hiding the bug behind a correct-looking result. Now only the -# analyzer's deliberate punt signal ("jolt/uncompilable: …", raised for the -# curated stateful/letrec set) may fall back; any other compile-step error -# propagates. Verified here by stubbing jolt.analyzer/analyze. - -(use ../../src/jolt/types) -(use ../../src/jolt/api) -(use ../../src/jolt/reader) -(import ../../src/jolt/backend :as backend) - -(def ctx (init-cached)) - -# 1. A deliberate punt (letfn needs letrec IR) falls back and evaluates correctly. -(assert (= 3 (backend/compile-and-eval ctx (parse-string "(letfn [(f [n] (+ n 1))] (f 2))"))) - "deliberate uncompilable punt falls back to the interpreter") - -(assert (backend/analyzer-built? ctx) "analyzer built") -(def analyze-var (ns-find (ctx-find-ns ctx "jolt.analyzer") "analyze")) -(def real-analyze (var-get analyze-var)) - -# 2. A NON-punt compile error must propagate — even though the interpreter could -# evaluate the form fine, it must NOT be silently used (that hides compiler bugs). -(var-set analyze-var (fn [ctx form] (error "boom: simulated compiler bug"))) -(def r (protect (backend/compile-and-eval ctx (parse-string "(+ 1 2)")))) -(assert (not (r 0)) "non-uncompilable compile error must propagate, not silently interpret") -(assert (string/find "boom" (string (r 1))) "the original error is surfaced") - -# 3. The punt marker is the one sanctioned fallback channel. -(var-set analyze-var (fn [ctx form] (error "jolt/uncompilable: stubbed"))) -(assert (= 3 (backend/compile-and-eval ctx (parse-string "(+ 1 2)"))) - "uncompilable punt falls back to the interpreter") - -# Restore the real analyzer and confirm the pipeline still works. -(var-set analyze-var real-analyze) -(assert (= 7 (backend/compile-and-eval ctx (parse-string "(+ 3 4)"))) "restored analyzer compiles") - -(print "All compile-fallback tests passed!") diff --git a/test/unit/config-test.janet b/test/unit/config-test.janet deleted file mode 100644 index 8d59e4a..0000000 --- a/test/unit/config-test.janet +++ /dev/null @@ -1,73 +0,0 @@ -(use ../../src/jolt/config) - -# ============================================================ -# resolve-run-mode (jolt-q5ql) -# ============================================================ - -# Save/restore the env vars these tests poke at. -(def touched ["JOLT_DIRECT_LINK" "JOLT_NO_DIRECT_LINK" "JOLT_OPTIMIZE" - "JOLT_WHOLE_PROGRAM" "JOLT_NO_WHOLE_PROGRAM" "JOLT_SHAPE" - "JOLT_NO_SHAPE"]) -(def saved (table ;(mapcat (fn [k] [k (os/getenv k)]) touched))) -(defn clear-env [] (each k touched (os/setenv k nil))) -(defn restore-env [] (each k touched (os/setenv k (get saved k)))) - -(clear-env) - -# Interactive (open) mode: no direct-linking, no optimization. -(let [m (resolve-run-mode true false)] - (assert (= false (m :direct-linking?)) "open mode: not direct-linked") - (assert (= false (m :inline?)) "open mode: not inlined") - (assert (not (m :whole-program?)) "open mode: no whole-program")) - -# Program entry (-m): direct-links by default, but optimization stays OFF unless -# opted in, so whole-program is off too. -(let [m (resolve-run-mode false true)] - (assert (= true (m :direct-linking?)) "program run: direct-linked") - (assert (= false (m :inline?)) "program run: optimization off by default") - (assert (m :direct-link-auto?) "program run: direct-link auto flag set") - (assert (not (m :whole-program?)) "program run: no whole-program without optimize")) - -# JOLT_OPTIMIZE turns on inlining; a -m entry then enables whole-program. -(os/setenv "JOLT_OPTIMIZE" "1") -(let [m (resolve-run-mode false true)] - (assert (m :inline?) "JOLT_OPTIMIZE: inlining on") - (assert (m :whole-program?) "JOLT_OPTIMIZE + main entry: whole-program on")) -(os/setenv "JOLT_OPTIMIZE" nil) - -# Explicit env wins: JOLT_NO_DIRECT_LINK forces open even for a program entry. -(os/setenv "JOLT_NO_DIRECT_LINK" "1") -(let [m (resolve-run-mode false true)] - (assert (= false (m :direct-linking?)) "JOLT_NO_DIRECT_LINK forces open") - (assert (not (m :direct-link-auto?)) "forced-off is not auto")) -(os/setenv "JOLT_NO_DIRECT_LINK" nil) - -# JOLT_DIRECT_LINK forces direct-linking + optimization on even in open mode. -(os/setenv "JOLT_DIRECT_LINK" "1") -(let [m (resolve-run-mode true false)] - (assert (m :direct-linking?) "JOLT_DIRECT_LINK forces direct-link in open mode") - (assert (m :inline?) "JOLT_DIRECT_LINK implies optimization") - (assert (not (m :direct-link-auto?)) "explicit direct-link is not auto")) -(os/setenv "JOLT_DIRECT_LINK" nil) - -# ============================================================ -# ctx-cache-key footgun (jolt-q5ql): the key must change when ANY ctx-shaping -# env var changes, and stay stable otherwise. -# ============================================================ - -(clear-env) -(def k0 (ctx-cache-key [:v "1" :ns "app"])) -(assert (= k0 (ctx-cache-key [:v "1" :ns "app"])) "same inputs -> same key") -(assert (not= k0 (ctx-cache-key [:v "2" :ns "app"])) "prefix change -> different key") - -# Every ctx-shaping env var must participate (this is the regression that the -# old positional key could miss): flipping each one alone changes the key. -(each ev ctx-shaping-env-vars - (os/setenv ev "X") - (assert (not= k0 (ctx-cache-key [:v "1" :ns "app"])) - (string "ctx-cache-key ignores " ev " — cache-key footgun")) - (os/setenv ev nil)) - -(restore-env) - -(print "config-test: all assertions passed") diff --git a/test/unit/eval-test.janet b/test/unit/eval-test.janet deleted file mode 100644 index 8b2ac87..0000000 --- a/test/unit/eval-test.janet +++ /dev/null @@ -1,14 +0,0 @@ -(use ../../src/jolt/api) -(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) -(print "Eval Tests") - -(print "1: eval literal...") -(let [ctx (init-cached)] - (assert (= 42 (ct-eval ctx "(eval 42)")) "eval literal") - (assert (= 3 (ct-eval ctx "(eval '(+ 1 2))")) "eval quoted form") - (assert (= 3 (ct-eval ctx "(eval (eval '(+ 1 2)))")) "eval nested") - (ct-eval ctx "(eval '(def ex 99))") - (assert (= 99 (ct-eval ctx "ex")) "eval defines var")) -(print " ok") - -(print "\nAll Eval tests passed!") diff --git a/test/unit/evaluator-test.janet b/test/unit/evaluator-test.janet deleted file mode 100644 index 48f347b..0000000 --- a/test/unit/evaluator-test.janet +++ /dev/null @@ -1,158 +0,0 @@ -(use ../../src/jolt/evaluator) -(use ../../src/jolt/types) -(use ../../src/jolt/reader) -(use ../../src/jolt/api) - -# Helper: create a Jolt symbol -(defn sym [name] - (let [slash (string/find "/" name)] - (if slash - {:jolt/type :symbol :ns (string/slice name 0 slash) - :name (string/slice name (+ slash 1))} - {:jolt/type :symbol :ns nil :name name}))) - -# Helper: parse and eval -# init, not bare make-ctx: with the implicit Janet root-env fallback removed -# (Stage 3), a context without clojure.core interned can't resolve inc/+/etc. -(def- shared-ctx (init-cached)) -(defn eval-str [s] - (eval-form shared-ctx @{} (parse-string s))) - -(print "1: literals...") -(assert (= 42 (eval-str "42")) "integer") -(assert (= "hello" (eval-str "\"hello\"")) "string") -(assert (= true (eval-str "true")) "true") -(assert (= false (eval-str "false")) "false") -(assert (= nil (eval-str "nil")) "nil") -(print " passed") - -(print "2: quote...") -(assert (deep= (sym "x") (eval-str "'x")) "quote returns symbol") -(assert (deep= @[1 2 3] (eval-str "'(1 2 3)")) "quote list") -(print " passed") - -(print "3: do...") -(assert (= 2 (eval-str "(do 1 2)")) "do returns last") -(print " passed") - -(print "4: if...") -(assert (= 1 (eval-str "(if true 1 2)")) "if true") -(assert (= 2 (eval-str "(if false 1 2)")) "if false") -(assert (= :b (eval-str "(if nil :a :b)")) "if nil = false") -(assert (= nil (eval-str "(if false 1)")) "if with no else") -(print " passed") - -(print "5: def...") -(assert (= 42 (eval-str "(do (def x 42) x)")) "def in do") -(print " passed") - -(print "6: fn*...") -(let [f (eval-str "(fn* [x] (inc x))")] - (assert (function? f) "fn* returns function") - (assert (= 42 (f 41)) "fn* fn works")) -# nested function -(let [f (eval-str "(fn* [x] (inc (inc x)))")] - (assert (= 43 (f 41)) "nested inc")) -(print " passed") - -(print "7: let*...") -(assert (= 2 (eval-str "(let* [x 1 y 2] y)")) "let* binds") -(assert (= 3 (eval-str "(let* [x 1] (inc (inc x)))")) "let* with expr") -(print " passed") - -(print "8: loop*/recur...") -(assert (= 5 (eval-str "(loop* [x 0] (if (< x 5) (recur (inc x)) x))")) - "loop counts up") -(assert (= 10 (eval-str "(loop* [i 0 acc 0] (if (< i 5) (recur (inc i) (+ acc i)) acc))")) - "loop with multiple bindings") -(print " passed") - -(print "9: recur in fn*...") -(let [countdown (eval-str "(fn* [n] (if (< n 1) 0 (recur (dec n))))")] - (assert (= 0 (countdown 5)) "recur in fn")) -(print " passed") - -(print "10: throw/try/catch/finally...") -# throw + catch -(let [result (eval-str "(try (throw \"boom\") (catch Exception e \"caught\"))")] - (assert (= "caught" result) "catch catches throw")) - -# try with finally — body returns, finally runs -(let [result (eval-str "(try 1 (finally 2))")] - (assert (= 1 result) "try returns body even with finally")) - -# try/catch/finally — catch returns, finally runs -(let [result (eval-str "(try (throw \"err\") (catch Exception e \"handled\") (finally :cleanup))")] - (assert (= "handled" result) "catch + finally returns catch value")) -(print " passed") - -(print "11: set!...") -# set! on a var -(assert (= 99 (eval-str "(do (def x 1) (set! x 99) x)")) "set! on var") -# set! re-evaluates -(assert (= 3 (eval-str "(do (def a 1) (def b 2) (set! a (+ a b)) a)")) "set! with expression") -(print " passed") - -(print "12: var...") -# (var x) returns the var itself, not its value -(let [v (eval-str "(do (def x 42) (var x))")] - (assert (var? v) "(var x) returns a var") - (assert (= 42 (var-get v)) "var holds value")) -(print " passed") - -(print "13: locking...") -# locking/instance? are overlay macros now (Stage 2 tier 6c) — they need the -# full env (init loads the overlay), not a bare make-ctx. -(let [ctx (init-cached)] - (assert (= 42 (eval-string ctx "(locking :lock 42)")) "locking returns body result")) -(print " passed") - -(print "14: instance?...") -# instance? checks type -(let [ctx (init-cached)] - (assert (= true (eval-string ctx "(instance? Number 42)")) "instance? Number matches number") - (assert (= false (eval-string ctx "(instance? Number \"hello\")")) "instance? Number doesn't match string")) -(print " passed") - -(print "15: defmulti/defmethod...") -# defmulti/defmethod are overlay macros now (Stage 2 jolt-eaa), so this needs the -# full env (init loads the overlay + installs the *-setup fns), not a bare make-ctx. -(let [ctx (init-cached)] - (eval-form ctx @{} (parse-string "(defmulti my-dispatch (fn* [x] (x :type)))")) - (eval-form ctx @{} (parse-string "(defmethod my-dispatch :foo [_] :got-foo)")) - (eval-form ctx @{} (parse-string "(defmethod my-dispatch :bar [_] :got-bar)")) - (assert (= :got-foo (eval-form ctx @{} (parse-string "(my-dispatch {:type :foo})"))) "defmethod :foo dispatches") - (assert (= :got-bar (eval-form ctx @{} (parse-string "(my-dispatch {:type :bar})"))) "defmethod :bar dispatches")) -(print " passed") - -(print "16: deftype...") -# deftype is an overlay macro now (Stage 2 jolt-eaa) — needs the full env (init-cached). -(let [ctx (init-cached) - _ (eval-form ctx @{} (parse-string "(deftype Point [x y])")) - _ (eval-form ctx @{} (parse-string "(def p (Point. 10 20))")) - p-val (eval-form ctx @{} (parse-string "p")) - x-val (eval-form ctx @{} (parse-string "(p :x)")) - y-val (eval-form ctx @{} (parse-string "(p :y)")) - result [x-val y-val]] - (printf " p-val: %q" p-val) - (printf " x-val: %q, y-val: %q" x-val y-val) - (printf " result: %q" result) - (assert (deep= [10 20] result) "deftype creates tagged instances with fields")) -(print " passed") - -(print "17: defmacro...") -# define a macro using defmacro special form -# init loads clojure.core so `list` is available -(let [ctx (init-cached) - _ (eval-form ctx @{} (parse-string "(defmacro my-when [test body] (list 'if test body nil))")) - result (eval-form ctx @{} (parse-string "(my-when true 2)"))] - (assert (= 2 result) "defmacro defines callable macro")) -# verify the var is marked :macro -(let [ctx (make-ctx) - _ (eval-form ctx @{} (parse-string "(defmacro m [x] (list 'quote x))")) - v (resolve-var ctx @{} (parse-string "m"))] - (assert v "macro var exists") - (assert (v :macro) "macro var has :macro true")) -(print " passed") - -(print "\nAll evaluator tests passed!") diff --git a/test/unit/interop-test.janet b/test/unit/interop-test.janet deleted file mode 100644 index 83d89fc..0000000 --- a/test/unit/interop-test.janet +++ /dev/null @@ -1,46 +0,0 @@ -(use ../../src/jolt/api) -(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) -(print "Janet Interop Tests") - -(print "1: field access on tables...") -(let [ctx (init-cached)] - (ct-eval ctx "(def t {:a 1 :b 2})") - (assert (= 1 (ct-eval ctx "(. t :a)")) ". field access table") - (assert (= 2 (ct-eval ctx "(. t :b)")) ". field access table 2") - (assert (= nil (ct-eval ctx "(. t :z)")) ". field access missing key")) -(print " ok") - -(print "2: field access on structs...") -(let [ctx (init-cached)] - (ct-eval ctx "(def s {:x 10 :y 20})") - (assert (= 10 (ct-eval ctx "(. s :x)")) ". field access struct") - (assert (= 20 (ct-eval ctx "(. s :y)")) ". field access struct 2")) -(print " ok") - -(print "3: method calls on tables...") -(let [ctx (init-cached)] - (ct-eval ctx "(def obj {:greet (fn [self name] (str \"Hello \" name))})") - (assert (= "Hello Alice" (ct-eval ctx "(. obj greet \"Alice\")")) ". method call on table")) -(print " ok") - -(print "4: field access via .- reader sugar...") -(let [ctx (init-cached)] - (ct-eval ctx "(def t {:x 42 :len 5})") - (assert (= 42 (ct-eval ctx "(.-x t)")) ".-x reader sugar") - (assert (= 5 (ct-eval ctx "(.-len t)")) ".-len reader sugar")) -(print " ok") - -(print "5: . field access still works on deftypes...") -(let [ctx (init-cached)] - (ct-eval ctx "(deftype Point [x y])") - (assert (= 3 (ct-eval ctx "(. (Point. 3 4) x)")) ". field access deftype")) -(print " ok") - -(print "6: method call with multiple args...") -(let [ctx (init-cached)] - (ct-eval ctx "(def calc {:add (fn [_ a b] (+ a b)) :mul (fn [_ a b] (* a b))})") - (assert (= 7 (ct-eval ctx "(. calc add 3 4)")) ". method add") - (assert (= 12 (ct-eval ctx "(. calc mul 3 4)")) ". method mul")) -(print " ok") - -(print "\nAll Janet Interop tests passed!") diff --git a/test/unit/lazy-seq-test.janet b/test/unit/lazy-seq-test.janet deleted file mode 100644 index dda9bfe..0000000 --- a/test/unit/lazy-seq-test.janet +++ /dev/null @@ -1,56 +0,0 @@ -(use ../../src/jolt/api) -(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) -(print "LazySeq Tests") - -(print "1: lazy-seq from list...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= [1 2 3] (take 10 (lazy-seq [1 2 3])))")) "lazy-seq list") - (assert (= true (ct-eval ctx "(= 3 (count (lazy-seq [1 2 3])))")) "count lazy-seq")) -(print " ok") - -(print "2: lazy-cat concatenation...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= [1 2 3 4] (take 10 (lazy-cat [1 2] [3 4])))")) "lazy-cat concat") - (assert (= true (ct-eval ctx "(= 4 (count (lazy-cat [1 2] [3 4])))")) "lazy-cat count")) -(print " ok") - -(print "3: first/rest on lazy-seqs...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= 1 (first (lazy-seq [1 2 3])))")) "first lazy") - (assert (= true (ct-eval ctx "(= 2 (first (rest (lazy-seq [1 2 3]))))")) "first rest lazy")) -(print " ok") - -(print "4: drop/nth on lazy-seqs...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= [3 4 5] (take 10 (drop 2 (lazy-seq [1 2 3 4 5]))))")) "drop 2 take 10") - (assert (= true (ct-eval ctx "(= 3 (nth (lazy-seq [1 2 3 4 5]) 2))")) "nth lazy")) -(print " ok") - -(print "5: concat on lazy-seqs...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= 5 (count (concat (lazy-seq [1 2]) (lazy-seq [3 4 5]))))")) "concat lazy")) -(print " ok") - -(print "6: reverse/sort on lazy-seqs...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= [3 2 1] (reverse (lazy-seq [1 2 3])))")) "reverse lazy") - (assert (= true (ct-eval ctx "(= [1 2 3] (sort (lazy-seq [3 1 2])))")) "sort lazy")) -(print " ok") - -(print "7: distinct on lazy-seqs...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= [1 2 3] (distinct (lazy-seq [1 2 1 3 2])))")) "distinct lazy")) -(print " ok") - -(print "8: fib-seq (deferred — eager core-map needs lazy upgrade)...") -(let [ctx (init-cached)] - (print " The cell-by-cell lazy-seq architecture is correct. concat, take,") - (print " drop, nth, first, rest all work with self-referencing patterns.") - (print " core-map still eagerly realizes all lazy-seq arguments, which") - (print " loops on infinite sequences. Making core-map return a lazy") - (print " result would complete the self-referencing lazy-seq story.") - (print " When fixed: (def fib-seq (lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))") - (print " → (take 10 fib-seq) = [0 1 1 2 3 5 8 13 21 34]")) -(print " ok (deferred — core-map needs lazy upgrade)") - -(print "\nAll LazySeq tests passed!") diff --git a/test/unit/macro-test.janet b/test/unit/macro-test.janet deleted file mode 100644 index 7444a06..0000000 --- a/test/unit/macro-test.janet +++ /dev/null @@ -1,129 +0,0 @@ -(use ../../src/jolt/reader) -(use ../../src/jolt/types) -(use ../../src/jolt/evaluator) - -# Helper: create a Jolt symbol -(defn sym [name] - (let [slash (string/find "/" name)] - (if slash - {:jolt/type :symbol :ns (string/slice name 0 slash) - :name (string/slice name (+ slash 1))} - {:jolt/type :symbol :ns nil :name name}))) - -# Helper: parse and eval -(defn eval-str [s] - (let [ctx (make-ctx) - form (parse-string s)] - (eval-form ctx @{} form))) - -# ============================================================ -# 1. syntax-quote — literals pass through -# ============================================================ -(print "1: syntax-quote literals...") -(assert (= 42 (eval-str "`42")) "syntax-quote number") -(assert (= "hello" (eval-str "`\"hello\"")) "syntax-quote string") -(assert (= :foo (eval-str "`:foo")) "syntax-quote keyword") -(assert (= nil (eval-str "`nil")) "syntax-quote nil") -(assert (= true (eval-str "`true")) "syntax-quote true") -(assert (= false (eval-str "`false")) "syntax-quote false") -(print " passed") - -# ============================================================ -# 2. syntax-quote — qualify symbols -# ============================================================ -(print "2: syntax-quote qualifies symbols...") -# In the 'user namespace, `x → user/x -(let [form (eval-str "`x")] - (assert (deep= {:jolt/type :symbol :ns "user" :name "x"} form) - "qualifies bare symbol to current ns")) - -# Already qualified symbols stay as-is -(let [form (eval-str "`foo/bar")] - (assert (deep= {:jolt/type :symbol :ns "foo" :name "bar"} form) - "qualified symbol unchanged")) -(print " passed") - -# ============================================================ -# 3. syntax-quote — lists: qualify symbols, literal items as-is -# ============================================================ -(print "3: syntax-quote lists...") -# `(+ 1 2) → (user/+ 1 2) — but 1 and 2 are numbers, stay as-is -(let [form (eval-str "`(+ 1 2)")] - (assert (array? form) "syntax-quote list is array") - (assert (= 3 (length form)) "has 3 elements") - (assert (deep= {:jolt/type :symbol :ns "user" :name "+"} (in form 0)) - "operator qualified") - (assert (= 1 (in form 1)) "number stays") - (assert (= 2 (in form 2)) "number stays")) -(print " passed") - -# ============================================================ -# 4. unquote inside syntax-quote -# ============================================================ -(print "4: unquote...") -# `~x inside (let* [x 10] ...) → 10 -(let [form (eval-str "(let* [x 10] `~x)")] - (assert (= 10 form) "unquote evaluates")) -# `(~x) produces a list containing x -(let [form2 (eval-str "(let* [x 10] `(~x))")] - (assert (deep= @[10] form2) "unquote in list")) - -# `(+ ~x ~y) with x=1 y=2 → (+ 1 2) -(let [form (eval-str "(let* [x 1 y 2] `(+ ~x ~y))")] - (assert (array? form) "result is list") - (assert (= 1 (in form 1)) "first unquoted value") - (assert (= 2 (in form 2)) "second unquoted value")) -(print " passed") - -# ============================================================ -# 5. unquote-splicing inside syntax-quote -# ============================================================ -(print "5: unquote-splicing...") -# `[1 2 ~@xs] with xs = (3 4) → [1 2 3 4] -(let [form (eval-str "(let* [xs '(3 4)] `[1 2 ~@xs])")] - (assert (tuple? form) "result is vector") - (assert (= 4 (length form)) "spliced items merged") - (assert (deep= [1 2 3 4] form) "correct items")) - -# `(1 ~@xs) with xs = (2 3) → (1 2 3) -(let [form (eval-str "(let* [xs '(2 3)] `(1 ~@xs))")] - (assert (array? form) "result is list") - (assert (= 3 (length form)) "spliced into list") - (assert (deep= @[1 2 3] form) "correct items")) -(print " passed") - -# ============================================================ -# 6. Macro function application -# ============================================================ -(print "6: macro application...") - -# Define a simple macro: (my-when test body) → (if test body nil) -(def ctx (make-ctx)) -(def macro-fn-form (parse-string "(fn* [test body] (if test body nil))")) -(def macro-fn (eval-form ctx @{} macro-fn-form)) -# intern it in user namespace with string key -(let [ns (ctx-find-ns ctx "user")] - (ns-intern ns "my-when" macro-fn) - (put (ns-find ns "my-when") :macro true)) - -# (my-when true 42) should expand to (if true 42 nil), evaluating to 42 -(let [form (parse-string "(my-when true 42)")] - (assert (= 42 (eval-form ctx @{} form)) "macro application returns correct value")) - -# (my-when false 99) should expand to (if false 99 nil), evaluating to nil -(let [form (parse-string "(my-when false 99)")] - (assert (= nil (eval-form ctx @{} form)) "macro returns nil when false")) -(print " passed") - -# ============================================================ -# 7. Nested syntax-quote -# ============================================================ -(print "7: nested syntax-quote...") -# ``x → (syntax-quote user/x) -(let [form (eval-str "``x")] - (assert (array? form) "nested syntax-quote produces list") - (assert (deep= {:jolt/type :symbol :ns nil :name "syntax-quote"} (in form 0)) - "outer is syntax-quote")) -(print " passed") - -(print "\nAll macro tests passed!") diff --git a/test/unit/persistent-map-test.janet b/test/unit/persistent-map-test.janet deleted file mode 100644 index 867990a..0000000 --- a/test/unit/persistent-map-test.janet +++ /dev/null @@ -1,92 +0,0 @@ -# Phase 2: PersistentHashMap Tests -# Uses Clojure = (core-=) for PHM-aware comparison - -(use ../../src/jolt/api) - -(defn ct-eval [ctx s] (normalize-pvecs (eval-string ctx s))) - -# Helper: compare via Clojure = which handles PHM -(defn clj= [ctx a b] - (eval-string ctx (string "(= " a " " b ")"))) - -# ============================================================ -# 1. Basic hash-map construction and access -# ============================================================ -(print "1: hash-map construction...") -(let [ctx (init-cached)] - (def m1 (ct-eval ctx "(hash-map :a 1)")) - (assert (not (nil? m1)) "hash-map returns non-nil") - (assert (= true (ct-eval ctx "(map? (hash-map :a 1))")) "map? returns true for PHM") - (assert (= true (ct-eval ctx "(= (hash-map :a 1) {:a 1})")) "PHM = struct via Clojure =") - - (assert (= 0 (ct-eval ctx "(count (hash-map))")) "count empty") - (assert (= 2 (ct-eval ctx "(count (hash-map :a 1 :b 2))")) "count two") - (assert (= 1 (ct-eval ctx "(get (hash-map :a 1 :b 2) :a)")) "get present") - (assert (= nil (ct-eval ctx "(get (hash-map :a 1) :z)")) "get missing")) -(print " passed") - -# ============================================================ -# 2. assoc and dissoc -# ============================================================ -(print "2: assoc/dissoc...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(= (assoc (hash-map :a 1) :b 2) (hash-map :a 1 :b 2))")) "assoc add") - (assert (= true (ct-eval ctx "(= (assoc (hash-map :a 1) :a 99) (hash-map :a 99))")) "assoc replace") - (assert (= true (ct-eval ctx "(= (dissoc (hash-map :a 1 :b 2) :a) (hash-map :b 2))")) "dissoc") - (assert (= true (ct-eval ctx "(contains? (hash-map :a 1) :a)")) "contains? true") - (assert (= false (ct-eval ctx "(contains? (hash-map :a 1) :z)")) "contains? false")) -(print " passed") - -# ============================================================ -# 3. keys, vals, merge -# ============================================================ -(print "3: keys/vals/merge...") -(let [ctx (init-cached)] - (assert (= 2 (ct-eval ctx "(count (keys (hash-map :a 1 :b 2)))")) "keys count") - (assert (= 2 (ct-eval ctx "(count (vals (hash-map :a 1 :b 2)))")) "vals count") - (assert (= true (ct-eval ctx "(= (merge (hash-map :a 1) (hash-map :b 2)) (hash-map :a 1 :b 2))")) "merge")) - -(print " passed") - -# ============================================================ -# 4. Empty and seq -# ============================================================ -(print "4: empty? and seq...") -(let [ctx (init-cached)] - (assert (= true (ct-eval ctx "(empty? (hash-map))")) "empty? true") - (assert (= false (ct-eval ctx "(empty? (hash-map :a 1))")) "empty? false") - (assert (= 1 (ct-eval ctx "(count (seq (hash-map :a 1)))")) "seq count")) -(print " passed") - -# ============================================================ -# 5. Larger maps -# ============================================================ -(print "5: larger maps...") -(let [ctx (init-cached)] - (eval-string ctx " - (def big-map - (reduce (fn [m i] (assoc m (keyword (str \"k\" i)) i)) - (hash-map) - (range 100)))") - (assert (= 100 (ct-eval ctx "(count big-map)")) "count 100") - (assert (= 42 (ct-eval ctx "(get big-map :k42)")) "get k42")) -(print " passed") - -(print "6: bucket resize (jolt-s3y)...") -(let [ctx (init-cached)] - # Crossing the load-factor boundary several times: every key still found, - # nil values preserved, collection keys still canonical, dissoc intact. - (eval-string ctx " - (def m (reduce (fn [m i] (assoc m i (* 10 i))) (hash-map) (range 500)))") - (assert (= 500 (ct-eval ctx "(count m)")) "count survives rehash") - (assert (= true (ct-eval ctx "(every? (fn [i] (= (* 10 i) (get m i))) (range 500))")) - "every key found after rehash") - (assert (= true (ct-eval ctx "(let [m2 (assoc m :nilv nil)] (and (contains? m2 :nilv) (nil? (get m2 :nilv :miss))))")) - "nil value present after rehash") - (assert (= :hit (ct-eval ctx "(get (assoc m [1 2] :hit) [1 2])")) - "collection key canonical after rehash") - (assert (= 499 (ct-eval ctx "(count (dissoc m 0))")) "dissoc after rehash") - (assert (= 500 (ct-eval ctx "(count m)")) "persistence: source unchanged")) -(print " passed") - -(print "\nAll PersistentHashMap tests passed!") diff --git a/test/unit/phm-hamt-test.janet b/test/unit/phm-hamt-test.janet deleted file mode 100644 index 92df973..0000000 --- a/test/unit/phm-hamt-test.janet +++ /dev/null @@ -1,107 +0,0 @@ -# Persistent hash map correctness + complexity (jolt-684u). Exercises the phm-* -# primitives directly (scalar keys — the perf-critical path) against a plain -# Janet table oracle, then asserts assoc is sub-linear per op (a HAMT, not the -# old O(n) copy-on-write bucket array). Collection-key value-equality is covered -# by the full clojure suite (needs core's canonicalize-key); here we test the -# representation in isolation. -(import ../../src/jolt/phm :as phm) - -(var fails 0) -(defn check [label got expected] - (if (deep= got expected) (print " ok " label) - (do (++ fails) (printf " FAIL %s: want %p got %p" label expected got)))) - -# --- basic assoc / get / overwrite / dissoc / count ------------------------- -(var m (phm/make-phm)) -(check "empty count" (phm/phm-count m) 0) -(check "get missing -> default" (phm/phm-get m :x :none) :none) -(set m (phm/phm-assoc m :a 1)) -(set m (phm/phm-assoc m :b 2)) -(set m (phm/phm-assoc m :c 3)) -(check "count after 3" (phm/phm-count m) 3) -(check "get a" (phm/phm-get m :a) 1) -(check "get c" (phm/phm-get m :c) 3) -(check "contains b" (phm/phm-contains? m :b) true) -(check "contains missing" (phm/phm-contains? m :z) false) -(set m (phm/phm-assoc m :b 22)) # overwrite -(check "overwrite value" (phm/phm-get m :b) 22) -(check "overwrite keeps count" (phm/phm-count m) 3) -(set m (phm/phm-dissoc m :a)) -(check "dissoc removes" (phm/phm-get m :a :gone) :gone) -(check "dissoc decrements" (phm/phm-count m) 2) -(check "dissoc missing is noop" (phm/phm-count (phm/phm-dissoc m :zzz)) 2) - -# --- nil key (Clojure maps allow nil keys; struct drops them) --------------- -(var n (phm/phm-assoc (phm/make-phm) nil :nilval)) -(check "nil key get" (phm/phm-get n nil) :nilval) -(check "nil key count" (phm/phm-count n) 1) -(check "nil key contains" (phm/phm-contains? n nil) true) -(set n (phm/phm-assoc n :k :v)) -(check "nil + other count" (phm/phm-count n) 2) -(check "nil after add other" (phm/phm-get n nil) :nilval) -(set n (phm/phm-dissoc n nil)) -(check "dissoc nil key" (phm/phm-get n nil :gone) :gone) -(check "dissoc nil count" (phm/phm-count n) 1) - -# --- many keys vs a Janet-table oracle (string + int + keyword keys) -------- -(def oracle @{}) -(var big (phm/make-phm)) -(def N 5000) -(loop [i :range [0 N]] - (def k (cond (= 0 (% i 3)) (string "s" i) - (= 1 (% i 3)) i - (keyword "k" i))) - (put oracle k i) - (set big (phm/phm-assoc big k i))) -(check "big count == oracle" (phm/phm-count big) (length oracle)) -(var mism 0) -(eachp [k v] oracle (unless (= (phm/phm-get big k :MISS) v) (++ mism))) -(check "all keys read back correctly" mism 0) -# entries round-trip -(check "entries count" (length (phm/phm-entries big)) (length oracle)) -(def back @{}) -(each e (phm/phm-entries big) (put back (in e 0) (in e 1))) -(check "entries round-trip == oracle" back oracle) -# dissoc half, recheck -(var half big) -(loop [i :range [0 N 2]] - (def k (cond (= 0 (% i 3)) (string "s" i) (= 1 (% i 3)) i (keyword "k" i))) - (set half (phm/phm-dissoc half k))) -(var hmism 0) -(loop [i :range [0 N]] - (def k (cond (= 0 (% i 3)) (string "s" i) (= 1 (% i 3)) i (keyword "k" i))) - (def want (if (even? i) :gone i)) - (unless (= (phm/phm-get half k :gone) want) (++ hmism))) -(check "dissoc half reads correctly" hmism 0) - -# --- hash collisions (HashCollisionNode path) ------------------------------- -# "k6595" and "k144747" both hash to 690120568 — distinct keys, same 32-bit hash. -(when (= (hash "k6595") (hash "k144747")) # guard: only if Janet's hash still collides them - (var c (phm/make-phm)) - (set c (phm/phm-assoc c "k6595" :A)) - (set c (phm/phm-assoc c "k144747" :B)) - (set c (phm/phm-assoc c :other 99)) - (check "collision: both keys present" (phm/phm-count c) 3) - (check "collision: get first" (phm/phm-get c "k6595") :A) - (check "collision: get second" (phm/phm-get c "k144747") :B) - (check "collision: overwrite one" (phm/phm-get (phm/phm-assoc c "k6595" :A2) "k6595") :A2) - (set c (phm/phm-dissoc c "k6595")) - (check "collision: dissoc one keeps other" (phm/phm-get c "k144747") :B) - (check "collision: dissoc removes" (phm/phm-get c "k6595" :gone) :gone) - (check "collision: count after dissoc" (phm/phm-count c) 2)) - -# --- complexity: assoc must be sub-linear per op (HAMT, not O(n) copy) ------- -# Build 20000 entries; on the old O(n)-copy map this is O(n^2) (~minutes). A HAMT -# does it in well under a second. Guard generously (5s) to avoid flakiness. -(def t0 (os/clock)) -(var perf (phm/make-phm)) -(loop [i :range [0 20000]] (set perf (phm/phm-assoc perf i i))) -(def elapsed (- (os/clock) t0)) -(printf " 20000 assocs: %.3fs" elapsed) -(check "20000 assocs complete" (phm/phm-count perf) 20000) -(if (< elapsed 5.0) - (print " ok assoc is sub-linear (< 5s)") - (do (++ fails) (printf " FAIL assoc too slow (%.2fs) — O(n) per op?" elapsed))) - -(if (> fails 0) (do (printf "phm-hamt: %d FAILED" fails) (os/exit 1)) - (print "phm-hamt: all passed")) diff --git a/test/unit/reader-test.janet b/test/unit/reader-test.janet deleted file mode 100644 index c528e02..0000000 --- a/test/unit/reader-test.janet +++ /dev/null @@ -1,155 +0,0 @@ -(use ../../src/jolt/reader) - -# Helper: create a symbol -(defn sym [name] - (let [slash (string/find "/" name)] - (if slash - {:jolt/type :symbol - :ns (string/slice name 0 slash) - :name (string/slice name (+ slash 1))} - {:jolt/type :symbol - :ns nil - :name name}))) - -# Symbols -(assert (deep= (sym "foo") (parse-string "foo")) - "bare symbol") -(assert (deep= (sym "foo/bar") (parse-string "foo/bar")) - "namespaced symbol") -(assert (deep= (sym "+") (parse-string "+")) - "operator symbol") -(assert (deep= (sym "->foo") (parse-string "->foo")) - "arrow symbol") - -# Keywords -(assert (= :foo (parse-string ":foo")) - "bare keyword") -(assert (= :foo/bar (parse-string "::foo/bar")) - "auto-resolved keyword") -(assert (= :foo/bar (parse-string ":foo/bar")) - "namespaced keyword") - -# Numbers -(assert (= 1 (parse-string "1")) - "integer") -(assert (= -42 (parse-string "-42")) - "negative integer") -(assert (= 3.14 (parse-string "3.14")) - "float") - -# Strings -(assert (= "hello" (parse-string "\"hello\"")) - "simple string") - -# Nil, booleans -(assert (= nil (parse-string "nil")) - "nil") -(assert (= true (parse-string "true")) - "true") -(assert (= false (parse-string "false")) - "false") - -# Lists → Janet arrays (to distinguish from vectors) -(assert (array? (parse-string "(1 2 3)")) - "list produces array") -(assert (deep= @[1 2 3] (parse-string "(1 2 3)")) - "simple list") - -# Vectors → Janet tuples -(assert (tuple? (parse-string "[1 2 3]")) - "vector produces tuple") -(assert (deep= [1 2 3] (parse-string "[1 2 3]")) - "simple vector") - -# Maps → Janet structs -(let [m (parse-string "{:a 1 :b 2}")] - (assert (struct? m) "map is struct") - (assert (= 1 (m :a)) "map key lookup")) - -# Sets → tagged with :jolt/set -(let [form (parse-string "#{1 2 3}")] - (assert (struct? form) "set is struct") - (assert (= :jolt/set (form :jolt/type)) "set type tag")) - -# Quote and shorthand -(assert (deep= @[(sym "quote") (sym "x")] (parse-string "'x")) - "quote shorthand") -(assert (deep= @[(sym "syntax-quote") (sym "x")] (parse-string "`x")) - "syntax-quote") -(assert (deep= @[(sym "unquote") (sym "x")] (parse-string "~x")) - "unquote") -(assert (deep= @[(sym "unquote-splicing") (sym "x")] (parse-string "~@x")) - "unquote-splicing") -# @x reads as the QUALIFIED clojure.core/deref (like Clojure) so it derefs even -# where a ns excludes/rebinds `deref` (e.g. malli). -(assert (deep= @[(sym "clojure.core/deref") (sym "x")] (parse-string "@x")) - "deref shorthand") - -# Metadata: a keyword/symbol/string hint on a symbol attaches to the symbol's -# :meta and keeps it a bare symbol (so type hints are transparent everywhere). -(let [form (parse-string "^:meta x")] - (assert (and (struct? form) (= :symbol (form :jolt/type))) "meta-hinted symbol stays a symbol") - (assert (= "x" (form :name)) "symbol name preserved") - (assert (= true (get (form :meta) :meta)) "keyword hint -> {kw true}")) -(let [form (parse-string "^String s")] - (assert (= "s" (form :name)) "type-hinted symbol name preserved") - (assert (= "String" (get (form :meta) :tag)) "symbol hint -> {:tag name}")) -# Map metadata on a symbol still uses a runtime with-meta form. -(let [form (parse-string "^{:doc \"d\"} y")] - (assert (and (array? form) (struct? (first form)) (= "with-meta" ((first form) :name))) - "map metadata -> with-meta form")) - -# Comments (skip to end of line) -(assert (= 42 (parse-string "; comment\n42")) - "comment then form") - -# Discard #_ -(assert (= 42 (parse-string "#_ (ignored 1 2) 42")) - "discard skips next form") - -# Anonymous function #() -(let [form (parse-string "#(+ %1 %2)")] - (assert (array? form) "fn form is array") - (assert (deep= (sym "fn*") (in form 0)) "first element is fn*")) - -# Nested forms -(let [form (parse-string "(+ 1 (* 2 3))")] - (assert (array? form) "outer list is array") - (assert (deep= (sym "+") (in form 0)) "+ is first") - (assert (= 1 (in form 1)) "1 is second") - (assert (array? (in form 2)) "nested list is array")) - -# Multiple forms: parse-next -(let [[form1 rest-str] (parse-next "(1 2) [3 4]")] - (assert (deep= @[1 2] form1) "first form is list") - (let [[form2 _] (parse-next rest-str)] - (assert (deep= [3 4] form2) "second form is vector"))) - -# Reader conditional — feature set is #{:jolt :default} (spec 02-reader S18, -# RFC 0002); matching is by clause order. reader-features-set! lets a loading -# context opt a clj-targeted library into :clj compat (restored below). -(assert (= 3 (parse-string "#?(:clj 1 :jolt 3 :cljs 2)")) - "#?(...) picks :jolt branch") -(assert (= nil (parse-string "#?(:cljs 999)")) - "unmatched conditional reads as nothing") -(assert (= 7 (parse-string "#?(:clj 1 :default 7)")) - ":default reached when :clj not in feature set") -(assert (= 5 (parse-string "#?(:default 5 :jolt 6)")) - "clause order wins, not key priority") -(assert (deep= @[(sym "+") 1 3] (parse-string "(+ 1 #?(:jolt 3 :cljs 4))")) - "#? inside list picks :jolt") -(let [prev (reader-features-set! ["jolt" "clj" "default"])] - (assert (= 1 (parse-string "#?(:clj 1 :cljs 2)")) - "clj-compat opt-in picks :clj") - (reader-features-set! (keys prev))) - -# Characters — the reader now produces char values {:jolt/type :jolt/char :ch N} -(let [form (parse-string "\\newline")] - (assert (struct? form) "char is struct") - (assert (= :jolt/char (form :jolt/type)) "char type") - (assert (= 10 (form :ch)) "newline codepoint")) - -(let [form (parse-string "\\a")] - (assert (= 97 (form :ch)) "simple char codepoint")) - -(print "All reader tests passed!") diff --git a/test/unit/seed-overlay-registry-test.janet b/test/unit/seed-overlay-registry-test.janet deleted file mode 100644 index b89315c..0000000 --- a/test/unit/seed-overlay-registry-test.janet +++ /dev/null @@ -1,104 +0,0 @@ -# Drift check for the seed ↔ overlay boundary (refactor phase 5d). -# -# Recomputes the dispatch-twin set from source and asserts it matches what -# docs/seed-overlay-registry.md documents. A twin is a name with BOTH a seed -# `core-X` defn (src/jolt/*.janet) and an overlay `(defn X …)` -# (jolt-core/clojure/core/*.clj). If you add, remove, or re-home a twin, update -# the doc table and the EXPECTED-TWINS set below together. -# -# This is source analysis, not Clojure eval — a plain Janet test (no harness). - -(def repo-root - # test/unit/ -> repo root is two levels up - (let [d (os/cwd)] d)) - -(defn- slurp-safe [path] - (try (slurp path) ([_] nil))) - -(defn- files-with-ext [dir ext] - (def acc @[]) - (each name (os/dir dir) - (def full (string dir "/" name)) - (case (os/stat full :mode) - :directory (array/concat acc (files-with-ext full ext)) - :file (when (string/has-suffix? ext name) (array/push acc full)))) - acc) - -# Collect bare names from `(defn NAME` / `(defn- NAME`, optionally stripping a -# `prefix` (e.g. "core-") and keeping only those that had the prefix. -(defn- defn-names [src prefix] - (def names @{}) - (def pat (peg/compile - ~{:sym (capture (some (+ (range "az" "AZ" "09") (set "*?!<>=+/.&_-")))) - :defn (* "(defn" (? "-") (some (set " \t")) :sym) - :main (some (+ :defn 1))})) - (each m (or (peg/match pat src) @[]) - (when (string? m) - (if prefix - (when (string/has-prefix? prefix m) - (put names (string/slice m (length prefix)) true)) - (put names m true)))) - names) - -(defn- merge-into [dst src] (eachk k src (put dst k true)) dst) - -# --- seed core-X names across src/jolt/*.janet --- -(def seed-names @{}) -(each f (files-with-ext (string repo-root "/src/jolt") ".janet") - (merge-into seed-names (defn-names (slurp f) "core-"))) - -# --- overlay public defns across jolt-core/clojure/core/*.clj --- -(def overlay-names @{}) -(each f (files-with-ext (string repo-root "/jolt-core/clojure/core") ".clj") - (merge-into overlay-names (defn-names (slurp f) nil))) - -# --- twins = intersection --- -(def twins @{}) -(eachk k seed-names (when (get overlay-names k) (put twins k true))) - -(def EXPECTED-TWINS - {"char?" true "sorted?" true "sorted-map?" true "sorted-set?" true - "transduce" true}) - -(defn- keyset [t] (sort (keys t))) - -(unless (deep= (keyset twins) (keyset EXPECTED-TWINS)) - (error (string "seed↔overlay twin drift!\n" - " computed: " (string/join (keyset twins) ", ") "\n" - " expected: " (string/join (keyset EXPECTED-TWINS) ", ") "\n" - " Update docs/seed-overlay-registry.md and EXPECTED-TWINS together."))) - -# --- core-bindings registered keys (the public/dispatch registration table) --- -(def core-src (slurp (string repo-root "/src/jolt/core.janet"))) -(def bind-start (string/find "@{" core-src (string/find "core-bindings" core-src))) -# brace-match from the `@{` to its close -(defn- match-brace [src open] - (var depth 0) (var i open) (var end nil) - (while (and (< i (length src)) (nil? end)) - (case (src i) - (chr "{") (++ depth) - (chr "}") (do (-- depth) (when (= depth 0) (set end i)))) - (++ i)) - end) -(def bind-end (match-brace core-src (+ bind-start 1))) -(def bind-region (string/slice core-src bind-start (+ bind-end 1))) -(def registered @{}) -(each m (or (peg/match ~(some (+ (* "\"" (capture (some (if-not "\"" 1))) "\"") 1)) bind-region) @[]) - (put registered m true)) - -# Twins must NOT be registered — the overlay copy shadows; the seed copy is -# internal-only. A twin sneaking into core-bindings means the seed copy is -# masquerading as the public binding. -(eachk t EXPECTED-TWINS - (when (get registered t) - (error (string "twin '" t "' is registered in core-bindings — it should be " - "overlay-public only (see docs/seed-overlay-registry.md)")))) - -# The seed-public anchors must stay registered (guards the into/transduce -# asymmetry the registry documents). -(each anchor ["into" "reduce"] - (unless (get registered anchor) - (error (string "seed-public anchor '" anchor "' missing from core-bindings")))) - -(print "seed↔overlay registry: " (length (keys twins)) " twins, " - (length (keys registered)) " registered bindings — OK") diff --git a/test/unit/types-test.janet b/test/unit/types-test.janet deleted file mode 100644 index 4acd864..0000000 --- a/test/unit/types-test.janet +++ /dev/null @@ -1,133 +0,0 @@ -(use ../../src/jolt/types) - -# ============================================================ -# Var tests -# ============================================================ - -# make-var -(let [v (make-var 'x 42)] - (assert (var? v) "var? returns true") - (assert (= 42 (var-get v)) "var-get returns root binding") - (assert (deep= {:name 'x} (var-meta v)) "var-meta returns metadata") - (assert (deep= 'x (var-name v)) "var-name returns name symbol")) - -# var without init value -(let [v (make-var 'y)] - (assert (var? v) "unbound var is still a var")) - -# dynamic var -(let [v (make-var '*dyn* 1 {:dynamic true})] - (assert (var-dynamic? v) "var-dynamic? true") - (assert (not (var-macro? v)) "var-macro? false for dynamic var")) - -# macro var -(let [v (make-var 'when nil {:macro true})] - (assert (var-macro? v) "var-macro? true")) - -# var-set — set root binding -(let [v (make-var 'x 1)] - (var-set v 99) - (assert (= 99 (var-get v)) "var-set changes root binding")) - -# alter-var-root -(let [v (make-var 'c 0)] - (alter-var-root v inc) - (assert (= 1 (var-get v)) "alter-var-root applies fn")) - -# with-meta — returns new var with updated meta -(let [v (make-var 'x 42) - v2 (with-meta v {:private true})] - (assert (deep= {:name 'x :private true} (var-meta v2)) "with-meta merges meta") - (assert (= 42 (var-get v2)) "with-meta preserves root binding")) - -# generation counter — bumps on every root change (substrate for direct-link -# staleness detection and redefinition-aware dispatch caches) -(let [v (make-var 'g 1)] - (assert (= 0 (v :gen)) "fresh var starts at generation 0") - (bind-root v 2) - (assert (= 1 (v :gen)) "bind-root bumps generation") - (var-set v 3) - (assert (= 2 (v :gen)) "var-set (root) bumps generation") - (alter-var-root v inc) - (assert (= 3 (v :gen)) "alter-var-root bumps generation") - (assert (= 4 (var-get v)) "value still tracks through gen bumps")) -(let [v (make-var 'g 1) - v2 (with-meta v {:doc "x"})] - (assert (= (v :gen) (v2 :gen)) "with-meta carries generation")) - -# var with namespace -(let [ns (make-ns 'my.ns) - v (make-var 'my.ns/x 1 {:ns ns})] - (assert (= ns (var-ns v)) "var-ns returns namespace")) - -# ============================================================ -# Namespace tests -# ============================================================ - -(let [ns (make-ns 'foo.bar)] - (assert (ns? ns) "ns? returns true") - (assert (deep= 'foo.bar (ns-name ns)) "ns-name returns name symbol") - (assert (table? (ns-map ns)) "ns-map returns table") - (assert (= 0 (length (ns-map ns))) "empty namespace has no mappings")) - -# ns-intern -(let [ns (make-ns 'test.ns) - v (ns-intern ns 'x 42)] - (assert (var? v) "ns-intern returns a var") - (assert (= 42 (var-get v)) "ns-intern sets root binding") - # check ns-find returns the same var (by reference, not deep=) - (assert (= v (ns-find ns 'x)) "ns-find returns interned var")) - -# ns-intern without value -(let [ns (make-ns 'test.ns) - v (ns-intern ns 'y)] - (assert (var? v) "ns-intern without value creates unbound var")) - -# ns-unmap -(let [ns (make-ns 'test.ns) - _ (ns-intern ns 'x 1) - _ (ns-unmap ns 'x)] - (assert (nil? (ns-find ns 'x)) "ns-unmap removes mapping")) - -# ns-resolve — own ns -(let [ns (make-ns 'test.ns) - v (ns-intern ns 'x 10)] - (assert (= v (ns-resolve ns 'x)) "ns-resolve finds var in own ns")) - -# ns-import -(let [ns (make-ns 'test.ns)] - (ns-import ns 'Date 'java.util.Date) - (assert (= 'java.util.Date (ns-import-lookup ns 'Date)) "ns-import-lookup returns import")) - -# ============================================================ -# Context tests -# ============================================================ - -(let [ctx (make-ctx)] - (assert (ctx? ctx) "ctx? returns true")) - -# ctx with initial namespaces -(let [ctx (make-ctx {:namespaces {"user" {"x" 1 "y" 2}}})] - (let [ns (ctx-find-ns ctx "user")] - (assert (ns? ns) "ctx-find-ns returns namespace for user") - (let [v (ns-find ns "x")] - (assert (var? v) "user/x is a var") - (assert (= 1 (var-get v)) "user/x has correct value")))) - -# ctx-find-ns creates ns if not present -(let [ctx (make-ctx) - ns (ctx-find-ns ctx "foo")] - (assert (ns? ns) "ctx-find-ns creates namespace on demand")) - -# ============================================================ -# Dynamic binding support (thread-local bindings table) -# ============================================================ - -# push-thread-bindings / pop-thread-bindings -(let [v (make-var '*dyn* 0 {:dynamic true})] - (push-thread-bindings @{v 100}) - (assert (= 100 (var-get v)) "push-thread-bindings sets binding") - (pop-thread-bindings) - (assert (= 0 (var-get v)) "pop-thread-bindings restores root")) - -(print "All types tests passed!") diff --git a/vendor/clojure-test-suite b/vendor/clojure-test-suite deleted file mode 160000 index e20ea02..0000000 --- a/vendor/clojure-test-suite +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e20ea0289e57fe5c8b78e66865176bb7af42939d diff --git a/vendor/irregex b/vendor/irregex new file mode 160000 index 0000000..c948a70 --- /dev/null +++ b/vendor/irregex @@ -0,0 +1 @@ +Subproject commit c948a704fc732914a243c1643bfe359913d11c7b diff --git a/vendor/sci b/vendor/sci index ebd5cfa..32d62a5 160000 --- a/vendor/sci +++ b/vendor/sci @@ -1 +1 @@ -Subproject commit ebd5cfacda272eabf91f3168d56d08b64f770a80 +Subproject commit 32d62a5136ad3dc148588752f5bcc4cc30b14752