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

📄 middle.c

📁 自己开发的c0文法编译器
💻 C
字号:

#include "world.h"
#include <stdio.h>

void term();
int mem = 0;
#define MAXLEN 100

char tempstr[BSIZE];
struct midcode * mid = NULL, * r = NULL;
int top=-1;

void factor();

char * exprbuf[MAXLEN];
void expr();




void push(char *s)   //中间变量#t1压栈 
{
	int len = strlen(s);
	exprbuf[++top]=(char *)malloc(len + 1);
	strcpy(exprbuf[top],s);
}




char * op(int i)
{
	char * s = (char *)malloc(10);
	switch(i)
	{
	case minus:strcpy(s,"-");break;
	case plus: strcpy(s,"+");break;
	case multiply: strcpy(s,"*");;break;
	case divide: strcpy(s,"/");break;
	default: strcpy(s,"existerror");
	}
	return s;	
}




char * newtemp()  //中间变量 t#1
{
	char *s = (char *)malloc(30);
	sprintf(s,"t%d",mem); /////////////////////////////////////////////
	mem++;
	return s;
}





void tokenget(int i)   //返回token 
{
	int ch;
	if(i==0)
	{
		while(isspace(ch=getchar()))
		{	if(ch=='\n')
				lineno++;
		}
		ungetc(ch,stdin);

		seehead = Word();
	}	
	else if(i==1)  //处理正负数+3,-2
	{
		while(isspace(ch=getchar()))
		{	
			if(ch=='\n')
				lineno++;
		}
		if(ch=='+')
			seehead=plus;
		else if(ch=='-')
			seehead=minus;
		else
		{
			ungetc(ch,stdin);
				seehead = Word();
		}
	}

}







void  factor(void)  //因子
{
	if(seehead==LK)
	{
		tokenget(0);
		expr();
		if(seehead==RK)
		{
			tokenget(0);
		}
		else
		{
			existerror("existerror!",lineno);
		tokenget(0);
		}
	}
	else if(seehead==NUM||seehead==ID)
	{
		tokenget(0);
		push(buffer);
	//	printf("%s",buffer);
	}
	else
	{
		existerror("existerror",lineno);
	}
}






struct midcode * nodegenerate(char *s1,char *s2,char *s3,char *s4) //生成一个中间代码
{
	struct midcode * tempnode = (struct midcode *)malloc(sizeof(struct midcode));
	strcpy(tempnode->op,s1);
	strcpy(tempnode->reg1,s2);
	strcpy(tempnode->reg2,s3);
	strcpy(tempnode->res,s4);
	tempnode->next = NULL;
	return tempnode;
}





void expr(void)
{
	int t;
	term();
	while(1)
	{
		switch(seehead)
		{
		case minus:case plus:
			t= seehead;
			tokenget(1);
			term();
			//push(op(t));
			strcpy(tempstr,newtemp());

			top--;
			strcpy(exprbuf[top],tempstr);
			continue;
		default:return;
		}
	}
}






void nodeadd(struct midcode * tempnode) //链表中添加一项
{
	if(mid==NULL)
	{
		mid = tempnode;
	}
	else
	{
		r->next = tempnode;
	}
	r = tempnode;

}


void mid1()
{

	int i;
	char s[10];
	char tempbuf[MAXLEN][BSIZE];  //存中间变量
	int temptop=0;
	seehead= Word();
	while(seehead!=fenghao)
	{
		expr();
		for(i=0;i<top;i++)
		{
		
		}
	
		
		
	}
	
}





void term(void)
{
	int t;
	factor();
	while(1)
	{
		switch(seehead)
		{
		case multiply:case divide:
			t = seehead;
			tokenget(1);
			factor();
			//push(op(t));
			strcpy(tempstr,newtemp());

			top--;
			strcpy(exprbuf[top],tempstr);
			continue;
		default :return ;
		}
	}
}


⌨️ 快捷键说明

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