Yacc Inherited Attributes

The examples so far have used synthesized attributes. At any point in a syntax tree we can determine the attributes of a node based on the attributes of its children. Consider the rule

expr: expr '+' expr           { $$ = $1 + $3; }

Since we are parsing bottom-up, the values of both operands are available and we can determine the value associated with the left-hand side. An inherited attribute of a node depends on the value of a parent or sibling node. The following grammar defines a C variable declaration:

decl: type varlist
type: INT | FLOAT
varlist: 
        VAR                   { setType($1, $0); }
        | varlist ',' VAR     { setType($3, $0); }

Here is a sample parse:

. INT VAR
INT . VAR
type . VAR
type VAR .
type varlist .
decl .

When we reduce VAR to varlist we should annotate the symbol table with the type of the variable. However, the type is buried in the stack. This problem is resolved by indexing back into the stack. Recall that $1 designates the first term on the right-hand side. We can index backwards, using $0, $-1, and so on. In this case, $0 will do just fine. If you need to specify a token type, the syntax is $<tokentype>0, angle brackets included. In this particular example care must be taken to ensure that type always precedes varlist.