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

标签 c yacc lex

我一直在处理一个示例问题来为表达式构造三地址代码。但令我惊讶的是,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 中的第一个标记。

关于c - 为什么 yytext 会跳过 YACC 中的第一个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55865265/

相关文章:

c - lextestpass.l :384: error: expected expression before ‘int’

c - Kernighan/Ritchie 的第 5.10 节命令行参数/可选参数

c++ - 是否可以堆叠Yacc文法规则代码?

parsing - lex & yacc 多重定义错误

c - 是否可以获取代币的值(value)?

bison - Lexx 和 Yacc 将 C 语法解析为符号表

c - 我如何错误地使用 C 中的 round() 函数?

c - 如何获取存储在数组中的字符串长度 (C)

ios - 将数据从支持 BLE 的 arduino 发送到 iOS 应用程序

parsing - 从生成的解析表中检索语法规则