I have written a flex and bison,
I am facing a problem which is illustrated via the below program.
The program is intended to parse the key-value pairs separated by an equals (=) sign
I am hoping that my bison script tokenizes the key and values and prints them.
Below is the snippet of my flex program
/* file : kvp.l */
#define YYSTYPE char*
. ; /* Do Nothing */
Below is the Bison program
/* file : kvp.y */
/* interface to the lexer */
int yyerror (char const *s);
%token IDENTIFIER EQUALS_OP
stmt: stmt pair | pair;
pair: IDENTIFIER EQUALS_OP IDENTIFIER
printf("YACC : Key = \"%s\"\n", $1);
printf("YACC : Equals = \"%s\"\n", $2);
printf("YACC : Value = \"%s\"\n", $3);
int yyerror (char const *s)
fprintf (stderr, "Error String = \"%s\"\n", s);
int main( int argc, char* argv)
The result which I am getting out of this program is as below.
[email protected]:~/stack-overflow$ flex kvp.l
[email protected]:~/stack-overflow$ bison -d --file-prefix=y kvp.y
[email protected]:~/stack-overflow$ gcc lex.yy.c y.tab.c -o parser
[email protected]:~/stack-overflow$ ./parser
YACC : Key = "earth=planet"
YACC : Equals = "=planet"
YACC : Value = "planet"
As one can see the tokens which are being printed is not right, the entire string beginning from the token is being printed.
Please tell me where I am going wrong in this program.
The problem is that you are saving a pointer to
yytext, which is later updated in the flex scanner. If you change that to save a copy of the string in
yytext, you will get more consistent results, e.g.,
yylval = strdup(yytext);
yylval = yytext;