【发布时间】:2019-07-31 03:27:03
【问题描述】:
我正在为搜索表达式编写解析器。 例如。
a = "zyx" and ( b < 5 or c > 9)
我写了这个解析器,但它不能匹配括号,得到这个错误:
failure: identifier expected
a = "zyx" and ( b < 5 or c > 9)
^
我该怎么做才能匹配括号
class SearchQueryParser extends StandardTokenParsers {
def expr: Parser[Expression] = orExp | "(" ~> orExp ~ ")"
def orExp: Parser[Expression] = {
andExp *("or" ^^^ {(a: Expression, b: Expression) => BoolExp("OR", (a, b))})
}
def andExp: Parser[Expression] = {
compareExp *("and" ^^^ {(a: Expression, b: Expression) => BoolExp("AND", (a, b))})
}
def compareExp: Parser[Expression] = {
identifier ~ rep(
("=" | "!=" | "<" | ">") ~ literal ^^ {
case op ~ rhs => (op, rhs)
}
) ^^ {
case (acc, ("=", rhs: Expression)) => Binomial("=", acc, rhs)
case (acc, ("!=", rhs: Expression)) => Binomial("!=", acc, rhs)
case (acc, ("<", rhs: Expression)) => Binomial("<", acc, rhs)
case (acc, (">", rhs: Expression)) => Binomial(">", acc, rhs)
}
}
}
【问题讨论】:
-
你的
compareExp规则对我来说看起来很奇怪。它允许x < 5 > 1,但不允许1 < x < 5。我不确定这是否是您的本意。 -
感谢您的评论。我实际上不需要任何表达式,因为应该只允许二项式。我相应地改变了我的语法。