Search code examples
cyacclex

Why does yytext skip the first imput in YACC?


I have been working with a sample problem to construct a three address code for an expression. But to my surprise, YACC seems to skip my first input symbol. I will attach an image with the output to make it clear.

The rules aren't too complicated so I don't seem to understand where the issue is.

Here is my lex file:

%{
#include"y.tab.h"
%}
%%
[a-zA-Z]+ return ID;
[0-9]+ return NUM;
. return yytext[0];
%%
int yywrap(){return 1;}

Here is my yacc file:

%{
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char st[50][50];
extern char * yytext;
int top=-1;char t[5]="0";char temp[5];
void push();
void code();
%}
%token NUM ID
%left '+' '-'
%left '*' '/'
%%
S:' 'E
|' 'A'='E
;
A:ID{push();printf("yytext is %s\n",yytext);}
;
E:E'+'{push();}T{code();}
|E'-'{push();}T{code();}
|T
;
T:T'*'{push();}F{code();}
|T'/'{push();}F{code();}
|F
;
F:ID{push();}
|NUM{push();}
;
%%
void push(){strcpy(st[++top],yytext);}

void code(){
strcpy(temp,"t");
strcat(temp,t);
t[0]++;
printf("%s = %s %s %s \n",temp,st[top-2],st[top-1],st[top]);
top=top-2;
strcpy(st[top],temp);

}

int main(){yyparse();}
int yyerror(){exit(0);}

i expect the print in the A:ID production to print the ID entered, but it is printing the '=' instead. here is my output: my output


Solution

  • In order to be sure that A was seen, yacc had to advance (look ahead) to see =. That overwrites your first token in yytext.