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