3

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"    
Ridcully
  • 23,362
  • 7
  • 71
  • 86

1 Answers1

3

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

haxscramper
  • 775
  • 7
  • 17
  • I'm aware of the possibility to add a pragma per proc, but what I want, is to add all the procs to a 'global' map. Would that be possible? As far as I understand, I would only get the AST of the annotated proc when using the pragma on the proc, and I do not know how I could add something to the 'global' AST from within the pragma macro. – Ridcully Dec 31 '20 at 13:30
  • It is **not** possible to get global AST, at least without some very hacky solutions with term rewriting. The best option is to just annotate procs with your pragma. – haxscramper Dec 31 '20 at 19:31