bison/flex: print erroneous line

Jakub M. picture Jakub M. · Jun 24, 2011 · Viewed 9k times · Source

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?

Answer

David Hammen picture David Hammen · Jun 24, 2011

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.