Skip to content

Commit

Permalink
Report error on duplicate named arg names
Browse files Browse the repository at this point in the history
  • Loading branch information
dinomight committed Feb 25, 2025
1 parent 7f76955 commit 167ec54
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
10 changes: 10 additions & 0 deletions include/fmt/base.h
Original file line number Diff line number Diff line change
Expand Up @@ -1071,6 +1071,11 @@ void init_named_arg(named_arg_info<Char>*, int& arg_index, int&, const T&) {
template <typename Char, typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
void init_named_arg(named_arg_info<Char>* named_args, int& arg_index,
int& named_arg_index, const T& arg) {
for (auto i = 0; i < named_arg_index; ++i) {
if (basic_string_view<Char>(named_args[i].name) == basic_string_view<Char>(arg.name)) {
report_error("duplicate named args found");
}
}
named_args[named_arg_index++] = {arg.name, arg_index++};
}

Expand All @@ -1084,6 +1089,11 @@ template <typename T, typename Char,
FMT_ENABLE_IF(is_static_named_arg<T>::value)>
FMT_CONSTEXPR void init_static_named_arg(named_arg_info<Char>* named_args,
int& arg_index, int& named_arg_index) {
for (auto i = 0; i < named_arg_index; ++i) {
if (basic_string_view<Char>(named_args[i].name) == basic_string_view<Char>(T::name)) {
report_error("duplicate named args found");
}
}
named_args[named_arg_index++] = {T::name, arg_index++};
}

Expand Down
8 changes: 8 additions & 0 deletions test/compile-error-test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,14 @@ if (CMAKE_CXX_STANDARD GREATER_EQUAL 20)
#error
#endif
" ERROR)
expect_compile(format-string-duplicate-name-error "
#if defined(FMT_HAS_CONSTEVAL) && FMT_USE_NONTYPE_TEMPLATE_ARGS
using namespace fmt::literals;
fmt::print(\"{bar}\", \"bar\"_a=42, \"bar\"_a=43);
#else
#error
#endif
" ERROR)
endif ()

# Run all tests
Expand Down
2 changes: 2 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,8 @@ TEST(format_test, named_arg) {
EXPECT_EQ("1/a/A", fmt::format("{_1}/{a_}/{A_}", fmt::arg("a_", 'a'),
fmt::arg("A_", "A"), fmt::arg("_1", 1)));
EXPECT_EQ(fmt::format("{0:{width}}", -42, fmt::arg("width", 4)), " -42");
EXPECT_THROW_MSG(fmt::format("{enum}", fmt::arg("enum", 1), fmt::arg("enum", 10)),
format_error, "duplicate named args found");
EXPECT_EQ("st",
fmt::format("{0:.{precision}}", "str", fmt::arg("precision", 2)));
EXPECT_EQ(fmt::format("{} {two}", 1, fmt::arg("two", 2)), "1 2");
Expand Down

0 comments on commit 167ec54

Please sign in to comment.