如何在运行时打印Nim的AST?

huangapple go评论55阅读模式
英文:

How to print Nim's AST at runtime?

问题

dumpTree 和类似的宏在编译时打印出 Nim 的 AST。我想知道如何在 运行时 打印相同的内容。用例是能够捕获输出以在 nimib 文档中记录它。

具体示例如下:

import macros

dumpTree:
  25 ⬇️
  10 

在编译时产生以下输出:

StmtList
  Command
    IntLit 25
    Ident ""⬇️""
  Command
    IntLit 10
    Ident ""➖""

我想要一个 dumpTreeRuntime,对于上述情况等效于:

echo """"
StmtList
  Command
    IntLit 25
    Ident ""⬇️""
  Command
    IntLit 10
    Ident ""➖""
""""
英文:

dumpTree and similar macros print Nim's AST at compile time. I was wondering how to print the same content at runtime. The use case is to be able to capture the output to document it in a nimib document.

To have a concrete example:

import macros

dumpTree:
  25 ⬇️
  10 

produces at compile time:

StmtList
  Command
    IntLit 25
    Ident "⬇️"
  Command
    IntLit 10
    Ident "➖"

I would like a dumpTreeRuntime that is equivalent for the above case to:

echo """
StmtList
  Command
    IntLit 25
    Ident "⬇️"
  Command
    IntLit 10
    Ident "➖"
"""

答案1

得分: 4

import macros

macro treeToString(code: untyped): untyped =
return newLit(treeRepr(code))

when isMainModule:
let x = treeToString:
25 ⬇️
10 ➖

echo(x)

英文:
import macros


macro treeToString(code: untyped): untyped =
   return newLit(treeRepr(code))


when isMainModule:
  let x = treeToString:
    25 ⬇️
    10 ➖

   echo(x)

</details>



huangapple
  • 本文由 发表于 2023年6月8日 01:48:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定