Skip to content

Commit 2e260b0

Browse files
authored
clang-tidy upgrade (to version 18) (#5272)
* `container: silkeh/clang:18-bookworm` in .github/workflows/format.yml * clang-tidy auto-fix (trivial, in test only) * Disable `performance-enum-size` (noisy, low value) * Temporarily turn off 3 diagnostics (to be tackled one-by-one). * Add explicit `switch` `default` to resolve clang-tidy `bugprone-switch-missing-default-case` Debian clang version 18.1.8 (++20240718080534+3b5b5c1ec4a3-1~exp1~20240718200641.143) Target: x86_64-pc-linux-gnu tests/test_numpy_dtypes.cpp:212:5: warning: switching on non-enum value without default case may not cover all cases [bugprone-switch-missing-default-case] * Add clang-17 and clang-18 testing. * Add `NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)` in test_tagbased_polymorphic.cpp Debian clang version 18.1.8 (++20240718080534+3b5b5c1ec4a3-1~exp1~20240718200641.143) Target: x86_64-pc-linux-gnu tests/test_tagbased_polymorphic.cpp:77:40: warning: The value '150' provided to the cast expression is not in the valid range of values for 'Kind' [clang-analyzer-optin.core.EnumCastOutOfRange] * Fix inconsistent pybind11/eigen/tensor.h behavior: This existing comment in pybind11/eigen/tensor.h ``` // move, take_ownership don't make any sense for a ref/map: ``` is at odds with the `delete src;` three lines up. In real-world client code `take_ownership` will not exist (unless the client code is untested and unused). I.e. the `delete` is essentially only useful to avoid leaks in the pybind11 unit tests. While upgrading to clang-tidy 18, the warning below appeared. Apparently it is produced during LTO, and it appears difficult to suppress. Regardless, the best way to resolve this is to remove the `delete` and to simply make the test objects `static` in the unit test code. ________ Debian clang version 18.1.8 (++20240718080534+3b5b5c1ec4a3-1~exp1~20240718200641.143) Target: x86_64-pc-linux-gnu ________ ``` lto-wrapper: warning: using serial compilation of 3 LTRANS jobs lto-wrapper: note: see the ‘-flto’ option documentation for more information In function ‘cast_impl’, inlined from ‘cast’ at /mounted_pybind11/include/pybind11/eigen/tensor.h:414:25, inlined from ‘operator()’ at /mounted_pybind11/include/pybind11/eigen/../pybind11.h:296:40, inlined from ‘_FUN’ at /mounted_pybind11/include/pybind11/eigen/../pybind11.h:267:21: /mounted_pybind11/include/pybind11/eigen/tensor.h:475:17: warning: ‘operator delete’ called on unallocated object ‘<anonymous>’ [-Wfree-nonheap-object] 475 | delete src; | ^ /mounted_pybind11/include/pybind11/eigen/../pybind11.h: In function ‘_FUN’: /mounted_pybind11/include/pybind11/eigen/../pybind11.h:297:75: note: declared here 297 | std::move(args_converter).template call<Return, Guard>(cap->f), | ^ ``` * Disable `bugprone-chained-comparison`: this clang-tidy check is incompatible with the Catch2 `REQUIRE` macro (26 warnings like the one below). ________ Debian clang version 18.1.8 (++20240718080534+3b5b5c1ec4a3-1~exp1~20240718200641.143) Target: x86_64-pc-linux-gnu ________ ``` /mounted_pybind11/tests/test_embed/test_interpreter.cpp:127:9: warning: chained comparison 'v0 <= v1 == v2' may generate unintended results, use parentheses to specify order of evaluation or a logical operator to separate comparison expressions [bugprone-chained-comparison] 127 | REQUIRE(ret == 42); | ^ /build/tests/catch/catch.hpp:17670:24: note: expanded from macro 'REQUIRE' 17670 | #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /build/tests/catch/catch.hpp:2710:47: note: expanded from macro 'INTERNAL_CATCH_TEST' 2710 | catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /mounted_pybind11/tests/test_embed/test_interpreter.cpp:127:9: note: operand 'v0' is here 127 | REQUIRE(ret == 42); | ^ /build/tests/catch/catch.hpp:17670:24: note: expanded from macro 'REQUIRE' 17670 | #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /build/tests/catch/catch.hpp:2710:47: note: expanded from macro 'INTERNAL_CATCH_TEST' 2710 | catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ | ^~~~~~~~~~~~~~~~~~~ /mounted_pybind11/tests/test_embed/test_interpreter.cpp:127:17: note: operand 'v1' is here 127 | REQUIRE(ret == 42); | ^ /build/tests/catch/catch.hpp:17670:90: note: expanded from macro 'REQUIRE' 17670 | #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) | ^~~~~~~~~~~ /build/tests/catch/catch.hpp:2710:70: note: expanded from macro 'INTERNAL_CATCH_TEST' 2710 | catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ | ^~~~~~~~~~~ /mounted_pybind11/tests/test_embed/test_interpreter.cpp:127:24: note: operand 'v2' is here 127 | REQUIRE(ret == 42); | ^ /build/tests/catch/catch.hpp:17670:90: note: expanded from macro 'REQUIRE' 17670 | #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) | ^~~~~~~~~~~ /build/tests/catch/catch.hpp:2710:70: note: expanded from macro 'INTERNAL_CATCH_TEST' 2710 | catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ | ^~~~~~~~~~~ ``` * Add 8 `// NOLINT(bugprone-empty-catch)` * Resolve clang-tidy `bugprone-multi-level-implicit-pointer-conversion` warnings. ________ Debian clang version 18.1.8 (++20240718080534+3b5b5c1ec4a3-1~exp1~20240718200641.143) Target: x86_64-pc-linux-gnu ________ ``` pybind11/detail/internals.h:556:53: warning: multilevel pointer conversion from 'internals **' to 'const void *', please use explicit cast [bugprone-multi-level-implicit-pointer-conversion] pybind11/detail/type_caster_base.h:431:20: warning: multilevel pointer conversion from 'void **' to 'void *', please use explicit cast [bugprone-multi-level-implicit-pointer-conversion] pybind11/numpy.h:904:81: warning: multilevel pointer conversion from '_object *const *' to 'const void *', please use explicit cast [bugprone-multi-level-implicit-pointer-conversion] pybind11/numpy.h:1989:39: warning: multilevel pointer conversion from 'typename vectorize_arg<const double *>::type *' (aka 'const double **') to 'void *', please use explicit cast [bugprone-multi-level-implicit-pointer-conversion] pybind11/numpy.h:1989:39: warning: multilevel pointer conversion from 'typename vectorize_arg<const VectorizeTestClass *>::type *' (aka 'const VectorizeTestClass **') to 'void *', please use explicit cast [bugprone-multi-level-implicit-pointer-conversion] pybind11/stl/filesystem.h:75:44: warning: multilevel pointer conversion from 'PyObject **' (aka '_object **') to 'void *', please use explicit cast [bugprone-multi-level-implicit-pointer-conversion] pybind11/stl/filesystem.h:83:42: warning: multilevel pointer conversion from 'PyObject **' (aka '_object **') to 'void *', please use explicit cast [bugprone-multi-level-implicit-pointer-conversion] ``` * Introduce `PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY` to resolve PyPy build errors: ``` In file included from /Users/runner/work/pybind11/pybind11/tests/test_stl.cpp:18: /Users/runner/work/pybind11/pybind11/include/pybind11/stl/filesystem.h:75:17: error: no matching function for call to 'PyPyUnicode_FSConverter' if (PyUnicode_FSConverter(buf, reinterpret_cast<void *>(&native)) != 0) { ^~~~~~~~~~~~~~~~~~~~~ /Users/runner/hostedtoolcache/PyPy/3.10.14/x64/include/pypy3.10/pypy_decl.h:969:31: note: expanded from macro 'PyUnicode_FSConverter' ^~~~~~~~~~~~~~~~~~~~~~~ /Users/runner/hostedtoolcache/PyPy/3.10.14/x64/include/pypy3.10/pypy_decl.h:970:17: note: candidate function not viable: cannot convert argument of incomplete type 'void *' to 'struct _object **' for 2nd argument PyAPI_FUNC(int) PyUnicode_FSConverter(struct _object *arg0, struct _object **arg1); ^ /Users/runner/hostedtoolcache/PyPy/3.10.14/x64/include/pypy3.10/pypy_decl.h:969:31: note: expanded from macro 'PyUnicode_FSConverter' ^ In file included from /Users/runner/work/pybind11/pybind11/tests/test_stl.cpp:18: /Users/runner/work/pybind11/pybind11/include/pybind11/stl/filesystem.h:83:17: error: no matching function for call to 'PyPyUnicode_FSDecoder' if (PyUnicode_FSDecoder(buf, reinterpret_cast<void *>(&native)) != 0) { ^~~~~~~~~~~~~~~~~~~ /Users/runner/hostedtoolcache/PyPy/3.10.14/x64/include/pypy3.10/pypy_decl.h:971:29: note: expanded from macro 'PyUnicode_FSDecoder' ^~~~~~~~~~~~~~~~~~~~~ /Users/runner/hostedtoolcache/PyPy/3.10.14/x64/include/pypy3.10/pypy_decl.h:972:17: note: candidate function not viable: cannot convert argument of incomplete type 'void *' to 'struct _object **' for 2nd argument PyAPI_FUNC(int) PyUnicode_FSDecoder(struct _object *arg0, struct _object **arg1); ^ /Users/runner/hostedtoolcache/PyPy/3.10.14/x64/include/pypy3.10/pypy_decl.h:971:29: note: expanded from macro 'PyUnicode_FSDecoder' ^ ``` * clang-tidy auto-fix * Fix silly oversight.
1 parent 8e7307f commit 2e260b0

15 files changed

+51
-24
lines changed

.clang-tidy

+2
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,12 @@ Checks: |
5757
readability-string-compare,
5858
readability-suspicious-call-argument,
5959
readability-uniqueptr-delete-release,
60+
-bugprone-chained-comparison,
6061
-bugprone-easily-swappable-parameters,
6162
-bugprone-exception-escape,
6263
-bugprone-reserved-identifier,
6364
-bugprone-unused-raii,
65+
-performance-enum-size,
6466
6567
CheckOptions:
6668
- key: modernize-use-equals-default.IgnoreMacros

.github/workflows/ci.yml

+6
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,12 @@ jobs:
340340
- clang: 16
341341
std: 20
342342
container_suffix: "-bullseye"
343+
- clang: 17
344+
std: 20
345+
container_suffix: "-bookworm"
346+
- clang: 18
347+
std: 20
348+
container_suffix: "-bookworm"
343349

344350
name: "🐍 3 • Clang ${{ matrix.clang }} • C++${{ matrix.std }} • x64"
345351
container: "silkeh/clang:${{ matrix.clang }}${{ matrix.container_suffix }}"

.github/workflows/format.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ jobs:
4141
# in .github/CONTRIBUTING.md and update as needed.
4242
name: Clang-Tidy
4343
runs-on: ubuntu-latest
44-
container: silkeh/clang:15-bullseye
44+
container: silkeh/clang:18-bookworm
4545
steps:
4646
- uses: actions/checkout@v4
4747

include/pybind11/detail/internals.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -553,7 +553,7 @@ PYBIND11_NOINLINE internals &get_internals() {
553553
}
554554
#endif
555555
internals_ptr->istate = tstate->interp;
556-
state_dict[PYBIND11_INTERNALS_ID] = capsule(internals_pp);
556+
state_dict[PYBIND11_INTERNALS_ID] = capsule(reinterpret_cast<void *>(internals_pp));
557557
internals_ptr->registered_exception_translators.push_front(&translate_exception);
558558
internals_ptr->static_property_type = make_static_property_type();
559559
internals_ptr->default_metaclass = make_default_metaclass();

include/pybind11/detail/type_caster_base.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ PYBIND11_NOINLINE void instance::allocate_layout() {
428428
// NOLINTNEXTLINE(readability-make-member-function-const)
429429
PYBIND11_NOINLINE void instance::deallocate_layout() {
430430
if (!simple_layout) {
431-
PyMem_Free(nonsimple.values_and_holders);
431+
PyMem_Free(reinterpret_cast<void *>(nonsimple.values_and_holders));
432432
}
433433
}
434434

include/pybind11/eigen/tensor.h

-3
Original file line numberDiff line numberDiff line change
@@ -469,9 +469,6 @@ struct type_caster<Eigen::TensorMap<Type, Options>,
469469
parent_object = reinterpret_borrow<object>(parent);
470470
break;
471471

472-
case return_value_policy::take_ownership:
473-
delete src;
474-
// fallthrough
475472
default:
476473
// move, take_ownership don't make any sense for a ref/map:
477474
pybind11_fail("Invalid return_value_policy for Eigen Map type, must be either "

include/pybind11/numpy.h

+6-2
Original file line numberDiff line numberDiff line change
@@ -901,7 +901,11 @@ class array : public buffer {
901901

902902
template <typename T>
903903
array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())
904-
: array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) {}
904+
: array(pybind11::dtype::of<T>(),
905+
std::move(shape),
906+
std::move(strides),
907+
reinterpret_cast<const void *>(ptr),
908+
base) {}
905909

906910
template <typename T>
907911
array(ShapeContainer shape, const T *ptr, handle base = handle())
@@ -1986,7 +1990,7 @@ struct vectorize_helper {
19861990
// Pointers to values the function was called with; the vectorized ones set here will start
19871991
// out as array_t<T> pointers, but they will be changed them to T pointers before we make
19881992
// call the wrapped function. Non-vectorized pointers are left as-is.
1989-
std::array<void *, N> params{{&args...}};
1993+
std::array<void *, N> params{{reinterpret_cast<void *>(&args)...}};
19901994

19911995
// The array of `buffer_info`s of vectorized arguments:
19921996
std::array<buffer_info, NVectorized> buffers{

include/pybind11/stl/filesystem.h

+11-2
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@
3333
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
3434
PYBIND11_NAMESPACE_BEGIN(detail)
3535

36+
#ifdef PYPY_VERSION
37+
# define PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(...) (__VA_ARGS__)
38+
#else
39+
# define PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(...) \
40+
(reinterpret_cast<void *>(__VA_ARGS__))
41+
#endif
42+
3643
#if defined(PYBIND11_HAS_FILESYSTEM) || defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)
3744
template <typename T>
3845
struct path_caster {
@@ -72,15 +79,17 @@ struct path_caster {
7279
}
7380
PyObject *native = nullptr;
7481
if constexpr (std::is_same_v<typename T::value_type, char>) {
75-
if (PyUnicode_FSConverter(buf, &native) != 0) {
82+
if (PyUnicode_FSConverter(buf, PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(&native))
83+
!= 0) {
7684
if (auto *c_str = PyBytes_AsString(native)) {
7785
// AsString returns a pointer to the internal buffer, which
7886
// must not be free'd.
7987
value = c_str;
8088
}
8189
}
8290
} else if constexpr (std::is_same_v<typename T::value_type, wchar_t>) {
83-
if (PyUnicode_FSDecoder(buf, &native) != 0) {
91+
if (PyUnicode_FSDecoder(buf, PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(&native))
92+
!= 0) {
8493
if (auto *c_str = PyUnicode_AsWideCharString(native, nullptr)) {
8594
// AsWideCharString returns a new string that must be free'd.
8695
value = c_str; // Copies the string.

include/pybind11/stl_bind.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ void vector_modifiers(
180180
v.end());
181181
try {
182182
v.shrink_to_fit();
183-
} catch (const std::exception &) {
183+
} catch (const std::exception &) { // NOLINT(bugprone-empty-catch)
184184
// Do nothing
185185
}
186186
throw;

tests/constructor_stats.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ class ConstructorStats {
190190
t1 = &p.first;
191191
}
192192
}
193-
} catch (const std::out_of_range &) {
193+
} catch (const std::out_of_range &) { // NOLINT(bugprone-empty-catch)
194194
}
195195
if (!t1) {
196196
throw std::runtime_error("Unknown class passed to ConstructorStats::get()");

tests/test_eigen_tensor.inl

+11-5
Original file line numberDiff line numberDiff line change
@@ -147,33 +147,39 @@ void init_tensor_module(pybind11::module &m) {
147147

148148
m.def(
149149
"take_fixed_tensor",
150-
151150
[]() {
152151
Eigen::aligned_allocator<
153152
Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>>
154153
allocator;
155-
return new (allocator.allocate(1))
154+
static auto *obj = new (allocator.allocate(1))
156155
Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>(
157156
get_fixed_tensor<Options>());
157+
return obj; // take_ownership will fail.
158158
},
159159
py::return_value_policy::take_ownership);
160160

161161
m.def(
162162
"take_tensor",
163-
[]() { return new Eigen::Tensor<double, 3, Options>(get_tensor<Options>()); },
163+
[]() {
164+
static auto *obj = new Eigen::Tensor<double, 3, Options>(get_tensor<Options>());
165+
return obj; // take_ownership will fail.
166+
},
164167
py::return_value_policy::take_ownership);
165168

166169
m.def(
167170
"take_const_tensor",
168171
[]() -> const Eigen::Tensor<double, 3, Options> * {
169-
return new Eigen::Tensor<double, 3, Options>(get_tensor<Options>());
172+
static auto *obj = new Eigen::Tensor<double, 3, Options>(get_tensor<Options>());
173+
return obj; // take_ownership will fail.
170174
},
171175
py::return_value_policy::take_ownership);
172176

173177
m.def(
174178
"take_view_tensor",
175179
[]() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> * {
176-
return new Eigen::TensorMap<Eigen::Tensor<double, 3, Options>>(get_tensor<Options>());
180+
static auto *obj
181+
= new Eigen::TensorMap<Eigen::Tensor<double, 3, Options>>(get_tensor<Options>());
182+
return obj; // take_ownership will fail.
177183
},
178184
py::return_value_policy::take_ownership);
179185

tests/test_modules.cpp

+6-6
Original file line numberDiff line numberDiff line change
@@ -90,32 +90,32 @@ TEST_SUBMODULE(modules, m) {
9090
try {
9191
py::class_<Dupe1>(dm, "Dupe1");
9292
failures.append("Dupe1 class");
93-
} catch (std::runtime_error &) {
93+
} catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)
9494
}
9595
try {
9696
dm.def("Dupe1", []() { return Dupe1(); });
9797
failures.append("Dupe1 function");
98-
} catch (std::runtime_error &) {
98+
} catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)
9999
}
100100
try {
101101
py::class_<Dupe3>(dm, "dupe1_factory");
102102
failures.append("dupe1_factory");
103-
} catch (std::runtime_error &) {
103+
} catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)
104104
}
105105
try {
106106
py::exception<Dupe3>(dm, "Dupe2");
107107
failures.append("Dupe2");
108-
} catch (std::runtime_error &) {
108+
} catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)
109109
}
110110
try {
111111
dm.def("DupeException", []() { return 30; });
112112
failures.append("DupeException1");
113-
} catch (std::runtime_error &) {
113+
} catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)
114114
}
115115
try {
116116
py::class_<DupeException>(dm, "DupeException");
117117
failures.append("DupeException2");
118-
} catch (std::runtime_error &) {
118+
} catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)
119119
}
120120

121121
return failures;

tests/test_numpy_dtypes.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,8 @@ py::array_t<int32_t, 0> test_array_ctors(int i) {
266266
return fill(arr_t(buf_ndim1_null));
267267
case 44:
268268
return fill(py::array(buf_ndim1_null));
269+
default:
270+
break;
269271
}
270272
return arr_t();
271273
}

tests/test_opaque_types.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ TEST_SUBMODULE(opaque_types, m) {
6565

6666
m.def("return_unique_ptr", []() -> std::unique_ptr<StringList> {
6767
auto *result = new StringList();
68-
result->push_back("some value");
68+
result->emplace_back("some value");
6969
return std::unique_ptr<StringList>(result);
7070
});
7171

tests/test_tagbased_polymorphic.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ std::vector<std::unique_ptr<Animal>> create_zoo() {
7474
// simulate some new type of Dog that the Python bindings
7575
// haven't been updated for; it should still be considered
7676
// a Dog, not just an Animal.
77+
// NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
7778
ret.emplace_back(new Dog("Ginger", Dog::Kind(150)));
7879

7980
ret.emplace_back(new Chihuahua("Hertzl"));

0 commit comments

Comments
 (0)