Next: , Previous: , Up: Mid-Rule Actions   [Contents][Index]


3.4.8.2 Typed Mid-Rule Actions

In the above example, if the parser initiates error recovery (see Error Recovery) while parsing the tokens in the embedded statement stmt, it might discard the previous semantic context $<context>5 without restoring it. Thus, $<context>5 needs a destructor (see Freeing Discarded Symbols), and Bison needs the type of the semantic value (context) to select the right destructor.

As an extension to Yacc’s mid-rule actions, Bison offers a means to type their semantic value: specify its type tag (‘<...>’ before the mid-rule action.

Consider the previous example, with an untyped mid-rule action:

stmt:
  "let" '(' var ')'
    {
      $<context>$ = push_context (); // ***
      declare_variable ($3);
    }
  stmt
    {
      $$ = $6;
      pop_context ($<context>5);     // ***
    }

If instead you write:

stmt:
  "let" '(' var ')'
    <context>{                       // ***
      $$ = push_context ();          // ***
      declare_variable ($3);
    }
  stmt
    {
      $$ = $6;
      pop_context ($5);              // ***
    }

then %printer and %destructor work properly (no more leaks!), C++ variants can be used, and redundancy is reduced (<context> is specified once).