0
votes

In Yacc / Bison, how do I know the parent rules so I can take actions accordingly?

For example:

Module
    :ModuleName "=" Functions

Functions
    :Functions Function
    | Function

Function
    : DEF ID ARGS BODY
      {
           /* here, I would like to identify the parent rule and do something like this*/
          if ($parent_rule == "Module") {
              /* take some actions */
          } else {
              /* this means the Function is matched recursively from the Functions rule. */
          }
      }
1

1 Answers

4
votes

LR(1) parsers are bottom-up. The "parent rule" is not yet known when a given production is reduced.

In any event, your production Function is only ever reduced in the context of Functions, although there are two possible productions which might apply.

There is, of course, no problem determining which production applies in the production itself. So one would normally do something like this:

%type <FunctionList> Functions
%type <FunctionDef>  Function
...

%%

...

Functions
    : Functions Function
      { $$ = $1;
        $$.append($2);
      }
    | Function
      { $$ = newFunctionList();
        $$.append($1);
      }

Function
    : DEF ID ARGS BODY
      {
          $$ = newFunctionDef($2, $3, $4);
      }