我编写了以下 hello-world parboiled2 解析器:
class MyParser(val input: ParserInput) extends Parser {
/*
Expr <- Sum
Sum <- Product ('+') Product)*
Product <- Value (('*') Value)*
Value <- Constant | '(' Expr ')'
Constant <- [0-9]+
*/
def Expr: Rule1[Int] = rule { Sum }
def Sum: Rule1[Int] = rule { oneOrMore(Product).separatedBy(" + ") ~> ((products: Seq[Int]) => products.sum) }
def Product: Rule1[Int] = rule { oneOrMore(Value).separatedBy(" * ") ~> ((values: Seq[Int]) => values.product) }
def Value: Rule1[Int] = rule { Constant | ('(' ~ Expr ~ ')') }
def Constant: Rule1[Int] = rule { capture(oneOrMore(Digit)) ~> ((digits: String) => digits.toInt) }
}
这主要按预期工作,例如它成功地将“1 + 2”解析为 3。
如果我给它输入无效的输入,例如“1 + (2”,我希望解析失败。但它实际上成功了,结果为 1。
看起来 parboiled2 只是解析输入的一部分,而忽略了它无法解析的其余部分。这是预期的行为吗?有没有办法强制解析器解析整个输入并在它不能这样做时失败?