📄 语法制导翻译.cpp
字号:
// 语法制导翻译器设计示范程序
// ----- 算数表达式四元式翻译(递归子程序法)
// 要求:1. 读懂该程序,并上机调试成功;
// 2. 运行该程序,输入源表达式(字母:表示变量,数字:表示常数。)
// 3. 反复运行,考查输出的各种四元式的正确性。
// 4. 实验报告内容:表达式的属性翻译文法;递归子程序框图;
// 运行结果的记录(输出的四元式不得少于10条!)
#include "string.h"
#include "stdio.h"
char w; //当前单词(w)
int j=1; //临时变量序号
struct TOKEN //单词的 TOKEN 结构
{
char t;
int i;
} ;
struct TOKEN word, sem[10]; //结构单词(word),语义栈(sem)
int i_sem;
struct QT //四元式结构
{
char w;
struct TOKEN word1;
struct TOKEN word2;
struct TOKEN temp;
};
char exp[50]; //原算术表达式区
int i=0; //原单词序号
struct QT qt[30]; //四元式区
int q=0; //四元式序号
int E();
int T();
int F();
void next(); //读下一个单词
void newt(); //申请一个临时变量函数
void quat(char); //生成四元式函数
int main() //主函数
{
printf("please input your expression: ");
scanf(" %s",exp); // 输入表达式
next(); // next(w)
E();
if (w=='\0')
{
printf("\n");
for (i=0;i<q;i++) //输出四元式序列
{
printf(" (%d) ",i+1);
printf(" ( %c",qt[i].w);
printf(" , %c.%d",qt[i].word1.t,qt[i].word1.i);
printf(" , %c.%d",qt[i].word2.t,qt[i].word2.i);
printf(" , %c.%d )\n",qt[i].temp.t,qt[i].temp.i);
}
}
else printf("err");
printf("\nHello World!\n");
return 0;
}
int E()
{
char w1; //算符(+\-)暂存变量
T();
while ( w=='+' || w=='-')
{
w1=w; //暂存运算符(+|-)
next(); //next(w)
T();
quat(w1);
}
return 1;
}
int T()
{
char w2; //算符(*|/)暂存变量
F();
while ( w=='*' || w=='/')
{
w2=w; //暂存运算符(*|/)
next(); //next(w)
F();
quat(w2);
}
return 1;
}
int F()
{
if ( w=='(')
{
next(); //next(w)
E();
if ( w!=')')
{
printf("err");
return 0;
}
}
else if ((w>='a' && w<='z')||(w>='0' && w<='9'))
{
word.t=w; word.i=0 ;
sem[++i_sem]=word; //push(SEM,w)
}
else
{
printf("err");
return 0;
}
next(); //next(w)
return 1;
}
void next()
{
w=exp[i];
i++;
}
void newt()
{
word.t='t';
word.i=j++;
}
void quat(char ww)
{
newt();
qt[q].w=ww; //QT[q]:=(ww,SEM[s-1],SEM[s],temp);
qt[q].word1=sem[i_sem-1];
qt[q].word2=sem[i_sem];
qt[q].temp=word;
i_sem--; //pop(SEM);
i_sem--; //pop(SEM);
sem[++i_sem]=word; //push(SEM,temp);
q++;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -