如何在PetitParserDart中无法完全匹配规则时失败并抛出异常?

时间:2013-07-11 02:59:47

标签: parsing petitparser

我已经使用PetitParserDart定义了一些规则:

def("start", ref("rule").separatedBy(char('\n'), includeSeparators: false);
def("rule", char('(').seq(word().plus()).seq(char(')')));

因此将匹配以下文本:

(aaa)
(bbbbbb)

但如果有一些行无法匹配:

(aaaa)
bbbbb
(cccccccc

如何定义语法以使其失败并在行(ccccccccc上抛出异常,但不在行bbbbb上?

我的意思是它只在规则未完全匹配时抛出异常。如果没有匹配,则不会抛出异常。

1 个答案:

答案 0 :(得分:1)

在语法的任何一点,你都可以引入一个失败的解析器:

failure('This parser always fails at this point');

通常,PetitParser在解析过程中不使用异常,成功和失败用相应的SuccessFailure响应上下文表示。

也就是说,可以抛出异常,但通常不建议,除非您的语法用户可以处理它。例如,您可以像这样定义一个抛出解析器工厂:

Parser thrower(String message) {
  return epsilon().map((value) => throw new IllegalStateException(message));
}

使用普通合成器,您可以生成非常精确的错误消息:

char('(')
  .seq(word().plus())
  .seq(char(')')
    // causes the parser to continue trying to parse the input
    .or(failure('something bad happened')))

或者使用上面的助手:

char('(')
  .seq(word().plus())
  .seq(char(')')
     // stops parsing altogether and throws an exception
    .or(thrower('something bad happened')))