| 1 |
The tt(exp) nonterminal has several rules, one for each kind of |
| 2 |
expression. The first rule handles the simplest kind of expression: just a |
| 3 |
single number. The second handles additions, which are two expressions |
| 4 |
followed by a plus-sign. The third handles subtractions, and so on. |
| 5 |
verb( |
| 6 |
exp: |
| 7 |
NUM |
| 8 |
| |
| 9 |
exp exp '+' |
| 10 |
{ |
| 11 |
$$ = $1 + $2; |
| 12 |
} |
| 13 |
| |
| 14 |
exp exp '-' |
| 15 |
{ |
| 16 |
$$ = $1 - $2; |
| 17 |
} |
| 18 |
... |
| 19 |
) |
| 20 |
Normally the production rule separator `tt(|)' is used to separate the |
| 21 |
various production rules, but the rules could equally well have separately |
| 22 |
been defined: |
| 23 |
verb( |
| 24 |
exp: |
| 25 |
NUM |
| 26 |
; |
| 27 |
|
| 28 |
exp: |
| 29 |
exp exp '+' |
| 30 |
{ |
| 31 |
$$ = $1 + $2; |
| 32 |
} |
| 33 |
; |
| 34 |
|
| 35 |
exp: |
| 36 |
exp exp '-' |
| 37 |
{ |
| 38 |
$$ = $1 - $2; |
| 39 |
} |
| 40 |
; |
| 41 |
|
| 42 |
... |
| 43 |
) |
| 44 |
Most rules have actions assoicated with them computing the value of the |
| 45 |
expression using the values of the elements of production rules. For example, |
| 46 |
in the rule for addition, tt($1) refers to the first component tt(exp) and |
| 47 |
tt($2) refers to the second one. The third component, 'tt(+)', has no semantic |
| 48 |
value associated with it, but if it had you could refer to it as tt($3). When |
| 49 |
the parser's parsing function recognizes a sum expression using this rule, the |
| 50 |
sum of the two subexpressions' values is produced as the value of the entire |
| 51 |
expression. See section ref(ACTIONS). |
| 52 |
|
| 53 |
You don't have to define actions for every rule. When a rule has no action, |
| 54 |
b() by default copies the value of tt($1) into tt($$). This is what happens |
| 55 |
in the first rule (the one that uses tt(NUM)). |
| 56 |
|
| 57 |
The formatting shown here shows the recommended layout, but b() does not |
| 58 |
require it. You can alter whitespace as much as you like. |