Rpcalc Expr
Previous: <Rpcalc Line=>RpcalcLine> * Next: <Rpcalc Lexer=>RpcalcLexf> * Up: <Rpcalc Rules=>RpcalcRulf>

#Wrap on
{fH5}Explanation of {fCode}expr{f}{f}

The {fCode}exp{f} grouping has several rules, one for each kind of expression.
The first rule handles the simplest expressions: those that are just numbers.
The second handles an addition-expression, which looks like two expressions
followed by a plus-sign.  The third handles subtraction, and so on.

#Wrap off
#fCode
exp:      NUM
        | exp exp '+'     \{ $$ = $1 + $2;    \}
        | exp exp '-'     \{ $$ = $1 - $2;    \}
        
        ;
#f
#Wrap on

We have used {fEmphasis}|{f} to join all the rules for {fCode}exp{f}, but we could
equally well have written them separately:

#Wrap off
#fCode
exp:      NUM ;
exp:      exp exp '+'     \{ $$ = $1 + $2;    \} ;
exp:      exp exp '-'     \{ $$ = $1 - $2;    \} ;
        
#f
#Wrap on

Most of the rules have actions that compute the value of the expression in
terms of the value of its parts.  For example, in the rule for addition,
{fCode}$1{f} refers to the first component {fCode}exp{f} and {fCode}$2{f} refers to
the second one.  The third component, {fCode}'+'{f}, has no meaningful
associated semantic value, but if it had one you could refer to it as
{fCode}$3{f}.  When {fCode}yyparse{f} recognizes a sum expression using this
rule, the sum of the two subexpressions' values is produced as the value of
the entire expression.  \*Note <Actions=>Actions>.

You don't have to give an action for every rule.  When a rule has no
action, Bison by default copies the value of {fCode}$1{f} into {fCode}$${f}.
This is what happens in the first rule (the one that uses {fCode}NUM{f}).

The formatting shown here is the recommended convention, but Bison does
not require it.  You can add or change whitespace as much as you wish.
For example, this:

#Wrap off
#fCode
exp   : NUM | exp exp '+' \{$$ = $1 + $2; \} | 
#f
#Wrap on

means the same thing as this:

#Wrap off
#fCode
exp:      NUM
        | exp exp '+'    \{ $$ = $1 + $2; \}
        | 
#f
#Wrap on

The latter, however, is much more readable.

