Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing and de-serializing Clojure code as EDN

Tags:

clojure

edn

I'm trying to use a standard serialization for Clojure code, one that will ignore white spaces, comments etc. I was thinking of using EDN for that.

According to the what I read, the standard way to serialize s-expressions to EDN is through pr-str, which seems to work nicely with most of Clojure's constructs. However, this seems not to work that well for code containing regular expressions (using the hash-string reader macro, like #"\d+").

user=> (pr-str '#"\d")
"#\"\\d\""

user=> (edn/read-string (pr-str '#"\d"))

RuntimeException No dispatch macro for: "  Clojure.lang.Util.runtimeException (Util.java:221)

I'm using Clojure 1.8.0.

Any suggestions?

Thanks!

EDIT: Thanks for your answers and comments. The reason I wanted to use EDN to begin with was that I want to handle untrusted code.

The idea is that I want to read this code (any syntactically-valid Clojure code), and then pass it through some special-purpose static analysis to make sure it complies with a specific subset of Clojure that I consider "safe", and only if it complies I would consider it safe to execute this code. For this reason I want to avoid load-file, which loads the file right away, and also possibly read-string, due to these warnings regarding it.

like image 374
Boaz Rosenan Avatar asked Nov 08 '22 01:11

Boaz Rosenan


1 Answers

Clojure is a superset of EDN, so not all Clojure features are supported. The output of pr-str is a valid Clojure program that has been escaped to fit in a String. The RuntimeException is complaining about the first escaped ", which is not supported by the EDN # reader macro.

(clojure.core/read-string (pr-str #"\d")) ;=> #"\d"
like image 136
Jeremy Avatar answered Nov 15 '22 06:11

Jeremy