1

I have a parser with me generated from yacc/lex. It is working fine for all the rules I have set except one case.

If file is empty which this parser is parsing it gives error. I want to add rule so that it does not give error when file is empty. I have not added any checks for that in either of my .l/.y file.

How can this be done with YACC/LEX?

Thanks in advance !!

nav_jan
  • 2,473
  • 4
  • 24
  • 42

1 Answers1

2

The lexer should recognize the end of input and return a token accordingly (i.e. EOF).

Your grammar's start rule could look like this:

%start program

...

program : EOF 
        | instructions EOF
        ;

As Ira Baxter pointed out a simple "empty" rule would also suffice. The GNU bison manual provides an example for this:

input   : /* empty */
        | input line
        ;
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
  • as you suggested i tried to recognize EOF in lexer i am foing this by `. { if(yytext[0]==EOF){ return tk_eof; } }` but by debugging i came to know that this check is never true am I doing something wrong here? – nav_jan Jun 15 '12 at 09:03
  • 2
    I think you'd be better off using an [End-Of-File rule](http://flex.sourceforge.net/manual/EOF.html#EOF). – Linus Kleen Jun 15 '12 at 09:07
  • 2
    Why can't he simply write: "program : | instruction"? – Ira Baxter Jun 15 '12 at 10:46
  • @LinusKleen Thanks!! that link in your last comment helped a lot. – nav_jan Jun 15 '12 at 12:29