一、实验目的
二、实验内容
针对CP语言中简单算术表达式文法G[E]:
E→TE’
E’→ATE’|ε
T→FT’
T’→MFT’ |ε
F→(E) | i
A → + | -
M → * | /
求解相应的FIRST、FOLLOW集,构造预测分析表,并编写LL(1)语法分析程序,并给出测试句子的分析过程。
(注:如果有选做专题7关于LL(1)文法判断的同学,可以将专题7的部分整合到这个实验的前面,自动产生预测分析表,相当于把这个程序做成一个通用的LL(1)分析器)
三、实验要求
四、程序代码
#include
#include
#include
#include
#include
using namespace std;
#define MAX 100
char c[8]={
'i','(','+','-','*','/',')','#'};
char w[7]={
'E','e','T','t','F','A','M'};
char mapp[7][8][5]= {
"Te","Te","%","%","%","%","%","%",
"%","%","ATe","ATe","%","%","#","#",
"Ft","Ft","%","%","%","%","%","%",
"%","%","#","#","MFt","MFt","#","#",
"i","(E)","%","%","%","%","%","%",
"%","%","+","-","%","%","%","%",
"%","%","%","%","*","/","%","%"};
int panduan(char ch)
{
for(int i=0;i<8;i++)
{
if(ch==c[i])
return 1;
}
return 0;
}
int findc(char ch)
{
if(ch>='0'&&ch<='9')
return 0;
for(int i=0;i<8;i++)
{
if(ch==c[i])
return i;
}
return 0;
}
int findw(char ch)
{
for(int i=0;i<7;i++)
{
if(ch==w[i])
return i;
}
return 0;
}
int main()
{
char str[MAX];
int ip;
stack <char> q;
cout<<"输入的格式为算数式后跟#号"<<endl;
cout<<"比如:"<<" 9+8*2#"<<endl;
cout<<"“e->#”此类产生式中的#号代表空集"<<endl;
cout<<"请输入你的表达式"<<endl;
cin>>str;
ip=0;
q.push('#');
q.push('E');
while(!q.empty())
{
char ch=q.top();
if(ch=='#')break;
int i=findw(ch);
int j=findc(str[ip]);
if(ch==str[ip])
{
q.pop();
cout<<"匹配"<<str[ip]<<endl;
ip++;
}
else if(str[ip]>='0'&&str[ip]<='9'&&ch=='i')
{
q.pop();
cout<<ch<<"->"<<str[ip]<<endl;
cout<<"匹配"<<str[ip]<<endl;
ip++;
}
else if(panduan(ch))
{
cout<<"不匹配"<<endl;
return 0;
}
else if(mapp[i][j][0]=='%')
{
cout<<"不匹配"<<endl;
return 0;
}
else if(mapp[i][j][0]=='#')
{
cout<<ch<<"->"<<"#"<<endl;
q.pop();
}
else
{
int n=strlen(mapp[i][j]);
q.pop();
for(int k=n-1;k>=0;k--)
{
q.push(mapp[i][j][k]);
}
cout<<ch<<"->"<<mapp[i][j]<<endl;
}
}
return 0;
}