Take the 2-minute tour ×

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 */
  header body_lines footer
    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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
will look into that; thanks. –  Will Mar 2 '11 at 2:56
+1 almost what I want - it does exit out of the parsing, albeit in a rather abrupt manner. –  Will Mar 2 '11 at 17:00

Your Answer


