资源描述:
《编译原理-预测分析法(附源码)》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、预测分析法实验报告一、实验项目名称预测分析法二、实验目的根据某一LL(1)文法编制调试预测分析程序,以便对任意输入的符号串进行分析。本次实验的目的主要是加深对预测分析法的理解。三、实验环境Windows10MicrosoftVisualStudio2015四、实验内容本次实验的LL(1)文法为表达式文法:E→E+T
2、TT→T*F
3、FF→i
4、(E)编写识别表达式文法的合法句子的预测分析程序,对输入的任意符号串,给出分析过程及分析结果。分析过程要求输出步骤、分析栈、剩余输入串和所用产生式。如果该符号串不是表达式文法的合法句子,要给出尽量详细的错误提示五、源程序清单、测试数据、结果#include
5、#includeusingnamespacestd;constintNUM=20;//初始化的栈的大小//非终结符数组集charVar[5]={'E','R','T','M','F'};//终结符数组集charTer[6]={'i','+','*','(',')','#'};stringpred[5][6]={{"TR","","","TR","",""},{"","+TR","","","@","@"},{"FM","","","FM","",""},{"","@","*FM","","@","@"},{"i","","","(E)","",""}};t
6、ypedefstruct{char*top;char*base;intstacksize;intnum;}Stack;//栈结构体voidinit(Stack*ss){//初始化栈ss->base=(char*)malloc(NUM*sizeof(char));if(!ss->base)exit(1);ss->top=ss->base;ss->stacksize=NUM;ss->num=0;}voidpush(Stack*ss,charc){//入栈操作if(ss->top-ss->base>=ss->stacksize)exit(1);*(ss->top)=c;ss->top++;ss->
7、num++;}voidpop(Stack*ss){//出栈操作if(ss->top==ss->base)exit(1);ss->top--;ss->num--;}chargetTop(Stack*ss){//取得栈顶元素if(ss->top==ss->base)exit(1);return*(ss->top-1);}intisT(charc){//判断是否为终结符inti=0;intret=0;for(i=0;i<6;i++){if(Ter[i]==c){ret=1;break;}}returnret;}stringisInPred(charv,chart){//查找预测分析表,并返回产生式
8、右部inti,j;for(i=0;i<5;i++){if(Var[i]==v)break;}for(j=0;j<6;j++){if(Ter[j]==t)break;}if(pred[i][j]!=""){returnpred[i][j];}elsereturn"";}voiddisplayStack(Stack*stack){//输出分析站的内容stringstr;inti=0;Stackss=*stack;while(ss.num!=0){str+=getTop(&ss);pop(&ss);}for(i=str.length()-1;i>=0;i--){cout<9、voidpredict(Stackstack,stringinput)//预测分析总函数{inta=1;charb;charctop;//当前栈顶符号charcinput;//当前输入符号inti=0,j=0,count=0;interror=0;cout<<"步骤"<<'t'<<"栈"<<'t'<<"输入缓冲区"<<'t'<<"所用的产生式"<10、"";ctop=getTop(&stack);cinput=input.at(i);if(isT(ctop))//栈顶符号为终结符{if(ctop==cinput){pop(&stack);i++;}else{error=1;break;}produce+=""";produce+=ctop;produce+=""匹配";}else//栈顶符号位非终结符{stringstr=isInPred(ctop,c