Reputation: 3670
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?
Upvotes: 4
Views: 3208
Reputation: 1
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.
Upvotes: -1
Reputation: 126508
You can use the macros YYERROR
or YYABORT
depending on what exactly you want. YYABORT
causes yyparse to immediately return with a failure, while YYERROR
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.
Upvotes: 6