I am new in Flex/Bison. I want to use only strings for values (is a language translator). I have this for test:
example.l:
%option noyywrap nodefault
%{
#include <string.h>
#include "example.tab.h"
%}
%%
[ \t\n] {;}
"<=" {return LEFT;}
"=>" {return RIGHT;}
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
. { return yytext[0]; }
%%
example.y:
%{
#include <stdio.h>
#define YYSTYPE char const *
%}
%token NUMBER
%token LEFT "<=" RIGHT "=>"
%%
start: %empty | start tokens
tokens:
NUMBER "<=" NUMBER { printf("%s <= %s\n",$1,$3); }
| NUMBER "=>" NUMBER { printf("%s => %s\n",$1,$3); }
| NUMBER '>' NUMBER { printf("%s > %s\n",$1,$3); }
| NUMBER '<' NUMBER { printf("%s < %s\n",$1,$3); }
%%
main(int argc, char **argv) { yyparse(); }
yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }
When I compiled:
bison -d example.y
flex example.l
cc -o example example.tab.c lex.yy.c -lfl
example.l: In function ‘yylex’:
example.l:13:9: warning: assignment makes integer from pointer without a cast
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
^
But work as awaited.
If I don't use #define YYSTYPE char const *
and use instead the %union:
%union {
char * txt;
}
%token <txt> NUMBER
And change the assignation to [0-9]+ { yylval.txt=strdup(yytext); return NUMBER; }
, it has no warning and works.
I tried thing like define the same YYSTYPE in flex file and cast the assignation without success. What is wrong? How to fix without using %union?
Thanks.
char *
and doing free():NUMBER "<=" NUMBER { printf("%s <= %s\n",$1,$3); free($1); free($3);} | | NUMBER "=>" NUMBER { printf("%s => %s\n",$1,$3); free($1); free($3);}
and so on. You can check your program with and without free for memory leaks with valgrind valgrind.org – komar