一、实验目的
通过设计、开发一个高级语言的递归下降语法分析程序,实现
对词法分析程序所提供的单词序列进行语法检查和结构分析,加
深对相关课堂教学内容的理解,提高语法分析方法的实践能力。
二、实验要求
(1)理解语法分析在编译程序中的作用,以及它与词法分析程序的
关系;
(2)掌握递归下降语法分析方法的主要原理;
(3)理解递归下降分析法对文法的要求;
(4)熟练掌握Select集合的求解方法;
(5)熟练掌握文法变换方法(消除左递归和提取公因子)
杭电的同学们一定要改一改再交哟-v-
#include<iostream>
using namespace std;
//这里九个关键词用1-9标识
const char *tab[9] = { "begin","if","then","else","while","do","Const","Var","end" };
//还有10表示变量名,11表示数字,
const char *typeName[4] = { "Reserved:","Identifier:","Number:","" };
/*获得字符串长度*/
int getStringSize(char* string) {
if (string == NULL) {
return 0;
}
int i = 0;
for (; string[i] != '\0'; i++);
return i;
}
/*判断是否有#结束符*/
bool isEnd(char* string) {
bool isend = false;
if (string == NULL) {
return false;
}
for (int i = 0; string[i] != '\0'; i++) {
if (string[i] == '#') {
isend = true;
}
}
return isend;
}
char* getTypeName(int type) {
return NULL;
}
class Result {
public:
int type;
char* token;
Result() {}
Result(int type, char* token) {
this->type = type;
this->token = token;
}
Result(Result &r) {
this->token = r.token;
this->type = r.type;
}
Result(Result* r) {
this->token = r->token;
this->type = r->type;
}
void printResult() {
cout << type << " :" << ((type<4 && type>0) ? typeName[type - 1] : "") << token << endl;
}
};
void programSlice(Result* resultList, int start, int end);
int Statement(Result* resultList, int start, int end);
int Express(Result* resultList, int start, int end);
int Item(Result* resultList, int start, int end);
int Condition(Result* resultList, int start, int end);
/*判断是否为数字*/
bool isDigital(char ch)
{
if (ch <= '9'&&ch >= '0')
return true;
else
return false;
}
/*判断是否为字母*/
bool isAlpha(char ch)
{
if (ch >= 'a'&&ch <= 'z' || ch >= 'A'&&ch <= 'Z')
return true;
else
return false;
}
Result* scanner(char* sentence, int& p) {
Result* result = new Result();
char* token = new char[10];
int num = 0;
int m = 0;
char ch;
int syn;