c - Bison解析全局变量和函数

标签 c parsing compiler-construction grammar bison

我正在构建一个编译器是为了好玩,目前我陷入了当多个全局变量或函数定义位于单个文件中时如何解析的问题

int a;
int b;

int main(){
    int c;
}

我的 Bison 文件(简化)如下所示:

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

关于c - Bison解析全局变量和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52344489/

相关文章:

c - 使用通过 MacPorts 安装的 GD2 库通过 GCC 编译 C 程序的问题

visual-studio-2008 - 如何全局设置 Visual Studio 2008 C/C++ 编译器选项?

c - 我如何返回双倍?

c++ - logb() 和 ilogb() 有什么区别?

位域结构可以实例化为立即数吗?

java - 使用打开的csv解析txt文件

c - 非常基本的 C 问题

PHP PDO MySQL高效解析SQL查询结果

Python - 解析带有自定义价格单位的字符串

c++ - 现代编译器是否优化 1 和 -1 的乘法