Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
naive Clojure macro for tracing all forms
;; there are quite a few cases where this code would not work, use with caution and check the macro expansion
(require '[clojure.walk :as walk])
(defn- clean-dont [form]
(walk/postwalk
(fn [form]
(if (and (list? form) (= 'dont (first form)))
(second form)
form))
form))
(defn- trace [code res]
(log/info (pr-str code) "=>" res)
res)
(defn- trace-maybe [form]
(cond (and (list? form) (= 'dont (first form))) (second form)
(list? form) `(trace-forms ~form)
:else form))
(defn- trace-let [form]
`(trace
(quote ~form)
(let ~(vec (mapcat (fn [[k v]]
[k (trace-maybe v)])
(partition 2 (second form))))
~@(map trace-maybe (drop 2 form)))))
(defmacro trace-forms [form]
(if-not (list? form)
form
(cond (and (list? form) (= 'dont (first form)))
(let [inner (second form)]
`(~(first inner) ~@(map trace-maybe (rest inner))))
(and (list? form) (= 'let (first form)))
(trace-let form)
:else
`(trace (quote ~(clean-dont form))
~(map trace-maybe form)))))
@stathissideris

This comment has been minimized.

Copy link
Owner Author

@stathissideris stathissideris commented Nov 29, 2017

Usage:

> (trace-forms (let [a 100] (+ 1 a (* 8 9))))
(* 8 9) => 72
(+ 1 a (* 8 9)) => 173
(let [a 100] (+ 1 a (* 8 9))) => 173
173

> (trace-forms (dont (let [a 100] (+ 1 a (* 8 9)))))
(* 8 9) => 72
(+ 1 a (* 8 9)) => 173
173

> (trace-forms (dont (let [a 100] (+ 1 a (dont (* 8 9))))))
(+ 1 a (* 8 9)) => 173
173

> (trace-forms (let [a 100] (dont (+ 1 a (* 8 9)))))
(* 8 9) => 72
(let [a 100] (+ 1 a (* 8 9))) => 173
173
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment