Previous: Mid-Rule Actions, Up: Semantics


3.5.6 Using Named References

While every semantic value can be accessed with positional references $n and $$, it's often much more convenient to refer to them by name. First of all, original symbol names may be used as named references. For example:

     invocation: op '(' args ')'
       { $invocation = new_invocation ($op, $args, @invocation); }

The positional $$, @$, $n, and @n can be mixed with $name and @name arbitrarily. For example:

     invocation: op '(' args ')'
       { $$ = new_invocation ($op, $args, @$); }

However, sometimes regular symbol names are not sufficient due to ambiguities:

     exp: exp '/' exp
       { $exp = $exp / $exp; } // $exp is ambiguous.
     
     exp: exp '/' exp
       { $$ = $1 / $exp; } // One usage is ambiguous.
     
     exp: exp '/' exp
       { $$ = $1 / $3; } // No error.

When ambiguity occurs, explicitly declared symbol names may be used. Explicit symbol names are declared as a bracketed name after a symbol appearance in rule definitions. For example:

     exp[result]: exp[left] '/' exp[right]
       { $result = $left / $right; }

Explicit symbol names may be declared for RHS and for LHS symbols as well. In order to access a semantic value generated by a mid-rule action, an explicit symbol name may also be declared by putting a bracketed name after the closing brace of the mid-rule action code:

     exp[res]: exp[x] '+' {$$ = $x;}[left] exp[right]
       { $$ = $left + $right; }

In order to access symbol names containing dots and dashes, an explicit bracketed syntax $[name] and @[name] must be used:

     if-stmt: IF '(' expr ')' THEN then.stmt ';'
       { $[if-stmt] = new_if_stmt ($expr, $[then.stmt]); }

It often happens that named references are followed by a dot, dash or other C punctuation marks and operators. By default, Bison will read $name.suffix as a reference to $name symbol followed by .suffix, i.e., an access to the suffix field of the semantic value. In order to force Bison to resolve a named reference as a reference to a symbol having the format name.suffix, bracketed syntax $[name.suffix] must be used.