我有一个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) {
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();
Run Code Online (Sandbox Code Playgroud)
当然,编译警告我返回使用指针进行整数而不进行强制转换.
我在flex手册页中读到了YY_DECL控制如何声明扫描例程的内容:
YY_DECL控制如何声明扫描例程.默认情况下,它是"int yylex()",或者,如果正在使用原型,"int yylex(void)".可以通过重新定义"YY_DECL"宏来更改此定义.
当我尝试重新定义时YY_DECL,生成的C文件无法编译.
#undef YY_DECL
#define YY_DECL (token *)yylex()
Run Code Online (Sandbox Code Playgroud)
完成我想要的东西的正确方法是什么?
正常的语法是:
#define YY_DECL token *yylex(void)
Run Code Online (Sandbox Code Playgroud)
这个最小的Flex源文件显示了如何:
%{
typedef struct token { int tok; } token;
#define YY_DECL token *yylex(void)
token t;
%}
%%
. { t.tok = 1; return &t; }
%%
Run Code Online (Sandbox Code Playgroud)
它为我编译.