llvm cookbook 2.5 简单表达式

本文实现简单表达式的解析和构造。

static int current_token;

static void next_token() {
  current_token = get_token();
}

static BaseAST* numeric_parser() {
  BaseAST* result = new NumericAST(Numeric_Val);
  next_token();
  return result;
}

static BaseAST* identifier_parser() {
  std::string   id_name = Identifier_string;
  next_token();

  if (current_token != '(') {
    return new VariableAST(id_name);
  }
  next_token();

  std::vector<BaseAST*> args;
  if (current_token != ')') {
    while(true) {
      BaseAST* arg = expression_parser();
      if (!arg) return 0;
      args.push_back(arg);
      if (current_token == ')') break;

      if (current_token != ',') return 0;

      next_token();
    }
  }
  next_token();

  return new FunctionCallAST(id_name, args);
}

static FunctionDeclAST* func_decl_parser() {
  if (current_token != IDENTIFIER_TOKEN) return 0;

  std::string fn_name = Identifier_string;
  next_token();

  if (current_token != '(') return 0;
  next_token();

  std::vector<std::string> func_arg_names;
  while (current_token == IDENTIFIER_TOKEN) {
    func_arg_names.push_back(Identifier_string);
    next_token();
  }
  if (current_token != ')') return 0;
  next_token();

  return new FunctionDeclAST(fn_name, func_arg_names);
}

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* expression_parser() {
  BaseAST* lhs = Base_Parser();
  if (!lhs) return 0;
  return binary_op_parser(0, lhs);
}

static FunctionDefnAST *func_defn_parser() {
  next_token();
  FunctionDeclAST *decl = func_decl_parser();
  if (!decl) return 0;

  if (BaseAST* body = expression_parser())
    return new FunctionDefnAST(decl, body);
  return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 2,911评论 2 9
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 13,135评论 2 59
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,744评论 25 709
  • 有一句古话:“百年修得同船渡,千年修得共枕眠。”这句话不仅道出了男女爱情的缘分,更说明了一个真理: “最亲的,都是...
    54谭小姐阅读 154评论 0 1
  • 有人,她奢求过爱情, 可是,后来缘分已尽, 于是她封锁了自己的心! 他可能依旧在,你大可用尽力气去爱。 隔绝所...
    桦灼阅读 260评论 0 0