#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <queue>
#include <cctype>
using namespace std;
map<string,int>Dict;
queue<int>Err;
ofstream out; //write to file
ifstream in; //read from file
void init()
{
Dict["+"]=3;Dict["-"]=4;Dict["*"]=5;
Dict["/"]=6;Dict["%"]=7;Dict["<"]=8;
Dict["<="]=9;Dict[">"]=10;Dict[">="]=11;
Dict["=="]=12;Dict["!="]=13;Dict["&&"]=14;
Dict["||"]=15;Dict["="]=16;Dict["("]=17;
Dict[")"]=18;Dict["["]=19;Dict["]"]=20;
Dict["{"]=21;Dict["}"]=22;Dict[";"]=23;
Dict[","]=24;Dict["void"]=25;Dict["int"]=26;
Dict["float"]=27;Dict["char"]=28;Dict["if"]=29;
Dict["else"]=30;Dict["while"]=31;Dict["do"]=32;
Dict["return"]=33;
}
void block_commend() //deal block commend
{
string str;
while(getline(cin,str))
{
int t=str.length()-1;
if(str[t]=='/'&&str[t-1]=='*')
return;
}
}
int word(const string &s,int n,int line) //read a word
{
string tmp;
tmp+=s[n];
int j;
for(j=n+1;j<s.length();j++)
{
if((isalpha(s[n])||isdigit(s[n]))&&(isalpha(s[j])||isdigit(s[j])))
tmp+=s[j];
else break;
}
map<string,int>::iterator idx=Dict.find(tmp);
if(idx!=Dict.end())
{
out<<"<"<<idx->second<<",->,";
}
else
{
if(tmp.length()==1)
{
if(isalpha(tmp[0]))
out<<"<1,"<<tmp<<">,";
else
out<<"<2,"<<tmp<<">,";
}
else
{
bool is_num=true;
for(int k=0;k<tmp.length();k++)
{
if(!isdigit(tmp[k]))
{
is_num=false;
break;
}
}
if(is_num)
out<<"<2,"<<tmp<<">,";
else
{
if(isdigit(tmp[0])&&isalpha(tmp[1]))
{
out<<"LexicalError,";
Err.push(line);
}
else out<<"<1,"<<tmp<<">,";
}
}
}
return j-1;
}
int main()
{
init();
string str;
int line=0;
out.open("file.txt");
while(getline(cin,str)&&str[0]!='#')
{
if(str.length()==0)continue; //empty line
line++;
bool enter=true;
for(int i=0;i<str.length();i++)
{
if(str[0]=='/'&&str[1]=='/') //commend line
{
out<<endl;
enter=false; //do not need to output enter
if(line!=0)--line;
break;
}
else if(str[0]=='/'&&str[1]=='*') //commend block
{
block_commend();
out<<endl; //do not need to output enter
enter=false;
if(line!=0)--line;
break;
}
else if(str[i]==' '||str[i]=='\t') //jump space and tab.. Notice the fucking Tab !!!!!!!!!!!
continue;
else i=word(str,i,line); //deal with signal word
}
if(enter)
out<<endl;
}
in.open("file.txt");
str.clear();
getline(in,str);
while(in) //read file
{
cout<<str<<endl;
getline(in,str);
}
if(!Err.empty())cout<<"LexicalError(s) on line(s) ";
while(!Err.empty()) //output errors
{
cout<<Err.front()<<",";
Err.pop();
}
return 0;
}
词法分析程序
最新推荐文章于 2024-04-24 14:56:38 发布