博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一个简单的语法制导翻译器
阅读量:6633 次
发布时间:2019-06-25

本文共 3239 字,大约阅读时间需要 10 分钟。

刚刚开始学习编译原理,重新开始写一个翻译器,从最简单的开始写一个最简单的例子,将中缀表达式改写成后缀表达式(单个数字)

#include
char lookhead;int main(){ void term(); lookhead=getchar(); term(); while(1) { if(lookhead == '+') { lookhead=getchar(); term(); putchar('+'); } if(lookhead == '-') { lookhead=getchar(); term(); putchar('-'); } } return 0; }void term(){ if(lookhead>='0'&&lookhead<='9') { putchar(lookhead); lookhead=getchar(); } else { printf("error"); }}

 改进版

#include
char lookhead;int main(){ char myget(); void term(); void rest(); lookhead=myget(); term(); rest();return 0; }char myget(){ char mylook; mylook = getchar(); for(;;mylook = getchar()) { if(mylook ==' '||mylook =='\t') { ; } else { return mylook; } } }void rest(){ while(1) { if(lookhead == '+') { lookhead=myget(); term(); putchar('+'); putchar(' '); continue; } if(lookhead == '-') { lookhead=myget(); term(); putchar('-'); putchar(' '); continue; } }}void term(){ int n; if(lookhead>='0' && lookhead<='9') { n=0; do { n = n*10 + lookhead - '0'; lookhead=myget(); }while(lookhead >= '0' && lookhead<='9'); printf("%d ",n); } else { printf("error"); }}

 改进版2(加入括号和乘除)

#include
char lookhead;int main(){ char myget(); void term(); void factor(); void expr(); lookhead=myget(); factor(); term(); expr();return 0; }char myget(){ char mylook; mylook = getchar(); for(;;mylook = getchar()) { if(mylook ==' '||mylook =='\t') { ; } else { return mylook; } } }void expr(){ if(lookhead == '+') { lookhead=myget(); expr(); term(); putchar('+'); putchar(' '); } if(lookhead == '-') { lookhead=myget(); expr(); term(); putchar('-'); putchar(' '); } term(); }void term(){ if(lookhead == '*') { lookhead=myget(); term(); putchar('*'); putchar(' '); factor(); } if(lookhead == '/') { lookhead=myget(); term(); putchar('/'); putchar(' '); factor(); } factor(); }void factor(){ int n; if(lookhead>='0' && lookhead<='9') { n=0; do { n = n*10 + lookhead - '0'; lookhead=myget(); }while(lookhead >= '0' && lookhead<='9'); printf("%d ",n); } if(lookhead == '(') { lookhead =myget(); do { expr(); }while(lookhead != ')'); lookhead =myget(); }}

 

转载于:https://www.cnblogs.com/lovehyy/articles/3568098.html

你可能感兴趣的文章