I am using bison+flex to parse file. On error yyerror() is invoked. How can I get the line number or string that is violating the rules, to print it with the error message?
2 Answers
Line number is easy: yylineno
is the line number. Specify %option yylineno
at the top of your .l file.
Well, almost easy. Lookahead can sometimes make the line number be off by one. Instead of saying something like "Error occurred at line #xxx" you might want to say that the error occurred near line #xxx.
As far as the rest, it's up to you. You are going to have to capture the not-quite valid syntax and call the appropriate warning or error handler. See the O'Reilly "flex & bison" book for details; it has an entire chapter on error messages. An entire chapter is a bit too much to reproduce at this Q&A site.

- 32,454
- 9
- 60
- 108
-
2Thanks for a fast response. "As far as the rest, it's up to you" : ) well, that's the point of my question - how to capture the violating line that? – Jakub M. Jun 24 '11 at 12:11
-
1@user497208: A belated answer to your last question: You are (inadvertently) asking me to write a book, or a chapter of a book. Writing a book, or even a chapter or section of a book, is a bit beyond the scope internet Q&A sites such as Stack Overflow. I gave the name of a book that covers this topic in detail. Read it! – David Hammen Jun 26 '11 at 15:01
yylineno
gives you the lineno being processed
You can also let the user know what text gave the error with yytext, in the flex side:
0|([1-9]{DIG}*) {
String msg("some error with number: "); msg.append(yytext);
yyerror(msg.c_str());
}
yytext only contains the text for the matched rule.
If you want to give the entire line you'll have to do it your self, opening the file looking for line number yylineno
and print it, a good place to do that is providing your own implementation of yyerror
function.

- 450
- 5
- 18