parsingerror-handlingyacc

When using yacc, how do you tell yyparse() that you want to stop parsing?


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?


Solution

  • 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.