【问题标题】:nim - custom macro/pragma to get ast of complete module but get "cannot attach a custom pragma"nim - 自定义宏/编译指示获取完整模块但得到“无法附加自定义编译指示”
【发布时间】:2020-12-31 09:54:53
【问题描述】:

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

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

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

【问题讨论】:

    标签: macros metaprogramming nim-lang


    【解决方案1】:

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

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

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

    template dbIgnore {.pragma.}
    
    {.push dbIgnore.}
    

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

    relevant manual section

    【讨论】:

    • 我知道可以为每个 proc 添加一个 pragma,但我想要的是将所有 proc 添加到“全局”映射中。那可能吗?据我了解,在 proc 上使用 pragma 时,我只会得到带注释的 proc 的 AST,而且我不知道如何从 pragma 宏中向“全局”AST 添加一些东西。
    • 获得全局 AST 是不可能的,至少没有一些带有术语重写的非常老套的解决方案。最好的选择是只用你的 pragma 注释 procs。
    猜你喜欢
    • 2011-03-03
    • 2019-11-06
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 2019-07-28
    • 1970-01-01
    相关资源
    最近更新 更多