⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 parser.c

📁 编译原理 做一个后缀翻译 还有抽象堆栈机代码翻译
💻 C
字号:
/**** parser.c *****/

#include "global.h"



int lookahead;

void judge();
void expr();
void match(int t)
{
	if(lookahead==t)
		lookahead=lexan();
	else error("syntax error");
}

void factor()
{
	int tt,ttv;
	switch(lookahead){
	case '(':
		match('(');expr();match(')');break;
	case NUM:
		emit(NUM,tokenval);match(NUM);break;
	/*case ID:
		emit(ID,tokenval);match(ID);break;*/
	case ID:
		{tt=lookahead;ttv=tokenval;match(ID);
			if(lookahead=='='){//id=expr();
				if(functype==0) {printf("lvalue ");fprintf(fpw,"lvalue ");
					emit(tt,ttv);
					match('=');
					expr();
					printf("=\n");fprintf(fpw,"=\n");
					break;
				}
				if(functype==1) {
					printf("%s ",symtable[ttv].lexptr);fprintf(fpw,"%s ",symtable[ttv].lexptr);
					match('=');expr();
					printf("= ");fprintf(fpw,"= ");
					break;
				}
			}
			else{//id;
				if(functype==0) {printf("rvalue ");fprintf(fpw,"rvalue ");}
				emit(tt,ttv);
				break;
			}
		}
	default:
		error("syntax error");
	}
}

void term()
{
	int t;
	factor();
	while(1)
		switch(lookahead){
		case '*':
		case '/':
		case DIV:
		case MOD: t=lookahead;match(lookahead);factor();emit(t,NONE);continue;
		default:return;
	}
}

void expr()
{
	int t;
	term();
	while(1)
		switch(lookahead){
		case '+':
		case '-': t=lookahead;match(lookahead);term();emit(t,NONE);continue;
		default :return;
	}
}

void parse()
{
	int tval,op,t;
	Elemtype *s,*n;
	lookahead=lexan();
	while(lookahead!=DONE){
		anserror=0;
	  judge();
		expr();
		match(';');
		if(functype==1) {//若是进行翻译
			if(anserror==0){//可以计算,输出结果
				Pop(&N,&ans);
				printf("%d\n",ans);
				fprintf(fpw,"%d\n",ans);
			}
			else{//不能计算,输出后缀表达式后换行
				printf("\n");
				fprintf(fpw,"\n");
			}
		}
		if(functype==0){//堆栈机代码显示后换一行
			printf("\n");
			fprintf(fpw,"\n");
		}
	 DestroyStack(&N);
 }
 fclose(fpo);//关闭输入文件
 fclose(fpw);//关闭输出文件
}

void judge(){
	char scan[80],ch,oper[4];
	int i=0,j;
	if(lookahead==ID) {//先判断lookahead,如果是ID特别处理
		ch=fgetc(fpo);
		if(ch!='='){
			ungetc(ch,fpo);
			anserror=1;
			return;
		}
		ungetc(ch,fpo);
	}
	
	ch=fgetc(fpo);
	while(ch!=';'){
		if(isdigit(ch)) ;
	  else if(isalpha(ch)) {
	  	j=i;
			while(isalnum(ch)){
				scan[i++]=ch;
				ch=fgetc(fpo);
				if(i>=79)
					error("compiler error");
			}
			oper[0]=scan[j++];oper[1]=scan[j++];oper[2]=scan[j++];oper[3]='\0';
			if(strcmp(oper,"mod")==0||strcmp(oper,"div")==0) anserror=0;
			else if(ch!='=') {anserror=1;break;}//判断出是否含有‘=’
		}
		scan[i++]=ch;
		ch=fgetc(fpo);
	}
	ungetc(ch,fpo);//退回';'
	while(i!=0){
		ungetc(scan[--i],fpo);
	}	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -