编译原理——LL(1)语法分析

       直接输入根据已知文法构造的分析表M,对于输入的文法和符号串,所编制的语法分析程序应能正确判断此串是否为文法的句子,并要求输出分析过程。


C++实现如下:

#include
using namespace std;
const int L_NUM=100000;
const int MAX=100;	//预测分析表容量 
const string ERROR="出错! 该文法无法识别该语言!";
string str[MAX][MAX];	//预测分析表 
int gone=0; 	//代表步骤 
char any[MAX];		//分析栈 
int top=-1;		//分析栈指针 
queue s;	//保存输入串的队列 
int n;	//非终结符个数  
int t;	//终结符个数  
map row;	//分析表行号映射 
map col;	//分析表列号映射 
map::iterator rit;	//访问行映射的迭代器
map::iterator cit;	//访问列映射的迭代器
void terror();	//出错处理 
void anysit();	//语法分析 
void inputx();	//输入函数 
void outputx();		//输出函数 
char c0;	//保存开始符号
char c;		//暂存终结符或非终结符
string s0;	//暂存产生式/输入串  

int main(){
	inputx();
	anysit();
	return 0; 
}
void terror(){
	cout<>n;
	cout<<"输入终结符个数:";
	cin>>t;
	cout<<"输入非终结符:";
	for(int i=0;i>c;
		row[c]=i+1;
		if(i==0){
			c0=c;
		} 
	}
	cout<<"输入终结符:";
	for(int i=0;i>c;
		col[c]=i+1;
	}
	cout<<"输入预测分析表(以@表示空白,以$表示空串 ):"<>s0;
			str[i][j]=s0;
		}
	} 
	cout<<"输入要识别的语言串:";
	cin>>s0;
	for(int i=0;i'Z')&&any[top]!=s.front()){
			terror();
			break;
		}
		else if(any[top]>='A'&&any[top]<='Z'){
			int x,y=L_NUM;
			for(rit=row.begin();rit!=row.end();rit++){
				if(rit->first==any[top]){
					x=rit->second;
					break;
				}
			}
			for(cit=col.begin();cit!=col.end();cit++){
				if(cit->first==s.front()){
					y=cit->second;
					break;
				}
			}
			if(y==L_NUM||str[x][y]=="@"){
				terror();
				break;
			}
			else{
				char h=any[top];
				top--;
				string ss=str[x][y];
				for(int j=ss.length()-1;j>1;j--){
					if(ss[j]!='$'){
						any[++top]=ss[j];
					}
				}
				cout<TA @ @ ->TA @ @
@ ->+TA @ @ ->$ ->$
->FB @ @ ->FB @ @
@ ->$ ->*FB @ ->$ ->$
->i @ @ ->(E) @ @
*/

以上面的预测分析表进行语法分析运行结果:

编译原理——LL(1)语法分析_第1张图片

 

你可能感兴趣的:(编译原理实验)