I'm currently trying to write a small compiler using Flex+Bison but I'm kinda of lost in terms of what to do with error handlling, specially how to make everything fit together. To motivate the discussion consider the following lexer fragment I'm using for string literals:
["] { BEGIN(STRING_LITERAL); init_string_buffer(); }
<STRING_LITERAL>{
\\\\ { add_char_to_buffer('\\'); }
\\\" { add_char_to_buffer('\"'); }
\\. { /*Invalid escape. How do I treat this error?*/ }
["] { BEGIN(INITIAL); yylval = get_string_buffer(); return TK_STRING; }
}
How do I handle the situation with invalid escapes? Right now I'm just printing an error message and calling exit
but I'd prefer to be able to keep going and detect more than one error per file if possible.
My questions:
- What function do I use to print out error messages? The same yyerror expected by bison later on? Where do I put the definition of yyerror if I have separate files for the lexer and parser?
- What token code should I return from my action? 0 for "end of file"? Some special TK_INVALID_STRING token?
- How do I make sure the parser can continue parsing after lexical errors (invalid literals, stray punctuation characters, etc)?