Implement the dbg!
macro from Rust in Clojure and ClojureScript https://doc.rust-lang.org/std/macro.dbg.html.
In my_project/utils.cljc
(defn current-file
[]
(some-> 'cljs.analyzer
(find-ns)
(ns-resolve '*cljs-file*)
(deref)))
(defmacro dbg!
[& forms]
(let [f (if (:ns &env)
(current-file)
*file*)
md (meta &form)]
`(let [res# ~@forms
forms# (pr-str '~@forms)
file# ~f
line# (:line ~md)
column# (:column ~md)]
(println (str
forms# " = " res#
(when file#
(str " in " file#))
(when line#
(str " line " line#))
(when column#
(str " column " column#))))
res#)))
- Save the above in a folder like
src/dbg/dbg.clj
- Create a test Clojure file similar to the following like
src/dbg/test.clj
(ns dbg.test (:require [dbg.dbg :refer [dbg!]])) (dbg! (+ 1 2))
- Run the test script. I’m using
babashka
here butclj
should work just as wellbb -cp src src/dbg/test.clj
Which outputs:
(+ 1 2) = 3 in /Users/j/Projects/clj-dbg-macro/src/dbg/test.clj line 5 column 1 3
- Logs the form we are supplying to the macro
(+ 1 2)
- Logs the evaluation result
3
- Logs the filename, line, and column that calls the dbg! macro
- @rushsteve on Doom Discord for sharing the dbg! macro https://discord.com/channels/406534637242810369/783402813799268382/783463857045372959
- jjttjj in the Clojurians Slack for sharing a Clojure code sample to get current file name, line, and column
- Braden Shepherdson in the Clojurians Slack for pointing me to this great macro ref https://code.thheller.com/blog/shadow-cljs/2019/10/12/clojurescript-macros.html