0

我希望能够解析简单的规则表达式,这些表达式可以使用连接词andorin parsimonious连接在一起。

我尝试了一个非常基本的语法,它解析一个简单的表达式,但是一旦我开始引入连词就失败了。

import parsimonious

grammar = parsimonious.grammar.Grammar( """
    rule = (rule)+
    rule = (fieldname function parameters) / (rule conjunction rule)
    fieldname = space? ("field1" / "field2" / "field3") space?
    function = space? ("equal to" / "not equal to") space?
    parameters = space? "()" space?
    conjunction = space? ("and" / "or") space?
    space = ~r"\s+"
    """)

测试一个简单的案例:

grammar.parse("field1 equal to ()")

成功解析(至少它似乎构建了一个节点树 - 我还没有深入了解它对内容的分割程度 - 但乍一看似乎很好)

但是对于更复杂的情况:

grammar.parse("field1 equal to () and field2 not equal to ()")

它返回IncompleteParseError: Rule 'rule' matched in its entirety, but it didn't consume all the text. The non-matching portion of the text begins with 'and field2 not equal' (line 1, column 20).

我制定的语法试图允许任意连词,但我一定遗漏了一些东西。

我尝试调整语法以明确区分顶级类和低级类:

grammar = parsimonious.grammar.Grammar( """
    rule = expr+
    expr = (fieldname function parameters) / (expr conjunction expr)
    fieldname = space? ("field1" / "field2" / "field3") space?
    function = space? ("equal to" / "not equal to") space?
    parameters = space? "()" space?
    conjunction = space? ("and" / "or") space?
    space = ~r"\s+"
    """)

现在,在运行两部分短语时:

grammar.parse("field1 equal to () and field2 not equal to ()")

而不是IncompleteParseError,我得到一个RecursionError: maximum recursion depth exceeded in comparison.

4

1 回答 1

1

在你的(expr conjunction expr)部分expr有一个左递归问题。因此,您需要将其分解为单独的规则,如下所示:

rule = expr+
expr = field_expr (conjunction expr)?
field_expr = fieldname function parameters
fieldname = space? ("field1" / "field2" / "field3") space?
function = space? ("not equal to" / "equal to") space?
parameters = space? "()" space?
conjunction = space? ("and" / "or") space?
space = ~r"\s+"
于 2019-12-02T15:26:15.087 回答