0
votes

I wrote a simple C-like grammar in Bison, and I have a weird problem.

In the following rule:

declaration:        "identifier" length init_values                      
                    {symbolTable.add($3,$4,$5);}

I want to get the int values of length and init_values, which are nonterminals, to store them in the symbol table. identifier is a token, and its literal value is stored correctly. However, I'm getting some integer values like 66236273 for the other symbols.

The nonterminal rules are:

length:             "number" {};                         
init_values:        "number" {};

I tried using tokens directly instead of nonterminals, but the parser couldn't differentiate between number and length and so on. It just parsed all integers as number, which made it crash.

Does anyone know how to get the actual values of these? i.e. the number values, which I was able to find in the last rules, but somehow they get lost when the parser goes a step back to the first rule.

1
Why are you using $3, $4, $5? There are only three symbols on the right hand side of that rule, so they should be. $1, $2, $3.rici

1 Answers

0
votes

Without seeing more of your grammar and scanner definitions, it is hard to say for sure what you are doing wrong. But here are a few suggestions:

  1. {symbolTable.add($3,$4,$5);} is incorrect with the provided grammar rule; it should be {symbolTable.add($1,$2,$3);} since right-hand-side values are counted from left to right starting with $1.

  2. Assuming that "identifier" is a char * and "integer" is a long (or some such), it is important that all terminals and non-terminals be declared with the correct semantic value tag. See the bison manual.

  3. There is no need for length: "number" {};, but since the default action is effectively $$ = $1, it shouldn't do any harm as long as both length and "number" are declared with the correct type tag. I have no idea what you mean by "I tried using tokens directly instead of nonterminals" if it doesn't mean that you tried declaration: "identifier" "number" "number"; there is no reason why that shouldn't work (as long as the type declarations are correct).

  4. If you are passing character strings in yylval, make sure you are copying the strings. yylval.str = yytext; is not correct, and will get you into trouble. See this FAQ entry.