首页 > 其他 > 详细

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

时间:2015-07-13 22:29:33      阅读:413      评论:0      收藏:0      [点我收藏+]

部分代码来自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:\n%s\n", str);
  int j = i;
  while (j--)
    fprintf (stderr, " ");
  fprintf (stderr, "^\n");
  fprintf (stderr, "Syntax error at position: %d\n"
           "\texpecting: %s\n"
           "\tbut got  : %c\n",
           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]=='\0')
    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;
}

与君共勉

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

原文:http://blog.csdn.net/lionel_d/article/details/46867461

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!