在 Nim 中,有没有一种方法可以获取在代码中给定点定义的具有给定名称的所有过程的声明列表?例如,我正在寻找一个函数 TYPE,其中包含以下代码
proc Sum(self: seq[int]):int =
do something
echo $TYPE(Sum)
proc Sum(self: seq[float]):float =
do something
echo $TYPE(Sum)
会打印
@[proc Sum(self: seq[int]):int]
@[proc Sum(self: seq[int]):int, proc Sum(self: seq[float]):float]
您可以使用宏来做到这一点。当存在多个重载时,符号将存储为
nnkClosedSymChoice
,您可以对其进行迭代和过滤以仅允许过程。
例如
macro definedProcs(x: typed) =
# If there are no overloads then it would just be a `nnkSym`
# so wrap it in `nnkClosedSymChoice` to make life easier
let syms = if x.kind == nnkSym: nnkClosedSymChoice.newTree(x) else: x
for x in syms:
# Lookup the type definition, and make sure its a proc
if x.getTypeInst().kind == nnkProcTy:
# Do something with the proc symbol.
# You can't call it here, but you can return
# some code to operate on the proc
这段代码缺少错误处理之类的东西,但应该可以完成工作