所以我想避免全局变量,但我想使用Flex来标记输入。我想知道是否有可能将值传递给yylex,以便我可以摆脱全局s。
现在我有了这个
%{
#include
#include
#include
#include
#include "lex.h"
%}
%option noyywrap
digit [0-9]
alpha [a-zA-Z]
alphanum {alpha}|{digit}|"_"
%%
[\t\n ] printf("WS:\n");
{alpha}{alphanum}* printf("symbol: %s\n",yytext);
{digit}+ printf("int: %s\n",yytext);
{digit}+"."{digit} printf("float: %s\n",yytext);
"\"".*"\"" printf("litral: %s\n",yytext);
"+" printf("op: %s\n",yytext);
"-" printf("op: %s\n",yytext);
"*" printf("op: %s\n",yytext);
"/" printf("op: %s\n",yytext);
"%" printf("op: %s\n",yytext);
"=" printf("op: %s\n",yytext);
"" printf("op: %s\n",yytext);
"==" printf("op: %s\n",yytext);
"!=" printf("op: %s\n",yytext);
"(" printf("op: %s\n",yytext);
")" printf("op: %s\n",yytext);
"," printf("op: %s\n",yytext);
"=" printf("op: %s\n",yytext);
%%
void LexInit() {
Tokens = malloc(sizeof(TokenStream));
Tokens->size=0;
}
void LexPush(const char* str) {
size_t size = strlen(str);
char* newstr = malloc(size*sizeof(char));
realloc(Tokens->tokens,++Tokens->size*sizeof(char*));
}
void Lex(const char* filepath) {
LexInit();
yyin = fopen(filepath,"r");
yylex();
}
答案 0 :(得分:1)
您应该阅读与可重入和额外类型选项相关的文章。
/* An example of overriding YY_EXTRA_TYPE. */
%{
#include
#include
%}
%option reentrant
%option extra-type="struct stat *"
%%
__filesize__ printf( "%ld", yyextra->st_size );
__lastmod__ printf( "%ld", yyextra->st_mtime );
%%
void scan_file( char* filename )
{
yyscan_t scanner;
struct stat buf;
FILE *in;
in = fopen( filename, "r" );
stat( filename, &buf );
yylex_init_extra( buf, &scanner );
yyset_in( in, scanner );
yylex( scanner );
yylex_destroy( scanner );
fclose( in );
}
http://www.cse.yorku.ca/tdb/_doc.php/userg/man_g/file/flex/node/Extra%20Data