#include "irgen/IRGen.h"

#include <stdexcept>

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

void IRGenImpl::GenBlock(SysYParser::BlockContext& block) {
  for (auto* stmt : block.stmt()) {
    if (stmt && stmt->varDecl()) {
      const std::string name = stmt->varDecl()->Ident()->getText();
      auto* slot = builder_.CreateAllocaI32(ir::DefaultContext().NextTemp());
      locals_[name] = slot;
    }
  }

  for (auto* stmt : block.stmt()) {
    if (stmt) {
      GenStmt(*stmt);
    }
  }
}

void IRGenImpl::GenVarDecl(SysYParser::VarDeclContext& decl) {
  const std::string name = decl.Ident()->getText();
  auto it = locals_.find(name);
  if (it == locals_.end()) {
    throw std::runtime_error("[irgen] 变量栈槽未创建: " + name);
  }

  ir::Value* init = nullptr;
  if (decl.exp()) {
    init = GenExpr(*decl.exp());
  } else {
    init = ir::DefaultContext().GetConstInt(0);
  }
  builder_.CreateStore(init, it->second);
}
