Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Report error on duplicate named arg names #4367

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions include/fmt/base.h
Original file line number Diff line number Diff line change
Expand Up @@ -1071,6 +1071,12 @@ 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 +1090,12 @@ 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 @@ -599,6 +599,8 @@ TEST(format_test, named_arg) {
EXPECT_THROW_MSG((void)fmt::format(runtime("{a} {}"), fmt::arg("a", 2), 42),
format_error,
"cannot switch from manual to automatic argument indexing");
EXPECT_THROW_MSG((void)fmt::format("{enum}", fmt::arg("enum", 1),
fmt::arg("enum", 10)), format_error, "duplicate named args found");
}

TEST(format_test, auto_arg_index) {
Expand Down
Loading