#include #include #include #include #include "frontend/AntlrDriver.h" #include "frontend/SyntaxTreePrinter.h" #if !COMPILER_PARSE_ONLY #include "ir/IR.h" #include "irgen/IRGen.h" #include "mir/MIR.h" #include "sem/Sema.h" #endif #include "utils/CLI.h" #include "utils/Log.h" int main(int argc, char** argv) { try { auto opts = ParseCLI(argc, argv); if (opts.show_help) { PrintHelp(std::cout); return 0; } // 确定输出流 std::ofstream ofs; std::ostream* out = &std::cout; if (!opts.output.empty()) { ofs.open(opts.output); if (!ofs) { throw std::runtime_error( FormatError("main", "无法打开输出文件: " + opts.output)); } out = &ofs; } auto antlr = ParseFileWithAntlr(opts.input); #if !COMPILER_PARSE_ONLY auto* comp_unit = dynamic_cast(antlr.tree); if (!comp_unit) { throw std::runtime_error(FormatError("main", "语法树根节点不是 compUnit")); } auto sema = RunSema(*comp_unit); auto module = GenerateIR(*comp_unit, sema); if (opts.opt) { ir::RunPasses(*module); } if (opts.emit_ir) { ir::IRPrinter printer; printer.Print(*module, *out); } if (opts.emit_asm) { auto machine_funcs = mir::LowerToMIR(*module); for (auto& mf : machine_funcs) { mir::RunRegAlloc(*mf); mir::RunFrameLowering(*mf); } mir::PrintAsm(machine_funcs, *out); } #else if (opts.emit_ir || opts.emit_asm) { throw std::runtime_error( FormatError("main", "当前为 parse-only 构建;IR/汇编输出已禁用")); } #endif } catch (const std::exception& ex) { PrintException(std::cerr, ex); return 1; } return 0; }