首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简约-一个简单的递归模式

简约-一个简单的递归模式
EN

Stack Overflow用户
提问于 2019-07-12 18:50:01
回答 1查看 184关注 0票数 0

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

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

代码语言:javascript
复制
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+"
    """)

测试一个简单的案例:

代码语言:javascript
复制
grammar.parse("field1 equal to ()")

成功解析(至少它看起来像是构建了一个节点树--我还没有深入了解它对内容的拆分有多好--但乍一看似乎还不错)

但是对于一个更复杂的情况:

代码语言:javascript
复制
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).

我所阐述的语法试图允许任意连接的语句,但我肯定遗漏了一些东西。

我试着调整语法,以明确顶级类和低级类之间的区别:

代码语言:javascript
复制
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+"
    """)

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

代码语言:javascript
复制
grammar.parse("field1 equal to () and field2 not equal to ()")

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

EN

回答 1

Stack Overflow用户

发布于 2019-12-02 23:26:15

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

代码语言:javascript
复制
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+"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57005484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档