Chinaunix首页 | 论坛 | 博客
  • 博客访问: 79683
  • 博文数量: 31
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 839
  • 用 户 组: 普通用户
  • 注册时间: 2013-03-12 14:38
个人简介

我在收集一些石头,我期待它们有一天能够串联成一串项链。

文章分类

全部博文(31)

文章存档

2013年(31)

我的朋友

分类: C/C++

2013-03-16 13:58:38

构造一个中缀表达式到后缀表达式的翻译器,初步了解递归下降语法分析原理及语法制导翻译的过程。包含+,-,*,/,()

expr ------> expr + term                {print(‘+’)} 

    | expr - term                  {print(‘-’)}

             | term

term ----->  term * factor                   {print(‘*’)}

          | term / factor               {print(‘/’)}

                  | factor

factor ----> (  expr  )

                | id                                        {print(id.lexeme)}            

         | num                                  {print(num.value)}



点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<ctype.h>
  3. void expr();
  4. int lookahead;
  5. void match(int t)
  6. {
  7.     if (lookahead == t)
  8.         lookahead = getchar();
  9.     else {
  10.         printf("syntax error!");
  11.         return;
  12.     }
  13. }
  14. void factor()
  15. {
  16.     if (isdigit(lookahead)){
  17.         printf("%c",lookahead);match(lookahead);
  18.     }else if(lookahead == '('){
  19.         match('(');expr();match(')');
  20.     }else if((lookahead >='a'&&lookahead <='z')||(lookahead >='A'&&lookahead <='Z')){
  21.         printf("%c",lookahead);match(lookahead);factor();
  22.     }
  23. }

  24. void term()
  25. {
  26.     factor();
  27.     while(1){
  28.         if(lookahead == '*'){
  29.             match('*');factor();printf("*");
  30.         }else if( lookahead == '/'){
  31.             match('/');factor();printf("/");
  32.         }else return;
  33.     }
  34. }
  35. void expr(){
  36.     term();
  37.     while(1){
  38.         if(lookahead == '+'){
  39.             match('+');term();printf("+");
  40.         }else if(lookahead == '-'){
  41.             match('-');term();printf("-");
  42.         }
  43.         else return;
  44.     }
  45. }
  46. int main(){
  47.     lookahead = getchar();
  48.     expr();
  49.     printf("\n");
  50.     getchar();
  51.     return 0;
  52. }

1.         实验采用递归下降方法,可识别单字符的factor ,未添加下划线等其余变量标识符。

2.         若在factor()函数中递归调用factor()函数,可识别多字符的factor,但识别效果可能会造成二义性,建议加入分割符。

       3.         递归调用factor()在原理上有待商榷,它将多字符id分割成多个factor,在形成词法单元时可能出错。


阅读(856) | 评论(0) | 转发(0) |
0

上一篇:图片抓取

下一篇:Java生成API

给主人留下些什么吧!~~