| 1 |
A program usually must do more than just parse its input; it must also produce |
| 2 |
some output based on the input. In a b() grammar, a grammar rule can have an |
| 3 |
action consisting of bf(C++) statements. Each time the parser recognizes a |
| 4 |
match for that rule, its associated action is executed. See section |
| 5 |
ref(ACTIONS). |
| 6 |
|
| 7 |
The purpose of an action usually is to compute the semantic value of the whole |
| 8 |
construct from the semantic values of its parts. For example, suppose we have |
| 9 |
a rule stating that an expression can be the sum of two expressions. Once the |
| 10 |
parser has recognized the rule's parts, each of its subexpressions has a |
| 11 |
semantic value of its own. The action for this rule |
| 12 |
could consist of a bf(C++) expression computing the rule's semantic value from |
| 13 |
its subexpressions. |
| 14 |
|
| 15 |
Actions usually compute semantic values and refer to semantic values of |
| 16 |
elements of production rules. This happens so frequently that several |
| 17 |
shorthand notations can be used to simplify referring to semantic |
| 18 |
values. These shorthand notations are covered extensively in section |
| 19 |
ref(ACTIONS) and its sub-sections. |
| 20 |
|
| 21 |
For example, here is a rule stating that an expression can be the sum of two |
| 22 |
subexpressions: |
| 23 |
verb( |
| 24 |
expr: expr '+' expr |
| 25 |
{ |
| 26 |
$$ = $1 + $3; |
| 27 |
} |
| 28 |
; |
| 29 |
) |
| 30 |
The action defines how the semantic value of the rule (using shorthand |
| 31 |
tt($$)) is computed from the values of the two sub-expressions (shorthands |
| 32 |
tt($1) and tt($3)). |