似乎 Scala 的解析器组合器不会回溯。我有一个语法(见底部)无法正确解析以下“stmt”:
copy in to out .
这应该很容易通过回溯解析:
stmt: (to out(copy in))
或者我错过了什么?
解析器:
type ExprP = Parser[Expr]
type ValueP = Parser[ValExpr]
type CallP = Parser[Call]
type ArgsP = Parser[Seq[Expr]]
val ident = "[a-zA-Z\\+\\-\\*/%><\\\\\\=]+".r
val sqstart = "\\[" .r
val sqend = "\\]" .r
val del = "," .r
val end = "\\." .r
def stmt: ExprP = expr <~ end
def expr: ExprP = ucall | call | value
def value: ValueP = ident ^^ {str => IdentExpr(str)}
def call: CallP = (args ~ ident ~ expr) ^^ {case args ~ method ~ upon => Call(args, method, upon)}
def ucall: CallP = (ident ~ expr) ^^ {case method ~ upon => Call(Seq(), method, upon)}
def args: ArgsP = advargs | smplargs
def smplargs: ArgsP = expr ^^ {e => Seq(e)}
def advargs: ArgsP = (sqstart ~> repsep(expr, del) <~ sqend) ^^ {seq => seq}
最佳答案
你的问题不是回溯。标准|
运算符(operator)在 scala.util.parsing.combinator
会做回溯。您的问题是左递归( expr
→ call
→ args
→ smplargs
→ expr
)。 Packrat 解析可能确实对此有所帮助。
关于parsing - 在 Scala 解析器组合器中回溯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4615588/