#include "irgen/IRGen.h"

#include <stdexcept>

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

namespace {

void VerifyFunctionStructure(const ir::Function& func) {
  for (const auto& bb : func.blocks()) {
    if (!bb || !bb->HasTerminator()) {
      throw std::runtime_error("[irgen] 基本块未正确终结: " +
                               (bb ? bb->name() : std::string("<null>")));
    }
  }
}

}  // namespace

IRGenImpl::IRGenImpl(ir::Module& module)
    : module_(module), func_(nullptr), builder_(nullptr) {}

void IRGenImpl::Gen(SysYParser::CompUnitContext& cu) {
  if (!cu.funcDef()) {
    throw std::runtime_error("[irgen] 缺少 main 定义");
  }
  GenFuncDef(*cu.funcDef());
}

void IRGenImpl::GenFuncDef(SysYParser::FuncDefContext& func) {
  if (!func.block()) {
    throw std::runtime_error("[irgen] 函数体为空");
  }
  if (!func.Ident()) {
    throw std::runtime_error("[irgen] 缺少函数名");
  }

  func_ = module_.CreateFunction(func.Ident()->getText(), ir::Type::Int32());
  builder_.SetInsertPoint(func_->entry());
  locals_.clear();

  GenBlock(*func.block());
  VerifyFunctionStructure(*func_);
}
