Search code examples
cyacclex

Yacc actions return 0 for any variable ($)


I'm new to Lex/Yacc. Found these lex & yacc files which parse ansi C.

To experiment I added an action to print part of the parsing:

constant
    : I_CONSTANT    { printf("I_CONSTANT %d\n", $1); }
    | F_CONSTANT
    | ENUMERATION_CONSTANT  /* after it has been defined as such */
    ;

The problem is, no matter where I put the action, and whatever $X I use, I always get value 0.

Here I got printed:

I_CONSTANT 0

Even though my input is:

int foo(int x)
{
    return 5;
}

Any idea?


Solution

  • Nothing in the lex file you point to actually sets semantic values for any token. As the author says, the files are just a grammar and "the bulk of the work" still needs to be done. (There are other caveats having to do with the need for a preprocessor.)

    Since nothing in the lex file ever sets yylval, it will always be 0, and that is what yacc/bison will find when it sets up the semantic value for the token ($1 in this case).