简单解析器生成器的 yylex 错误
yylex errors for simple parser generator
我只是在做家庭作业,我必须制作一个简单的多项式解析器生成器。所以它必须接受这样的赋值:a= 2x2+2 并且像 a[2] 这样的评估将打印 10。如果单独输入 a,它应该打印 2x2+2。它应该适用于任何多项式。在我应该使用的另一个文件中定义了一个 typedef 结构:
typedef struct Polyn {
int sign;
int coeff;
int exp;
struct Polyn *next;
} Polyn;
lex 文件:
%option noyywrap
%{
#include <stdio.h>
#include <string.h>
#define YY_DECL int yylex()
#include "calc.tab.h"
%}
%%
[0-9]+ {yylval = atoi(yytext); return T_INT;}
[a-wy-z]+ {yylval.string=strdup(yytext); return T_IDENT;}
. {return 1;}
<<EOF>> {return 0;}
%%
野牛档案:
%{
#include <stdio.h>
#include <stdlib.h>
#include "polyn.h"
#include "symbtab.h"
extern int yylex();
extern int yyparse();
void yyerror(const char* s);
%}
%token T_INT
%token T_EQUAL
%token T_IDENT T_POLYN
%start input
%%
input:
%empty
| input line
;
line:
T_NEWLINE
| expression T_NEWLINE { printf("\tResult: %i\n", ); }
| assign T_NEWLINE ;
| T_QUIT T_NEWLINE { exit(0); }
;
expression:
T_INT { $$ = ; }
| expression T_PLUS expression { $$ = + ; }
| expression T_MINUS expression { $$ = - ; }
| expression T_MULTIPLY expression { $$ = * ; }
| expression T_DIVIDE expression { $$ = / ; }
| T_LROUND expression T_RROUND { $$ = ; }
;
%%
int main() {
while (yyparse());
return 0;
}
void yyerror(const char* s) {
fprintf(stderr, "Parse error: %s\n", s);
}
当我 运行 现在进行测试时,我遇到了一个错误
./m
calc.y:54.5-11: warning: type clash on default action: <p> != <> [-Wother]
T_POLYN
^^^^^^^
calc.l: In function ‘yylex’:
calc.l:15:9: error: incompatible types when assigning to type ‘YYSTYPE {aka union YYSTYPE}’ from type ‘int’
[0-9]+ {yylval = atoi(yytext); return T_INT;}
^
calc.l:26:8: error: ‘YYSTYPE {aka union YYSTYPE}’ has no member named ‘string’
[a-wy-z]+ {yylval.string=strdup(yytext); return T_IDENT;}
YYSTYPE
是由 .y 文件中的 %union
指令定义的(联合)类型:
%union {
int intval;
char *chstr;
struct Polyn *p;
}
所以它是一个包含 3 个字段的联合:intval
、chstr
和 p
。现在看看你的错误:
calc.l:15:9: error: incompatible types when assigning to type ‘YYSTYPE {aka union YYSTYPE}’ from type ‘int’
[0-9]+ {yylval = atoi(yytext); return T_INT;}
您正在尝试将 atoi
(整数)中的 return 值分配给联合。类型不一样,所以你会从 C 编译器中得到一个类型错误。你需要 yylval.intval = atoi(
...
calc.l:26:8: error: ‘YYSTYPE {aka union YYSTYPE}’ has no member named ‘string’
[a-wy-z]+ {yylval.string=strdup(yytext); return T_IDENT;}
您正在尝试分配给联合的 string
字段,该字段不存在。你需要 yylval.chstr=
...
这些错误是简单的 C 错误,您使用 flex 和 bison 的事实是偶然的。