#include <exception>
#include <iostream>
#include <string>

#include "frontend/AntlrDriver.h"
#include "sem/Sema.h"
#include "utils/Log.h"

int main(int argc, char** argv) {
  if (argc < 2) {
    std::cerr << "usage: sema_check <input.sy> [more.sy...]\n";
    return 2;
  }

  bool failed = false;
  for (int i = 1; i < argc; ++i) {
    const std::string path = argv[i];
    try {
      auto antlr = ParseFileWithAntlr(path);
      auto* comp_unit = dynamic_cast<SysYParser::CompUnitContext*>(antlr.tree);
      if (!comp_unit) {
        throw std::runtime_error(FormatError("sema_check", "语法树根节点不是 compUnit"));
      }
      (void)RunSema(*comp_unit);
      std::cout << "OK " << path << "\n";
    } catch (const std::exception& ex) {
      failed = true;
      std::cout << "ERR " << path << "\n";
      PrintException(std::cout, ex);
    }
  }

  return failed ? 1 : 0;
}
