为什么生成的解析器会出现语法错误?
Why generated parser issues syntax error?
我正在尝试编写一个简单的语法,它接受以下形式的语句
7 = var int
9 = abc float
但对于以下 LEX 和 YACC 代码,生成的解析器会出现语法错误(调用 yyerror)
莱克斯:---
[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
;
%%
您需要在您的 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
;
我正在尝试编写一个简单的语法,它接受以下形式的语句
7 = var int
9 = abc float
但对于以下 LEX 和 YACC 代码,生成的解析器会出现语法错误(调用 yyerror)
莱克斯:---
[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
;
%%
您需要在您的 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
;