我正在尝试使用pyparsing在Python中实现一个简单的逻辑解析器。稍后需要解析以执行健全性检查。逻辑解析器的灵感来自simpleBool.py和fourFN.py(均由Paul McGuire提供)。
我想我几乎已经解决了,但是我的两个测试版都没有工作。我想我可能犯了一个思考错误,但我找不到它。所以我很高兴,如果有人能为我检查代码并帮助我理解,为什么它不起作用。这是我的pyparsing定义:
from pyparsing import Word, Keyword, infixNotation, Forward, nestedExpr, srange, opAssoc, nums, Suppress, ZeroOrMore, Group, Optional
TRUE = Keyword("True")
FALSE = Keyword("False")
boolOperand = TRUE | FALSE | Word(srange("[a-zA-Z0-9_']"))
LPARR,RPARR= map(Suppress, '()')
LPARC,RPARC=map(Suppress,'{}')
LPAR=LPARC | LPARR
RPAR=RPARC | RPARR
expr = Forward()
factor = Group(Optional(LPAR) + expr + Optional(RPAR)) | boolOperand
multibit = Group(Word(nums) + LPARC + factor + RPARC) | factor # should recognize expressions like 2{A & B}
inverted = ZeroOrMore('~') + multibit # should recognize expressions like ~A
leftsideor = ZeroOrMore('|') + inverted # should recognize expressions like |A, but also ~{A & B}
andterm = leftsideor + ZeroOrMore('&' + leftsideor) # should recognize expressions like |A & B
orterm = andterm + ZeroOrMore('|' + andterm) # should recognize expressions like A | B
expr = Group(Optional(LPAR) + orterm + ZeroOrMore(',' + orterm) + Optional(RPAR)) | orterm # {A,B,C&D}, (A,B,C&D)
以下是测试用例。
if __name__ == "__main__":
p = True
q = False
r = True
tests = ["p",
"q",
"p & q",
"p & ~q",
"(p & ~q)",
"{p & ~q}",
"~~p",
"q | ~p & r",
"q | ~p | ~r",
"q | ~(p & r)",
"p | q | r",
"p | q | r & False",
"(p | q | r) & False",
"|p",
"{p,q,d&c,r}",
"{2{p&q}}",
"{p,q,d&c,3'd4}",
"{2{p_1_&q}}",
"{2{p23padsf_1_&q_2_3}}",
"{~ITHERMSEL, ~IUNITSEL, ~IAVGSEL1} & {{2{EQEN}} , EQ3D }",
"{{~ITHERMSEL, ~IUNITSEL, ~IAVGSEL1} & {{2{EQEN}} , EQ3D }}",
"~(p & q)"
]
print()
for t in tests:
print t
res = expr.parseString(t)[0]
print res
print
以下测试用例存在问题:
{2{p&q}}
这被解析为2.我认为这里的问题是2可能是boolOperand,但是如何让booloperand排除数字(例如A2是好的,只有2个没有)
{{~ITHERMSEL, ~IUNITSEL, ~IAVGSEL1} & {{2{EQEN}} , EQ3D }}
没有最外面的花括号,它可以工作。使用附加括号时,会出现错误:
Traceback (most recent call last):
File "simpleVerilogLogic.py", line 104, in <module>
res = expr.parseString(t)[0]
File "/usr/lib/python2.6/site-packages/pyparsing-2.0.3-py2.6.egg/pyparsing.py", line 1125, in parseString
raise exc
pyparsing.ParseException: (at char 2), (line:1, col:3)
但我不明白问题所在。
也会出现同样的问题~(p & q)
我想我有某种基本的误解。我检查了不同的例子,但我无法弄清楚解决方案。如果有人能给我一个建议,我真的很感激。
非常感谢。