【发布时间】:2013-04-09 08:36:23
【问题描述】:
编辑:我做了第一个版本,Eike 帮助我在上面做了很多改进。我现在被困在一个更具体的问题上,我将在下面描述。您可以在history中查看原始问题
我正在使用 pyparsing 来解析一种用于从数据库请求特定数据的小语言。它具有众多关键字、运算符和数据类型以及布尔逻辑。
我正在尝试改进当用户出现语法错误时发送给用户的错误消息,因为当前的错误消息不是很有用。我设计了一个小例子,类似于我使用上述语言所做的,但要小得多:
#!/usr/bin/env python
from pyparsing import *
def validate_number(s, loc, tokens):
if int(tokens[0]) != 0:
raise ParseFatalException(s, loc, "number musth be 0")
def fail(s, loc, tokens):
raise ParseFatalException(s, loc, "Unknown token %s" % tokens[0])
def fail_value(s, loc, expr, err):
raise ParseFatalException(s, loc, "Wrong value")
number = Word(nums).setParseAction(validate_number).setFailAction(fail_value)
operator = Literal("=")
error = Word(alphas).setParseAction(fail)
rules = MatchFirst([
Literal('x') + operator + number,
])
rules = operatorPrecedence(rules | error , [
(Literal("and"), 2, opAssoc.RIGHT),
])
def try_parse(expression):
try:
rules.parseString(expression, parseAll=True)
except Exception as e:
msg = str(e)
print("%s: %s" % (msg, expression))
print(" " * (len("%s: " % msg) + (e.loc)) + "^^^")
所以基本上,我们可以用这种语言做的唯一事情就是写一系列x = 0,加上and和括号。
现在,有些情况下,当使用and 和括号时,错误报告不是很好。考虑以下示例:
>>> try_parse("x = a and x = 0") # This one is actually good!
Wrong value (at char 4), (line:1, col:5): x = a and x = 0
^^^
>>> try_parse("x = 0 and x = a")
Expected end of text (at char 6), (line:1, col:1): x = 0 and x = a
^^^
>>> try_parse("x = 0 and (x = 0 and (x = 0 and (x = a)))")
Expected end of text (at char 6), (line:1, col:1): x = 0 and (x = 0 and (x = 0 and (x = a)))
^^^
>>> try_parse("x = 0 and (x = 0 and (x = 0 and (x = 0)))")
Expected end of text (at char 6), (line:1, col:1): x = 0 and (x = 0 and (x = 0 and (xxxxxxxx = 0)))
^^^
实际上,如果解析器在and 之后不能解析(这里的解析很重要),它不会产生好的错误消息了:(
我的意思是解析,因为如果它可以解析5但解析操作中的“验证”失败,它仍然会产生一个很好的错误消息。但是,如果它无法解析有效的数字(如a)或有效的关键字(如xxxxxx),它将停止生成正确的错误消息。
有什么想法吗?
【问题讨论】:
-
对变量名也有一个验证解析操作。或者有一个像
Word(alphas)这样的catch all变量名,并对其进行解析操作,这总是会引发异常。 -
另外,您可以进行上一级的验证。有一个解析器
Word(alphas) - "==" - Word(nums)并对其进行更复杂的解析操作,以查找合法的变量名称,并确保数字的正确性。 -
目前,这将是最后的解决方案:)
-
原因很简单:解析器回溯:
"a = 0"是一个完整的程序。解析器碰巧最后检验了这个假设,它也失败了,因为"a = 0"后面还有更多的文本。这就是解析器期望“文本结束”的原因。它基本上是operatorPrecedence的一个实现细节。尽可能插入-以防止回溯,这将使错误消息至少稍微好一点。 -
我在
MatchFirst()的规则定义中将“+”替换为“-”,但它并没有改变任何东西:(我看不到其他地方可以使用它:(