Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nim - custom macro/pragma to get ast of complete module but get "cannot attach a custom pragma"

I want to get access to the AST of a complete module (file) with nim. I found, that any macro can be used as a custom pragma, so I did something like this in file foo.nim:

import macros

macro getAst(ast: untyped): untyped =
  echo "ast = ", treeRepr(ast)

{.getAst.}  # <-- This should invoke the getAst() macro with the AST of the file

proc hello() =
  echo "hello world"    

But I get compiler error cannot attach a custom pragma to 'foo'

Is there a way to achieve this? I found that I can use the macro as a block macro like so, but I would really prefer to use it via pragma.

getAst:
  proc hello() =
    echo "hello world"    
like image 590
Ridcully Avatar asked Oct 19 '25 18:10

Ridcully


1 Answers

It is not possible to attach custom pragma to a file, but you can do

proc hello() {.getAst.} =
  echo "hello world"    

to attach pragma to a proc. I'm not sure, but it seems like {.push.} does not work for macros, only for template pragmas, like this:

template dbIgnore {.pragma.}

{.push dbIgnore.}

So your best option is to annotate all procs you want with pragma.

relevant manual section

like image 157
haxscramper Avatar answered Oct 22 '25 06:10

haxscramper