Nim
Nim copied to clipboard
Generic function does not look for macro definition in the scope of the module where it is defined
Say we have the following modules.
mymacro.nim
(which defines a macro):
macro aMacro*(u:untyped):untyped =
echo "in macro"
result = u
myproc.nim
(which uses the macro as a pragma):
import mymacro
proc p*[T]() =
proc inner() {.aMacro.} =
discard
inner()
discard
main.nim
(which uses the proc):
import myproc
p[string]()
I get the error:
nim cpp -r --verbosity\:0 --hint\[Processing\]\:off --excessiveStackTrace\:on /home/deech/Nim/procmacro/main.nim
/home/deech/Nim/procmacro/myproc.nim(1, 8) Warning: imported and not used: 'mymacro' [UnusedImport]
/home/deech/Nim/procmacro/main.nim(3, 2) template/generic instantiation of `p` from here
/home/deech/Nim/procmacro/myproc.nim(3, 18) Error: invalid pragma: aMacro
but if I remove the generic T
and redefine p
as proc p*() ...
the macro is called.
It seems like p
is expanded in place and evaluated in the scope of main.nim
which doesn't import myMacro
and causes the error.
This at least seems like surprising behavior, I would expect the expansion of p[T]
to look for aMacro
in its own import scope and not the scope where it's called.
The workaround is to import mymacro
in main
which isn't ideal because main
shouldn't have to know about p
's implementation details.