一. 实验二: LL(1)分析法
二.实验目的及要求
实现目的:
通过完成预测分析法的语法分析程序,了解预测分析法和递归子程序法的区
别和联系。使学生了解语法分析的功能,掌握语法分析程序设计的原理和构造方
法,训练学生掌握开发应用程序的基本方法。有利于提高学生的专业素质,为培
养适应社会多方面需要的能力。
实验要求:
1、编程时注意编程风格:空行的使用、注释的使用、缩进的使用等。
2、如果遇到错误的表达式,应输出错误提示信息。
3、对下列文法,用 LL(1)分析法对任意输入的符号串进行分析:
(1)E->TG
(2)G->+TG|—TG
(3)G->ε
(4)T->FS
(5)S->*FS|/FS
(6)S->ε
(7)F->(E)
(8)F->i
三. 实验内容
根据某一文法编制调试 LL ( 1 )分析程序,以便对任意输入的符号串
进行分析。
u 构造预测分析表,并利用分析表和一个栈来实现对上述程序设计语言的分
析程序。
u 分析法的功能是利用 LL(1)控制程序根据显示栈栈顶内容、向前看符号
以及 LL(1)分析表,对输入符号串自上而下的分析过程
四. 核心算法流程
五.核心代码
/ /预测分析过程
stack<std::string> stackLL;
string stackStr{};
stackLL.push("#");
stackStr += '#';
auto pos = v_LL[0].find("->");
std::string begin = v_LL[0].substr(0, pos);
stackLL.push(begin);
stackStr += begin;
// print to test
std::cout << "------- stack init ------" << std::endl;
std::cout << stackLL.top() << std::endl;
std::cout << inputStr << std::endl;
// 预测分析
cout << "步骤\t\t" << "符号栈\t\t" << "输入串\t\t" << "所用产生式" << endl;
int stepNum = 0;
int index = 0; // 用来存取输入
cout << to_string(stepNum) << "\t\t" << stackStr << "\t\t" << inputStr << endl;
bool flag = true;
string a = inputStr.substr(index, 1);
while (flag)
{
string stack_top = stackLL.top();
stackLL.pop();
stackStr.pop_back();
auto pair_tmp = pair<string, string>(stack_top, a);
if (ll1.isInVT(stack_top)) {
if (stack_top == a) {
a = inputStr.substr(++index, 1);
}
else{
cout << "ERROR" << endl;
break;
}
}
else if (stack_top == "#") {
if (stack_top == a) {
flag = false;
}
else {
cout << "ERROR" << endl;
break;
}
}
else if (!ll1.table[pair_tmp].empty()) {
string right{};
string s_tmp = ll1.table[pair_tmp];
auto pos1 = s_tmp.find("->");
right = s_tmp.substr(pos1+2);
vector<string> v_tmp{};
LL1::splitString(v_tmp, right);
for (int i=int(v_tmp.size()-1); i>=0; i--) {
if (v_tmp[i] == "$")
continue;
stackLL.push(v_tmp[i]);
stackStr += v_tmp[i];
}
}
else {
cout << "ERROR" << endl;
break;
}
}
六. 具体代码
github仓库链接:https://github.com/1StephenCurry1/Compiler-Design.git