// LL(1).cpp : 此文件包含 “main“ 函数。程序执行将在此处开始并结束。//#include #include#include#include#include#include#includeusing namespace std;mapgetnum;char getchar1[100]; //获得对应字符vectorproce;int table[100][100]; //预测分析表int num = 0; int numvt = 0; //numvt是终结符集合,0是‘#’,numvt表空字string first[100];string follow[200];void readin(){ memset(table -1 sizeof(table)); getnum[‘#‘] = 0; getchar1[0] = ‘#‘; cout << “请输入终结符集:“ << endl; char x; do { cin >> x; getnum[x] = ++num; getchar1[num] = x; } while (cin.peek() != ‘\n‘); numvt = ++num; getnum[‘@‘] = numvt; //kong zi getchar1[num] = (‘@‘); cout << “请输入非终结符集:“ << endl; do { cin >> x; getnum[x] = ++num; getchar1[num] = x; } while (cin.peek() != ‘\n‘); cout << “输入需要用到的文法,并以‘end’结束:(空字ε用‘@’表示,方便输入)“ << endl; string pro; while (cin >> pro && pro != “end“) { string ss; ss += pro[0]; for (int i = 3; i < pro.size(); i++) { if (pro[i] == ‘|‘) { proce.push_back(ss); ss.clear(); ss += pro[0]; } else { ss += pro[i]; } } proce.push_back(ss); }}void jiaoji(string &a string b) //a=a or b 取ab交集赋值给a{ setse; for (int i = 0; i < a.size(); i++) se.insert(a[i]); for (int i = 0; i < b.size(); i++) se.insert(b[i]); string ans; set::iterator it; for (it = se.begin(); it != se.end(); it++) ans += *it; a = ans;}string get_f(int vn int & has_0) //dfs:vn能推出的不含空字的vt集合,并且判断vn能否推出空字{ if (vn == numvt)has_0 = 1; if (vn < numvt)return first[vn]; string ans; for (int i = 0; i < proce.size(); i++) { if (getnum[proce[i][0]] == vn) ans += get_f(getnum[proce[i][1]] has_0); } return ans;}void getfirst(){ for (int i = 1; i <= numvt; i++) //终结符,first集是其本身。 { first[i] += (‘0‘ + i); } for (int j = 0; j < proce.size(); j++) //扫描所有产生式 { int k = 0; int has_0 = 0; //k扫瞄该产生式 do { has_0 = 0; k++; if (k == proce[j].size()) //推到最后一个了,则附加空字 { first[getnum[proce[j][0]]] += (‘0‘ + numvt); break; } //合并之 jiaoji(first[getnum[proce[j][0]]] get_f(getnum[proce[j][k]] has_0)); } while (has_0); //到无法推出空字为止 }}void print_first(){ cout << “First集如下:“ << endl; for (int i = 1; i <= num; i++) { cout << “first [“ << getchar1[i] << “]: “; for (int j = 0; j < first[i].size(); j++) cout << getchar1[first[i][j] - ‘0‘] << “ “; cout << endl; } cout << endl;}void getfollow(){ jiaoji(follow[getnum[proce[0][0]]] “0“); //先添加‘#’; for (int j = 0; j < proce.size(); j++) //扫所有产生式 { for (int jj = 1; jj < proce[j].size(); jj++) //每个非终结符的follow集 { if (getnum[proce[j][jj]] <= numvt)continue; //vt无follow集 int k = jj; int has_0; do { has_0 = 0; k++; if (k == proce[j].size()) //都能推出空字,follow集=产生式
共有 条评论
评论
共有 条评论