How can I get the procedure name in Nim?

I am trying to write a macro for debug printing in Nim. Currently, this macro adds filenameand lineto the exit instantiationInfo().

import macros  
macro debugPrint(msg: untyped): typed =
  result = quote do:
    let pos = instantiationInfo()
    echo pos.filename, ":", pos.line, ": ", `msg`

proc hello() =
  debugPrint "foo bar"
hello()

currently displays:

debug_print.nim:9: foo bar

I would like to add the name of the procedure (or iterator) of the place where the macro was called.

desired result:

debug_print.nim:9(proc hello): foo bar

How can I get the name of a procedure (or iterator) in Nim, for example __func__in C?

+4
source share
1 answer

At runtime, you can do it getFrame().procname, but it only works with the stacktrace function enabled (not in build versions).

. callsite(), . , macros.LineInfo.

__func__ Nim:

template procName: string =
  var name: cstring
  {.emit: "`name` = __func__;".}
  ($name).rsplit('_', 1)[0]
+6

Source: https://habr.com/ru/post/1693369/


All Articles