diff --git a/include/rfl/cli/App.hpp b/include/rfl/cli/App.hpp index 356d61a44..98e7b5462 100644 --- a/include/rfl/cli/App.hpp +++ b/include/rfl/cli/App.hpp @@ -203,21 +203,38 @@ BuiltinOptions add_builtin_options(Options* _options) { "rfl::cli::App no version."); } if (builtin.help) { - _options->long_options[std::string(help_option)] = - Option{OptionKind::flag}; + _options->long_options.emplace_back(std::string(help_option), + Option{OptionKind::flag}); } if (builtin.help_short) { - _options->short_options[std::string(help_short_option)] = - std::string(help_option); + _options->short_options.emplace_back(std::string(help_short_option), + std::string(help_option)); } if (builtin.version) { - _options->long_options[std::string(version_option)] = - Option{OptionKind::flag}; + _options->long_options.emplace_back(std::string(version_option), + Option{OptionKind::flag}); } + _options->finalize(); } return builtin; } +/// Returns a process-lifetime cached pair of (Options, BuiltinOptions) for +/// , avoiding option-table reconstruction on +/// every read_app() or usage() call. +template + || separate_option_values_v + || allow_abbreviations_v> +const std::pair& cached_app_options() { + static const auto cached = []() { + auto options = make_options(); + const auto builtin = add_builtin_options(&options); + return std::pair{std::move(options), builtin}; + }(); + return cached; +} + /// The header of the help: "name version" and the description, each on a /// line of its own if it is given, and a blank line. Empty if the /// processors contain no rfl::cli::App or it has none of them. diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index 4d7a4d0eb..cdd150edb 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -1,17 +1,16 @@ #ifndef RFL_CLI_OPTIONS_HPP_ #define RFL_CLI_OPTIONS_HPP_ +#include #include -#include +#include #include -#include #include #include #include #include #include -#include "../Box.hpp" #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" @@ -78,20 +77,21 @@ struct Option { std::string_view implicit_value = {}; }; -/// The options that a target struct accepts, built from its fields by -/// make_options on every read. parse_argv uses it to decide whether an -/// option takes the next token as its value and whether a long option is -/// known, and resolve_args to map short aliases and positional arguments to -/// fields. Paths are dotted -/// (`database.host`) and use the field names after processors (kebab-case, -/// rfl::Rename) are applied. +/// The options that a target struct accepts, built once per +/// by make_options and cached via cached_options. parse_argv uses it to decide +/// whether an option takes the next token as its value and whether a long +/// option is known, and resolve_args to map short aliases and positional +/// arguments to fields. Paths are dotted (`database.host`) and use the field +/// names after processors (kebab-case, rfl::Rename) are applied. +/// All keyed tables are flat sorted vectors searched with std::string_view via +/// std::lower_bound after finalize(). struct Options { - /// The long options, by path. - std::map long_options; + /// The long options, sorted by path. + std::vector> long_options; - /// The short aliases given by rfl::Short (`p` for `-p`), mapped to the path - /// of their field. - std::map short_options; + /// The short aliases given by rfl::Short (`p` for `-p`), sorted by short + /// name, mapped to the path of their field. + std::vector> short_options; /// The paths of the rfl::Positional fields, in declaration order, wherever /// rfl::Positional sits among a field's wrappers. Each takes one positional @@ -101,20 +101,21 @@ struct Options { /// Prefixes (ending in path_separator, or empty for the root) under which /// the keys are not known in advance, such as maps and rfl::ExtraFields. - /// Maps to the option of a direct sub-key. - std::map open_prefixes; + /// Sorted by prefix; maps to the option of a direct sub-key. + std::vector> open_prefixes; /// For the open prefixes whose sub-keys hold structs or maps: the options /// inside one such value, with paths relative to it, so that - /// `--servers.eu.port` is looked up as `port`. - std::map> open_prefix_options; + /// `--servers.eu.port` is looked up as `port`. Sorted by prefix. + std::vector>> + open_prefix_options; /// Paths of fields wrapped in rfl::Hidden, which are parsed normally but - /// omitted from usage() and --help. - std::set hidden_options; + /// omitted from usage() and --help. Sorted. + std::vector hidden_options; - /// Section header name for fields wrapped in rfl::Group, by path. - std::map option_groups; + /// Section header name for fields wrapped in rfl::Group, sorted by path. + std::vector> option_groups; /// Whether options that match no field are an error (rfl::NoExtraFields). bool reject_unknown = false; @@ -132,11 +133,11 @@ struct Options { /// when it is given without '=' (rfl::cli::SeparateOptionValues). bool separate_values = false; - /// Builds the table with every long option through nested structs and - /// maps, if this one lists only the top-level fields (see make_options). + /// Returns the cached table with every long option through nested structs + /// and maps, if this one lists only the top-level fields (see make_options). /// parse_argv looks up nested options in it, for instance to tell whether /// a repeated nested option is a list. - Options (*make_all_paths)() = nullptr; + const Options& (*all_paths_options)() = nullptr; /// Whether tokens such as `-5` and `-.5` are short options rather than /// negative numbers. They are when parse_argv is called without the @@ -157,6 +158,52 @@ struct Options { /// token (rfl::cli::PureFlags). bool pure_flags = false; + /// Records one leaf long option along with its optional hidden/group + /// metadata. Non-template to avoid per-field template instantiations. + void add_leaf_option(std::string _path, const Option& _opt, + const bool _hidden, const std::string_view _group) { + if (_hidden) { + hidden_options.push_back(_path); + } + if (!_group.empty()) { + option_groups.emplace_back(_path, std::string(_group)); + } + long_options.emplace_back(std::move(_path), _opt); + } + + /// Records a short alias (and tracks the first duplicate, if any). + void add_short_alias(const std::string_view _short_name, + const std::string_view _long_name) { + const bool already_exists = std::any_of( + short_options.begin(), short_options.end(), + [&](const auto& _entry) { return _entry.first == _short_name; }); + if (already_exists) { + if (duplicate_short_name.empty()) { + duplicate_short_name = std::string(_short_name); + } + } else { + short_options.emplace_back(std::string(_short_name), + std::string(_long_name)); + } + } + + /// Sorts all lookup tables so binary search lookups work. Must be called + /// after populating or mutating any keyed table. + void finalize() { + sort_pairs(long_options); + sort_pairs(short_options); + sort_pairs(open_prefixes); + sort_pairs(open_prefix_options); + for (auto& entry : open_prefix_options) { + entry.second->finalize(); + } + std::sort(hidden_options.begin(), hidden_options.end()); + hidden_options.erase( + std::unique(hidden_options.begin(), hidden_options.end()), + hidden_options.end()); + sort_pairs(option_groups); + } + /// Returns the long options that `--_prefix` could abbreviate: every /// long option that starts with `_prefix`, in alphabetical order. Only the /// last segment of a dotted name is abbreviated, so `_prefix` must spell @@ -166,14 +213,14 @@ struct Options { /// them. Only meaningful if find_long(_prefix) is unknown: an exact match /// always wins. std::vector find_abbreviations( - const std::string& _prefix + const std::string_view _prefix ) const { std::vector names; if (_prefix.empty() || _prefix.back() == path_separator) { return names; } const auto last_separator = _prefix.rfind(path_separator); - for (auto it = long_options.lower_bound(_prefix); + for (auto it = lower_bound_pair(long_options, _prefix); it != long_options.end() && it->first.starts_with(_prefix); ++it) { if (it->first.rfind(path_separator) == last_separator) { names.push_back(it->first); @@ -183,26 +230,24 @@ struct Options { } /// Returns the long option `--_name`. - Option find_long(const std::string& _name) const { - const auto it = long_options.find(_name); - if (it != long_options.end()) { - return it->second; + Option find_long(const std::string_view _name) const { + if (const auto* opt = find_pair(long_options, _name)) { + return *opt; } // A key below an open leaf field (for example a variant of structs): the // reader decides what it means. - for (auto pos = _name.find(path_separator); pos != std::string::npos; + for (auto pos = _name.find(path_separator); pos != std::string_view::npos; pos = _name.find(path_separator, pos + 1)) { - const auto parent = long_options.find(_name.substr(0, pos)); - if (parent != long_options.end() - && parent->second.kind == OptionKind::other) { + if (const auto* parent = find_pair(long_options, _name.substr(0, pos)); + parent && parent->kind == OptionKind::other) { return Option{OptionKind::other}; } } // A key inside a map or a struct with rfl::ExtraFields. The longest // matching prefix wins. - const std::pair* open = nullptr; + const std::pair* open = nullptr; for (const auto& p : open_prefixes) { if (_name.size() > p.first.size() && _name.starts_with(p.first) && (!open || p.first.size() > open->first.size())) { @@ -212,7 +257,7 @@ struct Options { if (open) { const auto rest = _name.substr(open->first.size()); const auto sep = rest.find(path_separator); - if (open->first.empty() && sep != std::string::npos) { + if (open->first.empty() && sep != std::string_view::npos) { // A dotted key whose leading segment is a known nested struct or map // field (e.g. `--database.nope` beside rfl::ExtraFields) belongs to // that field, not to ExtraFields. @@ -222,12 +267,11 @@ struct Options { return Option{}; } } - if (sep == std::string::npos) { + if (sep == std::string_view::npos) { return open->second; } - const auto nested = open_prefix_options.find(open->first); - if (nested != open_prefix_options.end()) { - return nested->second->find_long(rest.substr(sep + 1)); + if (const auto* nested = find_pair(open_prefix_options, open->first)) { + return (*nested)->find_long(rest.substr(sep + 1)); } return open->second.kind == OptionKind::other ? Option{OptionKind::other} : Option{}; @@ -236,10 +280,28 @@ struct Options { return Option{}; } + /// Returns the long option path that `-_name` stands for, or nullptr. + const std::string* find_short_target(const std::string_view _name) const { + return find_pair(short_options, _name); + } + /// Returns the option that the short alias `-_name` stands for. - Option find_short(const std::string& _name) const { - const auto it = short_options.find(_name); - return it == short_options.end() ? Option{} : find_long(it->second); + Option find_short(const std::string_view _name) const { + const auto* target = find_short_target(_name); + return target ? find_long(*target) : Option{}; + } + + /// Whether `_path` is hidden from usage() and --help. + bool is_hidden(const std::string_view _path) const { + const auto it = + std::lower_bound(hidden_options.begin(), hidden_options.end(), _path); + return it != hidden_options.end() && *it == _path; + } + + /// Returns the rfl::Group name for `_path`, or empty string_view if none. + std::string_view find_group(const std::string_view _path) const { + const auto* g = find_pair(option_groups, _path); + return g ? std::string_view(*g) : std::string_view{}; } /// Whether the last rfl::Positional field is a list. It then takes every @@ -249,11 +311,38 @@ struct Options { } private: + template + static void sort_pairs(std::vector>& _vec) { + std::stable_sort(_vec.begin(), _vec.end(), + [](const auto& _a, const auto& _b) { + return _a.first < _b.first; + }); + } + + template + static typename std::vector>::const_iterator + lower_bound_pair(const std::vector>& _vec, + const std::string_view _key) { + return std::lower_bound( + _vec.begin(), _vec.end(), _key, + [](const auto& _entry, const std::string_view _k) { + return std::string_view(_entry.first) < _k; + }); + } + + template + static const V* find_pair( + const std::vector>& _vec, + const std::string_view _key) { + const auto it = lower_bound_pair(_vec, _key); + return (it != _vec.end() && it->first == _key) ? &it->second : nullptr; + } + static bool has_prefix( - const std::map& _map, const std::string& _prefix - ) { - const auto it = _map.lower_bound(_prefix); - return it != _map.end() && it->first.starts_with(_prefix); + const std::vector>& _vec, + const std::string_view _prefix) { + const auto it = lower_bound_pair(_vec, _prefix); + return it != _vec.end() && it->first.starts_with(_prefix); } }; @@ -348,6 +437,7 @@ struct field_info { static constexpr bool is_positional = Annotations::is_positional; static constexpr bool is_short = Annotations::is_short; + static constexpr bool is_hidden = Annotations::is_hidden; static constexpr bool has_implicit_value = Annotations::num_implicit_value > 0; @@ -538,14 +628,14 @@ void collect_value_options(Options* _options); template void add_open_prefix(const std::string& _prefix, Options* _options) { using U = unwrapped_option_t; - _options->open_prefixes[_prefix] = option_for(); + _options->open_prefixes.emplace_back(_prefix, option_for()); if constexpr (cli_annotations_t::num_implicit_value == 0 && (parsing::is_string_map_v || (is_option_struct_v && !VisitedType::template contains))) { - auto nested = rfl::Box::make(); + auto nested = std::make_unique(); collect_value_options(nested.get()); - _options->open_prefix_options.insert_or_assign(_prefix, std::move(nested)); + _options->open_prefix_options.emplace_back(_prefix, std::move(nested)); } } @@ -562,61 +652,7 @@ void collect_value_options(Options* _options) { collect_options("", _options); } else { - _options->open_prefixes[""] = Option{OptionKind::other}; - } -} - -template -void add_option(const std::string& _path, Options* _options) { - using U = unwrapped_option_t; - if constexpr (cli_annotations_t::is_hidden) { - _options->hidden_options.insert(_path); - } - if constexpr (cli_annotations_t::has_group) { - _options->option_groups[_path] = - std::string(cli_annotations_t::group_name.string_view()); - } - if constexpr (cli_annotations_t::num_implicit_value > 0) { - _options->long_options[_path] = - implicit_value_option(); - } - else if constexpr (std::is_same_v) { - _options->long_options[_path] = Option{OptionKind::flag}; - } - else if constexpr (is_open_option_v) { - _options->long_options[_path] = Option{OptionKind::other}; - } - else if constexpr (parsing::is_string_map_v) { - add_open_prefix( - _path + path_separator, _options); - } - else if constexpr (is_option_struct_v) { - if constexpr (VisitedType::template contains) { - // A recursive type: stop here and let the reader handle deeper keys. - _options->open_prefixes[_path + path_separator] = - Option{OptionKind::other}; - } - else { - collect_options( - _path + path_separator, _options); - } - } - else { - _options->long_options[_path] = - Option{OptionKind::value, is_option_list_v}; - } -} - -template -void add_option_for_field(const std::string& _prefix, Options* _options) { - using T = std::remove_cvref_t; - if constexpr (rfl::internal::is_extra_fields_v) { - add_open_prefix( - _prefix, _options); - } - else { - add_option( - _prefix + std::string(FieldType::name()), _options); + _options->open_prefixes.emplace_back("", Option{OptionKind::other}); } } @@ -625,62 +661,102 @@ void collect_options(const std::string& _prefix, Options* _options) { using NT = option_fields_t; using NextVisitedType = typename VisitedType::template add; [&](std::index_sequence<_is...>) { - (add_option_for_field< - rfl::tuple_element_t<_is, typename NT::Fields>, ProcessorsType, - NextVisitedType>(_prefix, _options), - ...); + auto add_one = [&]() { + using FieldType = rfl::tuple_element_t<_i, typename NT::Fields>; + using FT = std::remove_cvref_t; + if constexpr (rfl::internal::is_extra_fields_v) { + add_open_prefix(_prefix, _options); + } else { + using U = unwrapped_option_t; + using Ann = cli_annotations_t; + std::string path = _prefix + std::string(FieldType::name()); + constexpr bool is_hidden = Ann::is_hidden; + constexpr auto group_name = + Ann::has_group ? Ann::group_name.string_view() : std::string_view{}; + if constexpr (Ann::num_implicit_value > 0) { + _options->add_leaf_option( + std::move(path), implicit_value_option(), + is_hidden, group_name); + } else if constexpr (std::is_same_v) { + _options->add_leaf_option(std::move(path), Option{OptionKind::flag}, + is_hidden, group_name); + } else if constexpr (is_open_option_v) { + _options->add_leaf_option(std::move(path), Option{OptionKind::other}, + is_hidden, group_name); + } else if constexpr (parsing::is_string_map_v) { + if constexpr (is_hidden) { + _options->hidden_options.push_back(path); + } + if constexpr (!group_name.empty()) { + _options->option_groups.emplace_back(path, std::string(group_name)); + } + add_open_prefix(path + path_separator, _options); + } else if constexpr (is_option_struct_v) { + if constexpr (is_hidden) { + _options->hidden_options.push_back(path); + } + if constexpr (NextVisitedType::template contains) { + _options->open_prefixes.emplace_back(path + path_separator, + Option{OptionKind::other}); + } else { + collect_options( + path + path_separator, _options); + } + } else { + _options->add_leaf_option( + std::move(path), Option{OptionKind::value, is_option_list_v}, + is_hidden, group_name); + } + } + }; + (add_one.template operator()<_is>(), ...); }(std::make_index_sequence()); } -/// Adds the short alias and the positional slot of the _i-th top-level -/// field, if it has them. Two fields with the same short name are kept as -/// an error (Options::duplicate_short_name). -template -void add_short_and_positional(Options* _options) { - using Info = field_info; - if constexpr (Info::is_short) { - const auto name = - std::string(get_short_name().string_view()); - if (!_options->short_options.emplace(name, std::string(Info::name())) - .second - && _options->duplicate_short_name.empty()) { - _options->duplicate_short_name = name; - } - } - if constexpr (Info::is_positional) { - _options->positionals.emplace_back(Info::name()); - } -} - template void collect_short_and_positional(Options* _options) { using NT = option_fields_t; [&](std::index_sequence<_is...>) { - (add_short_and_positional(_options), ...); + auto add_one = [&]() { + using Info = field_info; + if constexpr (Info::is_short) { + constexpr auto short_lit = get_short_name(); + _options->add_short_alias(short_lit.string_view(), Info::name()); + } + if constexpr (Info::is_positional) { + _options->positionals.emplace_back(Info::name()); + } + }; + (add_one.template operator()<_is>(), ...); }(std::make_index_sequence()); } -template -void add_top_level_option(Options* _options) { - using T = std::remove_cvref_t; - if constexpr (!rfl::internal::is_extra_fields_v) { - _options->long_options[std::string(FieldType::name())] = - option_for(); - } -} - /// Adds the options of the top-level fields of T, which is all that short /// options need. template void collect_top_level_options(Options* _options) { using NT = option_fields_t; [&](std::index_sequence<_is...>) { - (add_top_level_option, - ProcessorsType>(_options), - ...); + auto add_one = [&]() { + using FieldType = rfl::tuple_element_t<_i, typename NT::Fields>; + using FT = std::remove_cvref_t; + if constexpr (!rfl::internal::is_extra_fields_v) { + _options->long_options.emplace_back(std::string(FieldType::name()), + option_for()); + } + }; + (add_one.template operator()<_is>(), ...); }(std::make_index_sequence()); } +template + || separate_option_values_v + || allow_abbreviations_v> +const Options& cached_options(); + /// Derives the options that T accepts from its fields: the long options, /// with whether each is a flag, takes a value or has an implicit value, and /// the rfl::Short aliases and rfl::Positional fields of the top-level struct. @@ -692,11 +768,7 @@ void collect_top_level_options(Options* _options) { /// rfl::cli::SeparateOptionValues, to tell whether a nested option takes the /// next token, and rfl::cli::AllowAbbreviations, to abbreviate nested /// options, need them all. -/// @return The options, with reject_unknown set if ProcessorsType contains -/// rfl::NoExtraFields, separate_values if it contains -/// rfl::cli::SeparateOptionValues, allow_abbreviations if it contains -/// rfl::cli::AllowAbbreviations, and options_first if it contains -/// rfl::cli::OptionsFirst +/// @return The finalized options table template || separate_option_values_v @@ -707,7 +779,7 @@ Options make_options() { options.reject_unknown = rfl::internal::no_extra_fields_v; options.separate_values = separate_option_values_v; if constexpr (!_all_paths) { - options.make_all_paths = &make_options; + options.all_paths_options = &cached_options; } options.allow_abbreviations = allow_abbreviations_v; options.options_first = options_first_v; @@ -731,6 +803,16 @@ Options make_options() { options.negative_numbers_are_options = true; } } + options.finalize(); + return options; +} + +/// Returns a process-lifetime cached Options table for +/// , avoiding table construction and sorting +/// on every read() call. +template +const Options& cached_options() { + static const Options options = make_options(); return options; } diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index c793518f2..42eb81588 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -92,15 +92,15 @@ inline rfl::Result parse_string_views( // Without rfl::NoExtraFields, `_options` lists only the top-level fields // (see make_options), so a nested option such as `--database.replicas` is - // looked up in the table of all paths, built the first time one is given. - std::optional all_paths; - const auto find_long = [&](const std::string& _key) { - if (!_options.make_all_paths - || _key.find(path_separator) == std::string::npos) { + // looked up in the cached table of all paths on first use. + const Options* all_paths = nullptr; + const auto find_long = [&](const std::string_view _key) { + if (!_options.all_paths_options + || _key.find(path_separator) == std::string_view::npos) { return _options.find_long(_key); } if (!all_paths) { - all_paths = _options.make_all_paths(); + all_paths = &_options.all_paths_options(); } return all_paths->find_long(_key); }; @@ -129,7 +129,7 @@ inline rfl::Result parse_string_views( if (_option.is_list) { // Under its long name, so that `-r a --report b` keeps argv order. A // short option is only a list if it is in `_options`. - return add_long(_options.short_options.find(_key)->second, + return add_long(*_options.find_short_target(_key), std::move(_val), _option, _raw); } result.short_order.emplace_back(_key); @@ -237,7 +237,7 @@ inline rfl::Result parse_string_views( // implicit value. val = std::string(option.implicit_value); } - const auto r = add_long(std::move(key), std::move(val), option, arg_raw); + const auto r = add_long(key, std::move(val), option, arg_raw); if (!r) { return error(r.error().what()); } continue; } @@ -316,8 +316,7 @@ inline rfl::Result parse_string_views( val = std::move(*v); } - const auto r = - add_short(std::move(key), std::move(val), option, arg_raw); + const auto r = add_short(key, std::move(val), option, arg_raw); if (!r) { return error(r.error().what()); } break; } diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index a22fde487..1439ca1eb 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -53,7 +53,7 @@ rfl::Result parse_and_read(const ParseFn& _parse) { "rfl::cli::App turns on --help and --version, which " "rfl::cli::read cannot report. Call rfl::cli::read_app " "instead."); - const auto options = make_options(); + const auto& options = cached_options(); return check_short_names(options) .and_then([&](bool) { return _parse(options); }) .and_then([&](ParsedArgs _parsed) { diff --git a/include/rfl/cli/read_app.hpp b/include/rfl/cli/read_app.hpp index 9dc4c56ef..2a4170cb6 100644 --- a/include/rfl/cli/read_app.hpp +++ b/include/rfl/cli/read_app.hpp @@ -55,8 +55,7 @@ rfl::Result> parse_and_read_app( using ProcessorsType = rfl::internal::flatten_processors_t; using ResultType = std::variant; - auto options = make_options(); - const auto builtin = add_builtin_options(&options); + const auto& [options, builtin] = cached_app_options(); const auto short_names = check_short_names(options); if (!short_names) { return error(short_names.error().what()); diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index abc6ad90f..0adc82644 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -137,11 +137,11 @@ inline rfl::Result resolve_args( // Merge short args. for (auto& [short_name, value] : _parsed.short_args) { - const auto it = _options.short_options.find(short_name); - if (it == _options.short_options.end()) { + const auto* long_name_ptr = _options.find_short_target(short_name); + if (!long_name_ptr) { return rfl::error("Unknown short argument: -" + short_name); } - const auto& long_name = it->second; + const auto& long_name = *long_name_ptr; if (result.count(long_name)) { return rfl::error( "Conflict: '-" + short_name + "' and '--" + long_name @@ -228,7 +228,7 @@ rfl::Result> resolve_args( + _parsed.later_occurrences.begin()->first); } using FlatProcessors = rfl::internal::flatten_processors_t; - const auto options = internal::make_options(); + const auto& options = internal::cached_options(); const auto short_names = internal::check_short_names(options); if (!short_names) { return rfl::error(short_names.error().what()); diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 252c80dee..8b545ad12 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -2,36 +2,50 @@ #define RFL_CLI_USAGE_HPP_ #include +#include #include #include #include -#include #include -#include +#include #include #include +#include +#include #include #include #include #include -#include "../Generic.hpp" #include "../Processors.hpp" #include "../Result.hpp" #include "../SnakeCaseToKebabCase.hpp" -#include "../generic/Writer.hpp" +#include "../Tuple.hpp" +#include "../apply.hpp" +#include "../enums.hpp" +#include "../internal/TransparentWrapper.hpp" +#include "../internal/always_inline.hpp" #include "../internal/default_if_missing_v.hpp" +#include "../internal/has_default_val_v.hpp" +#include "../internal/has_reflection_method_v.hpp" +#include "../internal/has_reflection_type_v.hpp" +#include "../internal/has_reflector.hpp" +#include "../internal/is_bitset.hpp" #include "../internal/is_default_val_v.hpp" +#include "../internal/is_deprecated.hpp" +#include "../internal/is_description.hpp" #include "../internal/is_extra_fields.hpp" +#include "../internal/is_literal.hpp" #include "../internal/is_named_tuple.hpp" +#include "../internal/is_positional.hpp" +#include "../internal/is_short.hpp" +#include "../internal/is_validator.hpp" #include "../internal/no_optionals_v.hpp" -#include "../internal/processed_t.hpp" -#include "../parsing/is_required.hpp" -#include "../parsing/schema/Definition.hpp" -#include "../parsing/schema/Type.hpp" +#include "../internal/underlying_enums_v.hpp" +#include "../parsing/ParserCommented.hpp" +#include "../parsing/ParserFilepath.hpp" #include "../parsing/schema/ValidationType.hpp" -#include "../parsing/schema/make.hpp" -#include "../to_generic.hpp" +#include "../to_view.hpp" #include "App.hpp" #include "ListDelimiter.hpp" #include "OptionsFirst.hpp" @@ -67,12 +81,6 @@ struct UsageOptions { namespace internal { -/// Whether a top-level field is required, which the schema cannot tell the -/// way the parser sees it. -struct UsageFieldMeta { - bool required = true; -}; - /// Everything usage() renders about one argument. struct UsageArg { /// The long name, including the path of nested objects ("database.host"). @@ -92,9 +100,6 @@ struct UsageArg { /// takes the remaining positional arguments. bool takes_rest = false; bool required = true; - /// Whether `required` was taken from the parser's compile-time traits, so - /// that the schema must not override it. - bool required_is_known = false; /// Whether the option is shown without a value, as the built-in `--help` /// and `--version` are. bool bare = false; @@ -112,63 +117,6 @@ struct UsageArg { std::string group; }; -template -void add_usage_field_meta(const bool _default_vals_are_optional, - std::map* _meta) { - using Info = field_info; - using ValueType = std::remove_cvref_t; - auto& meta = (*_meta)[std::string(Info::name())]; - // The same condition as in NamedTupleParser::handle_one_missing_field. - // is_default_val_v sees a DefaultVal through Short, Positional, Rename, - // Description and Deprecated, in any order, as the parser does. The schema - // cannot tell, because it marks a DefaultVal field as optional even where - // the parser requires it (see usage_default_vals_are_optional). - meta.required = - !(rfl::internal::is_default_val_v - && _default_vals_are_optional) - && !rfl::internal::is_extra_fields_v - && (rfl::internal::no_optionals_v - || parsing::is_required()); -} - -/// Collects whether each top-level field is required from the same -/// compile-time traits that the parser uses, so the help matches what the -/// parser accepts. Positional, Short, flags, implicit values and lists come -/// from the parser's option table (make_options). -template -std::map collect_usage_field_meta( - const bool _default_vals_are_optional, std::index_sequence<_is...>) { - std::map meta; - (add_usage_field_meta( - _default_vals_are_optional, &meta), - ...); - return meta; -} - -/// Whether the parser fills in the rfl::DefaultVal fields of T that are -/// missing. It does so by default-constructing T before reading it. If T is -/// not default-constructible (only possible if all of them are wrapped in -/// another type), or T{} throws (for instance because a validator rejects -/// another field's default value), they are required, or the read fails if -/// one of them is not wrapped in another type. An -/// rfl::NamedTuple has no in-class initializers, so it is never -/// default-constructed for its defaults. -template -bool usage_default_vals_are_optional() { - if constexpr (rfl::internal::is_named_tuple_v) { - return true; - } else if constexpr (std::is_default_constructible_v) { - try { - static_cast(T{}); - return true; - } catch (const std::exception&) { - return false; - } - } else { - return false; - } -} - /// Renders a number without locale-dependent separators. inline std::string usage_number_to_string(const double _value) { std::ostringstream stream; @@ -189,46 +137,152 @@ inline std::string usage_number_to_string( }); } -/// Renders a default value the way it would be passed on the command line. -/// Returns nullopt for values that cannot be rendered sensibly (null, -/// objects, empty arrays). -/// Lists are joined with the list delimiter. If lists are not split -/// (ListDelimiter<"">), a list of several items cannot be typed as one -/// value, so it is left out. -inline std::optional usage_default_to_string( - const Generic& _value, const std::optional _delimiter) { - return std::visit( - [&](const auto& _v) -> std::optional { - using V = std::remove_cvref_t; - if constexpr (std::is_same_v) { - return _v ? "true" : "false"; - } else if constexpr (std::is_same_v) { - return std::to_string(_v); - } else if constexpr (std::is_same_v) { - return usage_number_to_string(_v); - } else if constexpr (std::is_same_v) { - return _v.empty() ? std::string("\"\"") : _v; - } else if constexpr (std::is_same_v) { - if (_v.empty() || (!_delimiter && _v.size() > 1)) { - return std::nullopt; - } - std::string joined; - for (const auto& element : _v) { - const auto str = usage_default_to_string(element, _delimiter); - if (!str) { - return std::nullopt; - } - if (!joined.empty()) { - joined += *_delimiter; - } - joined += *str; - } - return joined; - } else { - return std::nullopt; - } - }, - _value.variant()); +/// Renders a C++ default value directly the way it would be passed on the +/// command line, without converting through rfl::Generic. +/// Returns nullopt for values that cannot be rendered sensibly (nullopt, +/// structs, maps, empty lists, or multi-element lists without a delimiter). +template +std::optional format_default_value( + const T& _val, const std::optional _delimiter) { + using U = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return _val ? std::string("true") : std::string("false"); + } else if constexpr (std::is_integral_v) { + return std::to_string(_val); + } else if constexpr (std::is_floating_point_v) { + return usage_number_to_string(static_cast(_val)); + } else if constexpr (std::is_same_v || + std::is_same_v) { + return _val.empty() ? std::string("\"\"") : std::string(_val); + } else if constexpr (parsing::is_filepath_v) { + const auto s = _val.string(); + return s.empty() ? std::string("\"\"") : s; + } else if constexpr (rfl::internal::is_bitset_v) { + return _val.to_string(); + } else if constexpr (rfl::internal::is_literal_v) { + const auto s = _val.str(); + return s.empty() ? std::string("\"\"") : s; + } else if constexpr (std::is_enum_v) { + if constexpr (rfl::internal::has_write_reflector && + requires(const U& _u) { Reflector::from(_u); }) { + return format_default_value(Reflector::from(_val), + _delimiter); + } else if constexpr (rfl::internal::underlying_enums_v) { + return std::to_string(static_cast>(_val)); + } else { + const auto s = rfl::enum_to_string(_val); + return s.empty() ? std::string("\"\"") : s; + } + } else if constexpr (parsing::is_optional_v || + parsing::is_unique_ptr_v || + parsing::is_shared_ptr_v) { + if (!_val) { + return std::nullopt; + } + return format_default_value(*_val, _delimiter); + } else if constexpr (parsing::is_box_v || parsing::is_ref_v) { + if (!_val.get()) { + return std::nullopt; + } + return format_default_value(*_val, _delimiter); + } else if constexpr (std::is_pointer_v) { + if constexpr (!std::is_void_v>) { + return _val ? format_default_value(*_val, _delimiter) + : std::nullopt; + } else { + return std::nullopt; + } + } else if constexpr (rfl::internal::is_short_v || + rfl::internal::is_positional_v || + rfl::internal::is_transparent_wrapper_v || + parsing::is_rename_v || + parsing::is_default_val_v || + parsing::is_skip_v || + rfl::internal::is_description_v || + rfl::internal::is_deprecated_v || + rfl::internal::is_validator_v || + parsing::is_commented_v) { + return format_default_value(_val.value(), _delimiter); + } else if constexpr (parsing::is_variant_v) { + if (_val.valueless_by_exception()) { + return std::nullopt; + } + return std::visit( + [&](const auto& _v) { + return format_default_value(_v, _delimiter); + }, + _val); + } else if constexpr (parsing::is_rfl_variant_v) { + return _val.visit([&](const auto& _v) { + return format_default_value(_v, _delimiter); + }); + } else if constexpr (parsing::is_rfl_array_v) { + return format_default_value(_val.arr_, _delimiter); + } else if constexpr (parsing::is_tuple_v || parsing::is_pair_v || + parsing::is_rfl_tuple_v) { + std::string joined; + size_t count = 0; + bool ok = true; + const auto append = [&](const auto& _elem) { + if (!ok) { + return; + } + if (count > 0 && !_delimiter) { + ok = false; + return; + } + const auto str = format_default_value(_elem, _delimiter); + if (!str) { + ok = false; + return; + } + if (count > 0) { + joined += *_delimiter; + } + joined += *str; + ++count; + }; + if constexpr (parsing::is_rfl_tuple_v) { + rfl::apply([&](const auto&... _es) { (append(_es), ...); }, _val); + } else { + std::apply([&](const auto&... _es) { (append(_es), ...); }, _val); + } + if (!ok || count == 0) { + return std::nullopt; + } + return joined; + } else if constexpr (is_option_list_v && std::ranges::range) { + std::string joined; + size_t count = 0; + for (const auto& elem : _val) { + if (count > 0 && !_delimiter) { + return std::nullopt; + } + const auto str = format_default_value(elem, _delimiter); + if (!str) { + return std::nullopt; + } + if (count > 0) { + joined += *_delimiter; + } + joined += *str; + ++count; + } + if (count == 0) { + return std::nullopt; + } + return joined; + } else if constexpr (rfl::internal::has_write_reflector && + requires(const U& _u) { Reflector::from(_u); }) { + return format_default_value(Reflector::from(_val), + _delimiter); + } else if constexpr (rfl::internal::has_reflection_type_v && + rfl::internal::has_reflection_method_v && + requires(const U& _u) { _u.reflection(); }) { + return format_default_value(_val.reflection(), _delimiter); + } else { + return std::nullopt; + } } /// Renders a numeric bound such as ">= 1", "1..10" or "< 0 or > 10". @@ -335,181 +389,518 @@ inline std::vector usage_constraints( }); } -/// Walks the format-agnostic schema of the struct and collects one UsageArg -/// per command-line argument, in declaration order. -class UsageCollector { +/// Compile-time metadata peeling for all transparent, documentation, optional, +/// pointer, and DefaultVal wrappers around a field's core type. Peeling at +/// compile time lets UsageWalker funnel all fields with the same unwrapped +/// core type (e.g. bool, int, std::string, std::vector) through a +/// single walk_core instantiation, keeping symbol tables and compile +/// times small on large CLI structs. +template +struct usage_peel; + +template +struct usage_peel_base { + using CoreType = T; + static constexpr std::string_view description = {}; + static constexpr bool is_deprecated = false; + static constexpr std::string_view deprecation_message = {}; + static constexpr bool has_outermost_default_val = false; + static constexpr bool has_any_default_val = false; + static constexpr bool has_nullable = false; + + static inline const CoreType* unwrap_ptr(const T* _p) noexcept { return _p; } +}; + +template +struct usage_peel : usage_peel_base, _outermost> {}; + +template +struct usage_peel, _outermost> { + using Next = usage_peel, _outermost>; + using CoreType = typename Next::CoreType; + static constexpr std::string_view description = + _desc.string_view().empty() ? Next::description : _desc.string_view(); + static constexpr bool is_deprecated = Next::is_deprecated; + static constexpr std::string_view deprecation_message = + Next::deprecation_message; + static constexpr bool has_outermost_default_val = + Next::has_outermost_default_val; + static constexpr bool has_any_default_val = Next::has_any_default_val; + static constexpr bool has_nullable = Next::has_nullable; + + static inline const CoreType* unwrap_ptr( + const Description<_desc, T>* _p) noexcept { + return Next::unwrap_ptr(_p ? &_p->value() : nullptr); + } +}; + +template +struct usage_peel, _outermost> { + using Next = usage_peel, _outermost>; + using CoreType = typename Next::CoreType; + static constexpr std::string_view description = + _desc.string_view().empty() ? Next::description : _desc.string_view(); + static constexpr bool is_deprecated = true; + static constexpr std::string_view deprecation_message = + Next::is_deprecated ? Next::deprecation_message : _msg.string_view(); + static constexpr bool has_outermost_default_val = + Next::has_outermost_default_val; + static constexpr bool has_any_default_val = Next::has_any_default_val; + static constexpr bool has_nullable = Next::has_nullable; + + static inline const CoreType* unwrap_ptr( + const Deprecated<_msg, _desc, T>* _p) noexcept { + return Next::unwrap_ptr(_p ? &_p->value() : nullptr); + } +}; + +template + requires(rfl::internal::is_short_v || rfl::internal::is_positional_v || + rfl::internal::is_transparent_wrapper_v || + parsing::is_rename_v || parsing::is_skip_v || + parsing::is_commented_v) +struct usage_peel { + using Next = usage_peel, _outermost>; + using CoreType = typename Next::CoreType; + static constexpr std::string_view description = Next::description; + static constexpr bool is_deprecated = Next::is_deprecated; + static constexpr std::string_view deprecation_message = + Next::deprecation_message; + static constexpr bool has_outermost_default_val = + Next::has_outermost_default_val; + static constexpr bool has_any_default_val = Next::has_any_default_val; + static constexpr bool has_nullable = Next::has_nullable; + + static inline const CoreType* unwrap_ptr(const T* _p) noexcept { + return Next::unwrap_ptr(_p ? &_p->value() : nullptr); + } +}; + +template +struct usage_peel, _outermost> { + using Next = usage_peel, false>; + using CoreType = typename Next::CoreType; + static constexpr std::string_view description = Next::description; + static constexpr bool is_deprecated = Next::is_deprecated; + static constexpr std::string_view deprecation_message = + Next::deprecation_message; + static constexpr bool has_outermost_default_val = _outermost; + static constexpr bool has_any_default_val = true; + static constexpr bool has_nullable = Next::has_nullable; + + static inline const CoreType* unwrap_ptr(const DefaultVal* _p) noexcept { + return Next::unwrap_ptr(_p ? &_p->value() : nullptr); + } +}; + +template +struct usage_peel, _outermost> { + using Next = usage_peel, false>; + using CoreType = typename Next::CoreType; + static constexpr std::string_view description = Next::description; + static constexpr bool is_deprecated = Next::is_deprecated; + static constexpr std::string_view deprecation_message = + Next::deprecation_message; + static constexpr bool has_outermost_default_val = + Next::has_outermost_default_val; + static constexpr bool has_any_default_val = Next::has_any_default_val; + static constexpr bool has_nullable = true; + + static inline const CoreType* unwrap_ptr( + const std::optional* _p) noexcept { + return Next::unwrap_ptr((_p && *_p) ? &(**_p) : nullptr); + } +}; + +template + requires(parsing::is_unique_ptr_v || parsing::is_shared_ptr_v) +struct usage_peel { + using Next = + usage_peel, false>; + using CoreType = typename Next::CoreType; + static constexpr std::string_view description = Next::description; + static constexpr bool is_deprecated = Next::is_deprecated; + static constexpr std::string_view deprecation_message = + Next::deprecation_message; + static constexpr bool has_outermost_default_val = + Next::has_outermost_default_val; + static constexpr bool has_any_default_val = Next::has_any_default_val; + static constexpr bool has_nullable = true; + + static inline const CoreType* unwrap_ptr(const T* _p) noexcept { + return Next::unwrap_ptr((_p && *_p) ? _p->get() : nullptr); + } +}; + +template + requires(parsing::is_box_v || parsing::is_ref_v) +struct usage_peel { + using Elem = std::conditional_t< + parsing::is_box_v, typename parsing::is_box::element_type, + typename parsing::is_ref::element_type>; + using Next = usage_peel, false>; + using CoreType = typename Next::CoreType; + static constexpr std::string_view description = Next::description; + static constexpr bool is_deprecated = Next::is_deprecated; + static constexpr std::string_view deprecation_message = + Next::deprecation_message; + static constexpr bool has_outermost_default_val = + Next::has_outermost_default_val; + static constexpr bool has_any_default_val = Next::has_any_default_val; + static constexpr bool has_nullable = Next::has_nullable; + + static inline const CoreType* unwrap_ptr(const T* _p) noexcept { + return Next::unwrap_ptr((_p && _p->get()) ? _p->get() : nullptr); + } +}; + +/// Walks the target struct's fields directly at compile time and collects one +/// UsageArg per command-line argument in declaration order, without building a +/// JSON schema or converting to rfl::Generic. +template +class UsageWalker { public: - using Type = parsing::schema::Type; - - UsageCollector(const parsing::schema::Definition* _definition, - const std::map* _meta, - const Options* _options, - const bool _optionals_are_required, - const std::optional _delimiter) - : definition_(_definition), - meta_(_meta), - options_(_options), - optionals_are_required_(_optionals_are_required), + UsageWalker(const Options* _options, const std::optional _delimiter) + : options_(_options), + optionals_are_required_(rfl::internal::no_optionals_v), delimiter_(_delimiter) { + short_names_.reserve(_options->short_options.size()); for (const auto& [short_name, path] : _options->short_options) { - short_names_[path] = short_name; + short_names_.emplace_back(path, short_name); } + std::sort(short_names_.begin(), short_names_.end(), + [](const auto& _a, const auto& _b) { + return _a.first < _b.first; + }); } - /// Collects the arguments. - /// @param _all_optional Whether no argument is required - /// (rfl::DefaultIfMissing). - /// @param _defaults The default values of all fields, if known. - std::vector collect(const bool _all_optional, - const std::optional& _defaults) { + template + std::vector collect() { auto root = UsageArg{}; - root.required = !_all_optional; - add(definition_->root_, std::move(root), _defaults, false); + constexpr bool all_optional = + rfl::internal::default_if_missing_v; + root.required = !all_optional; + walk_peeled, type_list<>, /*_outermost=*/false>( + std::move(root), static_cast*>(nullptr), + /*_emit_default=*/all_optional); mark_rest_positional(); return std::move(args_); } private: - /// @param _outermost Whether _type is the outermost type of a field. - void add(const Type& _type, UsageArg _arg, - const std::optional& _default, const bool _outermost) { - _type.variant_.visit([&](const auto& _t) { - using T = std::remove_cvref_t; - // Description and Deprecated do not change how a field is read, so a - // DefaultVal inside them still makes the field optional - // (is_default_val_v). Short, Positional and Rename leave no node. - if constexpr (std::is_same_v) { - if (_arg.description.empty()) { - _arg.description = _t.description_; - } - add(*_t.type_, std::move(_arg), _default, _outermost); + template + static std::optional try_default_construct() { + return U{}; + } - } else if constexpr (std::is_same_v) { - if (_arg.description.empty()) { - _arg.description = _t.description_; - } - _arg.deprecation = _t.deprecation_message_; - add(*_t.type_, std::move(_arg), _default, _outermost); + template + RFL_ALWAYS_INLINE void walk_peeled(UsageArg _arg, const T* _default_ptr, + const bool _emit_default) { + using Peel = usage_peel, _outermost>; + using Core = typename Peel::CoreType; + if constexpr (!Peel::description.empty()) { + if (_arg.description.empty()) { + _arg.description = std::string(Peel::description); + } + } + if constexpr (Peel::is_deprecated) { + _arg.deprecation = std::string(Peel::deprecation_message); + } + if constexpr (Peel::has_outermost_default_val) { + if (_default_ptr != nullptr) { + _arg.required = false; + } + } + if constexpr (Peel::has_nullable) { + if (!optionals_are_required_) { + _arg.required = false; + } + } + const bool emit = Peel::has_any_default_val ? (_default_ptr != nullptr) + : _emit_default; + const Core* core_ptr = Peel::unwrap_ptr(_default_ptr); + walk_core(std::move(_arg), core_ptr, emit); + } - } else if constexpr (std::is_same_v) { - if (!_arg.required_is_known && !optionals_are_required_) { - _arg.required = false; - } - add(*_t.type_, std::move(_arg), _default, false); - - } else if constexpr (std::is_same_v) { - // Like the parser (is_default_val_v), only count a DefaultVal that - // wraps the field, possibly inside Description or Deprecated. The - // schema has its default value only if the struct around it could be - // default-constructed, which is when the parser fills it in. - if (!_arg.required_is_known && _outermost && _t.default_value_) { - _arg.required = false; - } - add(*_t.type_, std::move(_arg), - _t.default_value_ ? _t.default_value_ : _default, false); - - } else if constexpr (std::is_same_v) { - const auto constraints = usage_constraints(_t.validation_); - _arg.constraints.insert(_arg.constraints.end(), constraints.begin(), - constraints.end()); - add(*_t.type_, std::move(_arg), _default, false); - - } else if constexpr (std::is_same_v) { - const auto it = definition_->definitions_.find(_t.name_); - if (it == definition_->definitions_.end() - || !visiting_.insert(_t.name_).second) { - // Unknown or recursive: there is no finite set of paths to list. - add_leaf(std::move(_arg), _default); - return; - } - add(it->second, std::move(_arg), _default, _outermost); - visiting_.erase(_t.name_); + template + void walk_core(UsageArg _arg, const U* _default_ptr, + const bool _emit_default) { + if constexpr (rfl::internal::is_validator_v) { + using Inner = std::remove_cvref_t; + using ValidationType = std::remove_cvref_t; + const auto constraints = + usage_constraints(ValidationType::template to_schema()); + _arg.constraints.insert(_arg.constraints.end(), constraints.begin(), + constraints.end()); + walk_peeled( + std::move(_arg), _default_ptr ? &_default_ptr->value() : nullptr, + _emit_default); - } else if constexpr (std::is_same_v) { - add_object(_t, _arg, _default); + } else if constexpr (rfl::internal::is_literal_v) { + add_choices(U::names(), std::move(_arg), + (_emit_default && _default_ptr) + ? format_default_value(*_default_ptr, + delimiter_) + : std::nullopt); - } else if constexpr (std::is_same_v) { - _arg.name += path_separator; - _arg.name += ""; - add_leaf(std::move(_arg), std::nullopt); + } else if constexpr (std::is_enum_v) { + if constexpr (rfl::internal::has_read_reflector) { + walk_reflector(std::move(_arg), _default_ptr, + _emit_default); + } else if constexpr (rfl::internal::underlying_enums_v || + rfl::internal::enums::is_flag_enum) { + add_leaf(std::move(_arg), + (_emit_default && _default_ptr) + ? format_default_value(*_default_ptr, + delimiter_) + : std::nullopt); + } else { + constexpr auto enumerators = rfl::get_enumerator_array(); + std::vector values; + values.reserve(enumerators.size()); + for (const auto& [name, val] : enumerators) { + values.emplace_back(name); + } + add_choices(values, std::move(_arg), + (_emit_default && _default_ptr) + ? format_default_value(*_default_ptr, + delimiter_) + : std::nullopt); + } + + } else if constexpr (std::is_same_v) { + _arg.value = ""; + add_leaf(std::move(_arg), + (_emit_default && _default_ptr) + ? format_default_value(*_default_ptr, + delimiter_) + : std::nullopt); - } else if constexpr (std::is_same_v) { - _arg.value = ""; - add_leaf(std::move(_arg), _default); + } else if constexpr (parsing::is_string_map_v) { + _arg.name += path_separator; + _arg.name += ""; + add_leaf(std::move(_arg), std::nullopt); - } else if constexpr (std::is_same_v) { - add_choices(_t.values_, std::move(_arg), _default); + } else if constexpr (rfl::internal::has_read_reflector) { + walk_reflector(std::move(_arg), _default_ptr, + _emit_default); - } else if constexpr (std::is_same_v) { - auto values = std::vector(); - for (const auto& v : _t.values_) { - values.push_back(v.value_); + } else if constexpr (rfl::internal::has_reflection_type_v) { + if constexpr (VisitedType::template contains) { + add_leaf(std::move(_arg), std::nullopt); + } else { + using Refl = std::remove_cvref_t; + using NextVisited = typename VisitedType::template add; + if constexpr (rfl::internal::has_reflection_method_v && + requires(const U& _u) { _u.reflection(); }) { + if (_default_ptr) { + const auto refl = _default_ptr->reflection(); + walk_peeled( + std::move(_arg), &refl, _emit_default); + return; + } } - add_choices(values, std::move(_arg), _default); + walk_peeled( + std::move(_arg), static_cast(nullptr), _emit_default); + } + } else if constexpr (is_option_struct_v) { + if constexpr (VisitedType::template contains) { + add_leaf(std::move(_arg), std::nullopt); } else { - // Lists, too: whether a field is a list comes from the option table - // (add_leaf), which is what the parser uses. - add_leaf(std::move(_arg), _default); + walk_struct>( + _arg, _default_ptr, _emit_default); } - }); + + } else { + add_leaf(std::move(_arg), + (_emit_default && _default_ptr) + ? format_default_value(*_default_ptr, + delimiter_) + : std::nullopt); + } } - void add_object(const Type::Object& _object, const UsageArg& _parent, - const std::optional& _defaults) { - const bool is_root = _parent.name.empty(); - for (const auto& [name, type] : _object.types_) { - auto arg = UsageArg{}; - arg.name = is_root ? name : _parent.name + path_separator + name; - if (options_->hidden_options.contains(arg.name)) { - continue; - } - // Children of an optional object are only needed if it is given. - arg.required = _parent.required; - if (is_root) { - const auto& positionals = options_->positionals; - arg.positional = std::find(positionals.begin(), positionals.end(), - name) != positionals.end(); - const auto short_name = short_names_.find(name); - if (short_name != short_names_.end()) { - arg.short_name = short_name->second; + template + void walk_reflector(UsageArg _arg, const U* _default_ptr, + const bool _emit_default) { + if constexpr (VisitedType::template contains) { + add_leaf(std::move(_arg), std::nullopt); + } else { + using Refl = std::remove_cvref_t::ReflType>; + using NextVisited = typename VisitedType::template add; + if constexpr (rfl::internal::has_write_reflector && + requires(const U& _u) { Reflector::from(_u); }) { + if (_default_ptr) { + const auto refl = Reflector::from(*_default_ptr); + walk_peeled( + std::move(_arg), &refl, _emit_default); + return; } - const auto it = meta_->find(name); - if (it != meta_->end()) { - arg.required = arg.required && it->second.required; - arg.required_is_known = true; + } + walk_peeled( + std::move(_arg), static_cast(nullptr), _emit_default); + } + } + + template + void walk_struct(const UsageArg& _parent, const S* _parent_default, + const bool _emit_all_defaults) { + using NT = option_fields_t; + constexpr size_t N = NT::size(); + + if constexpr (rfl::internal::is_named_tuple_v) { + std::optional local_defaults; + if (!_parent_default && _emit_all_defaults) { + if constexpr (std::is_default_constructible_v) { + try { + local_defaults.emplace(); + } catch (const std::exception&) { + } } } - auto child_default = std::optional(); - const auto* obj = _defaults - ? std::get_if(&_defaults->variant()) - : nullptr; - if (obj) { - if (auto res = obj->get(name)) { - child_default = std::move(*res); + const S* def_obj = + _parent_default ? _parent_default + : (local_defaults ? &(*local_defaults) : nullptr); + [&](std::index_sequence<_is...>) { + auto visit = [&]() { + using FieldType = rfl::tuple_element_t<_i, typename S::Fields>; + using FieldVal = std::remove_cvref_t; + if constexpr (!rfl::internal::is_extra_fields_v) { + auto arg = make_child_arg(_parent, FieldType::name()); + if (options_->is_hidden(arg.name)) { + return; + } + if constexpr (rfl::internal::is_default_val_v) { + arg.required = false; + } + const FieldVal* ptr = def_obj ? &rfl::get<_i>(*def_obj) : nullptr; + walk_peeled( + std::move(arg), ptr, _emit_all_defaults); + } + }; + (visit.template operator()<_is>(), ...); + }(std::make_index_sequence()); + return; + } else { + if constexpr (rfl::internal::has_unwrapped_default_val_v) { + static_assert(requires { S{}; }, + "A struct with rfl::DefaultVal fields must be " + "default-constructible, because the default values come " + "from a default-constructed instance."); + } + + std::optional local_defaults; + auto no_default = std::array{}; + const S* def_obj = _parent_default; + if (!def_obj) { + const bool want_defaults = + _emit_all_defaults || rfl::internal::has_default_val_v; + if constexpr (std::is_default_constructible_v) { + if (want_defaults) { + try { + local_defaults = try_default_construct(); + } catch (const std::exception&) { + if constexpr (rfl::internal::has_unwrapped_default_val_v) { + throw; + } + } + if (local_defaults) { + def_obj = &(*local_defaults); + } + } } } - add(type, std::move(arg), child_default, true); + + if (def_obj) { + auto view = ProcessorsType::template process(rfl::to_view(*def_obj)); + using ViewType = decltype(view); + [&](std::index_sequence<_is...>) { + auto visit = [&]() { + using FieldType = rfl::tuple_element_t<_i, typename NT::Fields>; + using FieldVal = std::remove_cvref_t; + if constexpr (!rfl::internal::is_extra_fields_v) { + auto arg = make_child_arg(_parent, FieldType::name()); + if (options_->is_hidden(arg.name)) { + return; + } + const FieldVal* ptr = nullptr; + using VFT = typename rfl::tuple_element_t< + _i, typename ViewType::Fields>::Type; + if constexpr (std::is_pointer_v) { + if (!no_default[_i]) { + ptr = rfl::get<_i>(view); + } + } + walk_peeled( + std::move(arg), ptr, _emit_all_defaults); + } + }; + (visit.template operator()<_is>(), ...); + }(std::make_index_sequence()); + return; + } + + [&](std::index_sequence<_is...>) { + auto visit = [&]() { + using FieldType = rfl::tuple_element_t<_i, typename NT::Fields>; + using FieldVal = std::remove_cvref_t; + if constexpr (!rfl::internal::is_extra_fields_v) { + auto arg = make_child_arg(_parent, FieldType::name()); + if (options_->is_hidden(arg.name)) { + return; + } + walk_peeled( + std::move(arg), static_cast(nullptr), + _emit_all_defaults); + } + }; + (visit.template operator()<_is>(), ...); + }(std::make_index_sequence()); + } + } + + UsageArg make_child_arg(const UsageArg& _parent, + const std::string_view _field_name) const { + const bool is_root = _parent.name.empty(); + auto arg = UsageArg{}; + arg.name = is_root + ? std::string(_field_name) + : _parent.name + path_separator + std::string(_field_name); + arg.required = _parent.required; + if (is_root) { + const auto& positionals = options_->positionals; + arg.positional = + std::find(positionals.begin(), positionals.end(), arg.name) + != positionals.end(); + const auto short_it = std::lower_bound( + short_names_.begin(), short_names_.end(), std::string_view(arg.name), + [](const auto& _entry, const std::string_view _key) { + return _entry.first < _key; + }); + if (short_it != short_names_.end() && short_it->first == arg.name) { + arg.short_name = std::string(short_it->second); + } } + return arg; } void add_choices(const std::vector& _values, UsageArg _arg, - const std::optional& _default) { + std::optional _default) { _arg.choices = _values; _arg.value = "<"; for (size_t i = 0; i < _values.size(); ++i) { _arg.value += (i == 0 ? "" : "|") + _values[i]; } _arg.value += ">"; - add_leaf(std::move(_arg), _default); + add_leaf(std::move(_arg), std::move(_default)); } - void add_leaf(UsageArg _arg, const std::optional& _default) { + void add_leaf(UsageArg _arg, std::optional _default) { if (_arg.name.empty()) { return; } - // How the parser treats the option, from the table that it uses. A map - // key ("labels.") is found through its open prefix. const auto option = options_->find_long(_arg.name); _arg.kind = option.kind; _arg.implicit_value = std::string(option.implicit_value); @@ -519,15 +910,11 @@ class UsageCollector { if (pure_flag) { _arg.bare = true; } - if (_default) { - auto def = usage_default_to_string(*_default, delimiter_); - if (!(pure_flag && def == "false")) { - _arg.default_value = std::move(def); - } + if (_default && !(pure_flag && *_default == "false")) { + _arg.default_value = std::move(_default); } - if (const auto it = options_->option_groups.find(_arg.name); - it != options_->option_groups.end()) { - _arg.group = it->second; + if (const auto grp = options_->find_group(_arg.name); !grp.empty()) { + _arg.group = std::string(grp); } args_.emplace_back(std::move(_arg)); } @@ -545,14 +932,10 @@ class UsageCollector { } private: - const parsing::schema::Definition* definition_; - const std::map* meta_; const Options* options_; const bool optionals_are_required_; const std::optional delimiter_; - /// The rfl::Short aliases, by the path of their field. - std::map short_names_; - std::set visiting_; + std::vector> short_names_; std::vector args_; }; @@ -725,6 +1108,7 @@ inline std::string format_usage(const std::string& _program_name, } auto rows = std::vector>(); + rows.reserve(_args.size()); size_t width = 0; for (const auto& arg : _args) { rows.emplace_back(usage_arg_to_string(arg, ", ", _delimiter), @@ -798,27 +1182,6 @@ inline std::string format_usage(const std::string& _program_name, return out; } -/// The default values of all fields, if they are known: only with -/// rfl::DefaultIfMissing (otherwise, plain fields are required and their -/// default member initializers are never used) and only if T is -/// default-constructible, which read requires, too. -template -std::optional usage_defaults() { - using ProcessorsType = - rfl::internal::flatten_processors_t; - if constexpr (rfl::internal::default_if_missing_v - && std::is_default_constructible_v) { - try { - return rfl::to_generic(T{}); - } catch (const std::exception&) { - // For instance, a default value that does not satisfy its validator. - return std::nullopt; - } - } else { - return std::nullopt; - } -} - } // namespace internal /// Generates the usage line, and optionally a help text with one row per @@ -838,7 +1201,7 @@ std::optional usage_defaults() { /// @tparam T The struct type that the arguments are parsed into /// @tparam Ps The processors passed to `rfl::cli::read` /// @param _program_name The name shown after "Usage:", usually argv[0] -/// @param _detailed Whether to add a line for every argument +/// @param _opts Customization options for the generated help text /// @return The usage text, ending with a newline, or an error if no read of /// T can succeed: two fields have the same short name, or T has a bare /// rfl::DefaultVal and default-constructing it throws. @@ -847,35 +1210,22 @@ rfl::Result usage(const std::string& _program_name, const UsageOptions& _opts) { using ProcessorsType = rfl::internal::flatten_processors_t; - using NamedTupleType = rfl::internal::processed_t; constexpr auto delimiter = internal::list_delimiter_v; // The table that read() parses with, so the help shows what the parser // accepts, including the options inside nested structs and maps, and the // built-in options of rfl::cli::App that read_app handles. - auto options = - internal::make_options(); - const auto builtin = internal::add_builtin_options(&options); + const auto& [options, builtin] = + internal::cached_app_options(); return internal::check_short_names(options).and_then( [&](auto) -> rfl::Result { try { - const auto meta = internal::collect_usage_field_meta< - NamedTupleType, ProcessorsType>( - internal::usage_default_vals_are_optional(), - std::make_index_sequence{}); - // The schema takes the default values from a default-constructed - // T, which can throw. - const auto definition = - parsing::schema::make(); - auto collector = internal::UsageCollector( - &definition, &meta, &options, - rfl::internal::no_optionals_v, delimiter); + auto walker = + internal::UsageWalker(&options, delimiter); auto builtin_args = internal::builtin_usage_args(builtin, _opts.help_group); - auto fields = collector.collect( - rfl::internal::default_if_missing_v, - internal::usage_defaults()); + auto fields = walker.template collect(); auto args = std::vector(); + args.reserve(builtin_args.size() + fields.size()); if (!_opts.help_group.empty() && !builtin_args.empty()) { const auto pos = std::find_if( fields.begin(), fields.end(),