[llvm] [orc_rt] adding a very simple CLI flags parser in (PR #172987)

Jared Wyles via llvm-commits llvm-commits at lists.llvm.org
Thu Jul 9 16:58:46 PDT 2026


https://github.com/jaredwy updated https://github.com/llvm/llvm-project/pull/172987

>From d5d735c3e919ebfeb8bc5537d4a9bd3674bc821c Mon Sep 17 00:00:00 2001
From: jared w <jared.wyles at gmail.com>
Date: Fri, 19 Dec 2025 22:20:19 +1100
Subject: [PATCH] [orc-rt] Add a lightweight command-line flag parser

  Adds orc_rt::CommandLineParser, a small header-only option parser in
  orc-rt-utils for use by orc-rt tools that need argument handling.

  Features:
   - Long (--name, --name=value) and short (-n, -nvalue) options.
   - Short-flag clustering (e.g. -vp9999) and "--" to terminate option
     parsing, with remaining tokens collected as positionals.
   - Typed values, with parse failures returning an orc_rt::Error.
   - printHelp() with aligned, optionally short-name-aware output.

  Values are bound to caller-owned storage supplied at registration time and
  reset to their defaults on each parse().

  Also adds CommandLineTest.cpp to the CoreTests unittest and fixes the
  indentation of the docs subdirectory guard in orc-rt/CMakeLists.txt.
---
 orc-rt/include/orc-rt-utils/CommandLine.h | 256 ++++++++++++++++++++++
 orc-rt/test/unit/CMakeLists.txt           |   1 +
 orc-rt/test/unit/CommandLineTest.cpp      | 145 ++++++++++++
 3 files changed, 402 insertions(+)
 create mode 100644 orc-rt/include/orc-rt-utils/CommandLine.h
 create mode 100644 orc-rt/test/unit/CommandLineTest.cpp

diff --git a/orc-rt/include/orc-rt-utils/CommandLine.h b/orc-rt/include/orc-rt-utils/CommandLine.h
new file mode 100644
index 0000000000000..3582d88bb7df6
--- /dev/null
+++ b/orc-rt/include/orc-rt-utils/CommandLine.h
@@ -0,0 +1,256 @@
+//===- CommandLine.h ------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Simple orc-rt command-line parser. Supports flags, values and positionals.
+// All storage owned by caller.
+//
+//===----------------------------------------------------------------------===//
+
+#include <algorithm>
+#include <charconv>
+#include <functional>
+#include <iomanip>
+#include <numeric>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "orc-rt/Error.h"
+
+namespace orc_rt {
+namespace detail {
+
+template <typename T> inline std::optional<T> parseValue(std::string_view Str);
+
+template <>
+inline std::optional<std::string>
+parseValue<std::string>(std::string_view Str) {
+  return std::string(Str);
+}
+
+template <>
+inline std::optional<std::string_view>
+parseValue<std::string_view>(std::string_view Str) {
+  return Str;
+}
+
+template <> inline std::optional<int> parseValue<int>(std::string_view Str) {
+  if (Str.empty())
+    return std::nullopt;
+  int Val{};
+  auto Ret = std::from_chars(Str.data(), Str.data() + Str.size(), Val);
+  if (Ret.ec != std::errc() || Ret.ptr != Str.data() + Str.size())
+    return std::nullopt;
+  return Val;
+}
+
+template <> inline std::optional<bool> parseValue<bool>(std::string_view Str) {
+  if (Str.empty())
+    return std::nullopt;
+
+  if (Str == "1")
+    return true;
+  if (Str == "0")
+    return false;
+
+  std::string Val;
+  std::transform(
+      Str.begin(), Str.end(), std::back_inserter(Val),
+      [](unsigned char C) { return static_cast<char>(std::tolower(C)); });
+
+  if (Val == "true")
+    return true;
+  if (Val == "false")
+    return false;
+
+  return std::nullopt;
+}
+} // namespace detail
+
+class CommandLineParser {
+public:
+  enum class OptionKind { Flag, Value };
+  CommandLineParser() = default;
+
+  CommandLineParser &addFlag(std::string_view Name, std::string_view Desc,
+                             bool DefaultVal, bool &Val,
+                             std::optional<char> ShortName = std::nullopt) {
+    return addValue(Name, Desc, DefaultVal, Val, OptionKind::Flag,
+                    std::move(ShortName));
+  }
+
+  template <typename T>
+  CommandLineParser &addValue(std::string_view Name, std::string_view Desc,
+                              T DefaultVal, T &Val,
+                              OptionKind Kind = OptionKind::Value,
+                              std::optional<char> ShortName = std::nullopt) {
+    Val = DefaultVal;
+    Opts.push_back({.Name = std::string(Name),
+                    .ShortName = std::move(ShortName),
+                    .Desc = std::string(Desc),
+                    .Kind = Kind,
+                    .Default = [&Val, DV = DefaultVal]() { Val = DV; },
+                    .FromString = [&Val, OptName = std::string(Name)](
+                                      std::string_view S) -> orc_rt::Error {
+                      if (auto V = detail::parseValue<T>(S)) {
+                        Val = *V;
+                        return orc_rt::Error::success();
+                      }
+                      return orc_rt::make_error<orc_rt::StringError>(
+                          std::string("Invalid value for '") + OptName +
+                          "': '" + std::string(S) + "'");
+                    }});
+    return *this;
+  }
+
+  void printHelp(std::ostream &OS, std::string_view ProgramName) const {
+    OS << "Usage: " << ProgramName << " [options] [positional arguments]\n\n";
+    OS << "OPTIONS:\n";
+
+    bool AnyShortNames =
+        std::any_of(Opts.begin(), Opts.end(),
+                    [](const Option &O) { return O.ShortName.has_value(); });
+
+    size_t MaxWidth = 0;
+    for (const auto &Opt : Opts) {
+      size_t CurrentWidth = 2; // "  "
+      if (AnyShortNames)
+        CurrentWidth += 4;                   // "-x, "
+      CurrentWidth += 2 + Opt.Name.length(); // "--name"
+      if (Opt.Kind == OptionKind::Value)
+        CurrentWidth += 8; // " <value>"
+      MaxWidth = std::max(MaxWidth, CurrentWidth);
+    }
+
+    for (const auto &Opt : Opts) {
+      std::string FlagStr = "  ";
+      if (AnyShortNames) {
+        if (Opt.ShortName) {
+          FlagStr += "-";
+          FlagStr += *Opt.ShortName;
+          FlagStr += ", ";
+        } else {
+          FlagStr += "    "; // Pad gutter
+        }
+      }
+      FlagStr += "--" + Opt.Name;
+      if (Opt.Kind == OptionKind::Value)
+        FlagStr += " <value>";
+
+      OS << std::left << std::setw(MaxWidth + 2) << FlagStr << Opt.Desc << "\n";
+    }
+  }
+
+  template <typename I> orc_rt::Error parse(I Begin, I End) {
+    std::for_each(Opts.begin(), Opts.end(),
+                  [](const Option &O) { O.Default(); });
+    Positionals.clear();
+    bool AfterDashDash = false;
+    if (Begin != End)
+      Begin++;
+
+    for (auto It = Begin; It != End; ++It) {
+      std::string_view Tok(*It);
+      if (!AfterDashDash && Tok == "--") {
+        AfterDashDash = true;
+        continue;
+      }
+      if (!AfterDashDash && startsWith(Tok, "--")) {
+        std::string_view K = Tok.substr(2);
+        std::string_view V;
+        bool HasValue = false;
+        if (auto P = K.find('='); P != std::string_view::npos) {
+          V = K.substr(P + 1);
+          K = K.substr(0, P);
+          HasValue = true;
+        }
+        auto FoundOpt = findOpt(K);
+        if (!FoundOpt)
+          return orc_rt::make_error<orc_rt::StringError>(
+              "Unknown option '" + std::string(Tok) + "'");
+        if (auto Err = consumeValue(FoundOpt, V, HasValue, It, End))
+          return Err;
+      } else if (!AfterDashDash && startsWith(Tok, "-") && Tok.size() > 1) {
+        std::string_view Group = Tok.substr(1);
+        for (size_t i = 0; i < Group.size(); ++i) {
+          auto FoundOpt = findOpt(Group[i]);
+          if (!FoundOpt)
+            return orc_rt::make_error<orc_rt::StringError>(
+                std::string("Unknown short option '-") + Group[i] + "'");
+          if (FoundOpt->Kind == OptionKind::Value) {
+            std::string_view V = Group.substr(i + 1);
+            bool HasValue = !V.empty();
+            if (auto Err = consumeValue(FoundOpt, V, HasValue, It, End))
+              return Err;
+            break;
+          } else {
+            if (auto Err = FoundOpt->FromString("true"))
+              return Err;
+          }
+        }
+      } else {
+        Positionals.emplace_back(Tok);
+      }
+    }
+    return orc_rt::Error::success();
+  }
+
+  orc_rt::Error parse(int argc, char **argv) {
+    return parse(argv, argv + argc);
+  }
+
+  const std::vector<std::string> &positionals() const { return Positionals; }
+
+private:
+  struct Option {
+    std::string Name;
+    std::optional<char> ShortName;
+    std::string Desc;
+    OptionKind Kind{};
+    std::function<void()> Default;
+    std::function<orc_rt::Error(std::string_view)> FromString;
+  };
+
+  std::vector<std::string> Positionals;
+  std::vector<Option> Opts;
+
+  const Option *findOpt(std::string_view L) const {
+    auto It = std::find_if(Opts.begin(), Opts.end(),
+                           [&](const Option &O) { return O.Name == L; });
+    return It != Opts.end() ? &(*It) : nullptr;
+  }
+
+  const Option *findOpt(char S) const {
+    auto It = std::find_if(Opts.begin(), Opts.end(), [&](const Option &O) {
+      return O.ShortName && *O.ShortName == S;
+    });
+    return It != Opts.end() ? &(*It) : nullptr;
+  }
+
+  template <typename I>
+  orc_rt::Error consumeValue(const Option *Opt, std::string_view ExplicitV,
+                             bool HasV, I &It, I End) {
+    std::string_view V = ExplicitV;
+    if (Opt->Kind == OptionKind::Flag) {
+      if (!HasV)
+        V = "true";
+    } else if (!HasV) {
+      if (++It == End)
+        return orc_rt::make_error<orc_rt::StringError>(
+            "Option '--" + Opt->Name + "' requires a value");
+      V = *It;
+    }
+    return Opt->FromString(V);
+  }
+
+  static bool startsWith(std::string_view S, std::string_view P) {
+    return S.size() >= P.size() && S.compare(0, P.size(), P) == 0;
+  }
+};
+} // namespace orc_rt
diff --git a/orc-rt/test/unit/CMakeLists.txt b/orc-rt/test/unit/CMakeLists.txt
index 0b66c646e6a37..3a39a6d7c8d7d 100644
--- a/orc-rt/test/unit/CMakeLists.txt
+++ b/orc-rt/test/unit/CMakeLists.txt
@@ -20,6 +20,7 @@ add_orc_rt_unittest(CoreTests
   SimpleSymbolTableTest.cpp
   EndianTest.cpp
   ErrorCAPITest.cpp
+  CommandLineTest.cpp
   ErrorTest.cpp
   ErrorExceptionInteropTest.cpp
   ExecutorAddressTest.cpp
diff --git a/orc-rt/test/unit/CommandLineTest.cpp b/orc-rt/test/unit/CommandLineTest.cpp
new file mode 100644
index 0000000000000..135e1f31cbf7c
--- /dev/null
+++ b/orc-rt/test/unit/CommandLineTest.cpp
@@ -0,0 +1,145 @@
+//===- CommandLineTest.cpp ------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt-utils/CommandLine.h"
+#include "orc-rt/Error.h"
+#include "llvm/Testing/Support/Error.h"
+#include "gtest/gtest.h"
+
+using namespace orc_rt;
+
+class CommandLineParserTest : public ::testing::Test {
+protected:
+  std::string Host;
+  int Port = 0;
+  bool Verbose = false;
+  bool Help = false;
+  CommandLineParser Parser;
+
+  void SetUp() override {
+    Parser.addValue("host", "Hostname", std::string("localhost"), Host,
+                    CommandLineParser::OptionKind::Value, 'h');
+    Parser.addFlag("help", "Display this help message", false, Help, '?');
+    Parser.addValue("port", "Port number", 8080, Port,
+                    CommandLineParser::OptionKind::Value, 'p');
+    Parser.addFlag("verbose", "Enable verbose logging", false, Verbose, 'v');
+  }
+};
+
+TEST_F(CommandLineParserTest, NoopTest) {
+  CommandLineParser Parser;
+  const char *Argv[] = {"appname"};
+  auto Err = Parser.parse(1, const_cast<char **>(Argv));
+  EXPECT_FALSE(!!Err);
+}
+
+TEST_F(CommandLineParserTest, ValueRequired) {
+  const char *Argv[] = {"appname", "--host"};
+  auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
+  if (!Err) {
+    ADD_FAILURE() << "--host requires a value, shouldn't succeed.";
+  } else {
+    orc_rt::consumeError(std::move(Err));
+  }
+}
+
+TEST_F(CommandLineParserTest, UnknownOption) {
+  const char *Argv[] = {"appname", "--unknown=foo"};
+  auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
+  if (!Err) {
+    ADD_FAILURE() << "unknown option, shouldn't succeed.";
+  } else {
+    orc_rt::consumeError(std::move(Err));
+  }
+}
+
+TEST_F(CommandLineParserTest, InvalidInteger) {
+  const char *Argv[] = {"appname", "--port=not_a_number"};
+  auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
+  if (!Err) {
+    ADD_FAILURE() << "Invalid integer, shouldn't succeed.";
+  } else {
+    orc_rt::consumeError(std::move(Err));
+  }
+}
+
+TEST_F(CommandLineParserTest, ParseFullConfiguration) {
+  const char *Argv[] = {"appname", "--host=example.com", "--port=8080",
+                        "--verbose=true"};
+  cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+  EXPECT_EQ(Host, "example.com");
+  EXPECT_EQ(Port, 8080);
+  EXPECT_EQ(Verbose, true);
+}
+
+TEST_F(CommandLineParserTest, ShortFlagClustering) {
+  const char *Argv[] = {"appname", "-v?"};
+  cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+  EXPECT_TRUE(Verbose);
+  EXPECT_TRUE(Help);
+}
+
+TEST_F(CommandLineParserTest, ShortFlagWithValue) {
+  const char *Argv[] = {"appname", "-p", "1234", "-hlocalhost"};
+  cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+  EXPECT_EQ(Port, 1234);
+  EXPECT_EQ(Host, "localhost");
+}
+
+TEST_F(CommandLineParserTest, ClusterWithValueAtEnd) {
+  const char *Argv[] = {"appname", "-vp9999"};
+  cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+  EXPECT_TRUE(Verbose);
+  EXPECT_EQ(Port, 9999);
+}
+
+TEST_F(CommandLineParserTest, DoubleDashTerminatesOptionParsing) {
+  const char *Argv[] = {"appname", "-v", "--", "-p", "1234"};
+  cantFail(Parser.parse(static_cast<int>(std::size(Argv)),
+                        const_cast<char **>(Argv)));
+
+  EXPECT_TRUE(Verbose);
+  EXPECT_EQ(Port, 8080); // Should remain default
+  ASSERT_EQ(Parser.positionals().size(), 2u);
+  EXPECT_EQ(Parser.positionals()[0], "-p");
+  EXPECT_EQ(Parser.positionals()[1], "1234");
+}
+
+TEST_F(CommandLineParserTest, PrintHelpAlignmentWithShortFlags) {
+  std::string LogFile;
+  Parser.addValue("log-file", "Path to log", std::string("out.log"), LogFile);
+
+  std::stringstream SS;
+  Parser.printHelp(SS, "appname");
+  std::string Result = SS.str();
+
+  auto GetColumn = [&](std::string_view SearchTerm) -> size_t {
+    size_t Pos = Result.find(SearchTerm);
+    if (Pos == std::string::npos)
+      return 0;
+    size_t LineStart = Result.rfind('\n', Pos);
+    return (LineStart == std::string::npos) ? Pos : (Pos - LineStart - 1);
+  };
+
+  size_t PortDescCol = GetColumn("Port number");
+  size_t LogDescCol = GetColumn("Path to log");
+  size_t VerbDescCol = GetColumn("Enable verbose");
+
+  ASSERT_NE(PortDescCol, 0u);
+  EXPECT_EQ(PortDescCol, LogDescCol)
+      << "Descriptions should align even if short flag is missing";
+  EXPECT_EQ(LogDescCol, VerbDescCol);
+
+  size_t LogFlagPos = Result.find("--log-file");
+  size_t PortFlagPos = Result.find("--port");
+
+  size_t LogFlagCol = (LogFlagPos - Result.rfind('\n', LogFlagPos) - 1);
+  size_t PortFlagCol = (PortFlagPos - Result.rfind('\n', PortFlagPos) - 1);
+
+  EXPECT_EQ(LogFlagCol, PortFlagCol);
+}



More information about the llvm-commits mailing list