(bison.info)Actions


Next: Action Types Prev: Multiple Types Up: Semantics

Actions
-------

   An action accompanies a syntactic rule and contains C code to be
executed each time an instance of that rule is recognized.  The task of
most actions is to compute a semantic value for the grouping built by
the rule from the semantic values associated with tokens or smaller
groupings.

   An action consists of C statements surrounded by braces, much like a
compound statement in C.  It can be placed at any position in the rule;
it is executed at that position.  Most rules have just one action at
the end of the rule, following all the components.  Actions in the
middle of a rule are tricky and used only for special purposes (Note:
Actions in Mid-Rule.).

   The C code in an action can refer to the semantic values of the
components matched by the rule with the construct `$N', which stands for
the value of the Nth component.  The semantic value for the grouping
being constructed is `$$'.  (Bison translates both of these constructs
into array element references when it copies the actions into the parser
file.)

   Here is a typical example:

     exp:    ...
             | exp '+' exp
                 { $$ = $1 + $3; }

This rule constructs an `exp' from two smaller `exp' groupings
connected by a plus-sign token.  In the action, `$1' and `$3' refer to
the semantic values of the two component `exp' groupings, which are the
first and third symbols on the right hand side of the rule.  The sum is
stored into `$$' so that it becomes the semantic value of the
addition-expression just recognized by the rule.  If there were a
useful semantic value associated with the `+' token, it could be
referred to as `$2'.

   If you don't specify an action for a rule, Bison supplies a default:
`$$ = $1'.  Thus, the value of the first symbol in the rule becomes the
value of the whole rule.  Of course, the default rule is valid only if
the two data types match.  There is no meaningful default action for an
empty rule; every empty rule must have an explicit action unless the
rule's value does not matter.

   `$N' with N zero or negative is allowed for reference to tokens and
groupings on the stack _before_ those that match the current rule.
This is a very risky practice, and to use it reliably you must be
certain of the context in which the rule is applied.  Here is a case in
which you can use this reliably:

     foo:      expr bar '+' expr  { ... }
             | expr bar '-' expr  { ... }
             ;
     
     bar:      /* empty */
             { previous_expr = $0; }
             ;

   As long as `bar' is used only in the fashion shown here, `$0' always
refers to the `expr' which precedes `bar' in the definition of `foo'.


automatically generated by info version 1.5

Dirfile and infopages generated Sat Dec 3 02:07:54 2005