// 格式化错误并统一打印异常与帮助信息。 #include "utils/Log.h" #include #include namespace { bool IsCLIError(const std::string_view msg) { return HasErrorPrefix(msg, "cli"); } } // namespace void LogInfo(const std::string_view msg, std::ostream& os) { os << "[info] " << msg << "\n"; } void LogError(const std::string_view msg, std::ostream& os) { os << "[error] " << msg << "\n"; } std::string FormatError(const std::string_view stage, const std::string_view msg) { return "[" + std::string(stage) + "] " + std::string(msg); } std::string FormatErrorAt(const std::string_view stage, const std::size_t line, const std::size_t column, const std::string_view msg) { return "[" + std::string(stage) + "] @" + std::to_string(line) + ":" + std::to_string(column) + " - " + std::string(msg); } bool HasErrorPrefix(const std::string_view msg, const std::string_view stage) { const std::string prefix = "[" + std::string(stage) + "]"; return msg.rfind(prefix, 0) == 0; } void PrintException(std::ostream& os, const std::exception& ex) { LogError(ex.what(), os); if (IsCLIError(ex.what())) { os << "\n"; PrintHelp(os); } } void PrintHelp(std::ostream& os) { os << "SysY Compiler\n" << "\n" << "用法:\n" << " compiler -IR -o [-O1] # 输出 IR\n" << " compiler -S -o [-O1] # 输出汇编\n" << "\n" << "选项:\n" << " -IR 输出中间代码(IR 文本)\n" << " -S 输出 AArch64 汇编码\n" << " -o 输出文件(默认 stdout)\n" << " -O1 启用 IR 优化(Mem2Reg + 标量优化)\n" << " -h, --help 打印帮助信息并退出\n" << "\n" << "兼容格式(仍可使用):\n" << " --emit-ir 同 -IR\n" << " --emit-asm 同 -S\n" << "\n" << "示例:\n" << " compiler test.sy -IR -o test.ll -O1 # 生成优化 IR\n" << " compiler test.sy -S -o test.s -O1 # 生成优化汇编\n" << " compiler test.sy -IR # IR 输出到 stdout\n"; }