generated at
Nimのmacro
nim-by-example


Nimのmacro
>1. Dump and examine the AST
>2. Modify the AST to match the desired shape

構文木を受け取り、構文木を返す関数
渡された引数を分析し、現在の位置に任意の方法で新しいASTを作成できる(?)
> But with templates you can only do constant substitutions in the AST. With macros you can analyze the passed arguments and create a new AST at the current position in any way you want.
他の言語と違って(?)、NimのmacroはNimで書けるので、他の文法を覚える必要がない

構造
txt
StmtList # ステートメントノード Command # Commandノード Ident "echo" StrLit "Hello, World!"

手順
import macros
proc の代わりに macro を使用
newNimNode() でノードを作成、引数にノードの種類を指定

サンプル
nim
# https://qiita.com/2vg/items/68ca18d22e2ce77ed073 import macros macro genEcho: untyped = result = newNimNode(nnkStmtList) result.add( newNimNode(nnkCommand).add( ident("echo"), newStrLitNode("Hello, World!") ) ) # マクロ呼び出し # 当たり前だけどこれがないとマクロが実行されないので genEcho()

ノードの構造を知る方法
dumpTree 関数を使う
treeRepr でも同じ出力(何が違う?)
Nim
import macros dumpTree: echo "Hello, World!" # 出力 # StmtList # Command # Ident "echo" # StrLit "Hello, World!"
nim
import macros dumpTree: result = 10 # 同じ結果 # static: # echo treeRepr(parseStmt("result = 10")) # 出力 # StmtList # Asgn # Ident ident"result" # IntLit 10

いつ使うのか
何が嬉しいのか