lr分析器:LR语法分析器程序设计来源: 发布时间:星期日, 2009年8月16日 浏览:5次 评论:0
# <fstream.h>
# <iostream.h> # <stdlib.h> # <.h> struct code_val{ char code;char val[20]; }; const char *p={ //产生式 "S→E","E→E+T","E→T","T→T*F","T→F","F→(E)","F→i" }; const char TNT[ ]="+*i#ETF"; //LR分析表列 const M[9]={ // LR分析表数字化 列+*i#ETF用数字012345678标识 { 0, 0, 4, 0, 5,0, 1, 2, 3}, //0表示出错s4用4表示 { 6, 0, 0, 0, 0,99}, //Acc用99表示 {-2, 7, 0,-2, 0,-2}, //r2用-2表示 {-4,-4, 0,-4, 0,-4}, { 0, 0, 4, 0, 5, 0, 8, 2, 3}, {-6,-6, 0,-6, 0,-6}, { 0, 0, 4, 0, 5, 0, 0, 9, 3}, { 0, 0, 4, 0, 5, 0, 0, 0,10}, { 6, 0, 0,11}, {-1, 7, 0,-1, 0,-1}, {-3,-3, 0,-3, 0,-3}, {-5,-5, 0,-5, 0,-5} }; col(char); //列定位原型 void { state[50]={0}; //状态栈初值 char symbol[50]={'#'}; //符号栈初值 top=0; //栈顶指针初值 ofstream cout("par_r.txt"); //语法分析结果输出至文件par_r.txt stream cin("lex_r.txt"); // 从lex_r.txt中输入词法分析结果 struct code_val t; //结构变量存放单词 2元式 cin>>t.code>>t.val; //读单词 action; i,j=0; //输出时使用计数器并非必要 cout<<"step"<<'\t'<<"状态栈"<<'\t'<<"符号栈"<<'\t'<<"输入符号"<<endl;//输出标题并非必要 do{ cout<<j<<')'<<'\t'; //输出step并非必要 for(i=0;i<=top;i)cout<<state[i];cout<<'\t';//输出状态栈内容并非必要 for(i=0;i<=top;i)cout<<symbol[i]; //输出符号栈内容并非必要 cout<<'\t'<<t.code<<endl; //输出当前输入符号(单词种别)并非必要 action=M[state[top]][col(t.code)]; (action>0 && action!=99){ //移进 state[top]=action; symbol[top]=t.code; cin>>t.code>>t.val; //读单词 } (action < 0){ //归约 (strcmp(p[-action]+3,"ε")) //ε产生式右部符号串长度为0无需退栈 top=top-(strlen(p[-action])-3); //"→"为汉字,占 2字节故减3 state[top+1]=M[state[top]][col(p[-action][0])]; //产生式左部符号 symbol[top]=p[-action][0]; } (action99){ //接受 cout<<'\t'<<"Acc"<<endl; ; } { //出错 cout<<"Err in >"<<action<<endl; ; } }while(1); } col(char c) //将+* i#ETF分别转换为数字012345678 { for( i=0;i<()strlen(TNT);i) (cTNT[i]) i; cout<<"Err in col char>"<<c<<endl; exit(0); //终止运行 } 0
相关文章读者评论发表评论 |