开发者

Bison: print stack with names on error

开发者 https://www.devze.com 2023-03-29 08:41 出处:网络
How can I display items on stack in yyerror function? I\'ve found yy_stack_print but it only prints numb开发者_开发知识库ers and requires 2 arguments which I don\'t how how to obtain.Unfortunately the

How can I display items on stack in yyerror function? I've found yy_stack_print but it only prints numb开发者_开发知识库ers and requires 2 arguments which I don't how how to obtain.


Unfortunately there is no public API to print the current stack contents. If you are not afraid to use possible-changing internals, you can access the parser state stack via the yyss(topmost) and yyssp(current item) variables, the value stack is represented by the yyvs and yyvsp variables. Both variables are variables of the yyparse function, and storing them at the parser start might not be sufficient if the parser is allowed to grow the stacks on demand.

You need to be aware that these variables are not guaranteed to exist in parsers which are generated with other versions of bison, and also that they might change their function in future bison versions.

If you only want to avoid these low quality "syntax error" messages, you can add %error-verbose at the top of the file, which makes bison to generate more user-friendly error messages.

$ cat foo.y
%token FOO
%token BAR
%token BAZ

%error-verbose

%{
void yyerror(const char* m);
%}

%%

file: FOO BAR | FOO BAZ;

%%

#include <stdio.h>

int yylex()
{
    return FOO;
}

void yyerror(const char* m)
{
    fprintf(stderr, "Error:%s\n", m);
}

int main()
{
    yyparse();
}

$ bison foo.y && gcc foo.tab.c && ./a.out
Error:syntax error, unexpected FOO, expecting BAR or BAZ
0

精彩评论

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

关注公众号