Search code examples
projectbisonyacclex

How can I customize my error message in yacc/lex project to display the line and type of problem?


I am new in programming but I have a yacc/lex project and some difficulty in writing the error message in detail (line and type of error). Any help with a small example, please.


Solution

  • Add the following to your flex scanner definition, to cause the scanner to track line numbers:

    %option yylineno
    

    (See the flex manual.)

    Then add the following declarations to your bison grammar:

    %define parse.error verbose
    %define parse.lac full
    

    (See the bison manual chapters on error reporting and LAC (lookahead correction).

    Finally, use a definition of yyerror which uses the line number information. At a minimum, something like:

    void yyerror(const char* msg) {
      fprintf(stderr, "At line %d: %s\n", yylineno, msg);
    }