Reputation: 11
I'm trying to build my compile in lex and yacc for my work I try for a long time but still get a syntax error in output this is my yacc
%token <ival> DIGIT
%token LOAD
%token ADD
%token MOD
%token SUB
%token MUL
%token INC
%token DEC
%token WS
%token EOL
%%
line :LOAD WS DIGIT EOL{ printf("load_cmd :%d\n",$3); }
| ADD EOL{ printf("add!\n"); }
| MOD EOL{ printf("mod!\n"); }
| SUB EOL{ printf("sub!\n"); }
| MUL EOL{ printf("mul!\n"); }
| INC EOL{ printf("inc!\n"); }
| DEC EOL{ printf("dec!\n"); }
;
%%
this is lex:
load [l][o][a][d]
add [a][d][d]
sub [s][u][b]
mul [m][u][l]
mod [m][o][d]
inc [i][n][c]
dec [d][e][c]
digit [0-9]+
character [a-zA-Z]
eol [\n\r]
%%
{eol} {return(EOL);}
[\t]+ {return(WS);}
[ ]+ {return(WS);}
{digit} {yylval.ival = atoi(yytext);return(DIGIT);}
{load} { return(LOAD); }
{add} { return(ADD); }
{sub} { return(SUB); }
{mul} { return(MUL); }
{mod} { return(MOD); }
{inc} { return(INC); }
{dec} { return(DEC); }
. {return(yytext[0]);}
%%
the input is :
load 1
load 2
sub
load 5
mod
and the out put is
load_cmd :1
syntax error
I have already define EOF, but still get a syntax error at end of line, why ? I cannot figure out why I am getting these results.
there a only one line of output "load_cmd :1", so it may be a EOF problem? or not?
Upvotes: 1
Views: 310
Reputation: 241721
Your grammar describes a single line. So that's what the parser expects.
Parsers built with yacc/bison expect the entire input to match the grammar. So after the parser recognises a line
, it expects to see the end of the file. When it sees something else, it reports that the input did not match the grammar. In your case, that would happen even if the only thing it sees after the first line is some more whitespace.
A minimal modification to the grammar which allows any number of input lines is:
program: %empty
| program line
| program EOL
The last line allows empty lines in the input.
That needs to go before the definition of line
, since yacc/bison assumes that the first non-terminal defined is that root of the grammar. Alternatively, you could put %start program
into your bison file, to explicitly declare where the grammar starts.
Upvotes: 0