6

通过Nimrod 教程的第二部分,我已经到达了解释宏的部分。文档说它们在编译时运行,所以我想我可以对字符串进行一些解析来为自己创建一种特定于域的语言。但是,没有示例说明如何执行此操作,调试宏示例未显示如何处理字符串参数。

我想转换如下代码:

instantiate("""
    height,f,132.4
    weight,f,75.0
    age,i,25
    """)

…变成我会手写的东西:

var height: float = 132.4
var weight: float = 75.0
var age: int = 25

显然这个例子不是很有用,但我想看看一些简单的东西(多行/逗号分割,然后是转换),它可以帮助我实现更复杂的东西。

我的问题是宏如何获取输入字符串,解析它(在编译时!),以及在编译时可以运行什么样的代码(它只是语言的一个子集?我可以使用其他的宏/代码吗?导入的模块)?

编辑:根据答案,这里有一个可能的代码解决方案:

import macros, strutils

# Helper proc, macro inline lambdas don't seem to compile.
proc cleaner(x: var string) = x = x.strip()

macro declare(s: string): stmt =
  # First split all the input into separate lines.
  var
    rawLines = split(s.strVal, {char(0x0A), char(0x0D)})
    buf = ""

  for rawLine in rawLines:
    # Split the input line into three columns, stripped, and parse.
    var chunks = split(rawLine, ',')
    map(chunks, cleaner)

    if chunks.len != 3:
      error("Declare macro syntax is 3 comma separated values:\n" &
        "Got: '" & rawLine & "'")

    # Add the statement, preppending a block if the buffer is empty.
    if buf.len < 1: buf = "var\n"
    buf &= "  " & chunks[0] & ": "

    # Parse the input type, which is an abbreviation.
    case chunks[1]
    of "i": buf &= "int = "
    of "f": buf &= "float = "
    else: error("Unexpected type '" & chunks[1] & "'")
    buf &= chunks[2] & "\n"

  # Finally, check if we did add any variable!
  if buf.len > 0:
    result = parseStmt(buf)
  else:
    error("Didn't find any input values!")

declare("""
x, i, 314
y, f, 3.14
""")
echo x
echo y
4

1 回答 1

7

总的来说,宏可以利用同一位置的过程也可以看到的所有纯 Nimrod 代码。例如,您可以导入strutilspeg解析您的字符串,然后从中构造输出。例子:

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

“调用”宏基本上会在编译时评估它,就好像它是一个过程一样(需要注意的是宏参数实际上是 AST,因此需要使用s.strVal上面而不是s),然后插入它返回的 AST宏调用的位置。

宏代码由编译器的内部虚拟机评估。

于 2013-11-13T14:28:53.000 回答