Bison 解析全局变量和函数

Bison parse global variables and functions

我正在构建一个编译器是为了好玩,我目前停留在如何解析多个全局变量或函数定义在一个文件中时 f.e。

int a;
int b;

int main(){
    int c;
}

我的野牛文件(简化版)如下所示:

ROOT : GLOB { printf("%s\n", "ACCEPTED" }
     ;

VAR_DEC // Assume this matches correctly

FUNC_DEF // Assume this matches correctly

GLOB_STMNT : VAR_DEC {  }
           | FUNC_DEF {  }
           ; 

GLOB_LIST : GLOB_LIST GLOB_STMNT {  }
          | GLOB_STMNT {  }
          ;

GLOB : GLOB_LIST {  }
     ;

我的问题是,它总是只会减少 firstvar 声明,然后打印接受。关于如何改进最后 3 条规则以减少所有 3 条全局语句的任何想法?

"The algorithm used by the yacc parser encourages so-called left recursive grammar rules. Rules of the following form match this algorithm:

    seq : item 
        | seq item 
        ;

The first rule is reduced for the first item only; and the second rule is reduced for the second and all succeeding items."

所以你应该把你的规则写成:

GLOB_LIST : GLOB_STMNT {  }
          | GLOB_LIST GLOB_STMNT {  }
          ;