对应虎书第2章。chap3例程。
1、windows已安装mingw和flex:
2、下载bison,并修改环境变量,选择安装目录时,路径中不能带有空格和中文
3、开启调试模式:在tiger.grm中加入int yydebug =1;
2、cmd使用命令将tiger.grm生成为.c.h文件:
bison -l --defines=y.tab.h --report=all --report-file=my.report --output=y.tab.c tiger.grm --debug
3、不使用提供的lex.yy.c,使用自己的tiger.lex,生成lex.yy.c文件:flex my_tiger.lex
4、依次输入如下命令,或创建批处理文件:
gcc -g -c util.c
gcc -g -c lex.yy.c
gcc -g -c errormsg.c
gcc -g -c y.tab.c
gcc -g -c parsetest.c
这里可能有报waring,在开头添加#include <stdlib.h>,可取消waring
gcc -g -o mytest.exe parsetest.o y.tab.o lex.yy.o errormsg.o util.o
5、测试,找一个tiger程序文件“test2.tig”,输入mytest.exe test2.tig,可看到输出,此时的语法分析器的功能只能识别ID,无其它功能。
下面是我写的tiger语法分析和测试用代码,testcases内的文件除tiger49.tig(这个文件本身有错)全部通过:
测试运行用代码parsetest.c(可读取一个目录下所有tig文件进行测试):
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include "util.h"
#include "errormsg.h"
extern int yyparse(void);
void parse(string fname)
{EM_reset(fname);
if (yyparse() == 0) /* parsing worked */
printf("Parsing successful!\n");
else printf("Parsing failed\n");
}
int main(int argc, char **argv) {
DIR *dp;
struct stat buf;
struct dirent *dirp;
char dirname[256];
if (argc<2) {fprintf(stderr,"usage: a.out filename\n"); exit(1);}
for (int c=1; c < argc; c++) {
printf("next:%s\r\n ", argv[c]);
if (stat(argv[c], &buf) < 0) {
printf("lstat error: %s\n", strerror(errno));
continue;
}
if (S_ISDIR(buf.st_mode)) {
printf("directory: %s\r\n",argv[c]);
if((d