Okay. So I was tasked to do a toy compiler in my compilers class and therefore I chose Bison and Flex. I've gotten most of the basics about Bison and know to some degree how LR, LALR and SLR parsers work. However, this is more of a technical problem. In my grammar I have started to add the error productions with the error
token. Now my problem is that everytime that Bison uses a rule with error
it prints syntax error
with yyerror
. I don't want this because I want a better message to display. An example:
I have the following rule to detect mismatched curly brackets (please keep in mind that uppercase are terminals and lowercase are non-terminals):
program_start:
PROGRAM IDENTIFIER '{' translation_unit '}'
| error '}' {yyerror("Mismatched }");}
;
So if I use a sample like:
program p {
}
}
Then clearly there is an unbalanced bracket. This however outputs:
LINE: 26 AT }
ERROR: syntax error
LINE: 26 AT }
ERROR: Mismatched }
With my yyerror
function being
void yyerror(const char* error_str) {
fprintf(stderr, "LINE: %d AT %c\nERROR: %s\n",yylineno, yytext[0], error_str);
}
So my problem really is that I don't want Bison to print "syntax error" and just print the error message I passed to yyerror
. I looked around in the Lex & Yacc book (I know it's not the same) and searched Google for anything to no avail.
error
productions in yacc/bison are for recovering from syntax errors, not for detecting them. So your rule program_start: error '}'
is basically saying "when there's a syntax error in a program_start
, recover from it by throwing away everything up to the next '}'
token". If you give it an input like program p { ..something with a syntax error.. }
, your rule can be used to recover from that error even though there are no imbalanced braces.
With this is mind, it makes sense what bison is doing -- it detects the syntax error, calls yyerror
to output a message, then tries to recover, looking for an error rule that can apply.
If you want to change/suppress the error message, you should do it yyerror
, not in the error recovery rule.