4#ifndef GREM_CORE_COMMAND_LINE_INTERFACE_HPP
5#define GREM_CORE_COMMAND_LINE_INTERFACE_HPP
31#include <system_error>
40concept convertible_to_boolean_reference =
41 convertible_to<T&, bool&> || convertible_to<T&, bool8_t&> || convertible_to<T&, bool16_t&> || convertible_to<T&, bool32_t&> || convertible_to<T&, bool64_t&>;
44concept convertible_to_integer_reference =
45 convertible_to<T&, signed char&> || convertible_to<T&, short&> || convertible_to<T&, int&> || convertible_to<T&, long&> || convertible_to<T&, long long&> ||
46 convertible_to<T&, unsigned char&> || convertible_to<T&, unsigned short&> || convertible_to<T&, unsigned&> || convertible_to<T&, unsigned long&> ||
47 convertible_to<T&, unsigned long long&>;
50concept convertible_to_character_reference =
51 convertible_to<T&, char&> || convertible_to<T&, wchar_t&> || convertible_to<T&, char8_t&> || convertible_to<T&, char16_t&> || convertible_to<T&, char32_t&>;
54concept optional_argument =
requires(
T t) {
62concept quantity_argument =
requires(
T t,
const float value) {
63 t = T::reinterpret(value);
64 static_cast<float>(t.in(T::UNIT));
65} && !optional_argument<T>;
68concept double_argument =
requires(
T t,
const double value) { t = value; } && !convertible_to<T&, float&> && !optional_argument<T> && !quantity_argument<T> &&
69 !convertible_to_character_reference<T> && !convertible_to_integer_reference<T> && !convertible_to_boolean_reference<T> && !convertible_to<T&, String&>;
70static_assert(double_argument<double>);
73concept float_argument =
requires(
T t,
const float value) { t = value; } && (!double_argument<T> || convertible_to<T&, float&>) && !optional_argument<T> && !quantity_argument<T> &&
74 !convertible_to_character_reference<T> && !convertible_to_integer_reference<T> && !convertible_to_boolean_reference<T> && !convertible_to<T&, String&>;
75static_assert(float_argument<float>);
78concept integer_argument = convertible_to_integer_reference<T> || (
requires(
T t,
const int64_t value) {
79 static_cast<int64_t
>(t);
80 t =
static_cast<T>(value);
81} && !optional_argument<T> && !quantity_argument<T> && !double_argument<T> && !float_argument<T> && !convertible_to_character_reference<T> && !convertible_to_boolean_reference<T>);
82static_assert(integer_argument<int8_t>);
83static_assert(integer_argument<int64_t>);
84static_assert(integer_argument<uint8_t>);
85static_assert(integer_argument<uint64_t>);
88concept character_argument = convertible_to_character_reference<T> || (
requires(
T t,
const char value) {
90 t =
static_cast<T>(value);
91} && !optional_argument<T> && !quantity_argument<T> && !double_argument<T> && !float_argument<T> && !convertible_to_integer_reference<T> && !convertible_to_boolean_reference<T>);
92static_assert(character_argument<char>);
93static_assert(character_argument<wchar_t>);
94static_assert(character_argument<char8_t>);
95static_assert(character_argument<char16_t>);
96static_assert(character_argument<char32_t>);
99concept string_argument =
requires(
T t,
const char*
const string) { t = string; } && !optional_argument<T> && !quantity_argument<T> && !double_argument<T> && !float_argument<T> &&
100 !integer_argument<T> && !character_argument<T> && !convertible_to_boolean_reference<T>;
101static_assert(string_argument<String>);
102static_assert(string_argument<CStringView>);
105concept boolean_argument =
106 requires(
T t,
const bool value) {
107 static_cast<bool>(t);
109 } && !optional_argument<T> && !quantity_argument<T> &&
110 ((!double_argument<T> && !float_argument<T> && !integer_argument<T> && !character_argument<T> && !string_argument<T>) || convertible_to_boolean_reference<T>);
111static_assert(boolean_argument<bool>);
112static_assert(boolean_argument<bool16_t>);
113static_assert(boolean_argument<bool32_t>);
114static_assert(boolean_argument<bool64_t>);
117concept list_argument =
requires(
T t) {
120} && !string_argument<T>;
123concept array_argument =
requires(
T t,
const size_t index) {
126} && !string_argument<T> && !list_argument<T>;
129concept duration_argument =
requires {
135[[nodiscard]]
constexpr auto& getIntegerReference(T& value)
noexcept {
136 if constexpr (integral<T>) {
138 }
else if constexpr (convertible_to<T&, int64_t&>) {
139 return static_cast<int64_t&
>(value);
140 }
else if constexpr (convertible_to<T&, uint64_t&>) {
141 return static_cast<uint64_t&
>(value);
142 }
else if constexpr (convertible_to<T&, int32_t&>) {
143 return static_cast<int32_t&
>(value);
144 }
else if constexpr (convertible_to<T&, uint32_t&>) {
145 return static_cast<uint32_t&
>(value);
146 }
else if constexpr (convertible_to<T&, int16_t&>) {
147 return static_cast<int16_t&
>(value);
148 }
else if constexpr (convertible_to<T&, uint16_t&>) {
149 return static_cast<uint16_t&
>(value);
150 }
else if constexpr (convertible_to<T&, int8_t&>) {
151 return static_cast<int8_t&
>(value);
152 }
else if constexpr (convertible_to<T&, uint8_t&>) {
153 return static_cast<uint8_t&
>(value);
160[[nodiscard]]
constexpr auto& getCharacterReference(T& value)
noexcept {
161 if constexpr (convertible_to<T&, char&>) {
162 return static_cast<char&
>(value);
163 }
else if constexpr (convertible_to<T&, wchar_t&>) {
164 return static_cast<wchar_t&
>(value);
165 }
else if constexpr (convertible_to<T&, char8_t&>) {
166 return static_cast<char8_t&
>(value);
167 }
else if constexpr (convertible_to<T&, char16_t&>) {
168 return static_cast<char16_t&
>(value);
169 }
else if constexpr (convertible_to<T&, char32_t&>) {
170 return static_cast<char32_t&
>(value);
177struct is_vector_argument : std::false_type {};
179template <
size_t N,
typename T>
180struct is_vector_argument<vec<
N,
T>> : std::true_type {};
182template <quantity_argument Quantity>
183struct is_vector_argument<Quantity> : std::bool_constant<Quantity::RANK >= 2> {};
186inline constexpr bool is_vector_argument_v = is_vector_argument<T>::value;
189struct vector_argument_size;
191template <
size_t N,
typename T>
192struct vector_argument_size<vec<
N,
T>> : std::integral_constant<size_t, N> {};
194template <quantity_argument Quantity>
195struct vector_argument_size<Quantity> : std::integral_constant<size_t, Quantity::RANK> {};
198inline constexpr size_t vector_argument_size_v = vector_argument_size<T>::value;
255 constexpr Proxy() noexcept = default;
257 constexpr
Proxy(T& reference) noexcept
267 template <
typename Arg>
268 decltype(
auto)
operator=(Arg&& arg)
269 requires(
requires(T t) { t = std::forward<Arg>(arg); }) {
272#pragma clang diagnostic push
273#pragma clang diagnostic ignored "-Wshorten-64-to-32"
274#pragma clang diagnostic ignored "-Wfloat-conversion"
275#elif defined(__GNUC__)
276#pragma GCC diagnostic push
277#pragma GCC diagnostic ignored "-Wconversion"
278#pragma GCC diagnostic ignored "-Wfloat-conversion"
280 return *
pointer = std::forward<Arg>(arg);
282#pragma clang diagnostic pop
283#elif defined(__GNUC__)
284#pragma GCC diagnostic pop
288 explicit operator bool() const noexcept requires(requires(const T t) {
static_cast<bool>(t); } && !
requires(
const T t) {
static_cast<const bool&
>(t); }) {
290 return static_cast<bool>(*pointer);
293 operator T&()
noexcept {
298 operator const T&()
const noexcept {
303 void reset() noexcept requires(requires(T t) { t.reset(); }) {
308 decltype(
auto)
emplace()
requires(
requires(T t) { t.emplace(); }) {
313 [[nodiscard]]
bool has_value() const noexcept requires(requires(const T t) { t.has_value(); }) {
318 [[nodiscard]]
decltype(
auto)
value()
requires(
requires(T t) { t.value(); }) {
323 [[nodiscard]]
decltype(
auto)
value()
const requires(
requires(
const T t) { t.value(); }) {
328 [[nodiscard]]
decltype(
auto)
emplace_back()
requires(
requires(T t) { t.emplace_back(); }) {
330 return pointer->emplace_back();
333 [[nodiscard]]
decltype(
auto)
back()
requires(
requires(T t) { t.back(); }) {
338 [[nodiscard]]
decltype(
auto)
back()
const requires(
requires(
const T t) { t.back(); }) {
343 [[nodiscard]]
decltype(
auto)
size()
const noexcept requires(
requires(
const T t) { std::size(t); }) {
348 [[nodiscard]]
decltype(
auto)
operator[](
size_t index)
requires(
requires(T t,
const size_t i) { t[i]; }) {
353 [[nodiscard]]
decltype(
auto)
operator[](
size_t index)
const requires(
requires(
const T t,
const size_t i) { t[i]; }) {
432template <detail::
boolean_argument T>
441 throw std::invalid_argument{
"Expected a boolean value (true/false)."};
455template <detail::
integer_argument T>
457 if constexpr (
integral<T> || detail::convertible_to_integer_reference<T>) {
458 auto& integerReference = detail::getIntegerReference(output);
459 const std::from_chars_result parseResult = std::from_chars(argument.
data(), argument.
data() + argument.
size(), integerReference);
460 if (parseResult.ec != std::errc{}) {
461 if constexpr (
unsigned_integral<std::remove_cvref_t<
decltype(integerReference)>>) {
462 throw std::invalid_argument{
"Expected a non-negative integer."};
464 throw std::invalid_argument{
"Expected an integer."};
469 const std::from_chars_result parseResult = std::from_chars(argument.
data(), argument.
data() + argument.
size(), value);
470 if (parseResult.ec != std::errc{}) {
471 throw std::invalid_argument{
"Expected an integer."};
473 output =
static_cast<T
>(value);
487template <detail::
character_argument T>
489 if constexpr (detail::convertible_to_character_reference<T>) {
490 auto& characterReference = detail::getCharacterReference(output);
491 using X = std::remove_cvref_t<
decltype(characterReference)>;
492 if (argument.
size() !=
sizeof(X)) {
493 throw std::invalid_argument{
"Expected a character."};
495 memcpy(&characterReference, argument.
data(),
sizeof(X));
497 if (argument.
size() != 1) {
498 throw std::invalid_argument{
"Expected a character."};
500 output =
static_cast<T
>(argument.
front());
514template <detail::
float_argument T>
518#pragma clang diagnostic push
519#pragma clang diagnostic ignored "-Wdeprecated-declarations"
521 if (std::sscanf(argument.
c_str(),
"%f", &value) != 1) {
522 throw std::invalid_argument{
"Expected a number."};
525#pragma clang diagnostic pop
540template <detail::
double_argument T>
544#pragma clang diagnostic push
545#pragma clang diagnostic ignored "-Wdeprecated-declarations"
547 if (std::sscanf(argument.
c_str(),
"%lf", &value) != 1) {
548 throw std::invalid_argument{
"Expected a number."};
551#pragma clang diagnostic pop
567template <detail::quantity_argument T>
571#pragma clang diagnostic push
572#pragma clang diagnostic ignored "-Wdeprecated-declarations"
574 if (std::sscanf(argument.
c_str(),
"%f", &value) != 1) {
575 throw std::invalid_argument{
"Expected a number."};
578#pragma clang diagnostic pop
580 output = T::reinterpret(value);
591template <detail::
string_argument T>
593 output = argument.
c_str();
605template <
typename Rep,
typename Period>
607 double milliseconds{};
609 output = duration_cast<DurationBase<Rep, Period>>(
DurationBase<double,
Ratio<1, 1'000>>{milliseconds});
614struct NoArguments {};
617struct ArgumentCounts {
618 size_t leadingArgumentCount = 0;
619 size_t trailingArgumentCount = 0;
620 size_t maxArgumentCount = 0;
623template <
typename Arguments>
624[[nodiscard]]
inline ArgumentCounts getArgumentCounts(
const Arguments& outputArguments) {
625 ArgumentCounts result{};
627 if constexpr (detail::is_vector_argument_v<T>) {
628 for (
size_t i = 0; i < detail::vector_argument_size_v<T>; ++i) {
629 if (result.leadingArgumentCount == result.maxArgumentCount) {
630 ++result.leadingArgumentCount;
631 ++result.maxArgumentCount;
633 ++result.trailingArgumentCount;
635 ++result.maxArgumentCount;
639 }
else if constexpr (aggregate<T>) {
640 const ArgumentCounts nestedArgumentCounts = getArgumentCounts(argument);
641 if (nestedArgumentCounts.leadingArgumentCount == nestedArgumentCounts.maxArgumentCount) {
642 const size_t size = nestedArgumentCounts.maxArgumentCount;
643 if (result.leadingArgumentCount == result.maxArgumentCount) {
644 result.leadingArgumentCount += size;
645 result.maxArgumentCount += size;
647 result.trailingArgumentCount += size;
649 result.maxArgumentCount += size;
653 GREM_ASSERT(result.leadingArgumentCount == result.maxArgumentCount &&
"Command line may only contain one range of optional arguments.");
657 result.trailingArgumentCount == 0 && result.maxArgumentCount !=
Limits<size_t>::MAX &&
"Command line may only contain one range of optional arguments.");
658 result.leadingArgumentCount += nestedArgumentCounts.leadingArgumentCount;
659 result.trailingArgumentCount = nestedArgumentCounts.trailingArgumentCount;
660 result.maxArgumentCount += nestedArgumentCounts.maxArgumentCount;
662 }
else if constexpr (optional_argument<T>) {
663 GREM_ASSERT(result.trailingArgumentCount == 0 && result.maxArgumentCount !=
Limits<size_t>::MAX &&
"Command line may only contain one range of optional arguments.");
664 ++result.maxArgumentCount;
665 }
else if constexpr (list_argument<T>) {
666 GREM_ASSERT(result.leadingArgumentCount == result.maxArgumentCount &&
"Command line may only contain one range of optional arguments.");
668 }
else if constexpr (array_argument<T>) {
669 const size_t size = std::size(argument);
670 if (result.leadingArgumentCount == result.maxArgumentCount) {
671 result.leadingArgumentCount += size;
672 result.maxArgumentCount += size;
674 result.trailingArgumentCount += size;
676 result.maxArgumentCount += size;
680 if (result.leadingArgumentCount == result.maxArgumentCount) {
681 ++result.leadingArgumentCount;
682 ++result.maxArgumentCount;
684 ++result.trailingArgumentCount;
686 ++result.maxArgumentCount;
696 result.reserve(namePrefix.size() + fieldName.size() + fieldName.size() / 4);
697 result.append(namePrefix);
698 bool inUppercaseSequence =
false;
699 for (
size_t i = 0; i < fieldName.size(); ++i) {
703 inUppercaseSequence =
true;
705 result.push_back(
'-');
710 if (inUppercaseSequence) {
711 inUppercaseSequence =
false;
712 result.push_back(
'-');
714 if ((ch !=
'-' && ch !=
'_') || result.empty() || result.back() !=
'-') {
716 result.push_back(
'-');
718 result.push_back(ch);
727[[nodiscard]]
inline String formatArgumentTypeName() {
728 if constexpr (boolean_argument<T>) {
730 }
else if constexpr (character_argument<T>) {
732 }
else if constexpr (integer_argument<T>) {
734 }
else if constexpr (quantity_argument<T>) {
735 const auto unitSymbolString = T::Unit::getSymbolString();
736 return (unitSymbolString.empty()) ?
String{
"number"} :
String{unitSymbolString};
737 }
else if constexpr (float_argument<T> || double_argument<T>) {
739 }
else if constexpr (string_argument<T>) {
741 }
else if constexpr (optional_argument<T>) {
742 return formatString(
"optional {}", formatArgumentTypeName<std::remove_cvref_t<
decltype(std::declval<T>().value())>>());
743 }
else if constexpr (list_argument<T>) {
744 return formatString(
"{}...", formatArgumentTypeName<std::remove_cvref_t<
decltype(std::declval<T>().back())>>());
745 }
else if constexpr (array_argument<T>) {
746 return formatString(
"{}...", formatArgumentTypeName<std::remove_cvref_t<
decltype(std::declval<T>()[0])>>());
747 }
else if constexpr (duration_argument<T>) {
748 return "milliseconds";
752 result.reserve(typeName.size() + typeName.size() / 4);
753 bool inUppercaseSequence =
false;
754 for (
size_t i = 0; i < typeName.size(); ++i) {
758 inUppercaseSequence =
true;
760 result.push_back(
' ');
765 if (inUppercaseSequence) {
766 inUppercaseSequence =
false;
767 result.push_back(
' ');
769 if ((ch !=
' ' && ch !=
'_') || result.empty() || result.back() !=
' ') {
771 result.push_back(
' ');
773 result.push_back(ch);
782template <
typename Arguments>
785 const String argumentName = formatArgumentName(namePrefix, name);
786 if constexpr (detail::is_vector_argument_v<T>) {
787 if constexpr (detail::vector_argument_size_v<T> == 1) {
789 }
else if constexpr (detail::vector_argument_size_v<T> == 2) {
790 output.append(
formatString(
" <{0}-x> <{0}-y>", argumentName));
791 }
else if constexpr (detail::vector_argument_size_v<T> == 3) {
792 output.append(
formatString(
" <{0}-x> <{0}-y> <{0}-z>", argumentName));
793 }
else if constexpr (detail::vector_argument_size_v<T> == 4) {
794 output.append(
formatString(
" <{0}-x> <{0}-y> <{0}-z> <{0}-w>", argumentName));
796 }
else if constexpr (aggregate<T>) {
797 appendArgumentsUsage<T>(output, argumentName +
"-");
798 }
else if constexpr (optional_argument<T>) {
800 }
else if constexpr (list_argument<T>) {
802 }
else if constexpr (array_argument<T>) {
810template <
typename Arguments,
typename Options>
811[[nodiscard]]
inline String formatUsageString(
CStringView commandName,
const CommandLineParserOptions& options) {
812 String result =
formatString(
"Usage: {}", commandName.substr(commandName.find_last_of(
"/\\") + 1));
814 result.append(
" [options...]");
816 appendArgumentsUsage<Arguments>(result, {});
817 if (!options.extraArgumentsSeparator.empty()) {
818 result.append(
formatString(
" [{} ...]", options.extraArgumentsSeparator));
824inline decltype(
auto) getDefaultArgumentValueForFormatting(
const T& value) {
825 if constexpr (quantity_argument<T>) {
826 return value.in(T::UNIT);
827 }
else if constexpr (duration_argument<T>) {
834template <
typename Option>
835inline void appendOptionHelp(
String& output,
const String& optionName,
const Option& outputOption,
const HashMap<char, String>& shortOptionNameMap,
836 const CommandLineParserOptions& options) {
838 using T = std::remove_cvref_t<Option>;
839 if constexpr (boolean_argument<T>) {
840 if (!options.useImplicitBooleanValues || outputOption) {
841 argumentString =
formatString(
" <boolean> (default: {})", getDefaultArgumentValueForFormatting(outputOption));
843 }
else if constexpr (optional_argument<T>) {
844 const String argumentTypeName = formatArgumentTypeName<std::remove_cvref_t<decltype(std::declval<T>().value())>>();
845 if (outputOption.has_value()) {
846 argumentString =
formatString(
" [{}] (default: {})", argumentTypeName, getDefaultArgumentValueForFormatting(outputOption.value()));
848 argumentString =
formatString(
" [{}] (default: null)", argumentTypeName);
851 argumentString =
formatString(
" <{}> (default: {})", formatArgumentTypeName<T>(), getDefaultArgumentValueForFormatting(outputOption));
853 const bool enableShortOptions = !options.shortOptionPrefix.empty() && options.shortOptionPrefix != options.longOptionPrefix;
854 if (enableShortOptions && !shortOptionNameMap.empty()) {
855 const char shortOptionName = optionName.front();
857 if (
const auto it = shortOptionNameMap.find(shortOptionName); it != shortOptionNameMap.end() && it->second == optionName) {
858 output.append(
formatString(
"\n -{} {}{}{}", shortOptionName, options.longOptionPrefix, optionName, argumentString));
859 }
else if (
const auto newIt = shortOptionNameMap.find(shortOptionNameInOppositeCase); newIt != shortOptionNameMap.end() && newIt->second == optionName) {
860 output.append(
formatString(
"\n -{} {}{}{}", shortOptionNameInOppositeCase, options.longOptionPrefix, optionName, argumentString));
862 output.append(
formatString(
"\n {}{}{}", options.longOptionPrefix, optionName, argumentString));
865 output.append(
formatString(
"\n {}{}{}", options.longOptionPrefix, optionName, argumentString));
869inline void appendOptionsHelp(
String& output,
StringView namePrefix,
const auto& defaultOptions,
const HashMap<char, String>& shortOptionNameMap,
870 const CommandLineParserOptions& options) {
873 String optionName = formatArgumentName(namePrefix, name);
874 using T = std::remove_cvref_t<
decltype(defaultOption)>;
875 if constexpr (detail::is_vector_argument_v<T>) {
876 if constexpr (detail::vector_argument_size_v<T> == 1) {
877 appendOptionHelp(output, std::move(optionName) +
"-x", defaultOption.x, shortOptionNameMap, options);
878 }
else if constexpr (detail::vector_argument_size_v<T> == 2) {
879 appendOptionHelp(output, optionName +
"-x", defaultOption.x, shortOptionNameMap, options);
880 appendOptionHelp(output, std::move(optionName) +
"-y", defaultOption.y, shortOptionNameMap, options);
881 }
else if constexpr (detail::vector_argument_size_v<T> == 3) {
882 appendOptionHelp(output, optionName +
"-x", defaultOption.x, shortOptionNameMap, options);
883 appendOptionHelp(output, optionName +
"-y", defaultOption.y, shortOptionNameMap, options);
884 appendOptionHelp(output, std::move(optionName) +
"-z", defaultOption.z, shortOptionNameMap, options);
885 }
else if constexpr (detail::vector_argument_size_v<T> == 4) {
886 appendOptionHelp(output, optionName +
"-x", defaultOption.x, shortOptionNameMap, options);
887 appendOptionHelp(output, optionName +
"-y", defaultOption.y, shortOptionNameMap, options);
888 appendOptionHelp(output, optionName +
"-z", defaultOption.z, shortOptionNameMap, options);
889 appendOptionHelp(output, std::move(optionName) +
"-w", defaultOption.w, shortOptionNameMap, options);
891 }
else if constexpr (aggregate<T>) {
892 appendOptionsHelp(output, std::move(optionName) +
"-", defaultOption, shortOptionNameMap, options);
894 appendOptionHelp(output, optionName, defaultOption, shortOptionNameMap, options);
900template <
typename Arguments,
typename Options>
901[[nodiscard]]
inline String formatHelpString(
CStringView commandName,
const HashMap<char, String>& shortOptionNameMap,
const CommandLineParserOptions& options) {
902 String result = formatUsageString<Arguments, Options>(commandName, options);
904 const Options defaultOptions{};
905 result.append(
"\nOptions:");
906 appendOptionsHelp(result, {}, defaultOptions, shortOptionNameMap, options);
911inline void addShortOptionName(HashMap<char, String>& output,
String optionName) {
912 const char shortOptionName = optionName.front();
913 const auto [it, inserted] = output.try_emplace(shortOptionName, std::move(optionName));
916 const auto [newIt, newInserted] = output.try_emplace(shortOptionNameInOppositeCase, std::move(optionName));
919 output[shortOptionName] = {};
924template <
typename Options>
925inline void addShortOptionNames(HashMap<char, String>& output,
StringView namePrefix) {
928 String optionName = formatArgumentName(namePrefix, name);
929 if constexpr (detail::is_vector_argument_v<T>) {
930 if constexpr (detail::vector_argument_size_v<T> == 1) {
931 addShortOptionName(output, std::move(optionName) +
"-x");
932 }
else if constexpr (detail::vector_argument_size_v<T> == 2) {
933 addShortOptionName(output, optionName +
"-x");
934 addShortOptionName(output, std::move(optionName) +
"-y");
935 }
else if constexpr (detail::vector_argument_size_v<T> == 3) {
936 addShortOptionName(output, optionName +
"-x");
937 addShortOptionName(output, optionName +
"-y");
938 addShortOptionName(output, std::move(optionName) +
"-z");
939 }
else if constexpr (detail::vector_argument_size_v<T> == 4) {
940 addShortOptionName(output, optionName +
"-x");
941 addShortOptionName(output, optionName +
"-y");
942 addShortOptionName(output, optionName +
"-z");
943 addShortOptionName(output, std::move(optionName) +
"-w");
945 }
else if constexpr (aggregate<T>) {
946 addShortOptionNames<T>(output, std::move(optionName) +
"-");
948 addShortOptionName(output, std::move(optionName));
954template <
typename Options>
955[[nodiscard]]
inline HashMap<char, String> getShortOptionNameMap() {
956 HashMap<char, String> result{};
957 addShortOptionNames<Options>(result, {});
958 erase_if(result, [](
const auto& kv) ->
bool {
return kv.second.empty(); });
962template <
typename Option>
963inline void trySetImplicitBooleanOption(
bool& foundSpecifiedOption,
StringView specifiedOptionName, Option& outputOption,
const String& optionName,
964 const CommandLineParserOptions& options) {
965 if (foundSpecifiedOption) {
968 if (optionName == specifiedOptionName) {
969 using T = std::remove_cvref_t<Option>;
970 if constexpr (boolean_argument<T>) {
972 foundSpecifiedOption =
true;
974 throw InvalidOptionValue{
formatString(
"Option {}{} requires an argument.", options.longOptionPrefix, optionName)};
979[[nodiscard]]
inline bool findAndSetImplicitBooleanOption(
StringView specifiedOptionName,
auto& outputOptions,
StringView namePrefix,
const CommandLineParserOptions& options) {
980 bool foundSpecifiedOption =
false;
983 String optionName = formatArgumentName(namePrefix, name);
984 using T = std::remove_cvref_t<
decltype(outputOption)>;
985 if constexpr (detail::is_vector_argument_v<T>) {
986 if constexpr (detail::vector_argument_size_v<T> == 1) {
987 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.x, std::move(optionName) +
"-x", options);
988 }
else if constexpr (detail::vector_argument_size_v<T> == 2) {
989 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.x, optionName +
"-x", options);
990 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.y, std::move(optionName) +
"-y", options);
991 }
else if constexpr (detail::vector_argument_size_v<T> == 3) {
992 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.x, optionName +
"-x", options);
993 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.y, optionName +
"-y", options);
994 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.z, std::move(optionName) +
"-z", options);
995 }
else if constexpr (detail::vector_argument_size_v<T> == 4) {
996 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.x, optionName +
"-x", options);
997 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.y, optionName +
"-y", options);
998 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.z, optionName +
"-z", options);
999 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption.w, std::move(optionName) +
"-w", options);
1001 }
else if constexpr (aggregate<T>) {
1002 foundSpecifiedOption = foundSpecifiedOption || findAndSetImplicitBooleanOption(specifiedOptionName, outputOption, std::move(optionName) +
"-", options);
1004 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption, optionName, options);
1008 return foundSpecifiedOption;
1014 }
catch (
const std::invalid_argument& e) {
1015 throw InvalidArgument{
formatString(
"Invalid {} value \"{}\": {}", name, argument, e.what())};
1019template <
typename Option>
1021 size_t& argumentIndex,
const String& optionName,
const CommandLineParserOptions& options) {
1022 if (foundSpecifiedOption) {
1025 if (optionName == specifiedOptionName) {
1026 using T = std::remove_cvref_t<Option>;
1027 if constexpr (boolean_argument<T>) {
1028 if (!specifiedOptionValue.empty()) {
1029 parseOptionValueOrThrow(outputOption, specifiedOptionValue, optionName);
1030 }
else if (!options.useImplicitBooleanValues || outputOption) {
1031 if (argumentIndex + 1 >= command.size()) {
1032 throw InvalidOptionValue{
formatString(
"Option {}{} requires an argument.", options.longOptionPrefix, optionName)};
1035 parseOptionValueOrThrow(outputOption, command[argumentIndex], optionName);
1037 outputOption =
true;
1039 }
else if constexpr (optional_argument<T>) {
1040 if (!specifiedOptionValue.empty()) {
1041 parseOptionValueOrThrow(outputOption.emplace(), specifiedOptionValue, optionName);
1043 if (argumentIndex + 1 >= command.size()) {
1044 throw InvalidOptionValue{
formatString(
"Option {}{} requires an argument.", options.longOptionPrefix, optionName)};
1047 parseOptionValueOrThrow(outputOption.emplace(), command[argumentIndex], optionName);
1050 if (!specifiedOptionValue.empty()) {
1051 parseOptionValueOrThrow(outputOption, specifiedOptionValue, optionName);
1053 if (argumentIndex + 1 >= command.size()) {
1054 throw InvalidOptionValue{
formatString(
"Option {}{} requires an argument.", options.longOptionPrefix, optionName)};
1057 parseOptionValueOrThrow(outputOption, command[argumentIndex], optionName);
1060 foundSpecifiedOption =
true;
1065 size_t& argumentIndex,
StringView namePrefix,
const CommandLineParserOptions& options) {
1066 bool foundSpecifiedOption =
false;
1068 String optionName = formatArgumentName(namePrefix, name);
1069 using T = std::remove_cvref_t<
decltype(outputOption)>;
1070 if constexpr (detail::is_vector_argument_v<T>) {
1071 if constexpr (detail::vector_argument_size_v<T> == 1) {
1072 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, specifiedOptionValue, outputOption.x, command, argumentIndex,
1073 std::move(optionName) +
"-x", options);
1074 }
else if constexpr (detail::vector_argument_size_v<T> == 2) {
1075 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.x, command, argumentIndex, optionName +
"-x", options);
1076 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.y, command, argumentIndex, std::move(optionName) +
"-y", options);
1077 }
else if constexpr (detail::vector_argument_size_v<T> == 3) {
1078 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.x, command, argumentIndex, optionName +
"-x", options);
1079 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.y, command, argumentIndex, optionName +
"-y", options);
1080 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.z, command, argumentIndex, std::move(optionName) +
"-z", options);
1081 }
else if constexpr (detail::vector_argument_size_v<T> == 4) {
1082 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.x, command, argumentIndex, optionName +
"-x", options);
1083 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.y, command, argumentIndex, optionName +
"-y", options);
1084 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.z, command, argumentIndex, optionName +
"-z", options);
1085 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption.w, command, argumentIndex, std::move(optionName) +
"-w", options);
1087 }
else if constexpr (aggregate<T>) {
1088 foundSpecifiedOption = foundSpecifiedOption ||
1089 findOptionAndParseValue(specifiedOptionName, specifiedOptionValue, outputOption, command, argumentIndex, std::move(optionName) +
"-", options);
1091 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption, command, argumentIndex, optionName, options);
1094 return foundSpecifiedOption;
1100 }
catch (
const std::invalid_argument& e) {
1101 throw InvalidArgument{
formatString(
"Invalid {} argument \"{}\": {}", formatArgumentName(namePrefix, fieldName), argument, e.what())};
1105template <
typename Argument>
1107 size_t trailingArgumentCount) {
1108 using T = std::remove_cvref_t<Argument>;
1109 if constexpr (optional_argument<T>) {
1110 if (arguments.size() - argumentIndex > trailingArgumentCount) {
1111 parseArgumentValueOrThrow(outputArgument.emplace(), arguments[argumentIndex++], namePrefix, fieldName);
1113 }
else if constexpr (list_argument<T>) {
1114 while (arguments.size() - argumentIndex > trailingArgumentCount) {
1115 parseArgumentValueOrThrow(outputArgument.emplace_back(), arguments[argumentIndex++], namePrefix, fieldName);
1117 }
else if constexpr (array_argument<T>) {
1118 const size_t size = std::size(outputArgument);
1119 GREM_ASSERT(arguments.size() - argumentIndex >= size);
1120 for (
size_t i = 0; i < size; ++i) {
1121 parseArgumentValueOrThrow(outputArgument[i], arguments[argumentIndex++], namePrefix, fieldName);
1124 GREM_ASSERT(arguments.size() - argumentIndex > 0);
1125 parseArgumentValueOrThrow(outputArgument, arguments[argumentIndex++], namePrefix, fieldName);
1129inline void parseArguments(
auto& outputArguments,
Span<const CStringView> arguments,
size_t& argumentIndex,
StringView namePrefix,
size_t trailingArgumentCount) {
1131 using T = std::remove_cvref_t<
decltype(outputArgument)>;
1132 if constexpr (detail::is_vector_argument_v<T>) {
1133 const String innerNamePrefix = formatArgumentName(namePrefix, name) +
"-";
1134 if constexpr (detail::vector_argument_size_v<T> == 1) {
1135 parseArgument(outputArgument.x, arguments, argumentIndex, innerNamePrefix,
"x");
1136 }
else if constexpr (detail::vector_argument_size_v<T> == 2) {
1137 parseArgument(outputArgument.x, arguments, argumentIndex, innerNamePrefix,
"x");
1138 parseArgument(outputArgument.y, arguments, argumentIndex, innerNamePrefix,
"y");
1139 }
else if constexpr (detail::vector_argument_size_v<T> == 3) {
1140 parseArgument(outputArgument.x, arguments, argumentIndex, innerNamePrefix,
"x");
1141 parseArgument(outputArgument.y, arguments, argumentIndex, innerNamePrefix,
"y");
1142 parseArgument(outputArgument.z, arguments, argumentIndex, innerNamePrefix,
"z");
1143 }
else if constexpr (detail::vector_argument_size_v<T> == 4) {
1144 parseArgument(outputArgument.x, arguments, argumentIndex, innerNamePrefix,
"x");
1145 parseArgument(outputArgument.y, arguments, argumentIndex, innerNamePrefix,
"y");
1146 parseArgument(outputArgument.z, arguments, argumentIndex, innerNamePrefix,
"z");
1147 parseArgument(outputArgument.w, arguments, argumentIndex, innerNamePrefix,
"w");
1149 }
else if constexpr (aggregate<T>) {
1150 parseArguments(outputArgument, arguments, argumentIndex, formatArgumentName(namePrefix, name) +
"-", trailingArgumentCount);
1152 parseArgument(outputArgument, arguments, argumentIndex, namePrefix, name, trailingArgumentCount);
1179template <aggregate Arguments, aggregate Options>
1183 if (command.
empty()) {
1184 throw InvalidUsage{detail::formatUsageString<Arguments, Options>(
"command", options)};
1187 const bool enableShortOptions = !options.shortOptionPrefix.empty() && options.shortOptionPrefix != options.longOptionPrefix;
1188 const HashMap<char, String> shortOptionNameMap = (enableShortOptions) ? detail::getShortOptionNameMap<Options>() : HashMap<char, String>{};
1190 if (options.enableHelpOption) {
1192 if ((argument.starts_with(options.longOptionPrefix) && argument.substr(options.longOptionPrefix.size()) ==
"help") ||
1193 (enableShortOptions && argument.starts_with(options.shortOptionPrefix) && argument.substr(options.shortOptionPrefix.size()) ==
"?") ||
1194 (!enableShortOptions && options.longOptionPrefix ==
"-" && argument ==
"--help")) {
1195 throw Help{detail::formatHelpString<Arguments, Options>(command.
front(), shortOptionNameMap, options)};
1200 ArrayList<CStringView> arguments{};
1201 ArrayList<CStringView> extraArguments{};
1202 arguments.reserve(command.
size() - 1);
1205 HashSet<String> optionsSpecified{};
1206 for (
size_t argumentIndex = 1; argumentIndex < command.
size(); ++argumentIndex) {
1207 const CStringView argument = command[argumentIndex];
1208 if (!options.extraArgumentsSeparator.empty() && argument == options.extraArgumentsSeparator) {
1209 extraArguments.assign(command.
begin() + argumentIndex + 1, command.
end());
1213 const auto throwUnknownOptionError = [&]() ->
void {
1214 if (options.enableHelpOption) {
1222 if (argument.starts_with(options.longOptionPrefix)) {
1223 const CStringView argumentWithoutPrefix = argument.
substr(options.longOptionPrefix.size());
1224 specifiedOptionName = argumentWithoutPrefix;
1225 if (options.allowEqualsValueSyntax) {
1226 if (
const size_t equalsPosition = specifiedOptionName.find(
'='); equalsPosition != StringView::npos) {
1227 if (equalsPosition + 1 == specifiedOptionName.size()) {
1230 specifiedOptionValue = argumentWithoutPrefix.substr(equalsPosition + 1);
1231 specifiedOptionName = specifiedOptionName.substr(0, equalsPosition);
1234 if (specifiedOptionName.empty()) {
1235 throwUnknownOptionError();
1237 }
else if (enableShortOptions && argument.starts_with(options.shortOptionPrefix)) {
1238 const CStringView argumentWithoutPrefix = argument.
substr(options.shortOptionPrefix.size());
1239 specifiedOptionName = argumentWithoutPrefix;
1240 if (options.allowEqualsValueSyntax) {
1241 if (
const size_t equalsPosition = specifiedOptionName.find(
'='); equalsPosition != StringView::npos) {
1242 if (equalsPosition + 1 == specifiedOptionName.size()) {
1245 specifiedOptionValue = argumentWithoutPrefix.substr(equalsPosition + 1);
1246 specifiedOptionName = specifiedOptionName.substr(0, equalsPosition);
1249 if (specifiedOptionName.empty()) {
1250 throwUnknownOptionError();
1252 if (specifiedOptionName.size() == 1) {
1253 const char shortOptionName = specifiedOptionName.front();
1254 const auto it = shortOptionNameMap.find(shortOptionName);
1255 if (it == shortOptionNameMap.end()) {
1256 throwUnknownOptionError();
1258 specifiedOptionName = it->second;
1260 const bool allowShortOptionGrouping = enableShortOptions && options.useImplicitBooleanValues && options.allowShortOptionGrouping;
1261 if (!allowShortOptionGrouping) {
1262 throwUnknownOptionError();
1264 for (
const char shortOptionName : specifiedOptionName) {
1265 const auto it = shortOptionNameMap.find(shortOptionName);
1266 if (it == shortOptionNameMap.end()) {
1267 throwUnknownOptionError();
1269 if (!optionsSpecified.emplace(it->second).second) {
1272 if (detail::findAndSetImplicitBooleanOption(it->second, outputOptions, {}, options)) {
1273 if (!specifiedOptionValue.empty()) {
1277 throwUnknownOptionError();
1284 if (specifiedOptionName.empty()) {
1285 arguments.push_back(argument);
1287 if (!optionsSpecified.emplace(specifiedOptionName).second) {
1290 if (!detail::findOptionAndParseValue(specifiedOptionName, specifiedOptionValue, outputOptions, command, argumentIndex, {}, options)) {
1291 throwUnknownOptionError();
1296 for (
size_t argumentIndex = 1; argumentIndex < command.
size(); ++argumentIndex) {
1297 const CStringView argument = command[argumentIndex];
1298 if (!options.extraArgumentsSeparator.empty() && argument == options.extraArgumentsSeparator) {
1299 extraArguments.assign(command.
begin() + argumentIndex + 1, command.
end());
1302 arguments.push_back(argument);
1307 const detail::ArgumentCounts argumentCounts = detail::getArgumentCounts(outputArguments);
1308 if (arguments.size() < argumentCounts.leadingArgumentCount + argumentCounts.trailingArgumentCount || arguments.size() > argumentCounts.maxArgumentCount) {
1309 throw InvalidUsage{detail::formatUsageString<Arguments, Options>(command.
front(), options)};
1312 size_t argumentIndex = 0;
1313 detail::parseArguments(outputArguments, arguments, argumentIndex, {}, argumentCounts.trailingArgumentCount);
1315 if (!arguments.empty()) {
1316 throw InvalidUsage{detail::formatUsageString<Arguments, Options>(command.
front(), options)};
1320 return extraArguments;
1345template <aggregate Arguments, aggregate Options>
1369template <aggregate Arguments>
1372 detail::NoOptions outputOptions{};
1396template <aggregate Arguments>
1399 detail::NoOptions outputOptions{};
1400 return parseCommandLine(outputArguments, outputOptions, argc, argv, options);
1421template <aggregate Options>
1424 detail::NoArguments outputArguments{};
1448template <aggregate Options>
1451 detail::NoArguments outputArguments{};
1452 return parseCommandLine(outputArguments, outputOptions, argc, argv, options);
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Definition ArrayList.hpp:27
GREM_ALWAYS_INLINE constexpr const_reference front() const
Definition CStringView.hpp:114
GREM_ALWAYS_INLINE constexpr const_pointer data() const noexcept
Definition CStringView.hpp:124
GREM_ALWAYS_INLINE constexpr CStringViewBase substr(size_type pos=0) const
Definition CStringView.hpp:166
GREM_ALWAYS_INLINE constexpr size_type size() const noexcept
Definition CStringView.hpp:132
GREM_ALWAYS_INLINE constexpr const_pointer c_str() const noexcept
Definition CStringView.hpp:128
Base exception type for runtime errors.
Definition Error.hpp:38
Error(CStringView message)
Definition Error.hpp:55
constexpr reference front() const noexcept
Definition Span.hpp:261
constexpr bool empty() const noexcept
Definition Span.hpp:257
constexpr detail::subspan_type_t< T, EXTENT, Offset, N > subspan() const
Definition Span.hpp:284
constexpr iterator end() const noexcept
Definition Span.hpp:219
constexpr size_type size() const noexcept
Definition Span.hpp:207
constexpr iterator begin() const noexcept
Definition Span.hpp:211
decltype(auto) emplace_back()
Definition command_line_interface.hpp:328
constexpr ~Proxy()=default
Proxy(const Proxy &)=delete
decltype(auto) value() const
Definition command_line_interface.hpp:323
decltype(auto) emplace()
Definition command_line_interface.hpp:308
bool has_value() const noexcept
Definition command_line_interface.hpp:313
Proxy & operator=(Proxy &&)=delete
decltype(auto) back() const
Definition command_line_interface.hpp:338
decltype(auto) size() const noexcept
Definition command_line_interface.hpp:343
constexpr Proxy() noexcept=default
decltype(auto) back()
Definition command_line_interface.hpp:333
Proxy & operator=(const Proxy &)=delete
void reset() noexcept
Definition command_line_interface.hpp:303
decltype(auto) value()
Definition command_line_interface.hpp:318
Definition concepts.hpp:144
Definition concepts.hpp:67
Definition concepts.hpp:106
Definition concepts.hpp:79
constexpr bool isUppercase(char ch) noexcept
Check if a character is an uppercase ASCII letter (A-Z).
Definition ascii.hpp:87
constexpr char convertToOppositeCaseCharacter(char ch) noexcept
Convert a character to its opposite case if it is an ASCII letter.
Definition ascii.hpp:186
constexpr bool caseInsensitiveEqual(char a, char b) noexcept
Check if two characters are equal if any ASCII letters are treated as the same case,...
Definition ascii.hpp:287
constexpr bool isLowercase(char ch) noexcept
Check if a character is a lowercase ASCII letter (a-z).
Definition ascii.hpp:98
constexpr char convertUppercaseToLowercaseCharacter(char ch)
Convert an uppercase ASCII letter (A-Z) to its corresponding lowercase ASCII letter (a-z).
Definition ascii.hpp:132
Definition aliases.hpp:13
ArrayList< CStringView > parseCommandLineOptions(Options &outputOptions, Span< const CStringView > command, const CommandLineParserOptions &options={})
Parse a command line into options.
Definition command_line_interface.hpp:1422
ArrayList< CStringView > parseCommandLineArguments(Arguments &outputArguments, Span< const CStringView > command, const CommandLineParserOptions &options={})
Parse a command line into arguments.
Definition command_line_interface.hpp:1370
void parseArgumentValue(T &output, CStringView argument)
Parse a command line argument into a boolean value.
Definition command_line_interface.hpp:433
ArrayList< CStringView > parseCommandLine(Arguments &outputArguments, Options &outputOptions, Span< const CStringView > command, const CommandLineParserOptions &options={})
Parse a command line into arguments and options.
Definition command_line_interface.hpp:1180
@ N
'n'
Definition keyboard.hpp:84
@ T
't'
Definition keyboard.hpp:90
ObjectBase< Allocator >::size_type erase_if(ObjectBase< Allocator > &container, Predicate predicate)
Definition json.hpp:7890
constexpr auto count(input_range auto &&range, const auto &value)
Definition algorithms.hpp:234
std::ratio< Num, Den > Ratio
Definition time.hpp:19
String formatString(FormatString< Args... > format, const Args &... args)
Format specification syntax examples:
Definition formatting.hpp:448
Span(R &&range) -> Span< std::remove_reference_t< decltype(*std::data(range))> >
std::chrono::duration< Rep, Period > DurationBase
Definition time.hpp:39
void unreachable()
Definition assertions.hpp:125
StringBase< char, std::char_traits< char >, std::allocator< char > > String
Definition String.hpp:17
StringViewBase< char, std::char_traits< char > > StringView
Definition StringView.hpp:16
CStringViewBase< char, std::char_traits< char > > CStringView
Definition CStringView.hpp:635
static constexpr T MAX
Definition fundamentals.hpp:29
Configuration options for command line parsing.
Definition command_line_interface.hpp:365
bool enableHelpOption
Throw an error with a help string for the user if the "help" option is supplied.
Definition command_line_interface.hpp:419
StringView shortOptionPrefix
Argument prefix that distinguishes short, single-character options from regular arguments.
Definition command_line_interface.hpp:372
StringView extraArgumentsSeparator
Argument that separates the main arguments of the command from any extra trailing arguments.
Definition command_line_interface.hpp:388
bool allowEqualsValueSyntax
Allow option values to be specified using option=value syntax as a single argument,...
Definition command_line_interface.hpp:413
bool useImplicitBooleanValues
Don't take explicit values for boolean options whose default values are false, and instead interpret ...
Definition command_line_interface.hpp:398
bool allowShortOptionGrouping
Allow short, single-character boolean options to be grouped into a single argument.
Definition command_line_interface.hpp:407
StringView longOptionPrefix
Argument prefix that distinguishes long, multi-character options from regular arguments.
Definition command_line_interface.hpp:380
Base exception type for errors originating from the command line interface.
Definition command_line_interface.hpp:205
Error(CStringView message)
Definition Error.hpp:55
Exception type thrown by the command line interface containing a help string that was requested by th...
Definition command_line_interface.hpp:213
Exception type thrown by the command line interface when an invalid argument value was provided.
Definition command_line_interface.hpp:229
Exception type thrown by the command line interface when an invalid option value was provided.
Definition command_line_interface.hpp:245
Exception type thrown by the command line interface when an incorrect number of arguments were provid...
Definition command_line_interface.hpp:221
Exception type thrown by the command line interface when an unknown option was specified.
Definition command_line_interface.hpp:237