我正在尝试使用parcon来解析布尔值语句和表达式的简单语法,如下所示:
foo = True
bar = foo or False
这是我正在尝试的语法定义:
from parcon import (
Word,
Literal,
SignificantLiteral,
Forward,
Return,
alpha_chars,
)
m_boolean = Literal("True")[lambda x: True] | Literal("False")[lambda x: False]
m_and = SignificantLiteral('and')(name='AND')
m_or = SignificantLiteral('or')(name='OR')
m_logical_operator = m_and | m_or
m_identifier = (Word(alpha_chars) - m_logical_operator)
m_expression = Forward()
m_subexpression = '(' + m_expression + ')'
m_term = m_boolean | m_identifier | m_subexpression
m_expression_tail= Forward()
m_infix_expression = m_term + m_expression_tail
m_expression_tail << (
(m_logical_operator + m_expression + m_expression_tail)
|
(Return(None))
)
m_expression << (m_term | m_infix_expression)
def test(toker, tests):
print '\n'
l = [x.strip() for x in tests.split('\n') if x.strip() != '']
for test in l:
print test, ':',
print toker.parse_string(test)
test(m_subexpression, '''
(True)
(foo)
''')
test(m_term, '''
True
foo
(True)
''')
test(m_infix_expression, '''
a and b
True and False
''')
test(m_expression, '''
True
( True )
True and False
a and b
not True
not a
True or (b)
a and (False)
foo
(foo)
(a or b) and (c or d)
''')
它适用于我的一些测试,但在解析m_expression
时我遇到了这个错误:
True and False :
Traceback (most recent call last):
File "boolean_parcon.py", line 78, in <module>
''')
File "boolean_parcon.py", line 18, in test
print toker.parse_string(test)
File "/usr/local/lib/python2.7/dist-packages/parcon/__init__.py", line 620, in parse_string
self, getattr(self,'name',''), format_failure(result.expected)))
parcon.ParseException: Parse (Forward() ) failure: At position 4: expected one of EOF
我不明白为什么。我想我已经消除了任何无限左递归的可能性。该错误似乎表明True and False
规则正在解析m_term
并放弃。在m_term
失败之后,我会想到,接下来会尝试m_infix_expression
。有什么指针吗?
或者,是否有人可以推荐一种语法定义工具,它可能比parcon更适合我?