1

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
Alex Craft
  • 13,598
  • 11
  • 69
  • 133

1 Answers1

2

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
haxscramper
  • 775
  • 7
  • 17
  • I'm not sure if this is *the* most optimal way of passing function name. I partially based my response on your https://stackoverflow.com/questions/67150226/macro-to-generate-function-implementation-by-its-definition/67150407?noredirect=1#comment118694399_67150407 earlier question. If you just need a name you can just pass `untyped` identifier and retrieve string from it. – haxscramper Apr 18 '21 at 15:50
  • thanks, it works! :) https://play.nim-lang.org/#ix=2WwW – Alex Craft Apr 18 '21 at 15:57