From 99500f41069a7a283617b2f080bca098a4649fd6 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 13 Nov 2026 04:09:53 +0100 Subject: [PATCH] Treat a bare negative number as a positional argument in rfl::cli `-5` or `-.5` on its own was parsed as a short option and failed with "Unknown short argument". The short-option branch now uses looks_like_option(), which the value lookahead already used. As in argparse, this does not apply if the struct has a short option whose name looks like a number, such as rfl::Short<"1", bool> for `ls -1`: then such tokens are short options as before, and negative positionals need `--`. rfl::cli::read passes that one bit to the parser. The public parse_argv, which does not know the struct, still reads such tokens as short options, as before. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 15 +++- include/rfl/cli/parse_argv.hpp | 51 ++++++++---- include/rfl/cli/read.hpp | 6 +- include/rfl/cli/resolve_args.hpp | 16 ++++ tests/cli/test_positional.cpp | 110 ++++++++++++++++++++++++++ 5 files changed, 181 insertions(+), 17 deletions(-) diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index aeeb9d83e..bd85ceade 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -51,6 +51,17 @@ The `--` separator forces all subsequent tokens into positional: ./app --verbose -- --not-a-flag.txt ``` +A token that starts with `-` and a digit or `.`, such as `-5`, `-1.5` or +`-1e3`, is a negative number, so it is read as a positional argument (or as +the value of a short option: `-n -5`). `-inf` and `-nan` start with a letter +and are read as short options; pass them after `--` or as `--offset=-inf`. + +As in argparse, this changes if the struct has a short option whose name +looks like a number, such as `rfl::Short<"1", bool>` for `ls -1`. Then such a +token is a short option, and negative positional arguments need `--`: +`./app -1 -- -5`. Right after a short option, such a token is still read as +that option's value, as any other token is: `-n -1` sets `n` to `-1`. + ## Short aliases Wrap a field with `rfl::Short<"x", T>` to add a single-character alias: @@ -109,7 +120,9 @@ struct Config { Parsing proceeds in three stages: 1. **`parse_argv`** — categorizes raw tokens into `named`, `short_args`, - and `positional` buckets (`ParsedArgs` struct). No type information needed. + and `positional` buckets (`ParsedArgs` struct). No type information + needed, except that `rfl::cli::read` tells it whether a short option's + name looks like a number. On its own, it reads `-5` as a short option. 2. **`resolve_args`** — uses compile-time metadata from the target struct to map short aliases to long names, reclaim values from bool short flags, and merge positional arguments. Produces a flat `map`. diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index fce6f016d..abf16cbf8 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -26,20 +26,15 @@ inline bool looks_like_option(std::string_view _token) noexcept { && _token[1] != '.'; } -/// Parses command-line arguments into categorized buckets. -/// Handles three types of arguments: -/// - Long options: --key=value or --flag (stored in `named`) -/// - Short options: -x value, -x=value, or -x (stored in `short_args`) -/// - Positional arguments: bare arguments not prefixed with dashes (stored in `positional`) -/// The special argument "--" forces all subsequent arguments to be treated as positional. -/// @param argc Number of command-line arguments -/// @param argv Array of command-line argument strings -/// @return A Result containing ParsedArgs with categorized arguments or an error -/// --key=value / --flag → named -/// -x value / -x=value / -x → short_args -/// bare arguments → positional -/// -- → everything after goes to positional -inline rfl::Result parse_argv(int argc, char* argv[]) { +namespace internal { + +/// Parses command-line arguments as parse_argv does. A token that looks like +/// a negative number (-5, -.5) is a positional argument unless +/// `_negative_numbers_are_options` is true, as it is when the target struct +/// has a short option whose name looks like a number (rfl::Short<"1", ...>). +/// Then such tokens are short options, as in argparse. +inline rfl::Result parse_args(int argc, char* argv[], + bool _negative_numbers_are_options) { if (argc < 0 || (argc > 0 && !argv)) { return error("Invalid argc/argv."); } @@ -91,7 +86,11 @@ inline rfl::Result parse_argv(int argc, char* argv[]) { } // Short argument: -x value, -x=value, or -x (bool). - if (arg_raw.size() >= 2 && arg_raw[0] == '-') { + // A negative number such as -5 or -.5 is not an option; it falls through + // to positional, unless the struct has a short option such as -1. + if (looks_like_option(arg_raw) + || (_negative_numbers_are_options && arg_raw.size() >= 2 + && arg_raw[0] == '-')) { const auto arg = arg_raw.substr(1); const auto eq = arg.find('='); @@ -121,6 +120,28 @@ inline rfl::Result parse_argv(int argc, char* argv[]) { return result; } +} // namespace internal + +/// Parses command-line arguments into categorized buckets. +/// Handles three types of arguments: +/// - Long options: --key=value or --flag (stored in `named`) +/// - Short options: -x value, -x=value, or -x (stored in `short_args`) +/// - Positional arguments: bare arguments not prefixed with dashes (stored in `positional`) +/// The special argument "--" forces all subsequent arguments to be treated as positional. +/// Without the target struct, a token such as -5 or -.5 is a short option. +/// rfl::cli::read, which knows the struct, reads it as a negative number +/// unless the struct has a short option like rfl::Short<"1", ...>. +/// @param argc Number of command-line arguments +/// @param argv Array of command-line argument strings +/// @return A Result containing ParsedArgs with categorized arguments or an error +/// --key=value / --flag → named +/// -x value / -x=value / -x → short_args +/// bare arguments → positional +/// -- → everything after goes to positional +inline rfl::Result parse_argv(int argc, char* argv[]) { + return internal::parse_args(argc, argv, true); +} + /// Parses wide-character command-line arguments into categorized buckets. /// Converts each wide string to UTF-8 and delegates to the narrow parse_argv. /// @param argc Number of wide-character command-line arguments diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index 13b07ac3e..1d70dda7d 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -24,7 +24,11 @@ namespace rfl::cli { template rfl::Result read(int argc, char* argv[]) { using ProcessorsType = Processors; - return parse_argv(argc, argv) + using NT = rfl::internal::processed_t; + constexpr bool negative_numbers_are_options = + internal::has_numeric_short_name( + std::make_index_sequence{}); + return internal::parse_args(argc, argv, negative_numbers_are_options) .and_then(resolve_args) .and_then([](auto _args) -> rfl::Result { const auto r = Reader(); diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index 9f3d1b500..3cf639f1d 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include #include "../Result.hpp" @@ -148,6 +150,20 @@ void collect_short_bool_names( std::index_sequence<> ) {} +/// Returns true if a field of NamedTupleType has a short name that looks +/// like a number, such as rfl::Short<"1", ...>. Then, as in argparse, +/// parse_argv treats tokens like -5 and -.5 as short options rather than as +/// negative numbers. +template +consteval bool has_numeric_short_name(std::index_sequence<_is...>) { + const auto is_numeric = [](std::string_view _name) { + return !_name.empty() + && ((_name[0] >= '0' && _name[0] <= '9') || _name[0] == '.'); + }; + return (is_numeric(get_short_name().string_view()) + || ...); +} + } // namespace internal /// Resolves ParsedArgs into a flat key-value map using compile-time diff --git a/tests/cli/test_positional.cpp b/tests/cli/test_positional.cpp index da1d41726..744c4dd1a 100644 --- a/tests/cli/test_positional.cpp +++ b/tests/cli/test_positional.cpp @@ -1,6 +1,9 @@ #include #include #include +#include +#include +#include #include namespace test_positional { @@ -95,4 +98,111 @@ TEST(cli, test_positional_optional_missing) { EXPECT_FALSE(result.value().optional_file().has_value()); } +struct NumberConfig { + rfl::Positional count; + rfl::Positional offset; +}; + +TEST(cli, test_positional_negative_numbers) { + const char* args[] = {"program", "-5", "-.5"}; + const auto result = rfl::cli::read(3, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().count(), -5); + EXPECT_DOUBLE_EQ(result.value().offset(), -0.5); +} + +TEST(cli, test_positional_negative_number_forms) { + const auto read = [](const char* _count, const char* _offset) { + const char* args[] = {"program", _count, _offset}; + return rfl::cli::read(3, const_cast(args)); + }; + + const auto a = read("-10", "-1.5"); + ASSERT_TRUE(a) << a.error().what(); + EXPECT_EQ(a.value().count(), -10); + EXPECT_DOUBLE_EQ(a.value().offset(), -1.5); + + const auto b = read("-0", "-1e3"); + ASSERT_TRUE(b) << b.error().what(); + EXPECT_EQ(b.value().count(), 0); + EXPECT_DOUBLE_EQ(b.value().offset(), -1000.0); +} + +// -inf and -nan start with a letter, so they are short options. They need +// "--" (or --offset=-inf). +TEST(cli, test_positional_negative_infinity_needs_separator) { + const char* args[] = {"program", "-5", "-inf"}; + const auto result = rfl::cli::read(3, const_cast(args)); + ASSERT_FALSE(result); + EXPECT_TRUE(std::string(result.error().what()) + .starts_with("Unknown short argument: -i")) + << result.error().what(); + + const char* separated[] = {"program", "--", "-5", "-inf"}; + const auto r = + rfl::cli::read(4, const_cast(separated)); + ASSERT_TRUE(r) << r.error().what(); + EXPECT_EQ(r.value().count(), -5); + EXPECT_TRUE(std::isinf(r.value().offset())); + EXPECT_LT(r.value().offset(), 0.0); +} + +struct NegativeOptions { + int x; + rfl::Short<"n", int> n; +}; + +TEST(cli, test_negative_option_values) { + const char* args[] = {"program", "--x=-5", "-n", "-7"}; + const auto result = + rfl::cli::read(4, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().x, -5); + EXPECT_EQ(result.value().n(), -7); + + const char* with_eq[] = {"program", "--x=-5", "-n=-7"}; + const auto r = rfl::cli::read(3, const_cast(with_eq)); + ASSERT_TRUE(r) << r.error().what(); + EXPECT_EQ(r.value().n(), -7); +} + +// As in argparse: if a short option's name looks like a number, tokens that +// look like negative numbers are short options. +struct Ls { + rfl::Short<"1", std::optional> one_per_line; + rfl::Positional> count; +}; + +TEST(cli, test_digit_short_option) { + const char* args[] = {"ls", "-1"}; + const auto result = rfl::cli::read(2, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().one_per_line(), std::optional(true)); + EXPECT_FALSE(result.value().count().has_value()); +} + +TEST(cli, test_digit_short_option_makes_negative_numbers_options) { + const char* args[] = {"ls", "-5"}; + const auto result = rfl::cli::read(2, const_cast(args)); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), "Unknown short argument: -5"); + + const char* separated[] = {"ls", "-1", "--", "-5"}; + const auto r = rfl::cli::read(4, const_cast(separated)); + ASSERT_TRUE(r) << r.error().what(); + EXPECT_EQ(r.value().one_per_line(), std::optional(true)); + EXPECT_EQ(r.value().count(), std::optional(-5)); +} + +// parse_argv does not know the struct, so it reads such tokens as short +// options. Only rfl::cli::read applies the rule. +TEST(cli, test_parse_argv_reads_negative_numbers_as_options) { + const char* args[] = {"program", "-1", "x", "-5"}; + const auto parsed = rfl::cli::parse_argv(4, const_cast(args)); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().short_args, + (std::map{{"1", "x"}, {"5", ""}})); + EXPECT_TRUE(parsed.value().positional.empty()); +} + } // namespace test_positional