📄 slr.cpp
字号:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
using namespace std;
using std::string;
//token表的数据结构
struct tokentype
{
int id;
int entry;
};
struct tokentype token[100];
//产生式的存储结构
struct generatype
{
char str[100];
int length;
int left;
};
struct generatype generate[38];
//堆栈的数据结构
struct stacktype
{
int content[200];
int top;
};
struct stacktype STACK;
int ACTION[69][32]; //action表
int GOTO[69][17]; //goto表
char vn[17]; //非终结符
int last; //token表长度
void init()
{
FILE *fp1,*fp2,*fp3,*fp4,*fvn;
int i=0,j;
//读入action表
fp1=fopen("action.txt","r");
while(!feof(fp1))
{
for(i=0;i<69;i++)
{
for(j=1;j<=31;j++)
{
fscanf(fp1,"%d",&ACTION[i][j]);
}
}
}
//读入goto表
fp2=fopen("goto.txt","r");
while(!feof(fp2))
{
for(i=0;i<69;i++)
{
for(j=1;j<=16;j++)
{
fscanf(fp2,"%d",&GOTO[i][j]);
}
}
}
//读入生成式表
fp3=fopen("production.txt","r");
while(!feof(fp3))
{
for(i=1;i<=37;i++)
{
fscanf(fp3,"%d%d%s",&generate[i].left,&generate[i].length,&generate[i].str);
}
}
last=0;
//读入token表
fp4=fopen("ftok.txt","r");
while(!feof(fp4))
{
fscanf(fp4,"%d%d",&token[last].id,&token[last].entry);
last++;
}
token[last-1].id=31;
//读入非终结符
fvn=fopen("Vn.txt","r");
while(!feof(fvn))
{
for(i=1;i<=16;i++)
fscanf(fvn,"%c",&vn[i]);
}
STACK.top=0;
STACK.content[STACK.top]=0;
fclose(fp1);
fclose(fp2);
fclose(fp3);
fclose(fp4);
fclose(fvn);
return;
}
//查action表
int checkact(int a,int b) //a为栈顶,b为当前输入符
{
return ACTION[a][b];
}
//查goto表
int checkgoto(int a,int b) //a为当前状态,b为栈顶
{
return GOTO[a][b];
}
//栈的操作
void push(int a)
{
STACK.top++;
STACK.content[STACK.top]=a;
return;
}
void pop(void)
{
STACK.content[STACK.top]=0;
STACK.top--;
return;
}
//用第a条产生式规约
void execute(int a)
{
int i;
//输出产生式
cout<<vn[generate[a].left]<<"->"<<generate[a].str<<endl;
for(i=0;i<generate[a].length;i++)
{
pop();
pop();
}
push(generate[a].left);
return;
}
//分析函数
void analyse()
{
int first=0;
int x,y;
while(1)
{
x=checkact(STACK.content[STACK.top],token[first].id);
while(x/1000!=0)
{
execute(x%1000); //规约
y=checkgoto(STACK.content[STACK.top-1],STACK.content[STACK.top]);
push(y);
x=checkact(STACK.content[STACK.top],token[first].id);
}
if(x==0)
return;
if(x==-1)
{
cout<<"error!\n";
cout<<STACK.content[STACK.top]<<" id="<<token[first].id<<" ptr="<<first<<endl;
return;
}
push(token[first].id);
push(x%1000);
first++;
}
}
void main()
{
init();
analyse();
return;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -