• 编译器实践三 之 针对算术表达式的语法分析器


    该算术表达式的上下文无关文法是:

    E -> E + T

       | E - T

       | T

    T -> T * F

       | T / F

       | F

    F -> num

       | (E)



    部分代码来自MOOC


    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    void parse_F();
    void parse_T();
    void parse_E();
    void error (char *want, char got);
    
    int i;
    char *str = 0;
    
    void error (char *want, char got)
    {
      fprintf (stderr, "Compling this expression:
    %s
    ", str);
      int j = i;
      while (j--)
        fprintf (stderr, " ");
      fprintf (stderr, "^
    ");
      fprintf (stderr, "Syntax error at position: %d
    "
               "	expecting: %s
    "
               "	but got  : %c
    ",
               i, want, got);
      exit (0);
      return;
    }
    
    void parse_F()
    {
      char c = str[i];
      if (isdigit(c)){
        i++;
        return;
      }
      if (c=='('){
        i++;
        parse_E();
        c = str[i];
        if (c==')'){
          i++;
          return;
        }
        error ("')'", c);
        return;
      }
      error ("'0-9' or '('", c);
      return;
    }
    
    
    void parse_T()
    {
      parse_F();
      char c = str[i];
      while (c=='*' || c =='/'){
        i++;
        parse_F();
        c = str[i];
      }
      return;
    }
    
    void parse_E()
    {
      parse_T();
      char c = str[i];
      while (c=='+' || c == '-'){
        i++;
        parse_T();
        c = str[i];
      }
      return;
    }
    
    void parse (char *e)
    {
      str = e;
      i = 0;
      parse_E();
      if (str[i]=='')
        return;
      error ("'+' or '\0'", str[i]);
      return;
    }
    ///////////////////////////////////////////////
    // Your job:
    // Add some code into the function parse_E() and
    // parse_T to parse "-" and "/" correctly.
    // When you finish your task, NO error message
    // should be generated.
    // Enjoy! :-P
    int main (char argc, char **argv)
    {
      // There are the following rules on an expression:
      //   1. Every expression is represented as a string;
      //   2. integers are non-negative;
      //   3. integers are between 0-9.
      char *e;
    
      e = "(2)";
      parse(e);
    
      e = "(3+4*5))";
      parse(e);
    
      e = "(8-2)*3";
      parse(e);
    
      e = "(8-2)/3";
      parse(e);
      
      return 0;
    }

    与君共勉

  • 相关阅读:
    php中运算符的分类及注意事项
    ecshopv3.6安装
    phpstudy多站点配置教程
    织梦dedecms出现DedeCMS Error: (PHP 5.3 and above) Please set 'request_order' ini value to i解决办法
    thinkphp3.2批量删除功能
    怎么使用阿里图标库
    人人网,微博,QQ空间,朋友圈,常用API调用实现方法
    ueditor注意事项
    大图在小于自身的div中,水平居中
    thinkphp3.2 实现分页功能
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5180377.html
Copyright © 2020-2023  润新知