【发布时间】:2021-04-19 17:17:01
【问题描述】:
假设我们要编写一个其行为取决于某种配置的宏。具体来说,在我的情况下,配置只是一个布尔值,表示输出代码中的一些优化。更具体地说,转换看起来像这样(表示==> 的宏扩展):
(transform ...) ==> (transform'-opt ...) ==> (transform' ...) ==> ...
当优化发生时,否则transform'-opt被省略,transform'被使用。
使用参数进行配置会导致过多的重复,因此最好以本地/with-... 样式配置宏(也可能以全局样式配置)。我的意思是,使用类似(with-opt <em><strong>value expr*</strong></em>) 的东西,在每个expr 的宏扩展期间value 被用作transform 的配置,除非这被另一个with-opt 更改。到目前为止,我选择的解决方案是通过以下方式使用动态 var 和 binding:
(require '[clojure.tools.analyzer.jvm :refer [macroexpand-all]])
(def ^:dynamic *opt* true)
(defmacro with-opt [value & body]
`(do ~@(binding [*opt* value] (mapv macroexpand-all body))))
(defmacro transform [...]
`(~(if *opt* `transform'-opt `transform') ...))
但是,在宏扩展中使用动态变量和macroexpand-all 对我来说有点不合常规。我考虑过的其他(也是非常规的)选项包括使用常规 var 和 with-redefs、原子、易失性以及将配置隐藏在闭包中,如下所示:
(let [opt ...]
(defmacro with-opt ...)
(defmacro transform ...))
[在这种情况下,避免突变和手动宏扩展的一种想象的通用方法可能是在宏中引入另一个隐式&config参数和一个新的特殊形式(with-macro-configs [<em><strong>(macro config)*</strong></em>] <em><strong>expr*</strong></em>),它将指定用于各种宏的此参数的值.]
这种情况有什么常见的做法吗?你的方法是什么,为什么?提前致谢。
【问题讨论】:
-
您能否添加一个更具体的示例来说明您正在尝试解决的问题以及如何使用它?另外,配置选项是什么?