Yacc / Bison父母规则

时间:2015-02-02 17:59:25

标签: bison yacc

在Yacc / Bison中,我如何知道父规则,以便我可以采取相应的行动?

例如:

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 个答案:

答案 0 :(得分:4)

LR(1)解析器是自下而上的。当给定的产量减少时,“父规则”尚不清楚。

无论如何,您的作品Function只会在Functions的上下文中减少,尽管可能会有两种可能适用的作品。

当然,确定哪种生产适用于生产本身没有问题。所以通常会做这样的事情:

%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);
      }