语义分析实验报告
一、 实验目的:
通过上机实习.加深对语法制导翻译原理的理解.掌握将语法分析所识别的语法成分变换为中间代码的语义翻译方法。
二、 实验要求:
采用递归下降语法制导翻译法.对算术表达式、赋值语句进行语义分析并生成四元式序列。
三、 算法思想:
1、设置语义过程。
(1)emit(char *result,char *ag1,char *op,char *ag2)
该函数的功能是生成一个三地址语句送到四元式表中。 四元式表的结构如下:
struct
{ char result[8];
char ag1[8]; char op[8]; char ag2[8]; }quad[20]; (2) char *newtemp()
该函数回送一个新的临时变量名.临时变量名产生的顺序为T1.T2.…
char *newtemp(void) { char *p;
char m[8];
p=(char *)malloc(8); k++;
itoa(k,m,10); strcpy(p+1,m); p[0]=’t’; return(p);
}
2、函数lrparser 在原来语法分析的基础上插入相应的语义动作:将输入串翻译成四元式序列。在实验中我们只对表达式、赋值语句进行翻译。
. .
四、 源程序代码:
#include
char result[12]; char ag1[12]; char op[12]; char ag2[12];
}quad;
char prog[80],token[12]; char ch;
int syn,p,m=0,n,sum=0,kk; //p是缓冲区prog的指针.m是token的指针 char *rwtab[6]={\void scaner(); char *factor(void); char *term(void); char *expression(void); int yucu();
void emit(char *result,char *ag1,char *op,char *ag2); char *newtemp(); int statement(); int k=0;
void emit(char *result,char *ag1,char *op,char *ag2) {
strcpy(quad.result,result); strcpy(quad.ag1,ag1);
strcpy(quad.op,op);
strcpy(quad.ag2,ag2);
. .
cout< char *newtemp() { } void scaner() { for(n=0;n<8;n++) token[n]=NULL; ch=prog[p++]; while(ch==' ') { } if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) { m=0; while((ch>='0'&&ch<='9')||(ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) { } token[m++]='\\0'; token[m++]=ch; ch=prog[p++]; ch=prog[p]; p++; char *p; char m[12]; p=(char *)malloc(12); k++; itoa(k,m,10); strcpy(p+1,m); p[0]='t'; return (p); . . } p--; syn=10; for(n=0;n<6;n++) if(strcmp(token,rwtab[n])==0) { } syn=n+1; break; else if((ch>='0'&&ch<='9')) { } else switch(ch) { { } p--; syn=11; if(sum>32767) syn=-1; sum=0; while((ch>='0'&&ch<='9')) { } sum=sum*10+ch-'0'; ch=prog[p++]; case'<':m=0;token[m++]=ch; ch=prog[p++]; if(ch=='>') { } else if(ch=='=') syn=21; token[m++]=ch; . .
相关推荐: