Clojure:如何获取定义了地图的文件/行号? [英] Clojure: How do I get the file/line number on which a map was defined?
问题描述
我知道我可以从元数据中获得:行
和:file
然而,我正在建立一个系统,用户可以传递原始地图,我将最终链接在一起的数据在以后的时间。当此链接失败时,我想报告他们指定地图的文件/行。例如:
I know I can get the :line
and :file
from the metadata on a var; however, I'm building a system where the user can pass me raw maps and I will end up "linking" the data together at a later time. When this linkage fails, I'd like to report the file/line in which they specified the map. E.g.:
(defn generate-stuff []
(make-thing { :k (make-thing { :k v }) }
)
)
(link (generate-stuff) (other-generator))
;; outputs file/line of the map containing the errant :k/v pair
将文件/行与集合的元数据相关联几乎肯定是要走的路,但由于没有任何var看看,我不知道在哪里得到行号。我看到get-line-number的定义,但它需要一个读者,虽然我可以找到所有的特殊读者和 * default-data-reader-fn *
数据读取器(这是nil),我似乎无法找出如何访问代码读取器。
I assume that writing a macro to associate file/line with the collection's metadata is almost certainly the way to go, but since there isn't any "var" to look at, I'm not sure where to get the line number. I see the definition of get-line-number, but it requires a reader, and while I can find all of the special readers and the *default-data-reader-fn*
data reader (which is nil), I cannot seem to figure out how to access the "code" reader.
推荐答案
,看起来在宏中使用& form
是答案。我写了以下位的通用测试代码,它似乎工作:
OK, it looks like using &form
in a macro is the answer. I wrote the following bit of generic test code, and it seems to work:
(defmacro make-thing [obj]
(let [f *file*]
(with-meta obj (assoc (meta &form) :file f))
)
)
& form
是指调用宏的表单,行/列的元数据。特殊的var 文件具有源文件的相对路径。因此,将两个元素组合到对象上的元数据产生期望的结果。
The &form
refers to the form that invoked the macro, and it has metadata for line/column. The special var file has the relative path of the source file. So, combining the two into the metadata onto the object results in the desired result.
这篇关于Clojure:如何获取定义了地图的文件/行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!