bison/flex:打印错误行
我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
行号很简单:
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.
yylineno
为您提供正在处理的 lineno您还可以让用户知道 yytext 中的哪些文本给出了错误,在 Flex 端:
yytext 仅包含匹配规则的文本。
如果你想给出整行,你必须自己做,打开文件查找行号
yylineno
并打印它,一个好的地方是提供你自己的yylineno
实现。代码>yyerror函数。yylineno
gives you the lineno being processedYou can also let the user know what text gave the error with yytext, in the flex side:
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 ofyyerror
function.