美文网首页
llvm cookbook 2.5 简单表达式

llvm cookbook 2.5 简单表达式

作者: peteyuan | 来源:发表于2018-11-16 16:49 被阅读3次

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

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

相关文章

网友评论

      本文标题:llvm cookbook 2.5 简单表达式

      本文链接:https://www.haomeiwen.com/subject/xmwpfqtx.html