[clang] [clang-tools-extra] [lld] [llvm] [llvm] Add subcommand support for OptTable (PR #155026)

via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 5 14:53:00 PDT 2025


================
@@ -741,17 +779,62 @@ void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
       Visibility(0));
 }
 
+static const OptTable::Command *
+getActiveCommand(ArrayRef<OptTable::Command> Commands, StringRef Subcommand) {
+  for (const auto &C : Commands) {
+    if (Subcommand == C.Name)
+      return &C;
+  }
+  return nullptr;
+}
+
 void OptTable::internalPrintHelp(
-    raw_ostream &OS, const char *Usage, const char *Title, bool ShowHidden,
-    bool ShowAllAliases, std::function<bool(const Info &)> ExcludeOption,
+    raw_ostream &OS, const char *Usage, const char *Title, StringRef Subcommand,
+    bool ShowHidden, bool ShowAllAliases,
+    std::function<bool(const Info &)> ExcludeOption,
     Visibility VisibilityMask) const {
   OS << "OVERVIEW: " << Title << "\n\n";
-  OS << "USAGE: " << Usage << "\n\n";
 
   // Render help text into a map of group-name to a list of (option, help)
   // pairs.
   std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
 
+  const Command *ActiveCommand = getActiveCommand(Commands, Subcommand);
+  if (ActiveCommand) {
+    OS << ActiveCommand->HelpText << "\n\n";
+    if (!StringRef(ActiveCommand->Usage).empty())
+      OS << "USAGE: " << ActiveCommand->Usage << "\n\n";
+  } else {
+    OS << "USAGE: " << Usage << "\n\n";
+    // Assume top level command (toolname) is active.
+    StringRef TopLevelCommandName = "TopLevelCommand";
+    if (Commands.size() > 1) {
+      OS << "SUBCOMMANDS:\n\n";
+      // This loop prints subcommands list and sets ActiveCommand to
+      // TopLevelCommand while iterating over all commands.
+      for (const auto &C : Commands) {
+        if (C.Name == TopLevelCommandName) {
----------------
PiJoules wrote:

Coud probably just do `C.Name == "TopLevelCommandName"` if it's not changed elsewhere and stick it as a `constexpr` global in `OptTable.h` if it's used elsewhere.

https://github.com/llvm/llvm-project/pull/155026


More information about the llvm-commits mailing list