我正在尝试编写一个简单的语法,该语法可以接受以下形式的语句
7 = var int
9 = abc float
但是使用下面的LEX和YACC代码,生成的解析器会发出语法错误(调用yyerror)
LEX:---
[0-9]+ { yylval.num = atof(yytext); return NUM; }
"int" return INT;
"float" return FLOAT;
[a-z]+ { yylval.str = strdup(yytext); return ID; }
\n /* Ignore end of lines */
[ \t]+ /* Ignore white spaces and tabs */
YACC:---
%%
commands: /* empty */
| commands command
;
command:
int_exp
|
float_exp
;
int_exp: exp INT
;
float_exp: exp FLOAT
;
exp : NUM '=' ID
;
%%
答案 0 :(得分:2)
您需要在lex文件中为'='
定义一个标记,并使用其终端符号名称代替语法定义中的'='
。
[0-9]+ { yylval.num = atof(yytext); return NUM; }
"int" return INT;
"float" return FLOAT;
[a-z]+ { yylval.str = strdup(yytext); return ID; }
\n /* Ignore end of lines */
[ \t]+ /* Ignore white spaces and tabs */
"=" return ASSIGN;
exp : NUM ASSIGN ID
;