From d2455836a45595905fa3d1ea460e08daff98b44a Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 4 Dec 2026 21:41:38 +0900 Subject: [PATCH 1/2] 0.2.0: usage errors carry a code, the command reached and similar names; the agent skills are checked against the tree - ParseError gains code, command and suggestions. A command with subcommands that declares no argument refuses an unknown word as unknown-command; an unknown long option names its closest declared options. The names come from the list help prints, and similar_names is exported for a program's own names. - run prints the reason, the closest name and the --help of the command the words reached. - App::parse_silent parses as parse_from does and writes nothing. - agent_skills::check reports a visible top-level command without a sheet, a sheet that names no command and an example in a fenced block that does not parse; install_default and install_runtime share one implementation of the lookup and the index. --- README.md | 7 + README.zh.md | 2 +- docs/api.md | 28 +- .../skills-fixture-hello/SKILL.md | 5 + .../skills-fixture-self/SKILL.md | 6 + fixtures/skills/src/main.cpp | 17 ++ mcpp.toml | 2 +- src/agent_skills.cppm | 245 ++++++++++++------ src/cmdline.cppm | 170 ++++++++++-- src/parse.cppm | 10 + tests/cmdline_test.cpp | 108 ++++++++ 11 files changed, 487 insertions(+), 113 deletions(-) create mode 100644 fixtures/skills/docs/skills-fixture-skills/skills-fixture-self/SKILL.md diff --git a/README.md b/README.md index e7f6ab8..58999b6 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,13 @@ export void install(mcpplibs::cmdline::App& app) { The fallback for development, never the default: `install_runtime(app, {.root = "docs/myapp-skills", ...})` reads the same layout from disk at install time. +A test keeps the sheets and the binary in agreement (0.2.0): `agent_skills::check(app, myapp::skills::sheets, +{.ascii_only = true})` returns one line per disagreement — a visible top-level command without a sheet, a sheet +that names no command, an example in a fenced block that does not parse by the tree. + +Usage errors carry a stable `code`, the `command` the words reached and the closest declared names +(`suggestions`); `run` prints the reason, the closest name and that command's `--help` (0.2.0). + ## Documentation - [`docs/api.md`](docs/api.md) — the API, option by option. diff --git a/README.zh.md b/README.zh.md index 9af93e8..8b93f5c 100644 --- a/README.zh.md +++ b/README.zh.md @@ -15,7 +15,7 @@ - **help 就是列表** — `.group()` 标题、`.help_options({.order, .ungrouped, .groups_as_sections})`、`.help_epilogue()`;help、补全候选和“缺子命令”的报错一致。 - **Shell 补全** — `app.completion()`;程序用自己的命令树回答 `__complete`,bash/zsh/fish/PowerShell 适配脚本不含命令表。 - **动作前应答的 flag** — `answer_flag(name, help, fn)`;`parse` → `answer_flags(parsed)` → action。`--help` 仍优先。 -- **Agent Skills(可选)** — `agent-skills` feature + `import mcpplibs.cmdline.agent_skills;`。默认构建期:`mcpplibs.mplugin.cmdline` 把 `docs/-skills` 渲染成 C++ module(`.skills`),`sheet[]` 表在二进制里;不生成头文件,开发者只 import module。运行时读取(`install_runtime`)保留,但不推荐用于发布。 +- **Agent Skills(可选)** — `agent-skills` feature + `import mcpplibs.cmdline.agent_skills;`。默认构建期:`mcpplibs.mplugin.cmdline` 把 `docs/-skills` 渲染成 C++ module(`.skills`),`sheet[]` 表在二进制里;不生成头文件,开发者只 import module。运行时读取(`install_runtime`)保留,但不推荐用于发布。`agent_skills::check(app, sheets)` 在测试中核对说明与命令树:每个可见的顶层命令都有说明,每份说明都对应一个命令,代码块中的每个例子都能按命令树解析(自 0.2.0)。 - **构建 helper** — `mcpp/cmdline/` 是独立构建包(`mcpplibs.mplugin.cmdline`),由 runtime 包 re-export;消费者的 `build.mcpp` 直接 import,不需要第二条依赖。它写 module 并用 `mcpp::source` 加入构建,不碰 include 路径。 - **C++ Modules** — 库与可选模块都是 module,没有头文件。 diff --git a/docs/api.md b/docs/api.md index ac64a83..58e84d3 100644 --- a/docs/api.md +++ b/docs/api.md @@ -9,7 +9,7 @@ | `Option` | 选项(短/长、带值、多值、全局) | | `ParsedArgs` | 解析结果 | | `OptionValue` | 单个选项取值(flag 计数 + values) | -| `ParseError` | 解析错误(kind + message) | +| `ParseError` | 解析错误(kind + message;自 0.2.0 另有 code、command、suggestions) | | `Argv` | `std::vector` 的别名,用于 `parse_from` | | `Shell` | 目标 shell 枚举:`bash` / `fish` / `zsh` / `powershell` | | `Command` | 命令树快照,补全引擎读取它 | @@ -30,6 +30,7 @@ | `.subcommand(App)` `.subcommand("name")` | 添加子命令 | | `.action(fn)` | 根/子命令执行函数:`int(const ParsedArgs&)`(返回值即退出码)或 `void(const ParsedArgs&)`(退出码 0) | | `.parse(argc, argv)` `.parse_from(Argv)` `.parse_from(string_view)` | 解析,返回 `ParseResult` | +| `.parse_silent(Argv)` `.parse_silent(string_view)` | 与 `parse_from` 相同的解析,不写出任何内容:help、版本与补全以各自的 `kind` 返回而不打印(自 0.2.0) | | `.run(parsed)` | 执行解析结果所命中的命令的 action,返回其退出码(规则见“分发规则”) | | `.run(argc, argv)` `.run(Argv)` | parse + dispatch,返回退出码(推荐主入口):help/version 为 0,解析错误写入标准错误并返回 2 | | `.print_help(program_name)` | 打印帮助(子命令的列表见“帮助的列表”) | @@ -89,14 +90,35 @@ |------|------| | `kind` | 枚举:`help` / `version` / `completion` / `error` | | `message` | 错误文本(仅 `kind == error` 时有内容) | +| `code` | 稳定的代码(自 0.2.0):`unknown-command`、`unknown-option`、`missing-value`、`invalid-value`、`missing-argument`、`invalid-argument`、`empty-command-line`;help、版本与补全时为空 | +| `command` | 词所到达的命令,按输入写出(`app sub`);它的 `--help` 适用于这个错误(自 0.2.0) | +| `suggestions` | 与未知的名字最相近的已声明名字,最近者在前,至多三个;取自 help 所列的同一份列表,选项带短横线(自 0.2.0) | | `.is_error()` | `kind == error` 时返回 `true` | +### 用法错误(自 0.2.0) + +- **未知的命令。** 一个有子命令而不声明任何位置参数的命令,收到一个既不是子命令也不是选项的词时,解析返回 + `unknown-command`。0.1.0 及以前,这个词成为一个没有动作读取的位置参数。声明了位置参数的命令不变。隐藏的命令 + 照常解析,但不出现在 `suggestions` 中。 +- **相近的名字。** 未知的命令取该级 help 所列的命令;未知的长选项取该命令的选项与根的全局选项,再加 `--help`。 + 判据是编辑距离不超过词长的三分之一(至少为 1;相邻两个字符的互换算一次编辑),或以该词开头。同一函数以 + `similar_names(word, candidates, limit = 3)` 导出,供程序用于自己的名字(例如错误代码)。 +- **`run` 的输出。** 解析错误写到标准错误,退出码 2,依次为原因、最相近的名字(有时)与所到达的那一级命令的 + help: + +``` +tool: unknown option: --jbos +tool: the most similar option is '--jobs' +tool: see 'tool build --help' +``` + ```cpp auto result = app.parse(argc, argv); if (!result) { if (!result.error().is_error()) return 0; // help / version,已打印 - std::println("Error: {}", result.error().message); - return 1; + std::println(std::cerr, "error: {} ({})", result.error().message, result.error().code); + for (const auto& name : result.error().suggestions) std::println(std::cerr, " similar: {}", name); + return 2; } ``` diff --git a/fixtures/skills/docs/skills-fixture-skills/skills-fixture-hello/SKILL.md b/fixtures/skills/docs/skills-fixture-skills/skills-fixture-hello/SKILL.md index 5af9e2b..073af10 100644 --- a/fixtures/skills/docs/skills-fixture-skills/skills-fixture-hello/SKILL.md +++ b/fixtures/skills/docs/skills-fixture-skills/skills-fixture-hello/SKILL.md @@ -4,3 +4,8 @@ description: Say hello. --- Say hello, then stop. + +``` +$ skills-fixture hello +skills-fixture hello --agent-skill-doc | head -1 +``` diff --git a/fixtures/skills/docs/skills-fixture-skills/skills-fixture-self/SKILL.md b/fixtures/skills/docs/skills-fixture-skills/skills-fixture-self/SKILL.md new file mode 100644 index 0000000..1f44d5c --- /dev/null +++ b/fixtures/skills/docs/skills-fixture-skills/skills-fixture-self/SKILL.md @@ -0,0 +1,6 @@ +--- +name: skills-fixture-self +description: The commands about the fixture itself. +--- + +The commands under self are listed below. diff --git a/fixtures/skills/src/main.cpp b/fixtures/skills/src/main.cpp index 915c7e4..41f73f6 100644 --- a/fixtures/skills/src/main.cpp +++ b/fixtures/skills/src/main.cpp @@ -16,5 +16,22 @@ int main() { if (app.run(Argv{"skills-fixture", "hello", "--agent-skill-doc"}) != 0) return 1; if (app.run(Argv{"skills-fixture", "self", "world", "--agent-skill-doc"}) != 0) return 2; if (app.run(Argv{"skills-fixture", "--agent-skill-doc"}) != 0) return 3; + + // The sheets agree with the tree; a sheet that does not is reported. + if (const auto problems = agent_skills::check(app, fixture::skills::sheets, {.ascii_only = true}); + !problems.empty()) { + for (const auto& line : problems) std::println(std::cerr, "{}", line); + return 4; + } + static constexpr unsigned char drifted[] = + "---\nname: x\n---\n\n```\nskills-fixture hello --loud\nskills-fixture helo\n```\n"; + static constexpr unsigned char plain[] = "---\nname: y\n---\n\nNo example.\n"; + const fixture::skills::sheet wrong[] = {{"hello", drifted, sizeof drifted - 1}, {"gone", plain, sizeof plain - 1}}; + const auto problems = agent_skills::check(app, wrong); + // --loud is unknown, helo is no command, 'gone' names no command, 'self' has no sheet. + if (problems.size() != 4) { + for (const auto& line : problems) std::println(std::cerr, "{}", line); + return 5; + } return 0; } diff --git a/mcpp.toml b/mcpp.toml index a1c7f5c..c7c6c31 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,7 +1,7 @@ [package] namespace = "mcpplibs" name = "cmdline" -version = "0.1.0" +version = "0.2.0" description = "A simple command-line parsing library/framework for modern C++" license = "Apache-2.0" authors = ["mcpplibs"] diff --git a/src/agent_skills.cppm b/src/agent_skills.cppm index 71bd8fe..1de0433 100644 --- a/src/agent_skills.cppm +++ b/src/agent_skills.cppm @@ -128,17 +128,20 @@ inline std::map> scan(const options& o, st } // namespace detail -/// Register the flag on `app`; `find` decides what each path answers. +/// Register the flag on `app`; `find` decides what each path answers. When +/// `o.root` is set, a path with no skill names where it was looked for. inline void install(App& app, options o = {}) { auto find = std::move(o.find); auto index = std::move(o.index); app.answer_flag(o.flag, o.help, - [find = std::move(find), index = std::move(index), name = std::string(app.name())]( + [find = std::move(find), index = std::move(index), name = std::string(app.name()), + where = std::move(o.root)]( std::string_view path, const ParsedArgs&) -> std::optional { const std::string_view key = path.empty() ? std::string_view("root") : path; const auto body = find ? find(key) : std::nullopt; if (!body) { - std::println(std::cerr, "{}: no skill for '{}'", name, key); + if (where.empty()) std::println(std::cerr, "{}: no skill for '{}'", name, key); + else std::println(std::cerr, "{}: no skill for '{}' (looked under {})", name, key, where); return 2; } std::print("{}", *body); @@ -150,31 +153,27 @@ inline void install(App& app, options o = {}) { }); } -/// The RECOMMENDED default: the sheets were rendered at build time into a -/// module by `mcpplibs.mplugin.cmdline`, and this reads its `sheet[]` table -/// (rows of key/data/size) once, at install. No filesystem, no build work at -/// run time. `root`/`agents_file`/`fallback_agents` are ignored here; the -/// generated table already applied them. -template -void install_default(App& app, const Sheet (&sheets)[N], options o = {}) { - std::map> index_of; - for (const auto& row : sheets) index_of.emplace(row.key, std::string_view(reinterpret_cast(row.data), row.size)); - const auto lookup = [index_of](std::string_view key) -> std::optional { - if (const auto it = index_of.find(key); it != index_of.end()) return it->second; - return std::nullopt; - }; - auto find = [lookup](std::string_view path) -> std::optional { +namespace detail { + +using Lookup = std::function(std::string_view)>; + +/// What both installers answer with, over one lookup of key -> skill text: +/// `find` takes the nearest ancestor that has a skill and drops the +/// frontmatter; `index` lists the root's (or `self`'s) commands from their +/// frontmatter. `keys` are every key the lookup knows, in order. +inline void answers(options& o, Lookup lookup, std::vector keys, std::string name) { + o.find = [lookup](std::string_view path) -> std::optional { if (path.empty()) path = "root"; - if (auto skill = lookup(path)) return detail::body(*skill); + if (auto skill = lookup(path)) return body(*skill); while (true) { const auto dot = path.rfind('.'); if (dot == std::string_view::npos) return std::nullopt; path = path.substr(0, dot); - if (auto skill = lookup(path)) return detail::body(*skill); + if (auto skill = lookup(path)) return body(*skill); } }; - auto index = [index_of, lookup, root_commands = std::move(o.root_commands), - self_commands = std::move(o.self_commands), name = std::string(app.name())](std::string_view path) -> std::string { + o.index = [lookup, keys = std::move(keys), root_commands = std::move(o.root_commands), + self_commands = std::move(o.self_commands), name = std::move(name)](std::string_view path) -> std::string { if (path.empty()) path = "root"; const bool root = path == "root"; if (!root && path != "self") return {}; @@ -183,8 +182,8 @@ void install_default(App& app, const Sheet (&sheets)[N], options o = {}) { const auto append = [&](std::string_view command) { const auto skill = lookup(command); if (!skill) return; - const auto skill_name = detail::frontmatter_field(*skill, "name"); - const auto description = detail::frontmatter_field(*skill, "description"); + const auto skill_name = frontmatter_field(*skill, "name"); + const auto description = frontmatter_field(*skill, "description"); if (skill_name.empty()) return; text += "| `" + prefix + std::string(command) + " --agent-skill-doc` | " + std::string(skill_name) + " | " + std::string(description) + " |\n"; @@ -193,7 +192,7 @@ void install_default(App& app, const Sheet (&sheets)[N], options o = {}) { if (!root_commands.empty()) { for (const auto& command : root_commands) append(command); } else { - for (const auto& [key, _] : index_of) + for (const auto& key : keys) if (key != "root" && key.find('.') == std::string::npos) append(key); } } else { @@ -203,7 +202,33 @@ void install_default(App& app, const Sheet (&sheets)[N], options o = {}) { return "\n## " + std::string(root ? "The skills in this binary" : "The skills under `" + name + " self`") + "\n\n| command | skill | use it when |\n|---|---|---|\n" + text; }; - install(app, options{.flag = o.flag, .help = o.help, .find = std::move(find), .index = std::move(index)}); +} + +template +std::map> table(const Sheet (&sheets)[N]) { + std::map> out; + for (const auto& row : sheets) + out.emplace(row.key, std::string_view(reinterpret_cast(row.data), row.size)); + return out; +} + +} // namespace detail + +/// The RECOMMENDED default: the sheets were rendered at build time into a +/// module by `mcpplibs.mplugin.cmdline`, and this reads its `sheet[]` table +/// (rows of key/data/size) once, at install. No filesystem, no build work at +/// run time. `root`/`agents_file`/`fallback_agents` are ignored here; the +/// generated table already applied them. +template +void install_default(App& app, const Sheet (&sheets)[N], options o = {}) { + auto index_of = std::make_shared>>(detail::table(sheets)); + std::vector keys; + for (const auto& [key, _] : *index_of) keys.push_back(key); + detail::answers(o, [index_of](std::string_view key) -> std::optional { + if (const auto it = index_of->find(key); it != index_of->end()) return it->second; + return std::nullopt; + }, std::move(keys), std::string(app.name())); + install(app, options{.flag = o.flag, .help = o.help, .find = std::move(o.find), .index = std::move(o.index)}); } /// The OPTIONAL runtime fallback: read the standard layout from disk at this @@ -211,67 +236,121 @@ void install_default(App& app, const Sheet (&sheets)[N], options o = {}) { /// not recommended for a release: the binary and its skills can then disagree. inline void install_runtime(App& app, options o = {}) { const std::string app_name = o.app.empty() ? std::string(app.name()) : o.app; - auto sheets = std::make_shared>>(detail::scan(o, app_name)); - const auto lookup = [sheets](std::string_view key) -> std::optional { - const auto it = sheets->find(key); - if (it == sheets->end()) return std::nullopt; - return std::string_view(it->second); - }; - auto find = [lookup](std::string_view path) -> std::optional { - if (path.empty()) path = "root"; - if (auto skill = lookup(path)) return detail::body(*skill); - while (true) { - const auto dot = path.rfind('.'); - if (dot == std::string_view::npos) return std::nullopt; - path = path.substr(0, dot); - if (auto skill = lookup(path)) return detail::body(*skill); + auto sheets = std::make_shared>>(detail::scan(o, app_name)); + std::vector keys; + for (const auto& [key, _] : *sheets) keys.push_back(key); + detail::answers(o, [sheets](std::string_view key) -> std::optional { + if (const auto it = sheets->find(key); it != sheets->end()) return std::string_view(it->second); + return std::nullopt; + }, std::move(keys), app_name); + const std::string where = o.root.empty() ? "docs/" + app_name + "-skills" : o.root; + install(app, options{.flag = o.flag, .help = o.help, .root = where, + .find = std::move(o.find), .index = std::move(o.index)}); +} + +/// What `check` compares; the defaults are the standard layout's. +struct check_options { + /// Top-level commands that need no sheet of their own. + std::vector exempt; + /// Refuse a byte outside printable ASCII (tabs and newlines aside): a sheet + /// printed to any console code page reads the same. + bool ascii_only = false; + /// 0: no limit. The build helper enforces its own limit when it renders. + std::size_t max_lines = 0; +}; + +namespace detail { + +inline std::vector lines_of(std::string_view text) { + std::vector out; + for (std::size_t i = 0; i <= text.size();) { + const auto eol = text.find('\n', i); + if (eol == std::string_view::npos) { + if (i < text.size()) out.push_back(text.substr(i)); + break; } - }; - auto index = [sheets, lookup, root_commands = std::move(o.root_commands), - self_commands = std::move(o.self_commands), name = app_name](std::string_view path) -> std::string { - if (path.empty()) path = "root"; - const bool root = path == "root"; - if (!root && path != "self") return {}; - std::string text; - const std::string prefix = root ? name + " " : name + " self "; - const auto append = [&](std::string_view command) { - const auto skill = lookup(command); - if (!skill) return; - const auto skill_name = detail::frontmatter_field(*skill, "name"); - const auto description = detail::frontmatter_field(*skill, "description"); - if (skill_name.empty()) return; - text += "| `" + prefix + std::string(command) + " --agent-skill-doc` | " - + std::string(skill_name) + " | " + std::string(description) + " |\n"; - }; - if (root) { - if (!root_commands.empty()) { - for (const auto& command : root_commands) append(command); - } else { - for (const auto& [key, _] : *sheets) - if (key != "root" && key.find('.') == std::string::npos) append(key); + out.push_back(text.substr(i, eol - i)); + i = eol + 1; + } + return out; +} + +// The command an example line runs: the line without its prompt, and without +// what the shell does after the program (a pipe, a redirection, a comment, a +// second command). Empty when the line does not run `app`. +inline std::string example_of(std::string_view line, std::string_view app) { + auto text = line.substr(std::min(line.find_first_not_of(' '), line.size())); + if (text.starts_with("$ ")) text.remove_prefix(2); + if (!text.starts_with(app) || text.size() <= app.size() || text[app.size()] != ' ') return {}; + for (const std::string_view stop : {" | ", " && ", " || ", " ; ", " > ", " >> ", " 2>", " # "}) + if (const auto at = text.find(stop); at != std::string_view::npos) text = text.substr(0, at); + while (!text.empty() && (text.back() == ' ' || text.back() == '\\')) text.remove_suffix(1); + return std::string(text); +} + +// The visible command at a dotted key (`build`, `self.config`), or nullptr. +inline const completions::Command* command_at(const completions::Command& root, std::string_view key) { + const completions::Command* at = &root; + while (!key.empty()) { + const auto dot = key.find('.'); + const auto part = key.substr(0, dot); + const auto it = std::ranges::find(at->subcommands, part, &completions::Command::name); + if (it == at->subcommands.end()) return nullptr; + at = &*it; + key = dot == std::string_view::npos ? std::string_view{} : key.substr(dot + 1); + } + return at; +} + +} // namespace detail + +/// The sheets and the command tree agree: every visible top-level command has +/// a sheet (`exempt` aside), every sheet names a visible command, and every +/// example in a fenced block that runs `app` parses (silently) by the tree. +/// Returns one line per disagreement, `sheet '', line : ...`; empty +/// when they agree. A program calls it from a test, with the table its build +/// rendered, so its documentation cannot drift from its binary. +template +std::vector check(const App& app, const Sheet (&sheets)[N], check_options o = {}) { + std::vector problems; + const auto tree = snapshot(app); + const auto by_key = detail::table(sheets); + const std::string name(app.name()); + for (const auto& command : tree.subcommands) { + if (std::ranges::find(o.exempt, command.name) != o.exempt.end()) continue; + if (!by_key.contains(command.name)) + problems.push_back(std::format("command '{} {}' has no sheet (docs/{}-skills/{}-{}/SKILL.md)", + name, command.name, name, name, command.name)); + } + for (const auto& [key, text] : by_key) { + if (key != "root" && !detail::command_at(tree, key)) + problems.push_back(std::format("sheet '{}' names no visible command of '{}'", key, name)); + const auto lines = detail::lines_of(text); + if (o.max_lines && lines.size() > o.max_lines) + problems.push_back(std::format("sheet '{}' has {} lines; the limit is {}", key, lines.size(), o.max_lines)); + bool fenced = false; + for (std::size_t n = 0; n < lines.size(); ++n) { + const auto line = lines[n]; + if (o.ascii_only) + for (const unsigned char c : line) + if ((c < 0x20 && c != '\t') || c > 0x7e) { + problems.push_back(std::format("sheet '{}', line {}: a byte outside printable ASCII", key, n + 1)); + break; + } + if (line.find_first_not_of(' ') != std::string_view::npos + && line.substr(line.find_first_not_of(' ')).starts_with("```")) { + fenced = !fenced; + continue; } - } else { - for (const auto& command : self_commands) append(command); + if (!fenced) continue; + const auto example = detail::example_of(line, name); + if (example.empty()) continue; + const auto parsed = app.parse_silent(std::string_view(example)); + if (!parsed && parsed.error().is_error()) + problems.push_back(std::format("sheet '{}', line {}: `{}`: {}", key, n + 1, example, parsed.error().message)); } - if (text.empty()) return {}; - return "\n## " + std::string(root ? "The skills in this binary" : "The skills under `" + name + " self`") - + "\n\n| command | skill | use it when |\n|---|---|---|\n" + text; - }; - app.answer_flag(o.flag, o.help, - [find = std::move(find), index = std::move(index), name = app_name]( - std::string_view path, const ParsedArgs&) -> std::optional { - const std::string_view key = path.empty() ? std::string_view("root") : path; - const auto body = find(key); - if (!body) { - std::println(std::cerr, "{}: no skill for '{}' (looked under {})", name, key, - "docs/" + name + "-skills"); - return 2; - } - std::print("{}", *body); - const auto extra = index(key); - if (!extra.empty()) std::print("{}", extra); - return 0; - }); + } + return problems; } } // namespace mcpplibs::cmdline::agent_skills diff --git a/src/cmdline.cppm b/src/cmdline.cppm index 377ecf5..4ff97c7 100644 --- a/src/cmdline.cppm +++ b/src/cmdline.cppm @@ -69,6 +69,66 @@ export using detail::ParsedArgs; /// readers, and the first that answers wins. export using FlagAnswer = std::function(std::string_view, const ParsedArgs&)>; +namespace detail { + +// True while `App::parse_silent` runs: the parse answers help, the version and +// a completion by their kinds and writes nothing. +inline thread_local bool silent_parse = false; + +struct SilentParse { + bool previous = silent_parse; + SilentParse() { silent_parse = true; } + ~SilentParse() { silent_parse = previous; } + SilentParse(const SilentParse&) = delete; + SilentParse& operator=(const SilentParse&) = delete; +}; + +inline char folded(char c) { + return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; +} + +// Optimal string alignment distance, ASCII case folded: a swap of two +// neighbours is one edit, which is what a typed `--jbos` is. +inline std::size_t edit_distance(std::string_view a, std::string_view b) { + std::vector> d(a.size() + 1, std::vector(b.size() + 1)); + for (std::size_t i = 0; i <= a.size(); ++i) d[i][0] = i; + for (std::size_t j = 0; j <= b.size(); ++j) d[0][j] = j; + for (std::size_t i = 1; i <= a.size(); ++i) { + for (std::size_t j = 1; j <= b.size(); ++j) { + const std::size_t cost = folded(a[i - 1]) == folded(b[j - 1]) ? 0 : 1; + d[i][j] = std::min({d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost}); + if (i > 1 && j > 1 && folded(a[i - 1]) == folded(b[j - 2]) && folded(a[i - 2]) == folded(b[j - 1])) + d[i][j] = std::min(d[i][j], d[i - 2][j - 2] + 1); + } + } + return d[a.size()][b.size()]; +} + +} // namespace detail + +/// The names of `candidates` closest to `word`, closest first and at most +/// `limit`: those within an edit distance of a third of the word's length (at +/// least one), and those that begin with it. Equal distances keep the order of +/// `candidates`, so a help's order passed in is the order handed out. +export [[nodiscard]] inline std::vector similar_names( + std::string_view word, std::span candidates, std::size_t limit = 3) { + std::vector> scored; + const std::size_t reach = std::max(1, word.size() / 3); + for (const auto candidate : candidates) { + if (candidate.empty() || candidate == word) continue; + const std::size_t distance = detail::edit_distance(word, candidate); + const bool prefix = word.size() >= 2 && candidate.starts_with(word); + if (distance <= reach || prefix) scored.emplace_back(prefix ? 0 : distance, candidate); + } + std::ranges::stable_sort(scored, {}, &std::pair::first); + std::vector out; + for (const auto& [_, name] : scored) { + if (out.size() == limit) break; + if (std::ranges::find(out, name) == out.end()) out.emplace_back(name); + } + return out; +} + export class App { template friend class AppItemBuilder; friend class SubcommandBuilder; @@ -217,7 +277,8 @@ public: return parse_tokens(tokens); } [[nodiscard]] ParseResult parse_from(std::span args) const { - if (args.empty()) return std::unexpected(ParseError{.message = "no program name"}); + if (args.empty()) + return std::unexpected(ParseError{.message = "no program name", .code = "empty-command-line", .command = name_}); std::vector tokens; tokens.reserve(args.size() - 1); for (std::size_t i = 1; i < args.size(); ++i) tokens.emplace_back(args[i]); @@ -225,9 +286,22 @@ public: } [[nodiscard]] ParseResult parse_from(std::string_view command_line) const { std::vector tokens = split_command_line(command_line); - if (tokens.empty()) return std::unexpected(ParseError{.message = "empty command line"}); + if (tokens.empty()) + return std::unexpected(ParseError{.message = "empty command line", .code = "empty-command-line", .command = name_}); return parse_from(std::span(tokens)); } + /// Parses as `parse_from` does and writes nothing: help, the version and a + /// completion come back as their kinds, unprinted. What checks the + /// examples a program documents against its tree parses with it + /// (`agent_skills::check`). + [[nodiscard]] ParseResult parse_silent(std::span args) const { + detail::SilentParse quiet; + return parse_from(args); + } + [[nodiscard]] ParseResult parse_silent(std::string_view command_line) const { + detail::SilentParse quiet; + return parse_from(command_line); + } /// Runs the action for a parse of this command and returns its status. /// @@ -338,16 +412,20 @@ private: if (completion_ && !tokens.empty()) { if (tokens[0] == completion_->entry) { std::vector words(tokens.begin() + 1, tokens.end()); - std::print("{}", completions::render(completions::complete(snapshot(*this), words))); + if (!detail::silent_parse) + std::print("{}", completions::render(completions::complete(snapshot(*this), words))); return std::unexpected(ParseError::make_completion()); } if (!completion_->command.empty() && tokens[0] == completion_->command && (tokens.size() < 2 || tokens[1] != "--help")) { const auto shell = tokens.size() > 1 ? shell_from_string(tokens[1]) : std::nullopt; if (!shell) - return std::unexpected(ParseError{.message = std::format( - "{} names a shell: bash, zsh, fish, powershell", completion_->command)}); - std::print("{}", completions::adapter(*shell, name_, completion_->entry)); + return std::unexpected(ParseError{ + .message = std::format("{} names a shell: bash, zsh, fish, powershell", completion_->command), + .code = "invalid-argument", + .command = std::format("{} {}", name_, completion_->command)}); + if (!detail::silent_parse) + std::print("{}", completions::adapter(*shell, name_, completion_->entry)); return std::unexpected(ParseError::make_completion()); } } @@ -361,9 +439,19 @@ private: int finish_run(const ParseResult& result) const { if (!result) { - if (!result.error().is_error()) return 0; - std::println(std::cerr, "{}: {}", name_, result.error().message); - std::println(std::cerr, "{}: see '{} --help'", name_, name_); + const ParseError& error = result.error(); + if (!error.is_error()) return 0; + std::println(std::cerr, "{}: {}", name_, error.message); + if (!error.suggestions.empty()) { + const std::string_view what = error.code == "unknown-option" ? "option" : "command"; + std::string names; + for (const auto& s : error.suggestions) names += (names.empty() ? "'" : ", '") + s + "'"; + if (error.suggestions.size() == 1) + std::println(std::cerr, "{}: the most similar {} is {}", name_, what, names); + else + std::println(std::cerr, "{}: the most similar {}s are {}", name_, what, names); + } + std::println(std::cerr, "{}: see '{} --help'", name_, error.command.empty() ? std::string_view(name_) : std::string_view(error.command)); return 2; } if (auto status = answer_flags(*result)) return *status; @@ -455,6 +543,25 @@ private: std::vector positionals; bool only_positionals = false; + auto fail = [program_name](std::string_view code, std::string message, + std::vector suggestions = {}) -> ParseResult { + return std::unexpected(ParseError{.message = std::move(message), .code = std::string(code), + .command = std::string(program_name), + .suggestions = std::move(suggestions)}); + }; + // An unknown option's neighbours: this command's long options, then the + // root's global ones, in the order its help lists them. + auto similar_options = [&](std::string_view key) { + std::vector spelled; + for (const auto& opt : options_) + if (!opt.long_name.empty()) spelled.push_back("--" + opt.long_name); + for (const auto& opt : root_global_options) + if (!opt.long_name.empty()) spelled.push_back("--" + opt.long_name); + spelled.emplace_back("--help"); + std::vector views(spelled.begin(), spelled.end()); + return similar_names(std::string("--") + std::string(key), views); + }; + auto apply_option = [&](const Option& opt, const std::string& key_str, std::string val, bool is_flag) { if (global_keys.contains(key_str)) { if (is_flag) global_opts[key_str].count++; @@ -485,11 +592,11 @@ private: continue; } if (token == "-h" || token == "--help") { - print_help(program_name); + if (!detail::silent_parse) print_help(program_name); return std::unexpected(ParseError::make_help()); } if (token == "--version" && !version_.empty()) { - std::println("{}", version_); + if (!detail::silent_parse) std::println("{}", version_); return std::unexpected(ParseError::make_version()); } if (!subcommands_.empty() && !token.starts_with('-')) { @@ -501,9 +608,18 @@ private: result.subcommand_matches = std::make_unique(std::move(*sub_result)); result.positionals = std::move(positionals); for (auto& [k, v] : global_opts) result.opts[k] = std::move(v); - return finish_parse(std::move(result)); + return finish_parse(program_name, std::move(result)); } } + // A command that has subcommands and declares no argument has + // nothing else a word can be (0.2.0; before, the word became a + // positional no action read). + if (args_.empty()) { + std::vector names; + for (const auto& c : listed(*this, true)) names.push_back(c.name); + return fail("unknown-command", std::format("unknown command '{}'", token), + similar_names(token, names)); + } } if (token.starts_with("--") && token.size() > 2) { std::string_view rest = token.substr(2); @@ -512,7 +628,7 @@ private: std::string_view value_part = eq_pos != std::string_view::npos ? rest.substr(eq_pos + 1) : std::string_view{}; auto opt = find_option(key, '\0'); if (!opt) opt = find_global_option(key, '\0'); - if (!opt) return std::unexpected(ParseError{.message = std::format("unknown option: --{}", key)}); + if (!opt) return fail("unknown-option", std::format("unknown option: --{}", key), similar_options(key)); const Option& found = opt->get(); std::string key_str = option_key(found); if (found.takes_value_) { @@ -522,11 +638,11 @@ private: else if (i + 1 < tokens.size()) val = std::string(tokens[++i]); else - return std::unexpected(ParseError{.message = std::format("option --{} requires a value", key)}); + return fail("missing-value", std::format("option --{} requires a value", key)); if (found.value_check_ && !found.value_check_(val)) - return std::unexpected(ParseError{.message = std::format("option --{} takes {}, not `{}`", key, found.value_kind_, val)}); + return fail("invalid-value", std::format("option --{} takes {}, not `{}`", key, found.value_kind_, val)); if (!found.admits(val)) - return std::unexpected(ParseError{.message = std::format("option --{} takes one of {}, not `{}`", key, found.values_text(), val)}); + return fail("invalid-value", std::format("option --{} takes one of {}, not `{}`", key, found.values_text(), val)); apply_option(found, key_str, std::move(val), false); } else { apply_option(found, key_str, "", true); @@ -537,16 +653,16 @@ private: char short_char = token[1]; auto opt = find_option("", short_char); if (!opt) opt = find_global_option("", short_char); - if (!opt) return std::unexpected(ParseError{.message = std::format("unknown option: -{}", short_char)}); + if (!opt) return fail("unknown-option", std::format("unknown option: -{}", short_char)); const Option& found = opt->get(); std::string key_str = option_key(found); if (found.takes_value_) { - if (i + 1 >= tokens.size()) return std::unexpected(ParseError{.message = std::format("option -{} requires a value", short_char)}); + if (i + 1 >= tokens.size()) return fail("missing-value", std::format("option -{} requires a value", short_char)); std::string val(tokens[++i]); if (found.value_check_ && !found.value_check_(val)) - return std::unexpected(ParseError{.message = std::format("option -{} takes {}, not `{}`", short_char, found.value_kind_, val)}); + return fail("invalid-value", std::format("option -{} takes {}, not `{}`", short_char, found.value_kind_, val)); if (!found.admits(val)) - return std::unexpected(ParseError{.message = std::format("option -{} takes one of {}, not `{}`", short_char, found.values_text(), val)}); + return fail("invalid-value", std::format("option -{} takes one of {}, not `{}`", short_char, found.values_text(), val)); apply_option(found, key_str, std::move(val), false); } else { apply_option(found, key_str, "", true); @@ -558,21 +674,25 @@ private: result.positionals = std::move(positionals); for (auto& [k, v] : global_opts) result.opts[k] = std::move(v); - return finish_parse(std::move(result)); + return finish_parse(program_name, std::move(result)); } - ParseResult finish_parse(ParsedArgs parsed) const { + ParseResult finish_parse(std::string_view program_name, ParsedArgs parsed) const { + auto fail = [program_name](std::string_view code, std::string message) -> ParseResult { + return std::unexpected(ParseError{.message = std::move(message), .code = std::string(code), + .command = std::string(program_name)}); + }; for (std::size_t idx = 0; idx < parsed.positionals.size(); ++idx) { const Arg* argument = idx < args_.size() ? &args_[idx] : (!args_.empty() && args_.back().repeatable_ ? &args_.back() : nullptr); if (argument && !argument->admits(parsed.positionals[idx])) - return std::unexpected(ParseError{.message = std::format( - "argument '{}' takes one of {}, not `{}`", argument->name, argument->values_text(), parsed.positionals[idx])}); + return fail("invalid-argument", std::format( + "argument '{}' takes one of {}, not `{}`", argument->name, argument->values_text(), parsed.positionals[idx])); } for (std::size_t idx = 0; idx < args_.size(); ++idx) { const auto& argument = args_[idx]; if (idx < parsed.positionals.size()) continue; - if (argument.required_) return std::unexpected(ParseError{.message = std::format("required argument '{}' missing", argument.name)}); + if (argument.required_) return fail("missing-argument", std::format("required argument '{}' missing", argument.name)); if (!argument.default_val.empty()) parsed.positionals.push_back(argument.default_val); } parsed.positional_names_.reserve(args_.size()); diff --git a/src/parse.cppm b/src/parse.cppm index bea4bc5..06ff679 100644 --- a/src/parse.cppm +++ b/src/parse.cppm @@ -26,6 +26,16 @@ export struct ParseError { enum Kind : std::uint8_t { help, version, error, completion }; Kind kind = error; std::string message; + /// What a program reads instead of the sentence (0.2.0). `code` is stable: + /// `unknown-command`, `unknown-option`, `missing-value`, `invalid-value`, + /// `missing-argument`, `invalid-argument`, `empty-command-line`; empty for + /// help, version and completion. `command` is the command the words + /// reached, as typed (`app sub`), whose `--help` applies. `suggestions` + /// are the declared names closest to an unknown one, closest first, from + /// the list help prints (an option with its dashes). + std::string code; + std::string command; + std::vector suggestions; bool is_error() const { return kind == error; } diff --git a/tests/cmdline_test.cpp b/tests/cmdline_test.cpp index b12ecfa..31f249f 100644 --- a/tests/cmdline_test.cpp +++ b/tests/cmdline_test.cpp @@ -787,3 +787,111 @@ TEST(Flags, AnUnsetFlagIsNotAnswered) { ASSERT_TRUE(parsed); EXPECT_FALSE(app.answer_flags(*parsed)); } + +// ----------------------------------------------------------------------------- +// Usage errors carry a code, the command reached and similar names (0.2.0) +// ----------------------------------------------------------------------------- +static App tree_for_errors() { + App app("tool"); + (void)app.option(Option("verbose").short_name('v').global(true)); + (void)app.subcommand(App("build").description("compile") + .option(Option("jobs").takes_value(true).value_type()) + .option(Option("target").takes_value(true))); + (void)app.subcommand(App("bench").description("measure")); + (void)app.subcommand(App("clean").description("remove")); + (void)app.subcommand(App("internal").hidden()); + return app; +} + +TEST(UsageErrors, AnUnknownCommandIsAnErrorWithSimilarNames) { + const auto app = tree_for_errors(); + const auto result = app.parse_from(Argv{"tool", "buidl"}); + ASSERT_FALSE(result.has_value()); + EXPECT_TRUE(result.error().is_error()); + EXPECT_EQ(result.error().code, "unknown-command"); + EXPECT_EQ(result.error().command, "tool"); + EXPECT_EQ(result.error().message, "unknown command 'buidl'"); + ASSERT_FALSE(result.error().suggestions.empty()); + EXPECT_EQ(result.error().suggestions.front(), "build"); +} + +TEST(UsageErrors, AHiddenCommandIsNeverSuggestedButStillParses) { + const auto app = tree_for_errors(); + const auto near = app.parse_from(Argv{"tool", "internl"}); + ASSERT_FALSE(near.has_value()); + EXPECT_TRUE(std::ranges::find(near.error().suggestions, "internal") == near.error().suggestions.end()); + EXPECT_TRUE(app.parse_from(Argv{"tool", "internal"}).has_value()); +} + +TEST(UsageErrors, AWordUnderACommandThatDeclaresAnArgumentStaysAPositional) { + App app("tool"); + (void)app.arg(Arg("file")); + (void)app.subcommand(App("build")); + const auto result = app.parse_from(Argv{"tool", "notes.txt"}); + ASSERT_TRUE(result.has_value()) << result.error(); + EXPECT_EQ(result->positional(0), "notes.txt"); +} + +TEST(UsageErrors, AnUnknownOptionNamesTheCommandAndItsNeighbours) { + const auto app = tree_for_errors(); + const auto result = app.parse_from(Argv{"tool", "build", "--jbos", "3"}); + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, "unknown-option"); + EXPECT_EQ(result.error().command, "tool build"); + ASSERT_FALSE(result.error().suggestions.empty()); + EXPECT_EQ(result.error().suggestions.front(), "--jobs"); + const auto global = app.parse_from(Argv{"tool", "build", "--verbsoe"}); + ASSERT_FALSE(global.has_value()); + EXPECT_EQ(global.error().suggestions.front(), "--verbose"); +} + +TEST(UsageErrors, ValueErrorsHaveTheirCodes) { + const auto app = tree_for_errors(); + const auto missing = app.parse_from(Argv{"tool", "build", "--target"}); + ASSERT_FALSE(missing.has_value()); + EXPECT_EQ(missing.error().code, "missing-value"); + const auto invalid = app.parse_from(Argv{"tool", "build", "--jobs", "many"}); + ASSERT_FALSE(invalid.has_value()); + EXPECT_EQ(invalid.error().code, "invalid-value"); + EXPECT_EQ(invalid.error().command, "tool build"); + App required("tool"); + (void)required.arg(Arg("file").required()); + const auto absent = required.parse_from(Argv{"tool"}); + ASSERT_FALSE(absent.has_value()); + EXPECT_EQ(absent.error().code, "missing-argument"); +} + +TEST(UsageErrors, RunPrintsTheReasonTheNeighbourAndTheHelpOfTheCommandReached) { + auto app = tree_for_errors(); + testing::internal::CaptureStderr(); + EXPECT_EQ(app.run(Argv{"tool", "build", "--jbos", "3"}), 2); + const auto err = testing::internal::GetCapturedStderr(); + EXPECT_NE(err.find("tool: unknown option: --jbos\n"), std::string::npos) << err; + EXPECT_NE(err.find("tool: the most similar option is '--jobs'\n"), std::string::npos) << err; + EXPECT_NE(err.find("tool: see 'tool build --help'\n"), std::string::npos) << err; +} + +TEST(UsageErrors, SimilarNamesAreOrderedAndBounded) { + const std::vector names{"build", "bench", "clean", "builder"}; + const auto near = similar_names("buld", names); + ASSERT_FALSE(near.empty()); + EXPECT_EQ(near.front(), "build"); + EXPECT_TRUE(similar_names("zzzzzz", names).empty()); + EXPECT_LE(similar_names("b", std::vector{"a", "c", "d", "e", "f"}).size(), 3u); + EXPECT_EQ(similar_names("buil", names).front(), "build"); +} + +TEST(UsageErrors, AParseSilentWritesNothing) { + App app("tool"); + (void)app.version("1.0").subcommand(App("build")); + testing::internal::CaptureStdout(); + testing::internal::CaptureStderr(); + const auto help = app.parse_silent(Argv{"tool", "build", "--help"}); + const auto version = app.parse_silent(std::string_view("tool --version")); + EXPECT_TRUE(testing::internal::GetCapturedStdout().empty()); + EXPECT_TRUE(testing::internal::GetCapturedStderr().empty()); + ASSERT_FALSE(help.has_value()); + EXPECT_EQ(help.error().kind, ParseError::help); + ASSERT_FALSE(version.has_value()); + EXPECT_EQ(version.error().kind, ParseError::version); +} From 54dc57378ca83ff0c2f24b36090647b7a11a6ad0 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 4 Dec 2026 22:09:39 +0900 Subject: [PATCH 2/2] plain loops where clang 23 on Windows crashed generating a projection through a member of an imported type --- src/agent_skills.cppm | 10 +++++++--- src/cmdline.cppm | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/agent_skills.cppm b/src/agent_skills.cppm index 1de0433..2654efa 100644 --- a/src/agent_skills.cppm +++ b/src/agent_skills.cppm @@ -294,9 +294,13 @@ inline const completions::Command* command_at(const completions::Command& root, while (!key.empty()) { const auto dot = key.find('.'); const auto part = key.substr(0, dot); - const auto it = std::ranges::find(at->subcommands, part, &completions::Command::name); - if (it == at->subcommands.end()) return nullptr; - at = &*it; + // A plain loop: clang 23 on Windows crashed generating code for a + // ranges::find projected through a member of an imported type here. + const completions::Command* next = nullptr; + for (const auto& sub : at->subcommands) + if (sub.name == part) { next = ⊂ break; } + if (!next) return nullptr; + at = next; key = dot == std::string_view::npos ? std::string_view{} : key.substr(dot + 1); } return at; diff --git a/src/cmdline.cppm b/src/cmdline.cppm index 4ff97c7..cdd95bb 100644 --- a/src/cmdline.cppm +++ b/src/cmdline.cppm @@ -120,7 +120,7 @@ export [[nodiscard]] inline std::vector similar_names( const bool prefix = word.size() >= 2 && candidate.starts_with(word); if (distance <= reach || prefix) scored.emplace_back(prefix ? 0 : distance, candidate); } - std::ranges::stable_sort(scored, {}, &std::pair::first); + std::ranges::stable_sort(scored, [](const auto& l, const auto& r) { return l.first < r.first; }); std::vector out; for (const auto& [_, name] : scored) { if (out.size() == limit) break;