为什么 yytext 会跳过 YACC 中的第一个输入?

Why does yytext skip the first imput in YACC?

我一直在处理示例问题,为表达式构造一个三地址代码。但令我惊讶的是,YACC 似乎跳过了我的第一个输入符号。我将在输出中附上一张图片以使其清晰。

规则并不太复杂,所以我似乎不明白问题出在哪里。

这是我的 lex 文件:

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

这是我的 yacc 文件:

%{
#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);}

我希望 A:ID 生产中的打印打印输入的 ID,但它打印的是“=”。 这是我的输出: my output

为了确保 A 被看到,yacc 必须提前(向前看)才能看到 =。这将覆盖您在 yytext 中的第一个标记。