LR(1)分析法一、实验目的构造LR(1)分析程序,利用它进行语法分析,判断给出的符号串是否为该文法识别的句子,了解LR(K)分析方法是严格的从左向右扫描,和自底向上的语法分析方法。二、实验内容对文法G[E]进行语法分析,文法G如下所示:G[E]:E→E+T|TT→T*F|FF→(E)|i根据LR(1)分析法,将表达式进行语法分析,判断一个表达式是否正确。三、实验步骤程序源代码#includeiostream#includestack#includestdlib.h#includestringusingnamespacestd;//初始化预测分析表stringaction[12][6]={{s5,error,error,s4,error,error},{error,s6,error,error,error,acc},{error,r2,s7,error,r2,r2},{error,r4,r4,error,r4,r4},{s5,error,error,s4,error,error},{error,r6,r6,error,r6,r6},{s5,error,error,s4,error,error},-1-{s5,error,error,s4,error,error},{error,s6,error,error,s11,error},{error,r1,r7,error,r1,r1},{error,r3,r3,error,r3,r3},{error,r5,r5,error,r5,r5}};stringgo[12][3]={{1,2,3},{error,error,error},{error,error,error},{error,error,error},{8,2,3},{error,error,error},{error,9,3},{error,error,10},{error,error,error},{error,error,error},{error,error,error},{error,error,error},};charVt[6]={'i','+','*','(',')','#'};//终结符表stringLR[6]={E-E+T,E-T,T-T*F,T-F,F-(E),F-i};//LR文法stackintS;//状态栈stackcharX;//符号栈charinput[10];//输入字符intnum(strings){//判断字符串中的数字inti;stringstr=;for(intj=0;js.length();j++){if(s[j]='0'&&s[j]='9')str=str+s[j];}i=atoi(str.c_str());returni;}voidpreview(char*c)-2-{for(intj=0;c[j]!='#';j++)coutc[j];coutendl;}voidprint(inti,char*c)//剩余输入串的输出{for(intj=i;c[j-1]!='#';j++)coutc[j];cout'\t';}intsame(chara){//用于查找终结符for(inti=0;i6;i++){if(a==Vt[i])returni;}return-1;}voidanalyse(){//**********分析程序boolflag=true;//循环条件控制intstep=1,point=0,state=0;//步骤、指针、状态charch1,ch2;intm,n,l;//用于判断终结符,分析表,表达式右部的长度stringstr1;//用于判断对应分析表中的符号stringstr2=#,str3=0;//记录符号栈的所有元素cout请输入要规约的字符串,并以#号结束:endl;cininput;cout您输入的字符串为:;preview(input);X.push('#');S.push(0);cout步骤'\t'状态栈'\t'符号栈'\t'输入串'\t'动作endl;coutstep++'\t'str3'\t'str2'\t';print(point,input);cout初始化endl;//*************初始化-3-while(flag){//************进入循环state=S.top();ch1=input[point];m=same(ch1);str1=action[state][m];//***********移进动作if(str1[0]=='s'){n=num(str1);S.push(n);X.push(ch1);str2=str2+ch1;ch2=n+48;str3=str3+ch2;point++;coutstep++'\t'str3'\t'str2'\t';print(point,input);coutstr1':'移进endl;}elseif(str1[0]=='r'){//**********归约动作n=num(str1);l=LR[n-1].length()-3;for(inti=1;i=l;i++){S.pop();str3=str3.substr(0,str3.length()-1);X.pop();str2=str2.substr(0,str2.length()-1);}X.push(LR[n-1][0]);str2=str2+LR[n-1][0];state=S.top();if(LR[n-1][0]=='E'){S.push(num(go[state][0]));ch2=num(go[state][0])+48;str3=str3+ch2;-4-}elseif(LR[n-1][0]=='T'){S.push(num(go[state][1]));ch2=num(go[state][1])+48;str3=str3+ch2;}elseif(LR[n-1][0]=='F'){S.push(num(go[state][2]));ch2=num(go[state][2])+48;str3=str3+ch2;}coutstep++'\t'str3'\t'str2'\t';print(point,input);coutstr1':'LR[n-1]归约endl;}//*********出错elseif(str1==error){coutError!\n程序错误,分析结束!endl;flag=false;}//**********分析成功elseif(str1==acc){coutAcc!\n分析成功,终止程序!endl;flag=false;}}}intmain(){analyse();return0;}-5-程序运行截图输入i+i输入i+ii