编译原理 LR分析法 表达式
在存储LR分析表时:
移进用1、2、3……来表示(例:S1用1表示)
规约用101、102、103……来表示(例:r1用101表示)
错误用-1表示
接收用-2表示
#include<stdio.h>
#include<iostream>
#include<string>
#include<stack>
using namespace std;
string expression;
stack<int> A; //状态
stack<char> B; //符号
stack<char> C; //表达式
void Error()
{
printf("错误\n");
exit(0);
}
int main()
{
int action[200][200];
int tmp[12][9] = {
{5,-1,-1,4,-1,-1,1,2,3},
{-1,6,-1,-1,-1,-2,-1,-1,-1},
{-1,102,7,-1,102,102,-1,-1,-1},
{-1,104,104,-1,104,104,-1,-1,-1},
{5,-1,-1,4,-1,-1,8,2,3},
{-1,106,106,-1,106,106,-1,-1,-1},
{5,-1,-1,4,-1,-1,-1,9,3},
{5,-1,-1,4,-1,-1,-1,-1,10},
{-1,6,-1,-1,11,-1,-1,-1,-1},
{-1,101,7,-1,101,101,-1,-1,-1},
{-1,103,103,-1,103,103,-1,-1,-1},
{-1,105,105,-1,105,105,-1,-1,-1}
};
int i = 0;
for (i=0;i<12;i++)
{
action[i]['i'] = tmp[i][0];
action[i]['+'] = tmp[i][1];
action[i]['*'] = tmp[i][2];
action[i]['('] = tmp[i][3];
action[i][')'] = tmp[i][4];
action[i]['#'] = tmp[i][5];
action[i]['E'] = tmp[i][6];
action[i]['T'] = tmp[i][7];
action[i]['F'] = tmp[i][8];
}
A.push(0);
B.push('#');
cin >> expression;
int len =expression.length();
//C是表达式栈
for(int index=len -1;i>=0;i--)
{
C.push(expression[i]);
}
int acc = false;
int act = 0;
while(!acc)
{
if(C.top()=='i'||C.top()=='+'||C.top()=='*'||C.top()=='('||C.top()==')'||C.top()=='#')
{
act = action[A.top()][C.top()];
printf("act:%d\n",act);
if(act == -1) Error();
if(act == -2)
{
acc = true;
printf("Accept\n");
}
if(act >= 0 && act <=100)
{
B.push(C.top());
A.push(action[A.top()][B.top()]);
C.pop();
}
if(act >= 101 && act <=200)
{
switch(act)
{
case 101:
A.pop();
A.pop();
A.pop();
B.pop();
B.pop();
B.pop();
B.push('E');
A.push(action[A.top()][B.top()]);
break;
case 102:
A.pop();
B.pop();
B.push('E');
A.push(action[A.top()][B.top()]);
break;
case 103:
A.pop();
A.pop();
A.pop();
B.pop();
B.pop();
B.pop();
B.push('T');
A.push(action[A.top()][B.top()]);
break;
case 104:
A.pop();
B.pop();
B.push('T');
A.push(action[A.top()][B.top()]);
break;
case 105:
A.pop();
A.pop();
A.pop();
B.pop();
B.pop();
B.pop();
B.push('F');
A.push(action[A.top()][B.top()]);
break;
case 106:
A.pop();
B.pop();
B.push('F');
A.push(action[A.top()][B.top()]);
break;
}
}
}
else
Error();
}
return 0;
}
运行截图: