I am using Bison with Flex. I have 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 program that is partially correct, but then there is some "garbage" before EOF, it will reduce according to the previous rule, report "success" and only then report an error.
I want to include EOF at the end of the rule above, but then, Flex would have to return EOF when it read <<EOF>>
, and how would Bison know when to end the program?
Now, I have this in Flex:
<<EOF>> {return 0;}
Here is an example that would do that:
First the lex file:
In the
<INITIAL>
condition the end-of-file generates a tokenEOP
. 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:
The question in your title is a bit misleading as
bison
will always only reduce the internal start symbol ifEOF
is found, that is what the internal end-of-file token is for. The difference is that you wanted the action, printingsuccess
, in the grammar only to be executed after theEOF
has been found and not before. That is, reduction of your start symbol.