野牛:错误消息中包括行号 [英] Bison : Line number included in the error messages
问题描述
好的,所以我想我的问题是不言自明的.
OK, so I suppose my question is quite self-explanatory.
我目前正在Bison中构建一个解析器,我想使错误报告更好一些.
I'm currently building a parser in Bison, and I want to make error reporting somewhat better.
当前,我设置了%define parse.error verbose
(实际上会发出类似syntax error, unexpected ***********************, expecting ********************
的消息.
Currently, I've set %define parse.error verbose
(which actually gives messages like syntax error, unexpected ***********************, expecting ********************
.
我只想在错误消息中添加更多信息,例如行号(在输入/文件/等中)
All I want is to add some more information in the error messages, e.g. line number (in input/file/etc)
我当前的yyerror
(好吧...不寻常...大声笑):
My current yyerror
(well nothing... unusual... lol) :
void yyerror(const char *str)
{
fprintf(stderr,"\x1B[35mInterpreter : \x1B[37m%s\n",str);
}
PS
- 我已经阅读过最新的Bison文档,但是我似乎很迷路...
- 我还研究了
%locations
指令,该指令很可能非常接近我所需要的-但是,我仍然找不到完整的工作示例,并且不确定该如何使用.
- I've gone through the latest Bison documentation, but I seem quite lost...
- I've also had a look into the
%locations
directive, which most likely is very close to what I need - however, I still found no complete working example and I'm not sure how this is to be used.
推荐答案
所以,这里我有分步解决方案:
- 我们在语法文件中(在
%}
和第一个%%
之间)添加了%locations
指令 - 我们确保我们的词法分析器文件顶部包含解析器的包含内容(例如
#include "mygrammar.tab.h"
) - 我们在lexer文件中添加
%option yylineno
选项(在%}
和第一个%%
之间)
- We add the
%locations
directive in our grammar file (between%}
and the first%%
) - We make sure that our lexer file contains an include for our parser (e.g.
#include "mygrammar.tab.h"
), at the top - We add the
%option yylineno
option in our lexer file (between%}
and the first%%
)
现在,在我们的yyerror
函数(应该在我们的lexer文件中)中,我们可以自由地使用此... yylineno
(=正在处理的文件中的当前行) :
And now, in our yyerror
function (which will supposedly be in our lexer file), we may freely use this... yylineno
(= current line in file being processed) :
void yyerror(const char *str)
{
fprintf(stderr,"Error | Line: %d\n%s\n",yylineno,str);
}
是的.就那么简单! :-)
Yep. Simple as that! :-)
这篇关于野牛:错误消息中包括行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!