gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:29:49 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com