2
votes

So I've got a Bison rule that looks like this:

VAR ID ':' INT '=' intexp ';' {printf("id is '%s'\n", $2);}

and I'm trying to print the value of the 'ID' using $2

when I pipe in my test code to parse

var x : int = 5;

Bison is printing:

id is 'x : int = 5;'

instead of what I want:

id is 'x'

ID is declared in my lexer as:

 {ID}        { yylval.id = yytext; return ID; }

and if I do a printf inside the lexer right here, the value of yytext is correct ('x')

And this is where I'm stuck. Using $2 prints the whole rest of the expression instead of just the specific ID and I have no idea why. Any insight would be greatly appreciated.

1

1 Answers

2
votes

You have to copy yytext, it's an internal buffer in flex.

I.e., instead of

{ID}        { yylval.id = yytext; return ID; }

something like:

{ID}    {yylval.id = malloc(yyleng + 1); strcpy(yylval.id, yytext); return ID;}

Obviously that's not robust, since it doesn't do error checking, and you have to deal with freeing the memory in the parser that doesn't end up in a tree, and deal with freeing it from the tree, etc. But that is the basic idea.