Skip to content

Instantly share code, notes, and snippets.

@AdamClements
Created June 17, 2014 12:39
Show Gist options
  • Save AdamClements/4a0619226ad56754ae51 to your computer and use it in GitHub Desktop.
Save AdamClements/4a0619226ad56754ae51 to your computer and use it in GitHub Desktop.
Debug arbitrary forms
(defmacro locals [] (zipmap (map #(list 'quote %) (keys &env)) (keys &env)))
(defn remove-autogenerated-locals
"Remove any locals generated by macros (heuristic - named something
with underscores in it). When we're doing something other than
println with the data, these could be left in but it's a bit noisy
at the moment"
[coll]
(into {} (remove (fn [[k v]] (re-find #"[_]" (name k))) coll)))
(defn contains-recur? [form]
(when (seq? form)
(if (= 'recur (first form))
true
(recur (last form)))))
(defn eval-printing-meta [location form subform]
(let [local-things `(locals)]
(cond
(contains-recur? form)
`(do (clojure.pprint/pprint {:special :recur :location ~location :form (quote ~form) :locals (remove-autogenerated-locals ~local-things)})
~subform)
(= (first form) 'catch)
subform
(= (first form) 'finally)
subform
:else
`(let [result# ~subform]
(clojure.pprint/pprint {:result result# :location ~location :form (quote ~form) :locals (remove-autogenerated-locals ~local-things)})
result#))))
(defn wrap-things-with-meta [form]
(if (meta form)
(eval-printing-meta (meta form) form (map wrap-things-with-meta form))
form))
(defmacro lexically-trace [body]
(list 'do
(list 'println "Entering wrap-meta at " (meta &form))
(wrap-things-with-meta body)))
(defmacro lexically-trace-all [& args]
(doseq [body args]
`(lexically-trace ~@body)))
(lexically-trace-all
(defn test-recursion [x y]
(if (= y 0) [x y] (recur (inc x) (dec y))))
(defn test-try-catch [x a]
(try
(let [test-array (int-array 1 2)]
(aget test-array x))
(catch IndexOutOfBoundsException e
(+ a (- (let [x 10] (/ 4 x a)) (let [a 2] (* a 7)))))))
(defn test-nested [a]
(+ a (- (let [x 10] (/ 4 x a)) (let [a 2] (* a 7)))))
(defn test-ranges [max]
(+ max (first (range)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment