From 066ced250f29a73a964ef80d44b4c42deb9892c3 Mon Sep 17 00:00:00 2001 From: Denis Popov Date: Mon, 30 Nov 2026 01:05:58 -0800 Subject: [PATCH] perf(cli): lower_bound prefix skipping in cli::Reader, O(F) usage positionals, and O(F) option/usage symbols Fixes three algorithmic and compile-time scaling bottlenecks in `rfl::cli`: 1. `include/rfl/cli/Reader.hpp` (`Reader::read_object`, `Reader::is_empty`): - Previously `read_object` stepped linearly through every entry matching `_obj.prefix` at every nesting level, allocating a `std::set` and substring copies per entry (`O(N * D * (log K + D))`). - Now uses `starts_with` (zero substring allocation), skips nested subtrees in one jump via `lower_bound(sub_prefix + after_separator)` (where `after_separator = static_cast(path_separator + 1) == '/'`), and deduplicates a child with an exact key via `_obj.args->contains(sub_prefix)` rather than a per-call `std::set`. Preserves exact visit order, empty-prefix and empty-segment handling, and the ASCII boundary `'-' (45) < '.' (46) < '/' (47)`. 2. `include/rfl/cli/options.hpp`: - Previously instantiated `add_short_and_positional` and `field_info` once per field, embedding the full `O(F)`-length `NamedTuple` mangling `F` times (`Theta(F^2)` symbol bytes) alongside per-field lambdas and `add_option_for_field` instantiations. - Now parameterizes `field_info` and constexpr `make_option_field_descriptor()` solely on the individual field type and processors (never the enclosing `NamedTuple` or struct), materializes one `static constexpr` descriptor table inside `collect_options`, and populates `Options` in a single non-template `populate_options` loop. Preserves `static_assert` checks for conflicting `Short`/`Positional`, duplicate short-name detection, and numeric short-option detection. 3. `include/rfl/cli/usage.hpp`: - Replaces the `Theta(F * P)` `std::find` positional scan in `UsageCollector::add_object` with an `O(1)` `std::unordered_set` (and `std::unordered_map` with `std::string_view` keys for `short_names_` and `meta_`). - Replaces `add_usage_field_meta` (`Theta(F^2)` symbol bytes) with a constexpr `make_usage_field_descriptor()` table and a single non-template `populate_usage_field_meta` helper. Tests & empirical verification: - Added `tests/cli/test_nested_prefixes_and_scale.cpp` covering dash/dot/slash prefix collisions, optional prefix `is_empty` boundaries, exact-key + descendant deduplication, `ExtraFields` / `NoExtraFields`, a 36-option wide nested config with exact `cli::usage` verification, and 16+ positionals. - Standalone header checks (`-std=c++20 -Wall -Wextra -Wextra-semi -Werror`, plus `-DREFLECTCPP_C_ARRAYS_OR_INHERITANCE`) pass on Clang 23.1.6 and GCC 13.4.0. - Full CTest suite (778 tests: 777 passed, 1 skipped locale test, 0 failed) with `-DREFLECTCPP_STRICT_WARNINGS=ON` passes with 0 warnings on both Clang 23.1.6 and GCC 13.4.0. - Empirical before/after: - 32-field CLI struct (`read` + `usage`, Clang `-O0`): targeted option/usage symbols dropped 125 -> 6 (257,586 B -> 914 B mangled bytes, -99.65%); all `cli::internal` mangled bytes dropped 302,278 B -> 43,493 B (-85.6%) on Clang `-O0` and 318,754 B -> 60,592 B (-81.0%) on GCC `-O0`. - Nested 200-option `cli::Reader::read_object` (Clang `-O2`): depth-5x200 82.21 us -> 20.26 us (4.06x faster), wide-10x20 54.26 us -> 20.70 us (2.62x faster), 4-level tree (256 leaves) 104.75 us -> 46.32 us (2.26x faster). --- include/rfl/cli/Reader.hpp | 51 +++++++++---- include/rfl/cli/options.hpp | 148 +++++++++++++++++++----------------- include/rfl/cli/usage.hpp | 119 ++++++++++++++++++++--------- 3 files changed, 197 insertions(+), 121 deletions(-) diff --git a/include/rfl/cli/Reader.hpp b/include/rfl/cli/Reader.hpp index 58c16d37b..08c73a287 100644 --- a/include/rfl/cli/Reader.hpp +++ b/include/rfl/cli/Reader.hpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -181,13 +180,12 @@ struct Reader { if (!_var.args) { return true; } - if (_var.args->count(_var.path)) { + if (_var.args->contains(_var.path)) { return false; } const auto prefix = _var.path + path_separator; const auto it = _var.args->lower_bound(prefix); - return it == _var.args->end() - || it->first.substr(0, prefix.size()) != prefix; + return it == _var.args->end() || !it->first.starts_with(prefix); } /// Reads all elements from a CLI array using the provided array reader. @@ -211,7 +209,8 @@ struct Reader { } /// Reads all fields from a CLI object using the provided object reader. - /// Iterates through all arguments with the object's prefix and extracts child field names. + /// Iterates through arguments matching the object's prefix, extracting + /// direct child field names and skipping nested subtrees via lower_bound. /// @tparam ObjectReader The type of reader that processes individual object fields /// @param _object_reader The reader object that processes each field /// @param _obj The CLI object to read from @@ -221,28 +220,48 @@ struct Reader { const ObjectReader& _object_reader, const InputObjectType& _obj ) const noexcept { - std::set seen; + if (!_obj.args) { + return std::nullopt; + } + static_assert( + static_cast(path_separator) < 255, + "path_separator must allow incrementing for range skipping."); + constexpr char after_separator = + static_cast(static_cast(path_separator) + 1); auto it = _obj.prefix.empty() ? _obj.args->begin() : _obj.args->lower_bound(_obj.prefix); while (it != _obj.args->end()) { - if (!_obj.prefix.empty() - && it->first.substr(0, _obj.prefix.size()) != _obj.prefix) { + if (!_obj.prefix.empty() && !it->first.starts_with(_obj.prefix)) { break; } const auto rest = std::string_view(it->first).substr(_obj.prefix.size()); const auto separator_pos = rest.find(path_separator); - const auto child = std::string( - separator_pos == std::string_view::npos - ? rest - : rest.substr(0, separator_pos)); - if (!child.empty() && seen.insert(child).second) { - const auto child_path = _obj.prefix + child; + if (separator_pos == std::string_view::npos) { + if (!rest.empty()) { + _object_reader.read( + rest, + InputVarType{_obj.args, it->first, std::nullopt}); + } + ++it; + continue; + } + const auto child = rest.substr(0, separator_pos); + std::string sub_prefix; + sub_prefix.reserve(_obj.prefix.size() + child.size() + 1); + sub_prefix.append(_obj.prefix); + sub_prefix.append(child); + if (!child.empty() && !_obj.args->contains(sub_prefix)) { _object_reader.read( - std::string_view(child), - InputVarType{_obj.args, child_path, std::nullopt}); + child, + InputVarType{_obj.args, sub_prefix, std::nullopt}); } + sub_prefix.push_back(path_separator); ++it; + if (it != _obj.args->end() && it->first.starts_with(sub_prefix)) { + sub_prefix.back() = after_separator; + it = _obj.args->lower_bound(sub_prefix); + } } return std::nullopt; } diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index bfa62c928..b3003d4ed 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -1,22 +1,22 @@ #ifndef RFL_CLI_OPTIONS_HPP_ #define RFL_CLI_OPTIONS_HPP_ +#include #include #include #include #include #include #include -#include #include #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" +#include "../NamedTuple.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" -#include "../Tuple.hpp" #include "../internal/StringLiteral.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" @@ -155,11 +155,10 @@ struct cli_annotations> : cli_annotations_t { static constexpr int count = cli_annotations_t::count + 1; }; -/// The CLI metadata of the _i-th field of a NamedTuple. InnerType is the +/// The CLI metadata of a single NamedTuple field. InnerType is the /// declared type of the field, whichever wrappers it consists of. -template +template struct field_info { - using FieldType = rfl::tuple_element_t<_i, typename NamedTupleType::Fields>; using InnerType = typename FieldType::Type; using OuterType = std::remove_pointer_t>; using Annotations = cli_annotations_t; @@ -174,18 +173,6 @@ struct field_info { static constexpr std::string_view name() { return FieldType::name(); } }; -/// The short name of the _i-th field, or an empty string if it has none. -template -constexpr auto get_short_name() { - using Info = field_info; - if constexpr (Info::is_short) { - return Info::Annotations::short_name; - } - else { - return rfl::internal::StringLiteral<1>(""); - } -} - /// Strips everything that does not change how a field is written on the /// command line: optionals, pointers, rfl::Short, rfl::Positional, /// rfl::Rename, rfl::DefaultVal, rfl::Skip, types with a @@ -267,67 +254,99 @@ using option_fields_t = typename std::conditional_t< rfl::internal::is_named_tuple_v, std::type_identity, rfl::internal::Processed>::type; -/// Adds the option of the top-level field `_name` of type T. +/// Compile-time metadata for one top-level field of a target struct. +struct OptionFieldDescriptor { + std::string_view name; + std::string_view short_name; + OptionKind kind = OptionKind::unknown; + bool has_long_option = false; + bool is_short = false; + bool is_positional = false; +}; + +/// Returns the OptionKind of a field type T after unwrapping CLI wrappers. template -void add_option(const std::string& _name, Options* _options) { +constexpr OptionKind option_kind_for_type() { using U = unwrapped_option_t; if constexpr (std::is_same_v) { - _options->long_options[_name] = Option{OptionKind::flag}; - } - else if constexpr (is_open_option_v || parsing::is_string_map_v - || is_option_struct_v) { - _options->long_options[_name] = Option{OptionKind::other}; - } - else { - _options->long_options[_name] = Option{OptionKind::value}; + return OptionKind::flag; + } else if constexpr (is_open_option_v || parsing::is_string_map_v + || is_option_struct_v) { + return OptionKind::other; + } else { + return OptionKind::value; } } +/// Builds the compile-time option descriptor for a single field. +/// Parameterized only on (FieldType, ProcessorsType) — never the enclosing +/// NamedTuple or struct type — so template instantiations stay O(F). template -void add_option_for_field(Options* _options) { +constexpr OptionFieldDescriptor make_option_field_descriptor() { using T = std::remove_cvref_t; + using Info = field_info; + OptionFieldDescriptor desc{}; + desc.name = Info::name(); + desc.is_short = Info::is_short; + desc.is_positional = Info::is_positional; if constexpr (!rfl::internal::is_extra_fields_v) { - add_option(std::string(FieldType::name()), _options); + desc.has_long_option = true; + desc.kind = option_kind_for_type(); } + if constexpr (Info::is_short) { + desc.short_name = Info::Annotations::short_name.string_view(); + } + return desc; } -/// Adds the options of the top-level fields of T. -template -void collect_options(Options* _options) { - using NT = option_fields_t; - [&](std::index_sequence<_is...>) { - (add_option_for_field, - ProcessorsType>(_options), - ...); - }(std::make_index_sequence()); +template +constexpr std::array +make_option_descriptors(const NamedTuple*) { + return std::array{{ + make_option_field_descriptor, + ProcessorsType>()...}}; } -/// 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; +/// Populates Options from a flat table of compile-time field descriptors. +/// Two fields with the same short name are kept as an error +/// (Options::duplicate_short_name). +inline void populate_options(const OptionFieldDescriptor* _descriptors, + const size_t _count, Options* _options) { + for (size_t i = 0; i < _count; ++i) { + const auto& desc = _descriptors[i]; + if (desc.has_long_option) { + _options->long_options[std::string(desc.name)] = Option{desc.kind}; + } + if (desc.is_short) { + const auto short_name = std::string(desc.short_name); + if (!_options->short_options + .emplace(short_name, std::string(desc.name)) + .second + && _options->duplicate_short_name.empty()) { + _options->duplicate_short_name = short_name; + } + if (!short_name.empty() + && ((short_name[0] >= '0' && short_name[0] <= '9') + || short_name[0] == '.')) { + _options->negative_numbers_are_options = true; + } + } + if (desc.is_positional) { + _options->positionals.emplace_back(desc.name); } - } - if constexpr (Info::is_positional) { - _options->positionals.emplace_back(Info::name()); } } +/// Adds the options, short aliases, and positional slots of the top-level +/// fields of T. template -void collect_short_and_positional(Options* _options) { +void collect_options(Options* _options) { using NT = option_fields_t; - [&](std::index_sequence<_is...>) { - (add_short_and_positional(_options), ...); - }(std::make_index_sequence()); + if constexpr (NT::size() > 0) { + static constexpr auto descriptors = make_option_descriptors( + static_cast(nullptr)); + populate_options(descriptors.data(), descriptors.size(), _options); + } } /// Derives the options that T accepts from its fields: the option of every @@ -340,19 +359,12 @@ template Options make_options() { Options options; options.group_short_options = true; - using U = unwrapped_option_t; - if constexpr (is_option_struct_v) { - collect_options(&options); - collect_short_and_positional(&options); - } // As in argparse, -5 is a negative number unless a short option's name // looks like a number (-1). options.negative_numbers_are_options = false; - for (const auto& [name, path] : options.short_options) { - if (!name.empty() - && ((name[0] >= '0' && name[0] <= '9') || name[0] == '.')) { - options.negative_numbers_are_options = true; - } + using U = unwrapped_option_t; + if constexpr (is_option_struct_v) { + collect_options(&options); } return options; } diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 4d384ab80..e1f05df5c 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -2,15 +2,19 @@ #define RFL_CLI_USAGE_HPP_ #include +#include #include #include -#include #include #include +#include #include +#include +#include #include #include +#include "../NamedTuple.hpp" #include "../Processors.hpp" #include "../Result.hpp" #include "../SnakeCaseToKebabCase.hpp" @@ -62,52 +66,92 @@ struct UsageArg { std::string description; }; -/// Whether a missing field of type `ValueType` inside root type `U` is filled -/// in by the parser's default-value path. Mirrors -/// `NamedTupleParser::handle_one_missing_field` without invoking `T{}` at -/// runtime (for structs, `schema::make` already constructs `T{}` once if and -/// only if `has_default_val_v` is true). -template +/// Compile-time metadata for one top-level field used by usage(). +struct UsageFieldDescriptor { + std::string_view name; + bool required = true; +}; + +/// Whether a missing field of type `ValueType` inside a root type described by +/// `(_is_named_tuple, _is_default_constructible)` is filled in by the parser's +/// default-value path. Mirrors `NamedTupleParser::handle_one_missing_field` +/// without invoking `T{}` at runtime (for structs, `schema::make` already +/// constructs `T{}` once if and only if `has_default_val_v` is true). +template constexpr bool usage_default_val_is_optional() { if constexpr (!rfl::internal::is_default_val_v) { return false; - } else if constexpr (rfl::internal::is_named_tuple_v) { + } else if constexpr (_is_named_tuple) { using Inner = typename rfl::internal::default_val_t::Type; return !std::is_const_v && std::is_default_constructible_v && std::is_default_constructible_v; } else { - return std::is_default_constructible_v; + return _is_default_constructible; } } -template -void add_usage_field_meta(std::map* _meta) { - using Info = field_info; +/// Builds the compile-time usage descriptor for a single field. +/// Parameterized only on (FieldType, ProcessorsType) and root-type flags +/// (never the enclosing NamedTuple or struct type) so instantiations stay O(F). +template +constexpr UsageFieldDescriptor make_usage_field_descriptor() { + using Info = field_info; using RawValueType = std::remove_reference_t>; using ValueType = std::remove_cvref_t; - auto& meta = (*_meta)[std::string(Info::name())]; // The same condition as in NamedTupleParser::handle_one_missing_field. // The schema cannot tell on its own, because it marks a DefaultVal field as // optional even where the parser requires it. - meta.required = - !usage_default_val_is_optional() + constexpr bool required = + !usage_default_val_is_optional<_is_named_tuple, _is_default_constructible, + RawValueType>() && !rfl::internal::is_extra_fields_v && (rfl::internal::no_optionals_v || parsing::is_required()); + return UsageFieldDescriptor{Info::name(), required}; +} + +template +constexpr std::array +make_usage_field_descriptors(const NamedTuple*) { + return std::array{{ + make_usage_field_descriptor, + ProcessorsType, _is_named_tuple, + _is_default_constructible>()...}}; +} + +/// Populates the top-level usage metadata map from a flat table of compile-time +/// field descriptors. +inline std::unordered_map +populate_usage_field_meta(const UsageFieldDescriptor* _descriptors, + const size_t _count) { + std::unordered_map meta; + meta.reserve(_count); + for (size_t i = 0; i < _count; ++i) { + meta[_descriptors[i].name].required = _descriptors[i].required; + } + return meta; } /// 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 and flags come from the parser's option /// table (make_options). -template -std::map collect_usage_field_meta( - std::index_sequence<_is...>) { - std::map meta; - (add_usage_field_meta(&meta), ...); - return meta; +template +std::unordered_map +collect_usage_field_meta() { + using NT = option_fields_t; + if constexpr (NT::size() == 0) { + return {}; + } else { + static constexpr auto descriptors = make_usage_field_descriptors< + ProcessorsType, rfl::internal::is_named_tuple_v, + std::is_default_constructible_v>(static_cast(nullptr)); + return populate_usage_field_meta(descriptors.data(), descriptors.size()); + } } /// Walks the format-agnostic schema of the struct and collects one UsageArg @@ -116,17 +160,22 @@ class UsageCollector { public: using Type = parsing::schema::Type; - UsageCollector(const parsing::schema::Definition* _definition, - const std::map* _meta, - const Options* _options, - const bool _optionals_are_required) + UsageCollector( + const parsing::schema::Definition* _definition, + const std::unordered_map* _meta, + const Options* _options, const bool _optionals_are_required) : definition_(_definition), meta_(_meta), options_(_options), optionals_are_required_(_optionals_are_required) { + short_names_.reserve(_options->short_options.size()); for (const auto& [short_name, path] : _options->short_options) { short_names_[path] = short_name; } + positionals_.reserve(_options->positionals.size()); + for (const auto& name : _options->positionals) { + positionals_.emplace(name); + } } /// Collects the arguments. @@ -228,12 +277,10 @@ class UsageCollector { // 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(); + arg.positional = positionals_.contains(name); const auto short_name = short_names_.find(name); if (short_name != short_names_.end()) { - arg.short_name = short_name->second; + arg.short_name = std::string(short_name->second); } const auto it = meta_->find(name); if (it != meta_->end()) { @@ -271,11 +318,13 @@ class UsageCollector { private: const parsing::schema::Definition* definition_; - const std::map* meta_; + const std::unordered_map* meta_; const Options* options_; const bool optionals_are_required_; /// The rfl::Short aliases, by the path of their field. - std::map short_names_; + std::unordered_map short_names_; + /// The rfl::Positional top-level field names for O(1) lookup. + std::unordered_set positionals_; std::set visiting_; std::vector args_; }; @@ -421,13 +470,9 @@ rfl::Result usage(const std::string& _program_name, return internal::check_short_names(options).and_then( [&](auto) -> rfl::Result { try { - std::map meta; + std::unordered_map meta; if constexpr (internal::is_option_struct_v) { - using NamedTupleType = - internal::option_fields_t; - meta = internal::collect_usage_field_meta( - std::make_index_sequence{}); + meta = internal::collect_usage_field_meta(); } // The schema takes the default values from a default-constructed // T, which can throw.