bison/flex:打印错误行

发布于 2024-11-17 03:43:35 字数 76 浏览 6 评论 0原文

我正在使用 bison+flex 来解析文件。出现错误时,调用 yyerror()。如何获取违反规则的行号或字符串,并与错误消息一起打印?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雄赳赳气昂昂 2024-11-24 03:43:35

行号很简单:yylineno 是行号。在 .l 文件顶部指定 %option yylineno

嗯,几乎很容易。前瞻有时会使行号偏离一。您可能不想说“错误发生在第 #xxx 行”,而是说错误发生在第 #xxx 行附近。

至于剩下的,就看你自己了。您将必须捕获不完全有效的语法并调用适当的警告或错误处理程序。详情请参阅 O'Reilly 的《flex & bison》一书;它有一整章关于错误消息。在这个问答网站上复制一整章有点太多了。

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.

心凉怎暖 2024-11-24 03:43:35

yylineno 为您提供正在处理的 lineno

您还可以让用户知道 yytext 中的哪些文本给出了错误,在 Flex 端:

0|([1-9]{DIG}*)    {
                    String msg("some error with number: "); msg.append(yytext);
                    yyerror(msg.c_str());
                   }

yytext 仅包含匹配规则的文本。

如果你想给出整行,你必须自己做,打开文件查找行号yylineno并打印它,一个好的地方是提供你自己的 yylineno 实现。代码>yyerror函数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文