我正在尝试为以下命令定义语法。
object ParserWorkshop {
def main(args: Array[String]) = {
ChoiceParser("todo link todo to database")
ChoiceParser("todo link todo to database deadline: next tuesday context: app.model")
}
}
第二个命令应标记为:
action = todo
message = link todo to database
properties = [deadline: next tuesday, context: app.model]
当我在下面定义的语法上运行此输入时,我收到以下错误消息:
[1.27] parsed: Command(todo,link todo to database,List())
[1.36] failure: string matching regex `\z' expected but `:' found
todo link todo to database deadline: next tuesday context: app.model
^
据我所见,它失败了,因为匹配消息单词的模式与属性键:值对的键模式几乎相同,因此解析器无法判断消息在哪里结束以及属性从哪里开始。我可以通过坚持为每个属性使用开始令牌来解决这个问题,如下所示:
todo link todo to database :deadline: next tuesday :context: app.model
但我更愿意让命令尽可能接近自然语言。我有两个问题:
错误消息的实际含义是什么?我将如何修改现有语法以适用于给定的输入字符串?
import scala.util.parsing.combinator._
case class Command(action: String, message: String, properties: List[Property])
case class Property(name: String, value: String)
object ChoiceParser extends JavaTokenParsers {
def apply(input: String) = println(parseAll(command, input))
def command = action~message~properties ^^ {case a~m~p => new Command(a, m, p)}
def action = ident
def message = """[\w\d\s\.]+""".r
def properties = rep(property)
def property = propertyName~":"~propertyValue ^^ {
case n~":"~v => new Property(n, v)
}
def propertyName: Parser[String] = ident
def propertyValue: Parser[String] = """[\w\d\s\.]+""".r
}