llvm cookbook 2.6 二元表达式

本文实现二元表达式的解析和构造。

static std::map<char, int> operator_precedence;

static void init_precedence() {
  operator_precedence['-'] = 1;
  operator_precedence['+'] = 2;
  operator_precedence['/'] = 3;
  operator_precedence['*'] = 4;
}

static int getBinOpPrecedence() {
  if(isascii(current_token)) {
    return -1;
  }
  int tokPrec = operator_precedence[current_token];
  if (tokPrec <= 0) return -1;
  return tokPrec;
}

static BaseAST* paran_parser() {
  next_token();
  BaseAST* v = expression_parser();
  if (!v) return 0;
  if (current_token != ')') return 0;
  return v;
}

static void HandleDefn() {
  if (FunctionDefnAST *f = func_defn_parser()) {
    if (Function* lf = f->Codegen()) {

    }
  } else {
    next_token();
  }
}

static void HandleTopExpression() {
  if (FunctionDefnAST* *f = top_level_parser()) {
    if (Function* lf = f->Codegen()) {
    }
  } else {
    next_token();
  }
}

static BaseAST* Base_Parser() {
  switch(current_token) {
    default: return 0;
    case IDENTIFIER_TOKEN: return identifier_parser();
    case NUMERIC_TOKEN: return numeric_parser();
    case '(': return paran_parser();
  }
}

static BaseAST* binary_op_parser(int old_prec, BaseAST* lhs) {
  while (true) {
    int operator_prec = getBinOpPrecedence();
    if (operator_prec < old_prec) return lhs;
    int BinOp = current_token;
    next_token();
    BaseAST* rhs = Base_Parser();
    if (!rhs) return 0;
    int next_prec = getBinOpPrecedence();
    if (operator_prec < next_prec) {
      rhs = binary_op_parser(operator_prec + 1, rhs);
      if (rhs == 0) return 0;
    }
    lhs = new BinaryAST(std::to_string(BinOp), lhs, rhs);
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,472评论 2 59
  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 7,925评论 2 9
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,447评论 25 709
  • 如果说,世界上有一种是我不怕还喜欢的昆虫,那绝对蜜蜂了。 我想,是跟在父亲身边,才会受到的影响。 父亲一辈子都是平...
    橘子屋阅读 3,613评论 11 14
  • 小时候看着大人们抽烟,已成为一种乡愁,望着好美好,心中很好奇。 看着大人们手上点着的香烟,在幼小的...
    辛苦快乐阅读 4,183评论 1 5