// 将语法树翻译为极简 IR。
// 实现拆分在 IRGenFunc/IRGenStmt/IRGenExp/IRGenDecl。

#pragma once

#include <memory>
#include <string>
#include <unordered_map>

#include "SysYParser.h"
#include "ir/IR.h"

namespace antlr4 {
namespace tree {
class ParseTree;
}
}  // namespace antlr4

namespace ir {
class Module;
class Function;
class IRBuilder;
class Value;
}

class IRGenImpl {
 public:
  explicit IRGenImpl(ir::Module& module);

  void Gen(SysYParser::CompUnitContext& cu);

 private:
  void GenFuncDef(SysYParser::FuncDefContext& func);
  void GenBlock(SysYParser::BlockContext& block);
  bool GenStmt(SysYParser::StmtContext& stmt);
  void GenVarDecl(SysYParser::VarDeclContext& decl);
  void GenReturnStmt(SysYParser::ReturnStmtContext& ret);

  ir::Value* GenExpr(SysYParser::ExpContext& expr);
  ir::Value* GenAddExpr(SysYParser::AddExpContext& add);
  ir::Value* GenPrimary(SysYParser::PrimaryContext& primary);

  ir::Module& module_;
  ir::Function* func_;
  ir::IRBuilder builder_;
  std::unordered_map<std::string, ir::Value*> locals_;
};

std::unique_ptr<ir::Module> GenerateIR(antlr4::tree::ParseTree* tree);
