编译原理实验:语义分析实验

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验四:语义分析

一.实验目的:通过上机实习,加深对语法制导翻译原理的理解,掌握将语法分析所识别的语法成分变换为中间代码的语义翻译方法

二.实验要求:采用的是递归下降语法制导翻译法,对算术表达式,赋值语进行语义分析并生成四元式序列。

1.实验的输入和输出分别为以下:

输入是语法分析后提供的正确的单词串,输出为三地址指令形式的四元式序列。

例如:对于语句串begin a:=2+3*4;x:=(a+b)/c end #

输出的三地址指令如下所示:

(1)t1=3*4;

(2)t2=2+t1;

(3)a=t2;

(4)t3=a+b;

(5)t4=t3/c;

(6)x=t4;

2.实验算法的思想为:

(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];

2char *newtemp()

该函数的功能是回送一个新的变量名,临时变量的名称产生的顺序依次为T1, T2 ,……..

Char *newtemp()

{

Char *p;

Char m[8];

P=(char *)malloc(8);

K++;

Iota(k,m,10);

Strcpy(p+1,m);

P[0]=’t’;

Return (p);

}

(2)主程序的示意图如图所示:

(3)函数lrparser在原来语法分析的基础上插入相应的语义分析动作,将输入串翻译成四元式序列,在实验中我们仅仅所作的是对表达

式和赋值语句进行翻译。

三,实验程序源码代码如下:

#include "stdio.h"

#include "string.h"

#include "ctype.h"

char token[20] ;

char prog[100];

char ch;

char *rwtab[6]={"begin","if","then","while","do","end"};

int syn,p,m,n,sum;

#define STACK_SIZE 100

int compute(int x,char c,int y);

int stack_num[STACK_SIZE];

int num_top=-1;

bool notfull_num()

{

if(num_top==STACK_SIZE)

return false;

else

return true;

}

void push_num(int value)

{

if(notfull_num())

{

num_top++;

stack_num[num_top]=value;

}

}

void pop_num()

{

num_top--;

}

int num_top_value()

{

int m=stack_num[num_top];

// printf("sing=====%d\n",m);

return m;

}

bool empty_num()

{

if(num_top==-1)

return true;

else

return false;

}

char stack_operation[STACK_SIZE]; int operation_top=-1;

bool notfull_operation()

{

if(operation_top==STACK_SIZE) return false;

else

return true;

}

void push_operation(char c)

{

if(notfull_operation())

stack_operation[++operation_top]=c; }

void pop_operation()

{

operation_top--;

}

char operation_top_value()

{

return stack_operation[operation_top];

}

bool empty_operation()

{

if(operation_top==-1)

return true ;

else

return false;

}

int compute(int x,char c,int y)

{

int m;

if(c=='+')m=x+y;

else if(c=='-') m=x-y;

else if(c=='*') m=x*y;

else if(c=='/') m=x/y;

return m;

}

struct {

int result;

int ag1;

char op ;

int ag2;

}quad[20];

void scanner();

相关文档
最新文档