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

#pragma once

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

#include "SysYBaseVisitor.h"
#include "SysYParser.h"
#include "ir/IR.h"
#include "sem/Sema.h"

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

class IRGenImpl final : public SysYBaseVisitor {
 public:
  IRGenImpl(ir::Module& module, const SemanticContext& sema);

  std::any visitCompUnit(SysYParser::CompUnitContext* ctx) override;
  std::any visitFuncDef(SysYParser::FuncDefContext* ctx) override;
  std::any visitBlockStmt(SysYParser::BlockStmtContext* ctx) override;
  std::any visitBlockItem(SysYParser::BlockItemContext* ctx) override;
  std::any visitDecl(SysYParser::DeclContext* ctx) override;
  std::any visitStmt(SysYParser::StmtContext* ctx) override;
  std::any visitVarDef(SysYParser::VarDefContext* ctx) override;
  std::any visitReturnStmt(SysYParser::ReturnStmtContext* ctx) override;
  std::any visitParenExp(SysYParser::ParenExpContext* ctx) override;
  std::any visitNumberExp(SysYParser::NumberExpContext* ctx) override;
  std::any visitVarExp(SysYParser::VarExpContext* ctx) override;
  std::any visitAdditiveExp(SysYParser::AdditiveExpContext* ctx) override;

 private:
  enum class BlockFlow {
    Continue,
    Terminated,
  };

  BlockFlow VisitBlockItemResult(SysYParser::BlockItemContext& item);
  ir::Value* EvalExpr(SysYParser::ExpContext& expr);

  ir::Module& module_;
  const SemanticContext& sema_;
  ir::Function* func_;
  ir::IRBuilder builder_;
  // 名称绑定由 Sema 负责；IRGen 只维护“声明 -> 存储槽位”的代码生成状态。
  std::unordered_map<SysYParser::VarDefContext*, ir::Value*> storage_map_;
};

std::unique_ptr<ir::Module> GenerateIR(SysYParser::CompUnitContext& tree,
                                       const SemanticContext& sema);
