[英]How to store errors in PLY yacc
I am using ply.yacc for building a parser, and I'm interesting in storing all syntax errors in a list.我正在使用 ply.yacc 构建解析器,并且我对将所有语法错误存储在列表中很感兴趣。 I want something like this:
我想要这样的东西:
parser = yacc.yacc()
parser.errors = []
parser.parse(program)
print(parser.errors) # do something with parser.errors
The problem is that when I define the rule for handling error问题是当我定义处理错误的规则时
def p_error(p):
...
I don't how to access the parser instance, so I can append the error to my list.我不知道如何访问解析器实例,所以我可以将 append 错误添加到我的列表中。 For the lexer, I used ply.lex and solved this problem because the token t which is passed as argument in the rule definition has a reference to the lexer.
对于词法分析器,我使用了 ply.lex并解决了这个问题,因为在规则定义中作为参数传递的标记t具有对词法分析器的引用。
def t_error(t):
t.lexer.error.append(LexicographicError(t.lineno, t.value[0]))
Is there any way to do something similar with yacc parser???有没有办法用yacc解析器做类似的事情???
The argument to p_error
is usually a token (so the prototype would be better written def p_error(t):
), so you could add the errors to the same list as you used in your lexer. p_error
的参数通常是一个标记(因此原型最好写为def p_error(t):
),因此您可以将错误添加到您在词法分析器中使用的相同列表中。 But that's not ideal;但这并不理想。 first, because that's an odd place to keep the errors (both lexical and syntactical), and second because sometimes the argument to
p_error
is None
(when the error occurs at the end of input).首先,因为这是保留错误(词汇和句法)的奇怪位置,其次是因为有时
p_error
的参数是None
(当错误发生在输入末尾时)。
A better solution is to make the parser a class rather than a global, which is explained rather briefly in the Ply documentation (mostly by reference to the section on making the lexer a class).一个更好的解决方案是使解析器成为 class 而不是全局的,这在 Ply 文档中得到了相当简要的解释(主要是通过参考关于使词法分析器成为类的部分)。 Normally, you would build the parser in the Parser class's
__init__
method, saving it as self.parser
.通常,您会在 Parser 类的
__init__
方法中构建解析器,并将其保存为self.parser
。 Then all of the p_*
member functions take a self
argument, as with any class function, and you can store the error list as a member attribute.然后所有
p_*
成员函数都接受一个self
参数,就像任何 class function 一样,您可以将错误列表存储为成员属性。 (You can get at the parser
using self.parser
but I think keeping the list of errors in the object instance itself is cleaner than adding it to the parser instance.) (您可以使用
self.parser
获取parser
,但我认为在 object 实例本身中保留错误列表比将其添加到解析器实例更干净。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.