#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
int line=1,row=1;
char c;
map<char,int>ma;
struct kind
{
string na; //单词
int num; //内码
string type; //类型
int l,r; //行列数
};
vector<kind>res; //视图表
int tree[10000][30];int numv=0;int w[10000];
int key=0; int flag=0;
void insert(string s) //关键词trie树
{
int u=0;
for(int i=0;i<s.size();i++)
{
if(tree[u][s[i]-'a']==0)
tree[u][s[i]-'a']=++numv;
u=tree[u][s[i]-'a'];
}
w[u]=key++;
}
void f1(char &c) // 关键字标识符分析器
{
int mark=1;
string s;
s+=c;
int u=0;
if(tree[u][c-'a']!=0)
u=tree[u][c-'a'];
else mark=0;
while(c=getchar())
{
if(!(c>='a'&&c<='z'))
if(c!='_')
if(!(c>='0'&&c<='9'))
break;
if(mark==1)
{
if(tree[u][c-'a']!=0)
u=tree[u][c-'a'];
else mark=0;
}
s+=c;
}
kind t;
t.na=s;
t.l=line;
t.r=row;
if(mark==0)
{
t.num=flag++;
t.type=" 标志符";
}
else
{
t.num=w[u];
t.type=" 关键字";
}
res.push_back(t);
return ;
}
void f2(char &c) //数字分析器
{
string s;
s+=c;
c=getchar();
while(c>='0'&&c<='9')
{
s+=c;
c=getchar();
}
int mark=1;
while(c>='a'&&c<='z')
{s+=c;mark=0;c=getchar();}
kind t;
t.na=s;
t.l=line;
t.r=row;
if(mark==1)
{
char *p;
strcpy(p,s.c_str());
t.num=atoi(p);
t.type=" 数字";
}
else
{
t.type=" error";
t.num=0;
}
res.push_back(t);
return ;
}
void f3(char &c) //分界符、运算符等其他分析器
{
string s;
kind t;
t.l=line;t.r=row;
if(ma.find(c)!=ma.end())
{
t.na+=c;
if(ma[c]<=8)t.type=" 分界符";
else t.type=" 运算符";
t.num=ma[c];
c=getchar();
}
else
{
t.type=" 关系运算符";
if(c=='>')
{
c=getchar();
if(c=='=')
{
t.na=">=";
t.num=1;
c=getchar();
}
else
{
t.na=">";
t.num=2;
}
}
else if(c=='<')
{
c=getchar();
if(c=='=')
{
t.na="<=";
t.num=3;
c=getchar();
}
else if(c=='>')
{
t.na="<>";
t.num=4;
c=getchar();
}
else
{
t.na="<";
t.num=5;
}
}
else if(c=='=')
{
t.na="=";
t.num=6;
c=getchar();
}
}
res.push_back(t);
return ;
}
int main() //总控程序
{
ma['[']=1;ma[']']=2;ma[',']=3;ma[';']=4;ma['(']=5;ma[')']=6;ma['{']=7;ma['}']=8;
ma['+']=9;ma['-']=10;ma['*']=11;ma['/']=12;ma['%']=13;
string s;
while(s!="end")
{
cin>>s;
insert(s);
}
getchar();
cout<<"请输入语句:"<<endl;
c=getchar();
while(1)
{
if(c=='@')break;
while(c==' '){c=getchar();row++;}
if(c>='a'&&c<='z')
f1(c);
else if(c>='0'&&c<='9')
f2(c);
else
f3(c);
row++;
if(c=='\n')
{
line++;
row=1;
c=getchar();
}
}
cout<<"单词"<<'\t'<<'\t'<<"二元序列"<<'\t'<<'\t'<<"类型"<<'\t'<<'\t'<<"位置(行,列)"<<endl;
for(int i=0;i<res.size();i++)
{
cout<<res[i].na<<'\t'<<'\t'<<"("<<res[i].num<<","<<res[i].na<<")"<<'\t'<<'\t'<<res[i].type<<'\t'<<'\t'<<"("<<res[i].l<<","<<res[i].r<<")"<<endl;
}
}
测试:
if while int char else then do
end
int a=10;
int b=11;
int s=0;
if(a>=10)
{
s=a+b%2;
}
else
{
s=a-b*a/11;
}
int 3b;
@