GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
command_line_interface.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_COMMAND_LINE_INTERFACE_HPP
5#define GREM_CORE_COMMAND_LINE_INTERFACE_HPP
6
8
9#include <GREM/core/Error.hpp>
23#include <GREM/core/math.hpp>
25#include <GREM/core/time.hpp>
26
27#include <charconv> // std::from_chars_result, std::from_chars
28#include <cstdio> // std::sscanf
29#include <iterator> // std::size
30#include <stdexcept> // std::invalid_argument
31#include <system_error> // std::errc
32#include <type_traits> // std::remove_cvref_t, std::false_type, std::true_type, std::bool_constant, std::integral_constant
33#include <utility> // std::move, std::forward, std::declval
34
35namespace grem::cli {
36
37namespace detail {
38
39template <typename T>
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&>;
42
43template <typename 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&>;
48
49template <typename T>
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&>;
52
53template <typename T>
54concept optional_argument = requires(T t) {
55 t.reset();
56 t.emplace();
57 t.has_value();
58 t.value();
59};
60
61template <typename 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>;
66
67template <typename 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>);
71
72template <typename T>
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>);
76
77template <typename T>
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>);
86
87template <typename T>
88concept character_argument = convertible_to_character_reference<T> || (requires(T t, const char value) {
89 static_cast<char>(t);
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>);
97
98template <typename 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>);
103
104template <typename T>
105concept boolean_argument =
106 requires(T t, const bool value) {
107 static_cast<bool>(t);
108 t = value;
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>);
115
116template <typename T>
117concept list_argument = requires(T t) {
118 t.emplace_back();
119 t.back();
120} && !string_argument<T>;
121
122template <typename T>
123concept array_argument = requires(T t, const size_t index) {
124 t[index];
125 std::size(t);
126} && !string_argument<T> && !list_argument<T>;
127
128template <typename T>
129concept duration_argument = requires {
130 typename T::rep;
131 typename T::period;
132};
133
134template <typename T>
135[[nodiscard]] constexpr auto& getIntegerReference(T& value) noexcept {
136 if constexpr (integral<T>) {
137 return value;
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);
154 } else {
155 unreachable();
156 }
157}
158
159template <typename T>
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);
171 } else {
172 unreachable();
173 }
174}
175
176template <typename T>
177struct is_vector_argument : std::false_type {};
178
179template <size_t N, typename T>
180struct is_vector_argument<vec<N, T>> : std::true_type {};
181
182template <quantity_argument Quantity>
183struct is_vector_argument<Quantity> : std::bool_constant<Quantity::RANK >= 2> {};
184
185template <typename T>
186inline constexpr bool is_vector_argument_v = is_vector_argument<T>::value;
187
188template <typename T>
189struct vector_argument_size;
190
191template <size_t N, typename T>
192struct vector_argument_size<vec<N, T>> : std::integral_constant<size_t, N> {};
193
194template <quantity_argument Quantity>
195struct vector_argument_size<Quantity> : std::integral_constant<size_t, Quantity::RANK> {};
196
197template <typename T>
198inline constexpr size_t vector_argument_size_v = vector_argument_size<T>::value;
199
200} // namespace detail
201
206 using grem::Error::Error;
207};
208
213struct Help : cli::Error {
214 using cli::Error::Error;
215};
216
222 using cli::Error::Error;
223};
224
230 using cli::Error::Error;
231};
232
238 using cli::Error::Error;
239};
240
248
252template <typename T>
253class Proxy {
254public:
255 constexpr Proxy() noexcept = default;
256
257 constexpr Proxy(T& reference) noexcept
258 : pointer(&reference) {}
259
260 constexpr ~Proxy() = default;
261
262 Proxy(const Proxy&) = delete;
263 Proxy(Proxy&&) = delete;
264 Proxy& operator=(Proxy&&) = delete;
265 Proxy& operator=(const Proxy&) = delete;
266
267 template <typename Arg>
268 decltype(auto) operator=(Arg&& arg) // NOLINT(cppcoreguidelines-c-copy-assignment-signature, misc-unconventional-assign-operator)
269 requires(requires(T t) { t = std::forward<Arg>(arg); }) {
271#ifdef __clang__
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"
279#endif
280 return *pointer = std::forward<Arg>(arg);
281#ifdef __clang__
282#pragma clang diagnostic pop
283#elif defined(__GNUC__)
284#pragma GCC diagnostic pop
285#endif
286 }
287
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);
291 }
292
293 operator T&() noexcept {
295 return *pointer;
296 }
297
298 operator const T&() const noexcept {
300 return *pointer;
301 }
302
303 void reset() noexcept requires(requires(T t) { t.reset(); }) {
305 pointer->reset();
306 }
307
308 decltype(auto) emplace() requires(requires(T t) { t.emplace(); }) {
310 return pointer->emplace();
311 }
312
313 [[nodiscard]] bool has_value() const noexcept requires(requires(const T t) { t.has_value(); }) {
315 return pointer->has_value();
316 }
317
318 [[nodiscard]] decltype(auto) value() requires(requires(T t) { t.value(); }) {
320 return pointer->value();
321 }
322
323 [[nodiscard]] decltype(auto) value() const requires(requires(const T t) { t.value(); }) {
325 return pointer->value();
326 }
327
328 [[nodiscard]] decltype(auto) emplace_back() requires(requires(T t) { t.emplace_back(); }) {
330 return pointer->emplace_back();
331 }
332
333 [[nodiscard]] decltype(auto) back() requires(requires(T t) { t.back(); }) {
335 return pointer->back();
336 }
337
338 [[nodiscard]] decltype(auto) back() const requires(requires(const T t) { t.back(); }) {
340 return pointer->back();
341 }
342
343 [[nodiscard]] decltype(auto) size() const noexcept requires(requires(const T t) { std::size(t); }) {
345 return std::size(*pointer);
346 }
347
348 [[nodiscard]] decltype(auto) operator[](size_t index) requires(requires(T t, const size_t i) { t[i]; }) {
350 return (*pointer)[index];
351 }
352
353 [[nodiscard]] decltype(auto) operator[](size_t index) const requires(requires(const T t, const size_t i) { t[i]; }) {
355 return (*pointer)[index];
356 }
357
358private:
359 T* pointer = nullptr;
360};
361
421
432template <detail::boolean_argument T>
433inline void parseArgumentValue(T& output, CStringView argument) {
434 if (argument == "1" || ascii::caseInsensitiveEqual(argument, "true") || ascii::caseInsensitiveEqual(argument, "on") || ascii::caseInsensitiveEqual(argument, "y") ||
435 ascii::caseInsensitiveEqual(argument, "yes")) {
436 output = true;
437 } else if (argument == "0" || ascii::caseInsensitiveEqual(argument, "false") || ascii::caseInsensitiveEqual(argument, "off") || ascii::caseInsensitiveEqual(argument, "n") ||
438 ascii::caseInsensitiveEqual(argument, "no")) {
439 output = false;
440 } else {
441 throw std::invalid_argument{"Expected a boolean value (true/false)."};
442 }
443}
444
455template <detail::integer_argument T>
456inline void parseArgumentValue(T& output, CStringView argument) {
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."};
463 } else {
464 throw std::invalid_argument{"Expected an integer."};
465 }
466 }
467 } else {
468 int64_t value = 0;
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."};
472 }
473 output = static_cast<T>(value);
474 }
475}
476
487template <detail::character_argument T>
488inline void parseArgumentValue(T& output, CStringView argument) {
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."};
494 }
495 memcpy(&characterReference, argument.data(), sizeof(X));
496 } else {
497 if (argument.size() != 1) {
498 throw std::invalid_argument{"Expected a character."};
499 }
500 output = static_cast<T>(argument.front());
501 }
502}
503
514template <detail::float_argument T>
515inline void parseArgumentValue(T& output, CStringView argument) {
516 float value = 0.0f;
517#ifdef __clang__
518#pragma clang diagnostic push
519#pragma clang diagnostic ignored "-Wdeprecated-declarations"
520#endif
521 if (std::sscanf(argument.c_str(), "%f", &value) != 1) {
522 throw std::invalid_argument{"Expected a number."};
523 }
524#ifdef __clang__
525#pragma clang diagnostic pop
526#endif
527 output = value;
528}
529
540template <detail::double_argument T>
541inline void parseArgumentValue(T& output, CStringView argument) {
542 double value = 0.0;
543#ifdef __clang__
544#pragma clang diagnostic push
545#pragma clang diagnostic ignored "-Wdeprecated-declarations"
546#endif
547 if (std::sscanf(argument.c_str(), "%lf", &value) != 1) {
548 throw std::invalid_argument{"Expected a number."};
549 }
550#ifdef __clang__
551#pragma clang diagnostic pop
552#endif
553 output = value;
554}
555
567template <detail::quantity_argument T>
568inline void parseArgumentValue(T& output, CStringView argument) {
569 float value = 0.0f;
570#ifdef __clang__
571#pragma clang diagnostic push
572#pragma clang diagnostic ignored "-Wdeprecated-declarations"
573#endif
574 if (std::sscanf(argument.c_str(), "%f", &value) != 1) {
575 throw std::invalid_argument{"Expected a number."};
576 }
577#ifdef __clang__
578#pragma clang diagnostic pop
579#endif
580 output = T::reinterpret(value);
581}
582
591template <detail::string_argument T>
592inline void parseArgumentValue(T& output, CStringView argument) {
593 output = argument.c_str();
594}
595
605template <typename Rep, typename Period>
607 double milliseconds{};
608 parseArgumentValue(milliseconds, argument);
609 output = duration_cast<DurationBase<Rep, Period>>(DurationBase<double, Ratio<1, 1'000>>{milliseconds});
610}
611
612namespace detail {
613
614struct NoArguments {};
615struct NoOptions {};
616
617struct ArgumentCounts {
618 size_t leadingArgumentCount = 0;
619 size_t trailingArgumentCount = 0;
620 size_t maxArgumentCount = 0;
621};
622
623template <typename Arguments>
624[[nodiscard]] inline ArgumentCounts getArgumentCounts(const Arguments& outputArguments) {
625 ArgumentCounts result{};
626 meta::forEachField(outputArguments, [&]<typename T>(const T& argument) -> void {
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;
632 } else {
633 ++result.trailingArgumentCount;
634 if (result.maxArgumentCount != Limits<size_t>::MAX) {
635 ++result.maxArgumentCount;
636 }
637 }
638 }
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;
646 } else {
647 result.trailingArgumentCount += size;
648 if (result.maxArgumentCount != Limits<size_t>::MAX) {
649 result.maxArgumentCount += size;
650 }
651 }
652 } else if (nestedArgumentCounts.maxArgumentCount == Limits<size_t>::MAX) {
653 GREM_ASSERT(result.leadingArgumentCount == result.maxArgumentCount && "Command line may only contain one range of optional arguments.");
654 result.maxArgumentCount = Limits<size_t>::MAX;
655 } else {
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;
661 }
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.");
667 result.maxArgumentCount = Limits<size_t>::MAX;
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;
673 } else {
674 result.trailingArgumentCount += size;
675 if (result.maxArgumentCount != Limits<size_t>::MAX) {
676 result.maxArgumentCount += size;
677 }
678 }
679 } else {
680 if (result.leadingArgumentCount == result.maxArgumentCount) {
681 ++result.leadingArgumentCount;
682 ++result.maxArgumentCount;
683 } else {
684 ++result.trailingArgumentCount;
685 if (result.maxArgumentCount != Limits<size_t>::MAX) {
686 ++result.maxArgumentCount;
687 }
688 }
689 }
690 });
691 return result;
692}
693
694[[nodiscard]] inline String formatArgumentName(StringView namePrefix, StringView fieldName) {
695 String result{};
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) {
700 if (const char ch = fieldName[i]; ascii::isUppercase(ch)) {
701 if (i != 0) {
702 if (ascii::isUppercase(fieldName[i - 1])) {
703 inUppercaseSequence = true;
704 } else if (ascii::isLowercase(fieldName[i - 1])) {
705 result.push_back('-');
706 }
707 }
709 } else {
710 if (inUppercaseSequence) {
711 inUppercaseSequence = false;
712 result.push_back('-');
713 }
714 if ((ch != '-' && ch != '_') || result.empty() || result.back() != '-') {
715 if (ch == '_') {
716 result.push_back('-');
717 } else {
718 result.push_back(ch);
719 }
720 }
721 }
722 }
723 return result;
724}
725
726template <typename T>
727[[nodiscard]] inline String formatArgumentTypeName() {
728 if constexpr (boolean_argument<T>) {
729 return "boolean";
730 } else if constexpr (character_argument<T>) {
731 return "character";
732 } else if constexpr (integer_argument<T>) {
733 return "integer";
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>) {
738 return "number";
739 } else if constexpr (string_argument<T>) {
740 return "string";
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";
749 } else {
751 String result{};
752 result.reserve(typeName.size() + typeName.size() / 4);
753 bool inUppercaseSequence = false;
754 for (size_t i = 0; i < typeName.size(); ++i) {
755 if (const char ch = typeName[i]; ascii::isUppercase(ch)) {
756 if (i != 0) {
757 if (ascii::isUppercase(typeName[i - 1])) {
758 inUppercaseSequence = true;
759 } else if (ascii::isLowercase(typeName[i - 1])) {
760 result.push_back(' ');
761 }
762 }
764 } else {
765 if (inUppercaseSequence) {
766 inUppercaseSequence = false;
767 result.push_back(' ');
768 }
769 if ((ch != ' ' && ch != '_') || result.empty() || result.back() != ' ') {
770 if (ch == '_') {
771 result.push_back(' ');
772 } else {
773 result.push_back(ch);
774 }
775 }
776 }
777 }
778 return result;
779 }
780}
781
782template <typename Arguments>
783inline void appendArgumentsUsage(String& output, StringView namePrefix) {
784 meta::forEachNamedFieldType<Arguments>([&]<typename T>(StringView name, meta::Type<T>) -> void {
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) {
788 output.append(formatString(" <{}-x>", argumentName));
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));
795 }
796 } else if constexpr (aggregate<T>) {
797 appendArgumentsUsage<T>(output, argumentName + "-");
798 } else if constexpr (optional_argument<T>) {
799 output.append(formatString(" [{}]", argumentName));
800 } else if constexpr (list_argument<T>) {
801 output.append(formatString(" [{}...]", argumentName));
802 } else if constexpr (array_argument<T>) {
803 output.append(formatString(" <{}...>", argumentName));
804 } else {
805 output.append(formatString(" <{}>", argumentName));
806 }
807 });
808}
809
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...]");
815 }
816 appendArgumentsUsage<Arguments>(result, {});
817 if (!options.extraArgumentsSeparator.empty()) {
818 result.append(formatString(" [{} ...]", options.extraArgumentsSeparator));
819 }
820 return result;
821}
822
823template <typename T>
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>) {
828 return duration_cast<DurationBase<double, Ratio<1, 1'000>>>(value).count();
829 } else {
830 return value;
831 }
832}
833
834template <typename Option>
835inline void appendOptionHelp(String& output, const String& optionName, const Option& outputOption, const HashMap<char, String>& shortOptionNameMap,
836 const CommandLineParserOptions& options) {
837 String argumentString{};
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));
842 }
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()));
847 } else {
848 argumentString = formatString(" [{}] (default: null)", argumentTypeName);
849 }
850 } else {
851 argumentString = formatString(" <{}> (default: {})", formatArgumentTypeName<T>(), getDefaultArgumentValueForFormatting(outputOption));
852 }
853 const bool enableShortOptions = !options.shortOptionPrefix.empty() && options.shortOptionPrefix != options.longOptionPrefix;
854 if (enableShortOptions && !shortOptionNameMap.empty()) {
855 const char shortOptionName = optionName.front();
856 const char shortOptionNameInOppositeCase = ascii::convertToOppositeCaseCharacter(shortOptionName);
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));
861 } else {
862 output.append(formatString("\n {}{}{}", options.longOptionPrefix, optionName, argumentString));
863 }
864 } else {
865 output.append(formatString("\n {}{}{}", options.longOptionPrefix, optionName, argumentString));
866 }
867}
868
869inline void appendOptionsHelp(String& output, StringView namePrefix, const auto& defaultOptions, const HashMap<char, String>& shortOptionNameMap,
870 const CommandLineParserOptions& options) {
871 meta::forEachNamedField(defaultOptions, [&](StringView name, const auto& defaultOption) -> void {
872 if (!name.empty()) {
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);
890 }
891 } else if constexpr (aggregate<T>) {
892 appendOptionsHelp(output, std::move(optionName) + "-", defaultOption, shortOptionNameMap, options);
893 } else {
894 appendOptionHelp(output, optionName, defaultOption, shortOptionNameMap, options);
895 }
896 }
897 });
898}
899
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);
903 if constexpr (meta::aggregate_size_v<Options> > 0) {
904 const Options defaultOptions{};
905 result.append("\nOptions:");
906 appendOptionsHelp(result, {}, defaultOptions, shortOptionNameMap, options);
907 }
908 return result;
909}
910
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));
914 if (!inserted) {
915 const char shortOptionNameInOppositeCase = ascii::convertToOppositeCaseCharacter(shortOptionName);
916 const auto [newIt, newInserted] = output.try_emplace(shortOptionNameInOppositeCase, std::move(optionName));
917 if (!newInserted) {
918 newIt->second = {};
919 output[shortOptionName] = {};
920 }
921 }
922}
923
924template <typename Options>
925inline void addShortOptionNames(HashMap<char, String>& output, StringView namePrefix) {
926 meta::forEachNamedFieldType<Options>([&]<typename T>(StringView name, meta::Type<T>) -> void {
927 if (!name.empty()) {
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");
944 }
945 } else if constexpr (aggregate<T>) {
946 addShortOptionNames<T>(output, std::move(optionName) + "-");
947 } else {
948 addShortOptionName(output, std::move(optionName));
949 }
950 }
951 });
952}
953
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(); });
959 return result;
960}
961
962template <typename Option>
963inline void trySetImplicitBooleanOption(bool& foundSpecifiedOption, StringView specifiedOptionName, Option& outputOption, const String& optionName,
964 const CommandLineParserOptions& options) {
965 if (foundSpecifiedOption) {
966 return;
967 }
968 if (optionName == specifiedOptionName) {
969 using T = std::remove_cvref_t<Option>;
970 if constexpr (boolean_argument<T>) {
971 outputOption = true;
972 foundSpecifiedOption = true;
973 } else {
974 throw InvalidOptionValue{formatString("Option {}{} requires an argument.", options.longOptionPrefix, optionName)};
975 }
976 }
977}
978
979[[nodiscard]] inline bool findAndSetImplicitBooleanOption(StringView specifiedOptionName, auto& outputOptions, StringView namePrefix, const CommandLineParserOptions& options) {
980 bool foundSpecifiedOption = false;
981 meta::forEachNamedField(outputOptions, [&](StringView name, auto& outputOption) -> void {
982 if (!name.empty()) {
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);
1000 }
1001 } else if constexpr (aggregate<T>) {
1002 foundSpecifiedOption = foundSpecifiedOption || findAndSetImplicitBooleanOption(specifiedOptionName, outputOption, std::move(optionName) + "-", options);
1003 } else {
1004 trySetImplicitBooleanOption(foundSpecifiedOption, specifiedOptionName, outputOption, optionName, options);
1005 }
1006 }
1007 });
1008 return foundSpecifiedOption;
1009}
1010
1011inline void parseOptionValueOrThrow(auto& output, CStringView argument, StringView name) {
1012 try {
1013 parseArgumentValue(output, argument);
1014 } catch (const std::invalid_argument& e) {
1015 throw InvalidArgument{formatString("Invalid {} value \"{}\": {}", name, argument, e.what())};
1016 }
1017}
1018
1019template <typename Option>
1020inline void tryParseOptionValue(bool& foundSpecifiedOption, StringView specifiedOptionName, CStringView specifiedOptionValue, Option& outputOption, Span<const CStringView> command,
1021 size_t& argumentIndex, const String& optionName, const CommandLineParserOptions& options) {
1022 if (foundSpecifiedOption) {
1023 return;
1024 }
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)};
1033 }
1034 ++argumentIndex;
1035 parseOptionValueOrThrow(outputOption, command[argumentIndex], optionName);
1036 } else {
1037 outputOption = true;
1038 }
1039 } else if constexpr (optional_argument<T>) {
1040 if (!specifiedOptionValue.empty()) {
1041 parseOptionValueOrThrow(outputOption.emplace(), specifiedOptionValue, optionName);
1042 } else {
1043 if (argumentIndex + 1 >= command.size()) {
1044 throw InvalidOptionValue{formatString("Option {}{} requires an argument.", options.longOptionPrefix, optionName)};
1045 }
1046 ++argumentIndex;
1047 parseOptionValueOrThrow(outputOption.emplace(), command[argumentIndex], optionName);
1048 }
1049 } else {
1050 if (!specifiedOptionValue.empty()) {
1051 parseOptionValueOrThrow(outputOption, specifiedOptionValue, optionName);
1052 } else {
1053 if (argumentIndex + 1 >= command.size()) {
1054 throw InvalidOptionValue{formatString("Option {}{} requires an argument.", options.longOptionPrefix, optionName)};
1055 }
1056 ++argumentIndex;
1057 parseOptionValueOrThrow(outputOption, command[argumentIndex], optionName);
1058 }
1059 }
1060 foundSpecifiedOption = true;
1061 }
1062}
1063
1064[[nodiscard]] inline bool findOptionAndParseValue(StringView specifiedOptionName, CStringView specifiedOptionValue, auto& outputOptions, Span<const CStringView> command,
1065 size_t& argumentIndex, StringView namePrefix, const CommandLineParserOptions& options) {
1066 bool foundSpecifiedOption = false;
1067 meta::forEachNamedField(outputOptions, [&](StringView name, auto& outputOption) -> void {
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);
1086 }
1087 } else if constexpr (aggregate<T>) {
1088 foundSpecifiedOption = foundSpecifiedOption ||
1089 findOptionAndParseValue(specifiedOptionName, specifiedOptionValue, outputOption, command, argumentIndex, std::move(optionName) + "-", options);
1090 } else {
1091 tryParseOptionValue(foundSpecifiedOption, specifiedOptionName, specifiedOptionValue, outputOption, command, argumentIndex, optionName, options);
1092 }
1093 });
1094 return foundSpecifiedOption;
1095}
1096
1097inline void parseArgumentValueOrThrow(auto& output, CStringView argument, StringView namePrefix, StringView fieldName) {
1098 try {
1099 parseArgumentValue(output, argument);
1100 } catch (const std::invalid_argument& e) {
1101 throw InvalidArgument{formatString("Invalid {} argument \"{}\": {}", formatArgumentName(namePrefix, fieldName), argument, e.what())};
1102 }
1103}
1104
1105template <typename Argument>
1106inline void parseArgument(Argument& outputArgument, Span<const CStringView> arguments, size_t& argumentIndex, StringView namePrefix, StringView fieldName,
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);
1112 }
1113 } else if constexpr (list_argument<T>) {
1114 while (arguments.size() - argumentIndex > trailingArgumentCount) {
1115 parseArgumentValueOrThrow(outputArgument.emplace_back(), arguments[argumentIndex++], namePrefix, fieldName);
1116 }
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);
1122 }
1123 } else {
1124 GREM_ASSERT(arguments.size() - argumentIndex > 0);
1125 parseArgumentValueOrThrow(outputArgument, arguments[argumentIndex++], namePrefix, fieldName);
1126 }
1127}
1128
1129inline void parseArguments(auto& outputArguments, Span<const CStringView> arguments, size_t& argumentIndex, StringView namePrefix, size_t trailingArgumentCount) {
1130 meta::forEachNamedField(outputArguments, [&](StringView name, auto& outputArgument) -> void {
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");
1148 }
1149 } else if constexpr (aggregate<T>) {
1150 parseArguments(outputArgument, arguments, argumentIndex, formatArgumentName(namePrefix, name) + "-", trailingArgumentCount);
1151 } else {
1152 parseArgument(outputArgument, arguments, argumentIndex, namePrefix, name, trailingArgumentCount);
1153 }
1154 });
1155}
1156
1157} // namespace detail
1158
1179template <aggregate Arguments, aggregate Options>
1180ArrayList<CStringView> parseCommandLine(Arguments& outputArguments, Options& outputOptions, Span<const CStringView> command, const CommandLineParserOptions& options = {})
1182 GREM_ASSERT(!options.longOptionPrefix.empty());
1183 if (command.empty()) {
1184 throw InvalidUsage{detail::formatUsageString<Arguments, Options>("command", options)};
1185 }
1186
1187 const bool enableShortOptions = !options.shortOptionPrefix.empty() && options.shortOptionPrefix != options.longOptionPrefix;
1188 const HashMap<char, String> shortOptionNameMap = (enableShortOptions) ? detail::getShortOptionNameMap<Options>() : HashMap<char, String>{};
1189
1190 if (options.enableHelpOption) {
1191 for (const CStringView argument : command.subspan(1)) {
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)};
1196 }
1197 }
1198 }
1199
1200 ArrayList<CStringView> arguments{};
1201 ArrayList<CStringView> extraArguments{};
1202 arguments.reserve(command.size() - 1);
1203
1204 if constexpr (meta::aggregate_size_v<Options> > 0) {
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());
1210 break;
1211 }
1212
1213 const auto throwUnknownOptionError = [&]() -> void {
1214 if (options.enableHelpOption) {
1215 throw UnknownOption{formatString("Unknown option {}. Try {}help.", argument, options.longOptionPrefix)};
1216 }
1217 throw UnknownOption{formatString("Unknown option {}.", argument)};
1218 };
1219
1220 StringView specifiedOptionName{};
1221 CStringView specifiedOptionValue{};
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()) {
1228 throw InvalidOptionValue{"Expected a value."};
1229 }
1230 specifiedOptionValue = argumentWithoutPrefix.substr(equalsPosition + 1);
1231 specifiedOptionName = specifiedOptionName.substr(0, equalsPosition);
1232 }
1233 }
1234 if (specifiedOptionName.empty()) {
1235 throwUnknownOptionError();
1236 }
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()) {
1243 throw InvalidOptionValue{"Expected a value."};
1244 }
1245 specifiedOptionValue = argumentWithoutPrefix.substr(equalsPosition + 1);
1246 specifiedOptionName = specifiedOptionName.substr(0, equalsPosition);
1247 }
1248 }
1249 if (specifiedOptionName.empty()) {
1250 throwUnknownOptionError();
1251 }
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();
1257 }
1258 specifiedOptionName = it->second;
1259 } else {
1260 const bool allowShortOptionGrouping = enableShortOptions && options.useImplicitBooleanValues && options.allowShortOptionGrouping;
1261 if (!allowShortOptionGrouping) {
1262 throwUnknownOptionError();
1263 }
1264 for (const char shortOptionName : specifiedOptionName) {
1265 const auto it = shortOptionNameMap.find(shortOptionName);
1266 if (it == shortOptionNameMap.end()) {
1267 throwUnknownOptionError();
1268 }
1269 if (!optionsSpecified.emplace(it->second).second) {
1270 throw InvalidOptionValue{formatString("Option {}{} was specified multiple times.", options.longOptionPrefix, it->second)};
1271 }
1272 if (detail::findAndSetImplicitBooleanOption(it->second, outputOptions, {}, options)) {
1273 if (!specifiedOptionValue.empty()) {
1274 throw InvalidOptionValue{"Cannot specify value for a group of boolean options."};
1275 }
1276 } else {
1277 throwUnknownOptionError();
1278 }
1279 }
1280 continue;
1281 }
1282 }
1283
1284 if (specifiedOptionName.empty()) {
1285 arguments.push_back(argument);
1286 } else {
1287 if (!optionsSpecified.emplace(specifiedOptionName).second) {
1288 throw InvalidOptionValue{formatString("Option {}{} was specified multiple times.", options.longOptionPrefix, specifiedOptionName)};
1289 }
1290 if (!detail::findOptionAndParseValue(specifiedOptionName, specifiedOptionValue, outputOptions, command, argumentIndex, {}, options)) {
1291 throwUnknownOptionError();
1292 }
1293 }
1294 }
1295 } else {
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());
1300 break;
1301 }
1302 arguments.push_back(argument);
1303 }
1304 }
1305
1306 if constexpr (meta::aggregate_size_v<Arguments> > 0) {
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)};
1310 }
1311
1312 size_t argumentIndex = 0;
1313 detail::parseArguments(outputArguments, arguments, argumentIndex, {}, argumentCounts.trailingArgumentCount);
1314 } else {
1315 if (!arguments.empty()) {
1316 throw InvalidUsage{detail::formatUsageString<Arguments, Options>(command.front(), options)};
1317 }
1318 }
1319
1320 return extraArguments;
1321}
1322
1345template <aggregate Arguments, aggregate Options>
1346ArrayList<CStringView> parseCommandLine(Arguments& outputArguments, Options& outputOptions, int argc, char* argv[], const CommandLineParserOptions& options = {})
1348 return parseCommandLine(outputArguments, outputOptions, Span<const CStringView>{reinterpret_cast<const CStringView*>(argv), static_cast<size_t>(argc)}, options);
1349}
1350
1369template <aggregate Arguments>
1372 detail::NoOptions outputOptions{};
1373 return parseCommandLine(outputArguments, outputOptions, command, options);
1374}
1375
1396template <aggregate Arguments>
1397ArrayList<CStringView> parseCommandLineArguments(Arguments& outputArguments, int argc, char* argv[], const CommandLineParserOptions& options = {})
1399 detail::NoOptions outputOptions{};
1400 return parseCommandLine(outputArguments, outputOptions, argc, argv, options);
1401}
1402
1421template <aggregate Options>
1424 detail::NoArguments outputArguments{};
1425 return parseCommandLine(outputArguments, outputOptions, command, options);
1426}
1427
1448template <aggregate Options>
1449ArrayList<CStringView> parseCommandLineOptions(Options& outputOptions, int argc, char* argv[], const CommandLineParserOptions& options = {})
1451 detail::NoArguments outputArguments{};
1452 return parseCommandLine(outputArguments, outputOptions, argc, argv, options);
1453}
1454
1455} // namespace grem::cli
1456
1457#endif
#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
Definition Span.hpp:146
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
Proxy(Proxy &&)=delete
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 void forEachField(Aggregate &&value, auto fn)
Execute a function for each field of an aggregate.
Definition metaprogramming.hpp:1297
constexpr void forEachNamedField(Aggregate &&value, auto fn)
Execute a function for each field of an aggregate, also including the field name.
Definition metaprogramming.hpp:1664
constexpr std::size_t aggregate_size_v
The number of fields in a given aggregate type.
Definition metaprogramming.hpp:921
constexpr auto unqualified_type_name_v
Unqualified name of a type.
Definition metaprogramming.hpp:1526
constexpr void forEachNamedFieldType(auto fn)
Execute a function for each field type of an aggregate, also including the field name.
Definition metaprogramming.hpp:1616
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