clojuremacros

How to access the source position while evaluating a clojure macro?


Inside of a macro I would like to get the source file and position of the caller of the macro.

Something like:

(defmacro my-macro []
  `(prn ~*source-position*))

where *source-position* contains information about the source position of the file which is currently compiled while evaluating the macro.

When calling this macro, it should print the source file, line and column of the caller.


Solution

  • Use the &form symbol to get the position of the original form during macroexpansion.

    =>(defmacro m [x] `(prn '~(meta &form)))
    #'user/m
    =>(m (+ 1 3 3))
    {:line 1, :column 1}
    nil
    

    And source-path should give you the file name.