我使用解析器组合器编写了一个scala解析器:
case class KW(str: String) {
val parser: Parser[String] = str
}
implicit class SymbolView(symbol: Symbol) {
val $: KW = {
KW(symbol.name.toLowerCase())
}
}
implicit def ks2Parser(ks: KW): Parser[String] = ks.parser
val _DELETE = 'delete $
val _REMOVE = 'remove $
val _DROP = 'drop $
val DELETE = _DELETE | _REMOVE | _DROP
lexical.reserved ++= Seq("delete", "remove", "drop")
val scanner: lexical.Scanner = new lexical.Scanner("delete")
phrase(DELETE).apply(scanner)
然而,scala解析器给我这个错误:
failure: You are trying to parse "drop", but it is neither contained in the delimiters list, nor in the reserved keyword list of your lexical object
我非常确定“删除”和“删除”都包含在词汇的保留关键字列表中(我在调试模式下都找到了)。所以这个错误信息显然是错误的。它是scala解析器组合器中的错误吗?我该怎么做才能解决它?
答案 0 :(得分:3)
当您使用$
时,StandardTokenParsers.keyword
最终会在行val parser: Parser[String] = str
中被隐含地调用。它在调用时使用lexical.reserved
的内容。当您在_DELETE
添加令牌之前创建_REMOVE
/ _DROP
/ lexical.reserved
解析器时,会发生这些调用。
所以要么在创建解析器之前移动该行以添加保留标记:
lexical.reserved ++= Seq("delete", "remove", "drop")
val _DELETE = 'delete $
val _REMOVE = 'remove $
val _DROP = 'drop $
val DELETE = _DELETE | _REMOVE | _DROP
或者使解析器定义def
s(或lazy val
s)而不是val
s:
def _DELETE = 'delete $
def _REMOVE = 'remove $
def _DROP = 'drop $
def DELETE = _DELETE | _REMOVE | _DROP