Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bison/flex: print erroneous line

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?

like image 812
Jakub M. Avatar asked Jun 24 '11 11:06

Jakub M.


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.

like image 153
David Hammen Avatar answered Oct 14 '22 18:10

David Hammen


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.

like image 5
GriffinHeart Avatar answered Oct 14 '22 19:10

GriffinHeart