Make bison reduce to start symbol only if EOF is found

时光怂恿深爱的人放手 提交于 2019-12-02 08:59:02

Here is an example that would do that:

First the lex file:

%{
#include "grammar.tab.h"
%}
%x REALLYEND
%option noinput nounput
%%
"END"                   { return END; }
.                       { return TOK; }
<INITIAL><<EOF>>        { BEGIN(REALLYEND); return EOP; }
<REALLYEND><<EOF>>      { return 0; }
%%

int yywrap(void)
{
        return 1;
}

In the <INITIAL> condition the end-of-file generates a token EOP. Note the explicit use of <INITIAL>, because otherwise the <<EOF>> will be used for all begin conditions. Then it switches to <REALLYEND> to generate the internal end-of-file "token" for bison.

The bison file could look like this:

%token END EOP TOK
%{
#include <stdio.h>
void yyerror(char * msg)
{
        fprintf(stderr, "%s\n", msg);
}
extern int yylex(void);
%}
%%
prog : END EOP { printf ("ok\n"); };
%%

int main(void)
{
        return yyparse();
}

The question in your title is a bit misleading as bison will always only reduce the internal start symbol if EOF is found, that is what the internal end-of-file token is for. The difference is that you wanted the action, printing success, in the grammar only to be executed after the EOF has been found and not before. That is, reduction of your start symbol.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!