使用 yacc 时,如何告诉 yyparse() 要停止解析?
仍在学习 yacc 和 flex,并遇到了我的操作方法和教程未涵盖的场景。我正在尝试解析一个文件,并且在进行过程中,我正在对放置在 parser.y
文件中的代码进行一些辅助错误检查。当我遇到字典顺序正确(即解析正确匹配)但逻辑错误(意外值或不适当值)的内容时,如何让 yyparse 退出?另外,我可以让它返回一个错误代码给我,我可以在我的调用代码中检查吗?
/* Sample */
my_file_format:
header body_lines footer
;
header:
OBRACE INT CBRACE
|
OBRACE STRING CBRACE {
if ( strcmp ( $1, "Contrived_Example" ) != 0 ) { /* I want to exit here */ }
}
;
/* etc ... */
我意识到在我的示例中我可以简单地使用规则查找“Contrived_Example”,但我的观点是在 if
块中 - 我可以告诉 yyparse
我想要在这里停止解析?
Still learning yacc and flex, and ran across a scenario that the how-to's and tutorials that I have do not cover. I am trying to parse a file, and as I'm going along, I'm doing some secondary error checking in the code I've placed in my parser.y
file. When I come across something that is lexicographically correct (that is, the parse matches properly) but logically incorrect (unexpected value or inappropriate value), how do I get yyparse
to exit? Also, can I have it return an error code back to me that I can check for in my calling code?
/* Sample */
my_file_format:
header body_lines footer
;
header:
OBRACE INT CBRACE
|
OBRACE STRING CBRACE {
if ( strcmp ( $1, "Contrived_Example" ) != 0 ) { /* I want to exit here */ }
}
;
/* etc ... */
I realize that in my example I can simply look for "Contrived_Example" using a rule, but my point is in the if
-block -- can I tell yyparse
that I want to stop parsing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以根据您的具体需要使用宏
YYERROR
或YYABORT
。YYABORT
导致 yyparse 立即返回失败,而YYERROR
导致它表现得好像发生了错误并尝试恢复(如果无法恢复,将返回失败)恢复)。您还可以使用
YYACCEPT
使 yyparse 立即返回成功。You can use the macros
YYERROR
orYYABORT
depending on what exactly you want.YYABORT
causes yyparse to immediately return with a failure, whileYYERROR
causes it to act as if there's been an error and try to recover (which will return failure if it can't recover).You can also use
YYACCEPT
to cause yyparse to immediately return success.就我而言,我想在词法分析时停止解析,并且 YYERROR、YYABORT 可能不可用。您可以只返回 YYerror,它已在 y.tab.h 中定义,如下所示:
'[^'\n]*$ { yyerror("未终止的字符串");返回YY错误;}
为什么它有效? yacc 解析时首先执行 lex(),如果函数返回 YYerror,则转到 yyerrlab1。
In my case, I want to stop parsing when lexing, and YYERROR, YYABORT may be unavaliable. You can just return YYerror, which has defined in y.tab.h, like this:
'[^'\n]*$ { yyerror("Unterminated string"); return YYerror;}
Why it works? firstly executes lex() when yacc parsing and if the function returns YYerror, it goes to yyerrlab1.