编译原理:语法分析 使用方法:LL(1) 分析方法 语法分析需求文件: 1. 预测分析表 2. 消除了左递归以及提取了左公因子的文法 3. 原文件。 #include <stdlib.h> #include <stdio.h> #include <string> #include<iostream> #include <fstream> #include<stack> #include <sstream> using namespace std; // 定义文法结构体 struct type { string leftContent; string rightContent; int length; }; //定义此法分析返回类型 struct lexicalType { string strToken; int pos; }; stack<string> stkGrammer; type grammerlist[17]; const int x = 10; const int y = 13; string terminalSymbol[y]; string nonterminalSymbol[x]; int analyzeTable[x][y]; // 从文档中读取文法 bool readGrammer(fstream* f) { string line; getline(*f, line); int pos = 0; do { istringstream is(line); is >> grammerlist[pos].leftContent>> grammerlist[pos].length; is >> grammerlist[pos].rightContent; while(!is.eof()) { string temp; is >> temp; grammerlist[pos].rightContent.append(" " + temp); } cout << grammerlist[pos].leftContent << " "<< grammerlist[pos].length << " " << grammerlist[pos].rightContent << endl; ++pos; getline(*f, line); }while(!f->eof()); return true; } // 从相应的文档中读入文法分析表 bool readGrammerAnalyze(fstream* f) { // 读取第1行终结符 string line; getline(*f, line); istringstream is(line); int pos = 0; while(!is.eof()) { is >> terminalSymbol[pos]; pos++; }; //for (int i = 0; i < 13; i++) // cout << ::terminalSymbol[i] << endl; // 读取第2行非终结符 getline(*f, line); istringstream iss(line); pos = 0; while(!iss.eof()) { iss >> nonterminalSymbol[pos]; pos++; }; int i = 0; while(!f->eof() && i < x) { int j = 0; getline(*f, line); istringstream iss(line); for(; j < y; j++) { iss >> ::analyzeTable[i][j]; } ++i; } return true; } //------------------------------------------------------ const int KEYLENGTH = 32; char enter[] = "/r/n"; char* key[KEYLENGTH] = { "#", "begin", "if", "then", "while", "do", "end","","","", // 0-9 "letter", "digit" ,"", "+", "-", "*", "/", ":", ":=", "", "<", // 10-20 "<>", "<=", ">", ">=", "=", ";", "(", ")", "string", "[", // 21-30 "]" // 31 }; int getSymbolPosOfKey(string t) { int pos = -1; for (int i = 0; i < KEYLENGTH; i++) { if (!_stricmp(key[i], t.c_str())) { pos = i; break; } } return pos; } int getTerminalSymbolPos(string t) { int pos = -1; for(int i = 0; i < y; i++) { string s = terminalSymbol[i]; if (s == t) { pos = i; break; } } return pos; } int getNonTermina