资源描述:
《实验4 LR(1)分析法》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、河南工业大学实验报告课程名称编译原理_实验项目实验四LR(1)分析法院系____信息科学与工程学院____专业班级计科F1402班姓名苏朋辉学号201416010211指导老师侯惠芳日期2017.5.6批改日期成绩一.实验目的1.掌握LR(1)分析法的基本原理2.掌握LR(1)分析表的构造方法3.掌握LR(1)驱动程序的构造方法二.实验内容及要求构造LR(1)分析程序,利用它进行语法分析,判断给出的符号串是否为该文法识别的句子,了解LR(K)分析方法是严格的从左向右扫描,和自底向上的语法分析方法。根据某一文法编制调试LR(1)分析程序,以便对任意输入的符号串进行分析。本次实验的目的主
2、要是加深对LR(1)分析法的理解。程序输入/输出示例:对下列文法,用LR(1)分析法对任意输入的符号串进行分析:(1)E->E+T(2)E->E—T(3)T->T*F(4)T->T/F(5)F->(E)(6)F->i输出的格式如下:(1)LR(1)分析程序,编制人:姓名,学号,班级(2)输入一以#结束的符号串(包括+—*/()i#):在此位置输入符号串(3)输出过程如下:步骤状态栈符号栈剩余输入串动作10#i+i*i#移进(4)输入符号串为非法符号串(或者为合法符号串)备注:(1)在“所用产生式”一列中如果对应有推导则写出所用产生式;如果为匹配终结符则写明匹配的终结符;如分析异常出错
3、则写为“分析出错”;若成功结束则写为“分析成功”。(2)在此位置输入符号串为用户自行输入的符号串。注意:1.表达式中允许使用运算符(+-*/)、分割符(括号)、字符i,结束符#;2.如果遇到错误的表达式,应输出错误提示信息(该信息越详细越好);3.对学有余力的同学,测试用的表达式事先放在文本文件中,一行存放一个表达式,同时以分号分割。同时将预期的输出结果写在另一个文本文件中,以便和输出进行对照;4.可采用的其它的文法。一.实验过程3.1代码如下:#include#include#include#includeusi
4、ngnamespacestd;//初始化预测分析表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"},{"
5、s5","error","error","s4","error","error"},{"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","
6、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','+','*','(',')','#'};//终结符表string
7、LR[6]={"E->E+T","E->T","T->T*F","T->F","F->(E)","F->i"};//LR文法stackS;//状态栈stackX;//符号栈charinput[10];//输入字符intnum(strings){//判断字符串中的数字inti;stringstr="";for(intj=0;j='0'&&s[j]<='9')str=str+s[j];}i