英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论