How do I deal with required Clojurescript code from Clojurescript macros?

风流意气都作罢 提交于 2021-02-07 11:51:46

问题


Let us say I have a X.clojurescript and a X.clojure namespace. Everything in X.clojurescript is Clojurescript code, everything in X.clojure is Clojure code. Unfortunately, I cannot define macros directly in Clojurescript, I have to define them in Clojure and then bring them into a Clojurescript namespace using

(ns X.clojurescript.abc
  (:require-macros [X.clojure.def :as clj]))

This is fine. However, what if the macro (defined in X.clojure) is going to need to reference something defined in a Clojurescript namespace (X.clojurescript)? The problem is that the Clojure compiler does not look in my Clojurescript namespace (a separate directory) when resolving other namespaces.

I have gotten around this problem by simply creating a namespace in my Clojure code that has the same namespace and needed definition as exist in Clojurescript, but this seems kind of stupid. So, for instance, if I need X.clojurescript.abc.y in my macro, I will just create an additional namespace on the Clojure side that defs a dummy y in my Clojure version of X.clojurescript.abc; kind of dumb.

How do I deal with a macro that needs to refer to something on the Clojurescript side?


回答1:


The only time a macro needs a specific namespace at the time of definition is if the macro is using code from said namespace to generate the list of symbols it will return.

you can follow along with these examples in the repl:

(defmacro foo
  [a]
  `(bar/bar ~a))

the definition of foo will compile even though bar is not a defined namespace

(foo :a)

calling foo will now fail because you have not defined the bar namespace, or the function bar yet

(ns bar)
(defn bar
  [x]
  [x x])

defines bar in the bar namespace

(ns user)
(foo :a)

=> [:a :a]

Notice that bar does not need to exist at the time of foo's definition. In fact the namespace does not even need to exist at the time of foo's definition.



来源:https://stackoverflow.com/questions/14781868/how-do-i-deal-with-required-clojurescript-code-from-clojurescript-macros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!