#include "irgen/IRGen.h"

#include <memory>

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

static void PredeclareLibraryFunctions(ir::Module& module) {
  module.CreateFunction("getint", ir::Type::GetInt32Type(), {});
  module.CreateFunction("getch", ir::Type::GetInt32Type(), {});
  module.CreateFunction("getfloat", ir::Type::GetFloatType(), {});
  module.CreateFunction("getarray", ir::Type::GetInt32Type(), {ir::Type::GetPtrInt32Type()});
  module.CreateFunction("getfarray", ir::Type::GetInt32Type(), {ir::Type::GetPtrFloatType()});
  module.CreateFunction("putint", ir::Type::GetVoidType(), {ir::Type::GetInt32Type()});
  module.CreateFunction("putch", ir::Type::GetVoidType(), {ir::Type::GetInt32Type()});
  module.CreateFunction("putfloat", ir::Type::GetVoidType(), {ir::Type::GetFloatType()});
  module.CreateFunction("putarray", ir::Type::GetVoidType(), {ir::Type::GetInt32Type(), ir::Type::GetPtrInt32Type()});
  module.CreateFunction("putfarray", ir::Type::GetVoidType(), {ir::Type::GetInt32Type(), ir::Type::GetPtrFloatType()});
  module.CreateFunction("starttime", ir::Type::GetVoidType(), {});
  module.CreateFunction("stoptime", ir::Type::GetVoidType(), {});
  // putf is special, but for now we might not support it fully or just declare it simply
  // module.CreateFunction("putf", ...);
}

std::unique_ptr<ir::Module> GenerateIR(SysYParser::CompUnitContext& tree,
                                       const SemanticContext& sema) {
  auto module = std::make_unique<ir::Module>();
  PredeclareLibraryFunctions(*module);
  IRGenImpl gen(*module, sema);
  tree.accept(&gen);
  return module;
}
