简约的ParseError

时间:2019-02-26 19:53:19

标签: python parsing parsimonious

深入研究语法和PEG,我想使用以下语法编写DSL:

a OR (b AND c)

我在以下语法中使用 parsimonious

from parsimonious.grammar import Grammar
grammar = Grammar(
    """
    expr            = (term operator term)+
    term            = (lpar term rpar) / (variable operator variable)
    operator        = and / or
    or              = _? "OR" _?
    and             = _? "AND" _?
    variable        = ~r"[a-z]+"
    lpar            = "("
    rpar            = ")"
    _               = ~r"\s*"
    """
)
print(grammar.parse('a OR (b AND c)'))

但是,对于上面的文字,此操作会失败

parsimonious.exceptions.ParseError: Rule 'variable' didn't match at '(b AND c)' (line 1, column 6).

为什么?我没有将term指定为( term )term吗?
为什么它为variable选择规则(当然失败了)?

1 个答案:

答案 0 :(得分:2)

expr中的第一件事是term,这就是解析器要查找的内容。

语法中的term要么是

( term )

variable operator variable

输入为

a OR (b AND c)

那不是以(开头的,所以它可以是term的唯一方法是匹配variable operator variableavariableORoperator。因此,接下来要匹配的是variable


也许您想要的是:

expr = term (operator term)*
term = (lpar expr rpar) / variable