资源描述:
《实验三 LR(1)分析报告法实验报告材料.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、实验三LR(1)分析法一、实验目的构造LR(1)分析程序,利用它进行语法分析,判断给出的符号串是否为该文法识别的句子,了解LR(K)分析方法是严格的从左向右扫描,和自底向上的语法分析方法。二、LR(1)分析法实验设计思想及算法(1)总控程序,也可以称为驱动程序。对所有的LR分析器总控程序都是相同的。(2)分析表或分析函数,不同的文法分析表将不同,同一个文法采用的LR分析器不同时,分析表将不同,分析表又可以分为动作表(ACTION)和状态转换(GOTO)表两个部分,它们都可用二维数组表示。(3)分析栈,包括文法符号栈和相应的状态栈,它们均是先进后出栈。分析器的动作就是由栈
2、顶状态和当前输入符号所决定。uLR分析器由三个部分组成:u其中:SP为栈指针,S[i]为状态栈,X[i]为文法符号栈。状态转换表用GOTO[i,X]=j表示,规定当栈顶状态为i,遇到当前文法符号为X时应转向状态j,X为终结符或非终结符。uACTION[i,a]规定了栈顶状态为i时遇到输入符号a应执行。动作有四种可能:(1)移进:action[i,a]=Sj:状态j移入到状态栈,把a移入到文法符号栈,其中i,j表示状态号。(2)归约:action[i,a]=rk:当在栈顶形成句柄时,则归约为相应的非终结符A,即文法中有A-B的产生式,若B的长度为R(即
3、B
4、=R),则从状
5、态栈和文法符号栈中自顶向下去掉R个符号,即栈指针SP减去R,并把A移入文法符号栈,j=GOTO[i,A]移进状态栈,其中i为修改指针后的栈顶状态。(3)接受acc:当归约到文法符号栈中只剩文法的开始符号S时,并且输入符号串已结束即当前输入符是'#',则为分析成功。(4)报错:当遇到状态栈顶为某一状态下出现不该遇到的文法符号时,则报错,说明输入端不是该文法能接受的符号串。三、程序结构描述1、定义的变量stringaction[12][6]={{"s5","error","error","s4","error","error"},{"error","s6","error",
6、"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"},{"s5","error","error","s4","error","error"},{"error","s6","erro
7、r","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"
8、},{"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文法stackS;状态栈stack<
9、char>X;符号栈charinput[10];输入字符2、定义的函数intnum(strings)判断字符串中的数字voidprint(inti,char*c)剩余输入串的输出intsame(chara)用于查找终结符voidanalyse()分析程序四、程序源代码及运行结果#include#include#include#includeusingnamespacestd;//初始化预测分析表stringaction[12][6]={{"s5","error","er