我正在创建一个DSL,并使用Scala的解析器组合库来解析DSL.DSL遵循简单的类似Ruby的语法.源文件可以包含一系列看起来像这样的块:
create_model do
at 0,0,0
end
Run Code Online (Sandbox Code Playgroud)
线路结尾在DSL中很重要,因为它们被有效地用作语句终止符.
我写了一个Scala解析器,看起来像这样:
class ML3D extends JavaTokenParsers {
override val whiteSpace = """[ \t]+""".r
def model: Parser[Any] = commandList
def commandList: Parser[Any] = rep(commandBlock)
def commandBlock: Parser[Any] = command~"do"~eol~statementList~"end"
def eol: Parser[Any] = """(\r?\n)+""".r
def command: Parser[Any] = commandName~opt(commandLabel)
def commandName: Parser[Any] = ident
def commandLabel: Parser[Any] = stringLiteral
def statementList: Parser[Any] = rep(statement)
def statement: Parser[Any] = functionName~argumentList~eol
def functionName: Parser[Any] = ident
def argumentList: Parser[Any] = repsep(argument, ",")
def argument: Parser[Any] = stringLiteral …Run Code Online (Sandbox Code Playgroud)