0
点赞
收藏
分享

微信扫一扫

编译原理—实验五 LL(1)语法分析(四)


一、实验目的
1.熟悉LL(1)语法分析的基本原理,语法分析的过程,以及语法分析中要注意的一些问题。
2. 复习高级语言及线性表、栈、图等典型数据结构,进一步加强用高级语言来解决实际问题的能力。
二、实验内容
将实验四编写的程序的基础之上,实现下面的功能:
按照教材5.2节算法,输入一个符号串,根据实验四的预测分析表,输出该符号串的最左推导,如果不能构造,提示字符串的出错位置。

S->a
S->^
S->(T)
T->SN
N->,SN
N->@

代码如下:

#include<bits/stdc++.h>
using namespace std;
int main()
{
typedef pair<char, pair<string, string> >PPP;
vector<PPP >SELECT; //SELECT集
SELECT.push_back(make_pair('S', make_pair("a","a")));
SELECT.push_back(make_pair('S', make_pair("^","^")));
SELECT.push_back(make_pair('S', make_pair("(T)","(")));
SELECT.push_back(make_pair('T', make_pair("SN","a")));
SELECT.push_back(make_pair('T', make_pair("SN","^")));
SELECT.push_back(make_pair('T', make_pair("SN","(")));
SELECT.push_back(make_pair('N', make_pair("@",")")));
SELECT.push_back(make_pair('N', make_pair(",SN",",")));
vector<char >Sentence;//要识别的句子
cout << "请输入要识别的串: " << endl;
string str;
cin >> str;
for (int i = 0; i < str.size(); i++)
{
Sentence.push_back(str[i]);
}
Sentence.push_back('#');
// for(int i=0;i<Sentence.size();i++)
// {
// cout<<Sentence[i];
// }
vector<char>::iterator a = Sentence.begin(), ii;
stack<char>S;
vector<char>vet;
S.push('#');
S.push('S');//分析栈
vet.push_back('#');//存储分析栈
vet.push_back('S');
cout << "分析栈" << " " << "剩余输入串" << " " << "推导所用的产生式或匹配" << endl;
int EMPTY = 7;
string ac[51];
int k=0;
while (!S.empty())
{
for (int i = 0; i < vet.size(); i++) //分析栈
{
cout << vet[i] << " ";
}
for (int i = vet.size(); i <= EMPTY+2; i++)
cout << " ";
int count = 0;
for (ii = a; ii != Sentence.end(); ii++) //剩余输入串
{
cout << (*ii) << " ";
count++;
}
for (; count <= EMPTY; count++)
cout << " ";
char X = S.top();//栈顶符号 *a当前输入符号
if (X == (*a))
{
S.pop();
vet.pop_back();
a++;
for (int i = 0; i <= EMPTY; i++)cout << " ";
if(X=='#')
cout<<"接受"<<endl;
else
cout << "匹配" << endl;
}
else
{
vector<PPP >::iterator it;
string ss = "";
bool flag = false;
for (it = SELECT.begin(); it != SELECT.end(); it++)
{
if (it->first == X)
{
ss = it->second.first;//产生式右部
for (int i = 0; i < (int)it->second.second.size(); i++)
{
if (it->second.second[i] == (*a))
{
flag = true;
break;
}
}
if (flag)break;
}
}
for (int i = 0; i <= EMPTY; i++)cout << " ";
if (!flag)
{
cout << "ERROR!!!" << endl;
return 0;
}
cout << X << "->" << ss << endl;
ac[k++]=X+ss;//最左推导存储
reverse(ss.begin(), ss.end()); //反转
if (ss == "@")
{
S.pop();
vet.pop_back();
}
else
{
S.pop();
vet.pop_back();
for (int i = 0; i < (int)ss.size(); i++)
{
S.push(ss[i]);
vet.push_back(ss[i]);
}
}
}
}
cout << "最左推导数:" << endl;
cout<<"S=>"<<ac[0].substr(1);
string qq=ac[0].substr(1);
for(int i=1; i<k; i++)
{
cout<<"=>";
string str1="";
for(int j=0; j<qq.size(); j++)
{
if(ac[i][0]==qq[j])
{
if(ac[i].substr(1)=="@")
{
str1+="";
}
else
str1+=ac[i].substr(1);
}
else
str1+=qq[j];
}
qq=str1;
cout<<str1;
}
}


举报

相关推荐

0 条评论