解析器组合器无法终止 - 如何记录正在发生的事情?

huy*_*hjl 7 scala parser-combinators

我正在尝试使用解析器组合器,我经常遇到无限递归.这是我遇到的第一个:

import util.parsing.combinator.Parsers
import util.parsing.input.CharSequenceReader

class CombinatorParserTest extends Parsers {

  type Elem = Char

  def notComma = elem("not comma", _ != ',')

  def notEndLine = elem("not end line", x => x != '\r' && x != '\n')

  def text = rep(notComma | notEndLine)

}

object CombinatorParserTest {

  def main(args:Array[String]): Unit = {
    val p = new CombinatorParserTest()
    val r = p.text(new CharSequenceReader(","))
    // does not get here
    println(r)
  }

}
Run Code Online (Sandbox Code Playgroud)

如何打印正在发生的事情?为什么没有完成?

Ran*_*ulz 4

记录解析尝试notCommanotEndLine显示正在重复解析的是文件结尾(在 log(...)("mesg") 输出中显示为 CTRL-Z)。以下是我为此目的修改解析器的方法:

def text = rep(log(notComma)("notComma") | log(notEndLine)("notEndLine"))
Run Code Online (Sandbox Code Playgroud)

我不完全确定发生了什么(我尝试了你的语法的许多变体),但我认为它是这样的: EOF 并不是真正人为引入到输入流中的字符,而是一种永久条件输入结束。因此,这个从未被消耗的 EOF 伪字符被重复解析为“要么不是逗号,要么不是行尾”。