Reputation: 15336
Can't figure out how to get function name as string in macro.
The code below should generate rlisten("multiply", multiply)
but it won't compile, playground.
import macros
proc rlisten*[A, B, R](fn: string, op: proc(a: A, b: B): R): void =
echo fn
macro remotefn(fn): void =
quote do:
rlisten($`fn`, `fn`) # It should generte `rlisten("multiply", multiply)`
proc multiply(a, b: int): int = discard
remotefn multiply
Upvotes: 1
Views: 321
Reputation: 775
First you need to accept typed
or untyped
parameters to a macro. In this particular case you need to use typed
argument in order to be able to access the function symbol (symbols are identifiers replaced by type resolution pass of the compiler).
import macros
proc rlisten*[A, B, R](fn: string, op: proc(a: A, b: B): R): void =
echo fn
macro remotefn(fn: typed): void =
echo fn.treeRepr()
# ^ Show tree representation of the argument. In this particular case it is just a
# single function symbol.
let name = fn.strVal()
echo "Function name is ", name
proc multiply(a, b: int): int = discard
remotefn multiply
Outputs
Sym "multiply"
Function name is multiply
Upvotes: 2