0
votes

I recently discovered lex and yacc (and flex and bison), and I get an error when trying to tell if a sentence is given to the program.

Here is the .lex file:

%{
        #include <stdio.h>
        #include "1.tab.h"
%}

%%
tweety|sylvester return NP;
a|the return AR;
cat|bird return NC;
run|fly return VI;
eat|hate return VT;
"." return POINT;
.|\n
%%

and the .yacc :

%{
        #include <stdio.h>
%}

%token NP AR NC VI VT POINT
%%
S: PH POINT {printf("Sentence found !\n");}
PH: GN VT GN|GN VI
GN: NP|AR NC
%%
main(){
    yyparse();
}

yyerror(char *s)
{
        fprintf(stderr, "error: %s\n", s);
}

Here is the command I use to compile the program:

lex file.lex
bison -d file.yacc
gcc lex.yy.c 1.tab.c -o test -lfl

When I try to run the program, it works well for the first input, but it then gives me an error quite often. Here's en example:

./test
tweety fly.
Sentence found !
tweety hate sylvester.
error: syntax error

Do you have any idea ?

Thank you.

1

1 Answers

1
votes

Your grammar only allows for one sentence in the input. You need a new first rule:

P : S | P S ;

where P is the new target symbol ('Program', 'Paragraph', etc., whatever you like).