Created
March 23, 2010 14:58
-
-
Save Licenser/341257 to your computer and use it in GitHub Desktop.
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 extract-expressions [string] | |
(second | |
(reduce (fn [[exp exps state cnt] c] | |
(cond | |
(= state :escape) | |
[(.append exp c) exps :string cnt] | |
(= state :string) (cond | |
(= c \") | |
[(.append exp c) exps :code cnt] | |
(= c \\) | |
[(.append exp c) exps :escape cnt] | |
(= c \\) | |
[(.append exp c) exps :escape cnt] | |
:else | |
[(.append exp c) exps :string cnt]) | |
(and (= cnt 1) (= c \))) | |
[(java.lang.StringBuilder.) (cons (str (.append exp c)) exps) :text 0] | |
(= c \() | |
[(.append exp c) exps :code (inc cnt)] | |
(and (> cnt 1) (= c \))) | |
[(.append exp c) exps :code (dec cnt)] | |
(and (> cnt 0) (= c \")) | |
[(.append exp c) exps :string cnt] | |
(> cnt 0) | |
[(.append exp c) exps :code cnt] | |
:else [exp exps state cnt])) | |
[(java.lang.StringBuilder.) '() :text 0] | |
string))) | |
(defn parse-template [string] | |
(let [[exp exps __] (reduce (fn [[exp exps state cnt] c] | |
(cond | |
(= state :escape) | |
[(.append exp c) exps :string cnt] | |
(= state :string) (cond | |
(= c \") | |
[(.append exp c) exps :code cnt] | |
(= c \\) | |
[(.append exp c) exps :escape cnt] | |
(= c \\) | |
[(.append exp c) exps :escape cnt] | |
:else | |
[(.append exp c) exps :string cnt]) | |
(and (= cnt 1) (= c \))) | |
[(java.lang.StringBuilder.) (conj exps [:code (str (.append exp c))]) :text 0] | |
(and (= c \() (= cnt 0)) | |
(if (> (.length exp) 0) | |
[(java.lang.StringBuilder. (str c)) (conj exps [:text (str exp)] ) :code 1] | |
[(java.lang.StringBuilder. (str c)) exps :code 1]) | |
(= c \() | |
[(.append exp c) exps :code (inc cnt)] | |
(and (> cnt 1) (= c \))) | |
[(.append exp c) exps :code (dec cnt)] | |
(and (> cnt 0) (= c \")) | |
[(.append exp c) exps :string cnt] | |
:else | |
[(.append exp c) exps :state cnt])) | |
[(java.lang.StringBuilder.) [] :text 0] | |
string)] | |
(if (> (.length exp) 0) | |
(conj exps [:text (str exp)]) | |
exps))) | |
(def *name*) | |
(defn run-template | |
[data] | |
(str (reduce | |
(fn [sb [type string]] | |
(.append sb (cond | |
(= type :code) (eval (read-string string)) | |
(= type :text) string))) | |
(java.lang.StringBuilder.) data))) | |
(defn run-template2 | |
[data] | |
(read-string (str (reduce | |
(fn [sb [type string]] | |
(.append sb (cond | |
(= type :code) string | |
(= type :text) (str "(str \"" (apply str (map (fn [c] (cond (= c \") "\\\"" :else c)) string)) "\")")))) | |
(java.lang.StringBuilder. "(apply str ") data) ")"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment