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


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

    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;
    }

    与君共勉

  • 相关阅读:
    你笑的时候真的很美
    我不会倒下
    创业靠的是“脑子”,教你如何运用谋略事半功倍~
    其实我真的很在乎你
    让你克服低效率的困扰:从实质上迅速提升你生活的方法
    沈科(帮别人名字作诗)
    Secrets of the NetBeans Window System
    PropertyUtils.copyProperties的性能
    Swing Threading的限制
    SwingSet2
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5180377.html
Copyright © 2020-2023  润新知