C “返回”;非整数“;来自yylex
我有一个从flex生成的扫描仪,它的输出不会被yacc或bison使用。yylex()需要返回指向类似令牌结构内存的指针,而不是指示令牌类型的intC “返回”;非整数“;来自yylex,c,flex-lexer,C,Flex Lexer,我有一个从flex生成的扫描仪,它的输出不会被yacc或bison使用。yylex()需要返回指向类似令牌结构内存的指针,而不是指示令牌类型的int // example definition from foo.l [A-Za-z_][A-Za-z0-9_]* { return scanner_token(T_IDENTIFIER); } // example implementation of scanner_token token *scanner_token(name) { to
// example definition from foo.l
[A-Za-z_][A-Za-z0-9_]* { return scanner_token(T_IDENTIFIER); }
// example implementation of scanner_token
token *scanner_token(name) {
token *t = (token *)calloc(1, sizeof(token));
t->name = name;
t->lexeme = (char *)calloc(yyleng + 1, 1);
if (t->lexeme == NULL) {
perror_exit("calloc");
}
memmove(t->lexeme, yytext, yyleng);
return t;
}
// example invocation of yylex
token *t;
t = (token *)yylex();
当然,编译警告我从指针返回整数而不进行强制转换。
我在flex手册页中看到,YY_DECL
控制如何声明扫描例程:
YY_DECL
控制扫描的方式
例程被声明。默认情况下
是“int yylex()
”,或者,如果
原型正在使用,“int
yylex(无效)
”。这个定义可能是错误的
通过重新定义“YY_DECL
”进行更改
宏
当我尝试重新定义YY_DECL
时,生成的C文件无法编译
#undef YY_DECL
#define YY_DECL (token *)yylex()
完成我所尝试的任务的正确方法是什么?yylex应该返回一个int。保持此行为,并在helper函数中封装对它的调用。助手返回您的令牌。别惹YY_DECL
[A-Za-z_][A-Za-z0-9_]* { return T_IDENTIFIER; }
token *scanner_token() {
token *t;
int name;
if ((name = yylex()) == 0)
return 0;
else {
t = (token *)calloc(1, sizeof(token));
t->name = name;
t->lexeme = (char *)calloc(yyleng + 1, 1);
if (t->lexeme == NULL)
perror_exit("calloc");
memmove(t->lexeme, yytext, yyleng);
return t;
}
}
token *t = scanner_token();
通常的语法是:
#define YY_DECL token *yylex(void)
此最小Flex源文件显示了如何:
%{
typedef struct token { int tok; } token;
#define YY_DECL token *yylex(void)
token t;
%}
%%
. { t.tok = 1; return &t; }
%%
它为我编译。如果在Yacc(Bison,Byacc)语法中使用,您是对的:yylex()应该返回一个int。因为问题断言那里没有使用词法分析器,所以它不再需要返回int。手册解释了如何修复它,使它不会返回int。