#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <algorithm>
using namespace std ;
const int MAX = 1005 ;
char iword[50][50] = {
"#","begin","if","then","while","do","end","","","","",
"l(l|d)*","dd*","+","-","*","/",":",":=",
"<","<>","<=",">",">=","=",";","(",")" ,
} ;
int wsym[100] ; // 保留字单词种别
char id[100] ;
int num ;
int cnt ;
int y[110];
stack<char> st ;
string ss = "" ;
char tmp[100] ;
int findc(string a ) {
memset(tmp,'\0',sizeof(tmp));
for(int i = 0 ;i<a.size() ; i++ ) {
tmp[i] = a[i] ;
}
tmp[a.size()] = '\0' ;
for(int i = 0 ; i<29; i++ ) {
if(!strcmp(tmp,iword[i]) ){
return i ;
}
}
return 0 ;
}
int check() {
ss.clear() ;
while(!st.empty()) {
ss+=st.top() ;
st.pop() ;
}
reverse(ss.begin(),ss.end()) ;
int t = findc(ss) ;
return t ;
}
int getsym(char *str) { // 词法分析
int len = strlen(str) ;
for(int i = 0 ; i<len; i++) {
if(str[i] >='a' && str[i] <='z') {
while(str[i]!=' ' && (str[i] >='a'&&str[i]<='z' ) ) {
st.push(str[i]) ;
i++ ;
}
int syn = check();
if(syn) { // 是关键字
printf("(%d,%s)",syn,iword[syn]) ;
}
else{ // 不是关键子 , 而是标识符
printf("(%d,%s)",10,tmp);
i-- ;
}
}
else if(str[i] >='0' && str[i] <='9'){ // 如果是数字
string number = "" ;
while(str[i] >='0' && str[i] <='9'){
number+=str[i] ;
i++ ;
}
cout<<"("<<11<<","<<number<<")";
i-- ;
}
else if (str[i]!=' '){
if(str[i]!=':'){
string s ="";
s+=str[i];
int num =findc(s) ;
cout<<"("<<findc(s)<<","<<s<<")" ;
if(str[i] =='#') {
return 0 ;
}
}
else if(str[i]==':'&&str[i+1]=='='){
string s =":=";
int num =findc(s) ;
cout<<"("<<findc(s)<<","<<s<<")" ;
i++ ;
}
}
}
}
char r[100] ;
int main(){
//freopen("in.txt","r",stdin) ;
//freopen("out.txt","w",stdout) ;
FILE *fp = fopen("in.txt","r");
if(!fp) {
printf("error\n") ;
exit(0) ;
}
char ch ;
fgets(r,100,fp);
printf("代码 : %s\n分析结果 : \n",r) ;
getsym(r);
cout<<endl ;
return 0 ;
}