我有一个逻辑表达式解析器简单下面的代码:
import scala.util.parsing.combinator.RegexParsers
import scala.util.parsing.combinator.PackratParsers
object Parsers extends RegexParsers with PackratParsers
// Entities definition
sealed trait LogicalUnit
case class Variable(name: String) extends LogicalUnit
case class Not(arg: LogicalUnit) extends LogicalUnit
case class And(arg1: LogicalUnit, arg2: LogicalUnit) extends LogicalUnit
import Parsers._
// In order of descending priority
lazy val pattern: PackratParser[LogicalUnit] =
((variable) | (not) | (and))
lazy val variable: PackratParser[Variable] =
"[a-zA-Z]".r ^^ { n => Variable(n) }
lazy val not: PackratParser[Not] =
("!" ~> pattern) ^^ { x => Not(x) }
lazy val and: PackratParser[And] =
((pattern <~ "&") ~ pattern) ^^ { case a ~ b => And(a, b) }
// Execution
println(Parsers.parseAll(pattern, "!a & !b"))
因此,试图解析字符串!a & !b
,它失败
[1.4] failure: string matching regex `\z' expected but `&' found
!a & !b
^
看来,根解析器试图解析整个字符串的pattern -> not -> variable
,当它发现不走回头路!a
还没有结束呢,所以pattern -> and
甚至没试过。 我认为使用PackratParsers
要解决这个问题,但是事实并非如此
我究竟做错了什么?