2015-02-02 2 views
0

Yacc/Bison에서 부모 규칙을 어떻게 알 수 있습니까 그에 따라 조치를 취할 수 있습니까? 예를 들어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. */ 
      } 
     } 

답변

3

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