如何处理Clojurescript宏中所需的Clojurescript代码? [英] How do I deal with required Clojurescript code from Clojurescript macros?

查看:55
本文介绍了如何处理Clojurescript宏中所需的Clojurescript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个X.clojurescript和一个X.clojure命名空间.X.clojurescript中的所有内容都是Clojurescript代码,X.clojure中的所有内容都是Clojure代码.不幸的是,我不能直接在Clojurescript中定义宏,我必须在Clojure中定义它们,然后使用

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

这很好.但是,如果宏(在X.clojurere中定义)需要引用在Clojurescript命名空间(X.clojurescript)中定义的内容,该怎么办?问题在于,在解决其他命名空间时,Clojure编译器不会在我的Clojurescript命名空间(单独的目录)中查找.

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.

我已经通过在Clojure代码中简单创建一个名称空间来解决这个问题,该名称空间具有与Clojurescript中存在的名称空间和所需的定义相同的名称,但这似乎有点愚蠢.因此,例如,如果我在宏中需要X.clojurescript.abc.y,我将仅在Clojure端创建一个额外的命名空间,以在我的X.clojurescript.abc的Clojure版本中定义一个虚拟y.有点愚蠢.

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.

我该如何处理需要引用Clojurescript方面的宏?

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

推荐答案

宏在定义时唯一需要特定命名空间的时间是,如果宏正在使用来自该命名空间的代码来生成符号列表,它将返回

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.

您可以在repl中遵循以下示例:

you can follow along with these examples in the repl:

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

即使bar不是定义的名称空间,foo的定义也会编译

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

(foo :a)

调用foo现在将失败,因为您尚未定义bar名称空间或功能bar

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

在bar名称空间中定义bar

defines bar in the bar namespace

(ns user)
(foo :a)

=> [:a:a]

=> [:a :a]

请注意,在foo定义时,bar不需要存在.实际上,在定义foo时,甚至不需要存在名称空间.

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.

这篇关于如何处理Clojurescript宏中所需的Clojurescript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆