Is it possible to get the file name and line number of the clojurescript file using a macro?

StackOverflow https://stackoverflow.com/questions/20352348

  •  07-08-2022
  •  | 
  •  

Question

I am looking for a way to grab the file name and line number information of a particular piece of code from the cljs analyser using a macro. Is this possible?

I.e

(page-info) => line: 1, file: test.clj

Pas de solution correcte

Autres conseils

Yes! It's actually quite easy to do this using standard clojure macro tools, plus a little bit of cljs.analyzer magic:

For example, here's a macro that explicitly adds metadata to a clojurescript expression (as long as it supports metadata):

(defmacro add-meta [expr]
  (let [namespace {:namespace (name cljs.analyzer/*cljs-ns*)}
        source-details (meta &form)]
  `(with-meta ~expr '~(merge namespace source-details)))) 

In your clojurescript file, you can use this to extract metadata from a form (as long as it supports metadata), e.g.

(meta (add-meta {:foo 'bar})) => {:namespace my.namespace :line 1 :column 4}

This macro relies on two sources of information:

  • cljs.analyzer/*cljs-ns* is a dynamically bound var that contains the current namespace during macro-expansion of clojurescript code.
  • &form is a special variable available in the body of a macro that gives access to the form that caused the macro to be invoked. This is the best way to get access to metadata about call-site of the macro.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top