Next: , Previous: , Up: Bison Grammar Files   [Contents][Index]

3.6 Named References

As described in the preceding sections, the traditional way to refer to any semantic value or location is a positional reference, which takes the form $n, $$, @n, and @$. However, such a reference is not very descriptive. Moreover, if you later decide to insert or remove symbols in the right-hand side of a grammar rule, the need to renumber such references can be tedious and error-prone.

To avoid these issues, you can also refer to a semantic value or location using a named reference. First of all, original symbol names may be used as named references. For example:

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

Positional and named references can be mixed 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 names may be used for values and locations. Explicit 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; }

In order to access a semantic value generated by a midrule action, an explicit name may also be declared by putting a bracketed name after the closing brace of the midrule action code:

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

In references, in order to specify 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 symbol value $name followed by ‘.suffix’, i.e., an access to the suffix field of the semantic value. In order to force Bison to recognize ‘name.suffix’ in its entirety as the name of a semantic value, the bracketed syntax ‘$[name.suffix]’ must be used.

Next: Bison Declarations, Previous: Tracking Locations, Up: Bison Grammar Files   [Contents][Index]