How do I parse a string at compile time in Nimrod?

风流意气都作罢 提交于 2019-12-04 07:34:43

Macros can, by and large, utilize all pure Nimrod code that a procedure in the same place could see, too. E.g., you can import strutils or peg to parse your string, then construct output from that. Example:

import macros, strutils

macro declare(s: string): stmt =
  var parts = split(s.strVal, {' ', ','})
  if len(parts) != 3:
    error("declare macro requires three parts")
  result = parseStmt("var $1: $2 = $3" % parts)

declare("x, int, 314")
echo x

"Calling" a macro will basically evaluate it at compile time as though it were a procedure (with the caveat that the macro arguments will actually be ASTs, hence the need to use s.strVal above instead of s), then insert the AST that it returns at the position of the macro call.

The macro code is evaluated by the compiler's internal virtual machine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!