Make bison decrease to start character only if EOF is found

I am using Bison with Flex. There is the following rule in my Yacc input file:

program     : PROGRAM m2 declarations m0 block {cout << "Success\n"} ;

The problem is that if I have a partially correct program, but then there is some β€œgarbage” before EOF, it will decrease according to the previous rule, report success and only then report an error.

I want to enable EOF at the end of the above rule, but then Flex will have to return the EOF when it reads <<EOF>>, and how would Bison know when to finish the program? Now I have this in Flex:

<<EOF>>    {return 0;}
0
source share
1 answer

Here is an example that would do this:

First 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;
}

<INITIAL> EOP. <INITIAL>, <<EOF>> . <REALLYEND>, "" .

:

%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();
}

, bison , EOF, , . , , success, , EOF , . , .

+1

All Articles