error handling in YACC

微笑、不失礼 提交于 2019-12-04 15:51:13
Kaz

so i write a=7 (without ';') in a line it just says syntax error Error at line:7. so where is my error message_?

Your error action tells Yacc to discard tokens until it finds a ';' token. Until that happens, it cannot reduce by that rule.

Also, you should execute yyerrok; somewhere in the rule body to signal to the parser that recovery has been achieved. Optionally, you can use yyclearin; to also throw away the token that triggered the error. Doing this is tricky because you're guessing that the token is inappropriate. It can actually be the right token, but something else before it is missing! E.g you're seeing a semicolon, because a closing brace was left out, etc.

Error actions will not replace the behavior of calling yyerror. When a syntax error occurs, the parser will call yyerror with a message (usually "syntax error"), and then are the error productions considered. Error productions are not anything like "custom overrides for syntax errors". (It looks like you're expecting "syntax error" to be replaced with your own generic error message "You made an error".)

In the error production, if you can guess the nature of the error, you can print an additional diagnostic that is more helpful.

One thing that is useful is the yychar variable which tells you the lookahead token. You can check this in the error recovery rule and try to guess what went wrong based on its value. You can check this not only for your own token types but for the value YYEOF which indicates that the syntax error is due to reaching not some bad token, but the end of input.

I wrote a parser in which, in some error productions, I simply took the token from yychar and converted it to its descriptive name and printed the message "unexpected in ". This is better than nothing; it tells the user at which token does the syntax depart from what is expected.

Also, yacc parsers can produce diagnostics even in a correct parse! (Obviously; for instance, how else would you implement warnings for a language.) Basically you need some central error reporting function that you can call yourself, and which yyerror will also call. That function should set a flag indicating whether or not fatal errors occurred (or keep a count of how many errors, warnings, etc). You may want to, for instance, throw away the parse tree and bail the program with a failed termination status, if there were fatal errors, even if the parser recovered from any syntax errors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!