通过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