简体   繁体   English

在scala解析器组合器中回溯?

[英]Backtracking in scala parser combinators?

It seems like scala's parser combinators don't backtrack. 似乎scala的解析器组合器不会回溯。 I have a grammar (see bottom) which can't parse the following "stmt" correctly: 我有一个语法(见底部),无法正确解析以下“stmt”:

copy in to out .

That should be easy to parse with backtracking: 这应该很容易用回溯解析:

stmt: (to out(copy in))

or am I missing something? 还是我错过了什么?

Parser: 分析器:

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}

You want to use PackratParsers in 2.8. 你想在2.8中使用PackratParsers I think the packrat parser is the only backtracking parser. 我认为packrat解析器是唯一的回溯解析器。

Edit: as of mid-year 2015, you should use fastparse instead. 编辑:截至2015年中期,您应该使用fastparse It's not only much faster, but also easier to use (especially when building data structures from parsing). 它不仅更快,而且更易于使用(特别是在从解析构建数据结构时)。

Your problem is not backtracking. 你的问题不是回溯。 The standard | 标准| operator in scala.util.parsing.combinator will do backtracking. scala.util.parsing.combinator运算符将执行回溯。 Your problem is left-recursion ( exprcallargssmplargsexpr ). 你的问题是左递归( exprcallargssmplargsexpr )。 Packrat parsing may indeed help with that. Packrat解析可能确实有助于此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM