Last active
October 4, 2018 12:48
-
-
Save jeroenvandijk/8187413d24433545eeb9579538a903f7 to your computer and use it in GitHub Desktop.
Repl compiling Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn compile-inline [ns-name code] | |
(let [tmp-dir *compile-path* | |
sanitized-ns-name (.replace (str ns-name) "-" "_") | |
clj-file (clojure.java.io/file (str tmp-dir "/" (clojure.string/join "/" (clojure.string/split sanitized-ns-name #"\.")) ".clj"))] | |
(clojure.java.io/make-parents clj-file) | |
(with-open [file (clojure.java.io/writer clj-file)] | |
(binding [*out* file] | |
(println | |
(str "(ns " ns-name ")\n" | |
code)))) | |
(binding [*compile-path* (str tmp-dir)] ;; str here is important, the compile doesn't like something else | |
(try | |
(compile (symbol ns-name)) | |
(catch java.io.FileNotFoundException e | |
;; *compile-path* also needs to be on the classpath! (how can we check this?! | |
(throw (ex-info (str "*compile-path* : " (pr-str (str tmp-dir)) " isn't on the classpath") | |
{:compile-path *compile-path* | |
:clj-file clj-file} | |
#_e ;; If we add the cause, the above error doesn't show directly | |
))))) | |
{:clj-file clj-file | |
:ns-name ns-name})) | |
(defn pp-str [x] | |
(with-out-str (clojure.pprint/pprint x))) | |
(defmacro script | |
[& lines] | |
(let [lines-str (map pp-str lines)] | |
`(clojure.string/join "\n" [~@lines-str]))) | |
(comment | |
(compile-inline 'foo | |
(script | |
(gen-class | |
:name "some.package.RefMap5" | |
;:implements [java.util.Map] | |
:state "state" | |
:init "init" | |
:constructors {[] []} | |
:prefix "ref-map-") | |
(defn ref-map-init []))) | |
;; Get an instance of our fresh class! | |
(some.package.RefMap5.)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment