[英]Tracking method invocations in Groovy closure
I'm writing a small DSL for reactive evaluation, need help with metaprogramming in Groovy. 我正在编写用于响应性评估的小型DSL,在Groovy中进行元编程时需要帮助。
Sample DSL code: DSL示例代码:
Signal<Integer> a = var(1)
Signal<Integer> b = var(2)
Signal<Integer> c = signal { a(it) + b(it) }
The 'var' function creates new Signal
instance. 'var'函数创建新的
Signal
实例。
The signal
function needs a list of Signal
instances inside the closure (references to a
and b
in example). signal
函数需要在闭包内部有一个Signal
实例列表(示例中引用a
和b
)。
Working implementation: 工作实施:
interface Signal<T> {
T now()
}
Signal.metaClass.call = { dependencies ->
dependencies?.add(delegate)
delegate.now()
}
def signal = { Closure<?> body ->
def dependencies = new HashSet<>()
body.call(dependencies)
createSignal(dependencies, body)
}
Is there any way to awoit passing it
variable, so sample looks like 有没有什么办法awoit路过
it
的变量,因此样品看起来像
Signal<Integer> a = var(1)
Signal<Integer> b = var(2)
Signal<Integer> c = signal { a() + b() }
EDIT: Stub Signal
implementation for testing: 编辑:存根
Signal
实现的测试:
class SignalStub<T> implements Signal<T> {
T value
Collection<Signal<?>> dependencies
static def var(value) { new SignalStub<>(value: value, dependencies: [])}
static def createSignal(deps, body) { new SignalStub<Object>(value: body.call(), dependencies: deps) }
@Override
T now() {
return value
}
}
Test case for DSL: DSL测试用例:
def a = var(1)
def b = var(2)
def c = signal { a() + b() }
assert c.now() == 3
assert c.dependencies.contains(a)
assert c.dependencies.contains(b)
The question is: "Is there a way to avoid passing the it variable?" 问题是:“是否有避免传递it变量的方法?” Since a and b are local variables and local variables are not taking part in the MOP, it should be impossible to do using runtime meta programming.
由于a和b是局部变量,并且局部变量不参与MOP,因此使用运行时元编程应该是不可能的。
Using a transform it is possible, but I don't know if you want to go that far here 使用变换是可能的,但我不知道您是否想在这里走那么远
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.