开发者

bison/flex: print erroneous line

I am using bison+flex to parse f开发者_如何学JAVAile. 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜