diff --git a/src/main.cpp b/src/main.cpp index cc0d5e3..78d0d72 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,11 +7,16 @@ #include "irgen/IRGen.h" #include "sem/Sema.h" #include "utils/CLI.h" +#include "utils/Log.h" #include "ast/AstNodes.h" int main(int argc, char** argv) { try { auto opts = ParseCLI(argc, argv); + if (opts.show_help) { + PrintHelp(std::cout); + return 0; + } auto antlr = ParseFileWithAntlr(opts.input); auto ast = BuildAst(antlr.tree); ast::PrintAST(*ast); // 调试 AST diff --git a/src/utils/CLI.cpp b/src/utils/CLI.cpp index d9882db..f8120bc 100644 --- a/src/utils/CLI.cpp +++ b/src/utils/CLI.cpp @@ -5,13 +5,38 @@ #include "utils/CLI.h" +#include +#include #include CLIOptions ParseCLI(int argc, char** argv) { + CLIOptions opt; + if (argc <= 1) { - throw std::runtime_error("用法: compiler "); + throw std::runtime_error("用法: compiler [--help] "); + } + + for (int i = 1; i < argc; ++i) { + const char* arg = argv[i]; + if (std::strcmp(arg, "-h") == 0 || std::strcmp(arg, "--help") == 0) { + opt.show_help = true; + return opt; + } + + if (arg[0] == '-') { + throw std::runtime_error(std::string("未知参数: ") + arg + + "(使用 --help 查看用法)"); + } + + if (!opt.input.empty()) { + throw std::runtime_error( + "参数过多:当前只支持 1 个输入文件(使用 --help 查看用法)"); + } + opt.input = arg; + } + + if (opt.input.empty()) { + throw std::runtime_error("缺少输入文件:请提供 (使用 --help 查看用法)"); } - CLIOptions opt; - opt.input = argv[1]; return opt; } diff --git a/src/utils/CLI.h b/src/utils/CLI.h index f69c583..618b9e1 100644 --- a/src/utils/CLI.h +++ b/src/utils/CLI.h @@ -5,6 +5,7 @@ struct CLIOptions { std::string input; + bool show_help = false; }; CLIOptions ParseCLI(int argc, char** argv); diff --git a/src/utils/Log.cpp b/src/utils/Log.cpp index af90bdc..e1702a3 100644 --- a/src/utils/Log.cpp +++ b/src/utils/Log.cpp @@ -3,3 +3,19 @@ // - 提供可配置的日志级别与输出位置(按需要实现) #include "utils/Log.h" + +#include + +void PrintHelp(std::ostream& os) { + os << "SysY Compiler (课程实验最小可运行示例)\n" + << "\n" + << "用法:\n" + << " compiler [--help] \n" + << "\n" + << "选项:\n" + << " -h, --help 打印帮助信息并退出\n" + << "\n" + << "说明:\n" + << " - 当前默认将 IR 输出到标准输出,可使用重定向写入文件:\n" + << " compiler test/test_case/simple_add.sy > out.ll\n"; +} diff --git a/src/utils/Log.h b/src/utils/Log.h index 09d31a7..ac15b2c 100644 --- a/src/utils/Log.h +++ b/src/utils/Log.h @@ -1,7 +1,11 @@ // 轻量日志接口。 #pragma once +#include #include #define LOG_INFO(msg) std::cerr << "[info] " << msg << "\n" #define LOG_ERROR(msg) std::cerr << "[error] " << msg << "\n" + +// 打印命令行帮助信息(用于 `compiler --help`)。 +void PrintHelp(std::ostream& os);