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