From 28e253b49c264fa5c8477e6a94984f53c4438013 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 01:08:30 +0300 Subject: [PATCH] Argparse: derive enum option fields with possible values --- include/Void/Configuration/Argparse.hpp | 21 +++++++++++++++++ .../Configuration/ArgparseReflect.cpp | 23 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/include/Void/Configuration/Argparse.hpp b/include/Void/Configuration/Argparse.hpp index a229731..45ecd27 100644 --- a/include/Void/Configuration/Argparse.hpp +++ b/include/Void/Configuration/Argparse.hpp @@ -290,6 +290,27 @@ namespace Void::Argparse } else if constexpr (std::same_as) { const std::string def = out.[:m:]; parser.option_default(lng, sht, desc, out.[:m:], def); + } else if constexpr (std::is_enum_v) { + auto sink = std::make_unique(); + sink->option = lng; + sink->text = std::string{Void::Meta::enum_name(out.[:m:])}; + const std::string initial = sink->text; + std::vector allowed; + for (const auto& entry : Void::Meta::enum_entries()) { + allowed.emplace_back(entry.second); + } + sink->assign = [target = &out.[:m:], initial](std::string_view text) { + if (const auto parsed = Void::Meta::enum_parse(text)) { + *target = *parsed; + return true; + } + // A default that is not an enumerator name (e.g. a cast value) + // is left untouched rather than failing the whole parse. + return text == initial; + }; + parser.option_default_checked(lng, sht, desc, sink->text, sink->text, + std::move(allowed)); + numeric_sinks.push_back(std::move(sink)); } else if constexpr (std::is_arithmetic_v) { auto sink = std::make_unique(); sink->option = lng; diff --git a/tests/standalone/Configuration/ArgparseReflect.cpp b/tests/standalone/Configuration/ArgparseReflect.cpp index a9a6c57..7a2acc5 100644 --- a/tests/standalone/Configuration/ArgparseReflect.cpp +++ b/tests/standalone/Configuration/ArgparseReflect.cpp @@ -68,3 +68,26 @@ Void::Testing::Test argparse_reflect_numeric_fields() auto bad = Void::Argparse::parse(3, bad_argv); Void::Testing::expect(!bad.has_value()); } + +Void::Testing::Test argparse_reflect_enum_fields() +{ + enum class Color { Red, Green, Blue }; + + struct Options { + Color color = Color::Red; + }; + + const char* default_argv[] = {"app"}; + auto defaults = Void::Argparse::parse(1, default_argv); + Void::Testing::require(defaults.has_value()); + Void::Testing::expect(defaults->color == Color::Red); + + const char* argv[] = {"app", "--color", "Blue"}; + auto parsed = Void::Argparse::parse(3, argv); + Void::Testing::require(parsed.has_value()); + Void::Testing::expect(parsed->color == Color::Blue); + + const char* bad_argv[] = {"app", "--color", "Purple"}; + auto bad = Void::Argparse::parse(3, bad_argv); + Void::Testing::expect(!bad.has_value()); +}