开发者

passing values to yylex

so i want to avoid global variables but i want to use Flex to tokenize input. i want to know if it is possible to pass a value to yylex so that i can get rid of global s.

right now i have this


%{
#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("symbo开发者_JAVA技巧l: %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();
}


You should read article related to the reentrant and extra-type options.

    /* 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜