nim - 自定义宏/pragma 获取完整模块的 ast 但得到“无法附加自定义 pragma”

问题描述

我想使用 nim 访问完整模块(文件)的 AST。我发现,任何宏都可以用作自定义编译指示,所以我在文件 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"    

但我收到编译器错误 cannot attach a custom pragma to 'foo'

有没有办法做到这一点?我发现我可以像这样使用宏作为块宏,但我真的更喜欢通过编译指示使用它。

getAst:
  proc hello() =
    echo "hello world"    

解决方法

无法将自定义编译指示附加到文件,但您可以这样做

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

将编译指示附加到 proc。我不确定,但似乎 {.push.} 不适用于宏,仅适用于 template 编译指示,如下所示:

template dbIgnore {.pragma.}

{.push dbIgnore.}

所以你最好的选择是用 pragma 注释你想要的所有 proc。

relevant manual section