【Lut语言(1)】词法分析器

发布时间 2023-07-22 15:14:52作者: 夏一锐

先为我的Lut语言写个词法分析器再说吧。

#include<bits/stdc++.h>
using namespace std;
string word[11]={"","int","char","double","goto","if","print","scan","eq","daf"};
string s,t,pp;char ch;int now,cnt;
int isword(string p){
	for(int i=1;i<=10;i++){
		if(word[i]==p)return i;
	}
	return 0;
}
char get(){return ch=s[now++];}
void retract(){--now,ch=0;}
void skip(){while(isspace(ch))get();}
void analysis(){
	while(now<s.size()){
		get();
		pp="";
		if(isspace(ch));else if(isalpha(ch)){
			while(isdigit(ch)||isalpha(ch))pp+=ch,get();
			retract();
			if(isword(pp)){
				cout<<++cnt<<":<"<<pp<<","<<"关键字"<<isword(pp)<<">\n";
			}
			else cout<<++cnt<<":<"<<pp<<","<<"标识符>\n";
		}
		else if(isdigit(ch)){
			while(isdigit(ch)||ch=='.')pp+=ch,get();
			retract();
			cout<<++cnt<<":<"<<pp<<","<<"常数>\n";
		}
		else if(ch=='='){
			get();
			if(ch=='=')cout<<++cnt<<":<==,运算符>\n";
			else cout<<++cnt<<":<=,运算符>\n",retract();
		}
		else if(ch=='+'){
			get();
			if(ch=='+')cout<<++cnt<<":<++,运算符>\n";
			else if(ch=='=')cout<<++cnt<<":<+=,运算符>\n";
			else cout<<++cnt<<":<+,运算符>\n",retract();
		}
		else if(ch=='-'){
			get();
			if(ch=='-')cout<<++cnt<<":<--,运算符>\n";
			else if(ch=='=')cout<<++cnt<<":<-=,运算符>\n";
			else cout<<++cnt<<":<-,运算符>\n",retract();
		}
		else if(ch=='*'){
			get();
			if(ch=='=')cout<<++cnt<<":<*=,运算符>\n";
			else cout<<++cnt<<":<*,运算符>\n",retract();
		}
		else if(ch=='/'){
			get();
			if(ch=='=')cout<<++cnt<<":</=,运算符>\n";
			else cout<<++cnt<<":</,运算符>\n",retract();
		}
		else if(ch=='%'){
			get();
			if(ch=='=')cout<<++cnt<<":<%=,运算符>\n";
			else cout<<++cnt<<":<%,运算符>\n",retract();
		}
		else if(ch=='&'){
			get();
			if(ch=='=')cout<<++cnt<<":<&=,运算符>\n";
			else cout<<++cnt<<":<&,运算符>\n",retract();
		}
		else if(ch=='^'){
			get();
			if(ch=='=')cout<<++cnt<<":<^=,运算符>\n";
			else cout<<++cnt<<":<^,运算符>\n",retract();
		}
		else if(ch=='|'){
			get();
			if(ch=='=')cout<<++cnt<<":<|=,运算符>\n";
			else cout<<++cnt<<":<|,运算符>\n",retract();
		}
		else if(ch=='>'){
			get();
			if(ch!='>')cout<<++cnt<<":<>,运算符>\n",retract();
			else{
				get();
				if(ch=='=')cout<<++cnt<<":<>>=,运算符>\n";
				else cout<<++cnt<<":>>,运算符>\n",retract();
			}
		}
		else if(ch=='<'){
			get();
			if(ch!='<')cout<<++cnt<<":<<,运算符>\n",retract();
			else{
				get();
				if(ch=='=')cout<<++cnt<<":<<<=,运算符>\n";
				else cout<<++cnt<<":<<<,运算符>\n",retract();
			}
		}
		else cout<<++cnt<<":<"<<ch<<",未知字符>\n";
	}
}
int main(){
	while(1){
		getline(cin,t);
		if(t=="end")break;
		s+=t+' ';
	}
	analysis();
	return 0;
}