Small Clojure Interpreter
I want a limited dialect of Clojure for a single-purpose, scripted application. SCI will fit nicely.
โ
@tiagoluchini
Quickstart
Use from Clojure(Script)
(require '[sci.core :as sci])
(sci/eval-string "(inc 1)") => ;; 2
(sci/eval-string "(inc x)" {:namespaces {'user {'x 2}}}) ;;=> 3
Try SCI in your browser at NextJournal.
For usage with GraalVM native-image check here.
Why
You want to evaluate code from user input, or use Clojure for a DSL inside your
project, but eval isn't safe or simply doesn't work.
This library works with:
- Clojure on the JVM
- Clojure compiled with GraalVM native
- ClojureScript, even when compiled with
:advanced, and JavaScript
- ClojureDart, compiled to Dart. See the Flutter REPL example.
API docs
See API.md.
Projects using SCI
SCI is used in:
- Babashka. A Clojure scripting tool that plays well with Bash.
- nbb. Ad-hoc CLJS scripting on Node.js. (Node.js babashka)
- scittle. Execute Clojure(Script) directly from browser script tags
- Clerk. Local-First Notebooks for Clojure.
- 4ever-clojure. 4clojure as a static web page.
- Clj-kondo. A Clojure linter that sparks joy.
- Jet. CLI to convert between JSON, EDN and Transit.
- Joyride. Making VS Code Hackable since 2022.
- Portal. A clojure tool to navigate through your data.
- Zprint. Tool to beautifully format Clojure(script) code and data.
- TryClojure.org. Try Clojure!
- SICMUtils. Computer Algebra System in Clojure, tailored for math and physics investigations.
- Maria.cloud: a Clojure coding environment for beginners.
- Datalevin: A simple, fast and versatile Datalog database
- Overarch: A data driven description of software architecture based on UML and the C4 model.
- Logseq. A local-only outliner notebook which supports both Markdown and Org mode.
- Malli. Plain data Schemas for Clojure/Script.
Expand for more projects...
- Bootleg. An HTML templating CLI.
- Bytefield-svg. NodeJS library to generate byte field diagrams.
- Cardigan Bay. Wiki engine in Clojure.
- clj-browser-eval. Turn any HTML input field into a Clojure interpreter.
- ClojureBlocks, A visual editor for Clojure
- Chlorine. Socket-REPL and nREPL package for Atom editor.
- Cq. Clojure Command-line Data Processor for JSON, YAML, EDN, XML and more.
- Dad. A configuration management tool.
- For-science. Discord bot.
- Keycloak-clojure. Clojure library for Keycloak.
- Lighthouse. A data-driven Kubernetes pre-processor.
- Obsidian Wielder. Write and evaluate Clojure code directly in your Obsidian vault.
- PCP. Clojure Processor (PHP replacement).
- PGMig. Fast Standalone PostgreSQL Migration Runner.
- Prose. Alternate syntax for Clojure, similar to what Pollen brings to Racket.
- Spire. Pragmatic provisioning using Clojure.
- Tesserae. A Clojure spreadsheet and more!
Are you using SCI in your company or projects? Let us know here.
Installation
Use as a dependency:
Usage
The main API function is sci.core/eval-string which takes a string to evaluate
and an optional options map.
In SCI, defn does not mutate the outside world, only the evaluation
context inside a call to sci/eval-string.
By default SCI only enables access to most of the Clojure core functions. More
functions can be enabled by using :namespaces and :classes. Normally you
would use SCI's version of println but here, for the purposes of
demonstration, we use Clojure's version of println instead:
user=> (require '[sci.core :as sci])
user=> (sci/eval-string "(println \"hello\")" {:namespaces {'clojure.core {'println println}}})
hello
nil
It is also possible to provide namespaces which can be required inside a SCI program:
user=> (def opts {:namespaces {'foo.bar {'println println}}})
user=> (sci/eval-string "(require '[foo.bar :as lib]) (lib/println \"hello\")" opts)
hello
nil
You can provide a list of allowed symbols. Using other symbols causes an exception:
user=> (sci/eval-string "(inc 1)" {:allow '[inc]})
2
user=> (sci/eval-string "(dec 1)" {:allow '[inc]})
ExceptionInfo dec is not allowed! [at line 1, column 2] clojure.core/ex-info (core.clj:4739)
Providing a list of disallowed symbols has the opposite effect:
user=> (sci/eval-string "(inc 1)" {:deny '[inc]})
ExceptionInfo inc is not allowed! [at line 1, column 2] clojure.core/ex-info (core.clj:4739)
Unrestricted mode
By default built-in vars are read-only and CLJS instance interop is limited to
:classes. Hosts that embed SCI as a general purpose runtime can opt out with
the :unrestricted option:
user=> (sci/eval-string "(with-redefs [inc dec] (inc 1))" {:unrestricted true})
0
:unrestricted applies only to the context it was passed to. When code
running in an unrestricted context calls eval-string again, the context of
that call is sandboxed unless it also passes :unrestricted true.
Macros
Providing a macro as a binding can be done by providing a normal function that:
- has
:sci/macro on the metadata set to true
- has two extra arguments at the start for
&form and &env:
user=> (def do-twice ^:sci/macro (fn [_&form _&env x] (list 'do x x)))
user=> (sci/eval-string "(do-twice (f))" {:namespaces {'user {'do-twice do-twice 'f #(println "hello")}}})
hello
hello
nil
Alternatively you can refer to the macro from the Clojure environment via the
var (this only works in a JVM environment):
user=> (defmacro do-twice [x] (list 'do x x))
user=> (sci/eval-string "(do-twice (f))" {:namespaces {'user {'do-twice #'do-twice 'f #(println "hello")}}})
Tips:
- To get the name of the namespace the macro is called from at expansion time, use
(str (deref sci.core/ns))
- Have a look at Emmy's sci-macro, which behaves like
defmacro in Clojure, but emits a :sci/macro defn with the extra args in cljs
Vars
To remain safe and sandboxed, SCI programs do not have access to Clojure vars,
unless you explicitly provide that access. SCI has its own var type,
distinguished from Clojure vars.
In a SCI program these vars are created with def and defn just like in
normal Clojure:
(def x 1)
(defn foo [] x)
(foo) ;;=> 1
(def x 2)
(foo) ;;=> 2
Dynamic vars with thread-local bindings are also supported (for vars defined inside your scripts, and thus evaluated by SCI,
or for SCI dynamic vars (see below)):
(def ^:dynamic *x* 1)
(binding [*x* 10] *x*) ;;=> 10
(binding [*x* 10] (set! *x* 12) *x*) ;;=> 12
*x* ;;=> 1
Creating SCI vars from Clojure, to be exposed to your SCI scipts, can be done using sci/new-var:
(def x (sci/new-var 'x 10))
(sci/eval-string "(inc x)" {:namespaces {'user {'x x}}}) ;;=> 11
To create a dynamic SCI var from Clojure you can set metadata or use sci/new-dynamic-var:
(def x1 (sci/new-var 'x 10 {:dynamic true}))
(sci/eval-string "(binding [*x* 12] (inc *x*))" {:namespaces {'user {'*x* x1}}}) ;;=> 13
(def x2 (sci/new-dynamic-var 'x 10))
(sci/eval-string "(binding [*x* 12] (inc *x*))" {:namespaces {'user {'*x* x2}}}) ;;=> 13
These dynamic SCI vars can be bound from Clojure using sci/binding:
(def x (sci/new-dynamic-var 'x 10))
(sci/binding [x 11] (sci/eval-string "(inc *x*)" {:namespaces {'user {'*x* x}}})) ;;=> 12
Notice that you cannot set host dynamic variables from your SCI scripts - binding will only work
on dynamic variables you defined in the script itself, or on SCI dynamic variables exposed from Clojure.
This applies also to :sci/macros (which expand into more code in the scripts). There workaround is to
only bind them from Clojure, i.e. from functions exposed to and called by your scripts:
(def ^:dynamic *x* 1)
(defn with-x [x-val f] (binding [*x* x-val] (f)))
(defn get-x [] *x*)
(def userns (sci/create-ns 'user))
(sci/eval-string "(with-x 42 #(get-x))"
{:namespaces {'user {'with-x (sci/copy-var with-x userns)
'get-x (sci/copy-var get-x userns)}}})
;;=> 42
If you want to be bind the value from your script, then you can expose a SCI dynamic var to it,
and bind its value to the host dynamic var in Clojure:
(def ^:dynamic *x* 1)
(def userns (sci/create-ns 'user))
(def sci-x (sci/copy-var *x* userns)) ; ^:dynamic is copied too
(defn get-x [] (binding [*x* @sci-x] *x*)) ; bind host var to SCI dyn var value
(sci/eval-string "(binding [*x* 42] (get-x))"
{:namespaces {'user {'get-x (sci/copy-var get-x userns)
'*x* sci-x}}}) ; expose SCI dyn var
;; => 42
Using *in*, *out*, *err*
The dynamic vars *in*, *out*, *err* in a SCI program correspond to the
dynamic SCI vars sci/in, sci/out and sci/err in the API. These
vars can be rebound as well:
(def sw (java.io.StringWriter.))
(sci/binding [sci/out sw] (sci/eval-string "(println \"hello\")")) ;;=> nil
(str sw) ;;=> "hello\n"
A shorthand for rebinding sci/out is sci/with-out-str:
(sci/with-out-str (sci/eval-string "(println \"hello\")")) ;;=> "hello\n"
Reader conditionals
To tell SCI which branch of a reader conditional to take,
such as the :cljs one in #?(:clj "JVM" :cljs "JS"), you need to tell it which features it should support:
(sci/eval-string "(str \"I'm \" #?(:clj \"JVM\" :cljs \"JS\"))" {:features #{:cljs :bb}}) ;;=> "I'm JS"
See eval-string docs for details.
Copy a namespace
To copy the public vars of a Clojure namespace and to reify the Clojure vars into
corresponding SCI vars, you can use ns-publics