使用LEPL解析布尔搜索查询

Sar*_*els 4 python grammar parsing boolean lepl

我正在尝试编写LEPL语法来描述布尔搜索语言.这是我到目前为止:

from lepl import *
text = String() | Word()
tail = ~Lookahead('AND') & ~Lookahead('OR') & text
with DroppedSpace():
    andClause = (tail & Lookahead('AND') & Drop('AND') & tail)[1:] > tuple
    orClause = (tail & Lookahead('OR') & Drop('OR') & tail)[1:] > list
    andOrText = (andClause & Lookahead('OR') & Drop('OR') & tail)[1:] > list
    orAndText = (orClause & Lookahead('AND') & Drop('AND') & tail)[1:] > tuple
    oredAnds = (andClause & Lookahead('OR') & Drop('OR') & andClause)[1:] > list
    andedOrs = (orClause & Lookahead('AND') & Drop('AND') & orClause)[1:] > tuple
    query = (oredAnds | andedOrs | orAndText | andOrText | orClause | andClause | text)[:]

query.parse('foo AND bar') # Works
query.parse('"bar none" OR foo') # Works
query.parse('foo AND "bar none" OR baz AND floo') # Works
query.parse('a AND b OR c AND d OR e') # Doesn't work
Run Code Online (Sandbox Code Playgroud)

最后parse产生这个:

[[('a', 'b'), ('c', 'd')], 'OR', 'e']
Run Code Online (Sandbox Code Playgroud)

它应该产生这个:

[[('a', 'b'), ('c', 'd'), 'e']]
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题以获得我想要的解析?我认为如果我能说"无论什么和不管"变成了tuple什么,并且"无论什么或者什么"变成了它,它就会解决它list.

Sar*_*els 5

编辑:由于这篇文章并添加了关键字参数,摆脱了sloooooow左递归.

from lepl import *
def ander(result):
    if len(result) == 2:
        return (result[0], result[1])
    return result[0]
text = String() | Word()
andClausePrime = Delayed()
label = text & Drop(':')
with DroppedSpace():
    parameter = label & text > (lambda r: {r[0]: r[1]})
    andClause = (parameter | text) & andClausePrime > ander
    andClausePrime += (Drop('AND') & (andClause | parameter | text) & andClausePrime)[:]
    expr = andClause | parameter | text
    query = expr & (Drop('OR') & expr)[:]
Run Code Online (Sandbox Code Playgroud)

结果:

>>> query.parse('a AND b')
[('a', 'b')]
>>> query.parse('a AND b AND c')
[('a', ('b', 'c'))]
>>> query.parse('a AND b AND c AND d')
[('a', ('b', ('c', 'd')))]
>>> query.parse('a AND b AND c AND d OR e AND f')
[('a', ('b', ('c', 'd'))), ('e', 'f')]
>>> query.parse('a AND b AND c AND d OR e OR f')
[('a', ('b', ('c', 'd'))), 'e', 'f']
>>> query.parse('foo AND bar')
[('foo', 'bar')]
>>> query.parse('"bar none" OR foo')
['bar none', 'foo']
>>> query.parse('key:value AND "hey now":5 OR "what is":up')
[({'key': 'value'}, {'hey now': '5'}), {'what is': 'up'}]
Run Code Online (Sandbox Code Playgroud)