首页 > 解决方案 > nim - 自定义宏/编译指示获取完整模块但得到“无法附加自定义编译指示”

问题描述

我想使用 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"    

标签: macrosmetaprogrammingnim-lang

解决方案


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

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

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

template dbIgnore {.pragma.}

{.push dbIgnore.}

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

相关手册部分


推荐阅读