Skip to content

Instantly share code, notes, and snippets.

@jaidetree
Last active May 18, 2022 01:19
Show Gist options
  • Save jaidetree/e7121b090957bab26b5843124917d101 to your computer and use it in GitHub Desktop.
Save jaidetree/e7121b090957bab26b5843124917d101 to your computer and use it in GitHub Desktop.
Clojure and ClojureScript dbg! macro from rust

Purpose

Implement the dbg! macro from Rust in Clojure and ClojureScript https://doc.rust-lang.org/std/macro.dbg.html.

Implementation

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#)))

Example

  1. Save the above in a folder like src/dbg/dbg.clj
  2. 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))
        
  3. Run the test script. I’m using babashka here but clj should work just as well
    bb -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
        

So what does it do?

  • 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

Thanks to…

  1. @rushsteve on Doom Discord for sharing the dbg! macro https://discord.com/channels/406534637242810369/783402813799268382/783463857045372959
  2. jjttjj in the Clojurians Slack for sharing a Clojure code sample to get current file name, line, and column
  3. 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment