From e96221befff9108f46a497bff96be0b28f0fa80c Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Thu, 10 Feb 2022 11:42:03 -0800 Subject: [PATCH] Final manual curation in preparation for global `clang-format`ing (#3712) * Manual line breaks to pre-empt undesired `clang-format`ing. Informed by work under https://github.com/pybind/pybind11/pull/3683: https://github.com/pybind/pybind11/commit/60b7eb410fefe2b23aeb6906f2a9184e91b11a15 https://github.com/pybind/pybind11/commit/59572e65598b4b9f2c9ae0b8a0e5fcb6d65c7f92 * Manual curation of clang-format diffs involving source code comments. Very labor-intensive and dull. * Pulling .clang-format change from @henryiii's https://github.com/pybind/pybind11/pull/3683/commits/9057962d40ca520b9d26abbe0ff125796e2323dd * Adding commonly used .clang-format `CommentPragmas:` * Ensure short lambdas are allowed Co-authored-by: Aaron Gokaslan --- .clang-format | 19 ++++++++ include/pybind11/buffer_info.h | 6 ++- include/pybind11/cast.h | 7 ++- include/pybind11/chrono.h | 3 +- include/pybind11/detail/common.h | 24 +++++---- include/pybind11/detail/internals.h | 12 +++-- include/pybind11/detail/type_caster_base.h | 3 +- include/pybind11/iostream.h | 3 +- include/pybind11/numpy.h | 3 +- include/pybind11/options.h | 3 +- include/pybind11/pybind11.h | 57 +++++++++++++--------- include/pybind11/pytypes.h | 13 +++-- include/pybind11/stl_bind.h | 9 ++-- tests/constructor_stats.h | 6 ++- tests/pybind11_tests.h | 3 +- tests/test_class.cpp | 43 ++++++++-------- tests/test_kwargs_and_defaults.cpp | 6 ++- tests/test_modules.cpp | 3 +- tests/test_numpy_array.cpp | 3 +- tests/test_numpy_dtypes.cpp | 8 +-- tests/test_virtual_functions.cpp | 27 +++++----- 21 files changed, 167 insertions(+), 94 deletions(-) diff --git a/.clang-format b/.clang-format index 8e0fd8b01..b477a1603 100644 --- a/.clang-format +++ b/.clang-format @@ -3,17 +3,36 @@ # clang-format --style=llvm --dump-config BasedOnStyle: LLVM AccessModifierOffset: -4 +AllowShortLambdasOnASingleLine: true AlwaysBreakTemplateDeclarations: Yes BinPackArguments: false BinPackParameters: false BreakBeforeBinaryOperators: All BreakConstructorInitializers: BeforeColon ColumnLimit: 99 +CommentPragmas: 'NOLINT:.*|^ IWYU pragma:' +IncludeBlocks: Regroup IndentCaseLabels: true IndentPPDirectives: AfterHash IndentWidth: 4 Language: Cpp SpaceAfterCStyleCast: true Standard: Cpp11 +StatementMacros: ['PyObject_HEAD'] TabWidth: 4 +IncludeCategories: + - Regex: '' + Priority: 4 + - Regex: '.*' + Priority: 5 ... diff --git a/include/pybind11/buffer_info.h b/include/pybind11/buffer_info.h index 052551ff3..9f1d04780 100644 --- a/include/pybind11/buffer_info.h +++ b/include/pybind11/buffer_info.h @@ -44,10 +44,12 @@ struct buffer_info { void *ptr = nullptr; // Pointer to the underlying storage ssize_t itemsize = 0; // Size of individual items in bytes ssize_t size = 0; // Total number of entries - std::string format; // For homogeneous buffers, this should be set to format_descriptor::format() + std::string format; // For homogeneous buffers, this should be set to + // format_descriptor::format() ssize_t ndim = 0; // Number of dimensions std::vector shape; // Shape of the tensor (1 entry per dimension) - std::vector strides; // Number of bytes between adjacent entries (for each per dimension) + std::vector strides; // Number of bytes between adjacent entries + // (for each per dimension) bool readonly = false; // flag to indicate if the underlying storage may be written to buffer_info() = default; diff --git a/include/pybind11/cast.h b/include/pybind11/cast.h index 4277d87ab..4f65356e0 100644 --- a/include/pybind11/cast.h +++ b/include/pybind11/cast.h @@ -996,7 +996,9 @@ PYBIND11_NAMESPACE_BEGIN(detail) template ::value, int>> object object_or_cast(T &&o) { return pybind11::cast(std::forward(o)); } -struct override_unused {}; // Placeholder type for the unneeded (and dead code) static variable in the PYBIND11_OVERRIDE_OVERRIDE macro +// Placeholder type for the unneeded (and dead code) static variable in the +// PYBIND11_OVERRIDE_OVERRIDE macro +struct override_unused {}; template using override_caster_t = conditional_t< cast_is_temporary_value_reference::value, make_caster, override_unused>; @@ -1463,7 +1465,8 @@ handle type::handle_of() { }} /// Lets you pass a type containing a `,` through a macro parameter without needing a separate -/// typedef, e.g.: `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType), PYBIND11_TYPE(Parent), f, arg)` +/// typedef, e.g.: +/// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType), PYBIND11_TYPE(Parent), f, arg)` #define PYBIND11_TYPE(...) __VA_ARGS__ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/include/pybind11/chrono.h b/include/pybind11/chrono.h index b24533b90..cfa635a01 100644 --- a/include/pybind11/chrono.h +++ b/include/pybind11/chrono.h @@ -38,7 +38,8 @@ public: using rep = typename type::rep; using period = typename type::period; - using days = std::chrono::duration>; // signed 25 bits required by the standard. + // signed 25 bits required by the standard. + using days = std::chrono::duration>; bool load(handle src, bool) { using namespace std::chrono; diff --git a/include/pybind11/detail/common.h b/include/pybind11/detail/common.h index 14788b652..aa3c617c4 100644 --- a/include/pybind11/detail/common.h +++ b/include/pybind11/detail/common.h @@ -42,8 +42,9 @@ # endif # endif #elif defined(_MSC_VER) && __cplusplus == 199711L -// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented) -// Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer +// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully +// implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 +// or newer. # if _MSVC_LANG >= 201402L # define PYBIND11_CPP14 # if _MSVC_LANG > 201402L && _MSC_VER >= 1910 @@ -722,8 +723,8 @@ template constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); } PYBIND11_NAMESPACE_END(constexpr_impl) -/// Return the index of the first type in Ts which satisfies Predicate. Returns sizeof...(Ts) if -/// none match. +/// Return the index of the first type in Ts which satisfies Predicate. +/// Returns sizeof...(Ts) if none match. template class Predicate, typename... Ts> constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate::value...); } @@ -842,7 +843,9 @@ PYBIND11_NAMESPACE_END(detail) #if defined(_MSC_VER) # pragma warning(push) -# pragma warning(disable: 4275) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class. +# pragma warning(disable: 4275) +// warning C4275: An exported class was derived from a class that wasn't exported. +// Can be ignored when derived from a STL class. #endif /// C++ bindings of builtin Python exceptions class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error { @@ -870,7 +873,9 @@ PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError) PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError) PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError) PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError) -PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error +PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or + /// handle::call fail due to a type + /// casting error PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) { throw std::runtime_error(reason); } @@ -974,13 +979,14 @@ public: template ::value>> any_container(It first, It last) : v(first, last) { } - // Implicit conversion constructor from any arbitrary container type with values convertible to T + // Implicit conversion constructor from any arbitrary container type + // with values convertible to T template ())), T>::value>> // NOLINTNEXTLINE(google-explicit-constructor) any_container(const Container &c) : any_container(std::begin(c), std::end(c)) { } - // initializer_list's aren't deducible, so don't get matched by the above template; we need this - // to explicitly allow implicit conversion from one: + // initializer_list's aren't deducible, so don't get matched by the above template; + // we need this to explicitly allow implicit conversion from one: template ::value>> any_container(const std::initializer_list &c) : any_container(c.begin(), c.end()) { } diff --git a/include/pybind11/detail/internals.h b/include/pybind11/detail/internals.h index 537719064..5bddbe35f 100644 --- a/include/pybind11/detail/internals.h +++ b/include/pybind11/detail/internals.h @@ -147,18 +147,22 @@ struct override_hash { /// Whenever binary incompatible changes are made to this structure, /// `PYBIND11_INTERNALS_VERSION` must be incremented. struct internals { - type_map registered_types_cpp; // std::type_index -> pybind11's type information - std::unordered_map> registered_types_py; // PyTypeObject* -> base type_info(s) + // std::type_index -> pybind11's type information + type_map registered_types_cpp; + // PyTypeObject* -> base type_info(s) + std::unordered_map> registered_types_py; std::unordered_multimap registered_instances; // void * -> instance* std::unordered_set, override_hash> inactive_override_cache; type_map> direct_conversions; std::unordered_map> patients; std::forward_list registered_exception_translators; - std::unordered_map shared_data; // Custom data to be shared across extensions + std::unordered_map shared_data; // Custom data to be shared across + // extensions #if PYBIND11_INTERNALS_VERSION == 4 std::vector unused_loader_patient_stack_remove_at_v5; #endif - std::forward_list static_strings; // Stores the std::strings backing detail::c_str() + std::forward_list static_strings; // Stores the std::strings backing + // detail::c_str() PyTypeObject *static_property_type; PyTypeObject *default_metaclass; PyObject *instance_base; diff --git a/include/pybind11/detail/type_caster_base.h b/include/pybind11/detail/type_caster_base.h index ea5ef6a2b..34100c3ae 100644 --- a/include/pybind11/detail/type_caster_base.h +++ b/include/pybind11/detail/type_caster_base.h @@ -426,7 +426,8 @@ PYBIND11_NOINLINE void instance::allocate_layout() { space += t->holder_size_in_ptrs; // holder instance } size_t flags_at = space; - space += size_in_ptrs(n_types); // status bytes (holder_constructed and instance_registered) + space += size_in_ptrs(n_types); // status bytes (holder_constructed and + // instance_registered) // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values, // in particular, need to be 0). Use Python's memory allocation functions: in Python 3.6 diff --git a/include/pybind11/iostream.h b/include/pybind11/iostream.h index 8c0772c28..d6cf22372 100644 --- a/include/pybind11/iostream.h +++ b/include/pybind11/iostream.h @@ -164,7 +164,8 @@ PYBIND11_NAMESPACE_END(detail) .. code-block:: cpp { - py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")}; + py::scoped_ostream_redirect output{ + std::cerr, py::module::import("sys").attr("stderr")}; std::cout << "Hello, World!"; } \endrst */ diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index 57f0c9094..489587835 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -325,7 +325,8 @@ template struct array_info : array_info using remove_all_extents_t = typename array_info::type; template using is_pod_struct = all_of< - std::is_standard_layout, // since we're accessing directly in memory we need a standard layout type + std::is_standard_layout, // since we're accessing directly in memory + // we need a standard layout type #if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803) // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after 5) // don't implement is_trivially_copyable, so approximate it diff --git a/include/pybind11/options.h b/include/pybind11/options.h index d74db1c68..810e5e010 100644 --- a/include/pybind11/options.h +++ b/include/pybind11/options.h @@ -51,7 +51,8 @@ private: struct state { bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings. - bool show_function_signatures = true; //< Include auto-generated function signatures in docstrings. + bool show_function_signatures = true; //< Include auto-generated function signatures + // in docstrings. }; static state &global_state() { diff --git a/include/pybind11/pybind11.h b/include/pybind11/pybind11.h index 58ac55996..754f22e9b 100644 --- a/include/pybind11/pybind11.h +++ b/include/pybind11/pybind11.h @@ -242,7 +242,8 @@ protected: rec->nargs_pos = cast_in::args_pos >= 0 ? static_cast(cast_in::args_pos) - : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if we have a kw_only + : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if + // we have a kw_only rec->has_args = cast_in::args_pos >= 0; rec->has_kwargs = cast_in::has_kwargs; @@ -263,7 +264,8 @@ protected: static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos, "py::pos_only must come before py::kw_only"); } - /* Generate a readable signature describing the function's arguments and return value types */ + /* Generate a readable signature describing the function's arguments and return + value types */ static constexpr auto signature = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name; PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); @@ -400,7 +402,8 @@ protected: handle th((PyObject *) tinfo->type); signature += th.attr("__module__").cast() + "." + - th.attr("__qualname__").cast(); // Python 3.3+, but we backport it to earlier versions + // Python 3.3+, but we backport it to earlier versions + th.attr("__qualname__").cast(); } else if (rec->is_new_style_constructor && arg_index == 0) { // A new-style `__init__` takes `self` as `value_and_holder`. // Rewrite it to the proper class type. @@ -639,7 +642,8 @@ protected: const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr), *it = overloads; - /* Need to know how many arguments + keyword arguments there are to pick the right overload */ + /* Need to know how many arguments + keyword arguments there are to pick the right + overload */ const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in); handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr, @@ -715,7 +719,8 @@ protected: function_call call(func, parent); - size_t args_to_copy = (std::min)(pos_args, n_args_in); // Protect std::min with parentheses + // Protect std::min with parentheses + size_t args_to_copy = (std::min)(pos_args, n_args_in); size_t args_copied = 0; // 0. Inject new-style `self` argument @@ -956,7 +961,8 @@ protected: - catch the exception and call PyErr_SetString or PyErr_SetObject to set a standard (or custom) Python exception, or - do nothing and let the exception fall through to the next translator, or - - delegate translation to the next translator by throwing a new type of exception. */ + - delegate translation to the next translator by throwing a new type of exception. + */ auto &local_exception_translators = get_local_internals().registered_exception_translators; if (detail::apply_exception_translators(local_exception_translators)) { @@ -1169,8 +1175,8 @@ public: Adds an object to the module using the given name. Throws if an object with the given name already exists. - ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11 has - established will, in most cases, break things. + ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11 + has established will, in most cases, break things. \endrst */ PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) { if (!overwrite && hasattr(*this, name)) { @@ -1197,7 +1203,8 @@ public: static module_ create_extension_module(const char *name, const char *doc, module_def *def) { #if PY_MAJOR_VERSION >= 3 // module_def is PyModuleDef - def = new (def) PyModuleDef { // Placement new (not an allocation). + // Placement new (not an allocation). + def = new (def) PyModuleDef { /* m_base */ PyModuleDef_HEAD_INIT, /* m_name */ name, /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr, @@ -1456,7 +1463,8 @@ public: none_of...>::value || // no base class arguments, or: ( constexpr_sum(is_pyobject::value...) == 1 && // Exactly one base constexpr_sum(is_base::value...) == 0 && // no template option bases - none_of...>::value), // no multiple_inheritance attr + // no multiple_inheritance attr + none_of...>::value), "Error: multiple inheritance bases must be specified via class_ template options"); type_record record; @@ -2562,10 +2570,11 @@ inline function get_type_override(const void *this_ptr, const type_info *this_ty PYBIND11_NAMESPACE_END(detail) /** \rst - Try to retrieve a python method by the provided name from the instance pointed to by the this_ptr. + Try to retrieve a python method by the provided name from the instance pointed to by the + this_ptr. - :this_ptr: The pointer to the object the overridden method should be retrieved for. This should be - the first non-trampoline class encountered in the inheritance chain. + :this_ptr: The pointer to the object the overridden method should be retrieved for. This should + be the first non-trampoline class encountered in the inheritance chain. :name: The name of the overridden Python method to retrieve. :return: The Python method by this name from the object or an empty function wrapper. \endrst */ @@ -2590,9 +2599,10 @@ template function get_override(const T *this_ptr, const char *name) { } while (false) /** \rst - Macro to populate the virtual method in the trampoline class. This macro tries to look up a method named 'fn' - from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return - the appropriate type. See :ref:`overriding_virtuals` for more information. This macro should be used when the method + Macro to populate the virtual method in the trampoline class. This macro tries to look up a + method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument + conversions to call this method and return the appropriate type. + See :ref:`overriding_virtuals` for more information. This macro should be used when the method name in C is not the same as the method name in Python. For example with `__str__`. .. code-block:: cpp @@ -2613,8 +2623,8 @@ template function get_override(const T *this_ptr, const char *name) { } while (false) /** \rst - Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it - throws if no override can be found. + Macro for pure virtual functions, this function is identical to + :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found. \endrst */ #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \ do { \ @@ -2623,9 +2633,10 @@ template function get_override(const T *this_ptr, const char *name) { } while (false) /** \rst - Macro to populate the virtual method in the trampoline class. This macro tries to look up the method - from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return - the appropriate type. This macro should be used if the method name in C and in Python are identical. + Macro to populate the virtual method in the trampoline class. This macro tries to look up the + method from the Python side, deals with the :ref:`gil` and necessary argument conversions to + call this method and return the appropriate type. This macro should be used if the method name + in C and in Python are identical. See :ref:`overriding_virtuals` for more information. .. code-block:: cpp @@ -2650,8 +2661,8 @@ template function get_override(const T *this_ptr, const char *name) { PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) /** \rst - Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`, except that it throws - if no override can be found. + Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`, + except that it throws if no override can be found. \endrst */ #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \ PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index d39e71045..bdb3b9174 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -161,7 +161,8 @@ public: /// Return the object's current reference count int ref_count() const { return static_cast(Py_REFCNT(derived().ptr())); } - // TODO PYBIND11_DEPRECATED("Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()") + // TODO PYBIND11_DEPRECATED( + // "Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()") handle get_type() const; private: @@ -337,7 +338,9 @@ PYBIND11_NAMESPACE_END(detail) #if defined(_MSC_VER) # pragma warning(push) -# pragma warning(disable: 4275 4251) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class. +# pragma warning(disable: 4275 4251) +// warning C4275: An exported class was derived from a class that wasn't exported. +// Can be ignored when derived from a STL class. #endif /// Fetch and hold an error which was already set in Python. An instance of this is typically /// thrown to propagate python-side errors back through C++ which can either be caught manually or @@ -1745,7 +1748,8 @@ public: See also: Python C API documentation for `PyMemoryView_FromBuffer`_. - .. _PyMemoryView_FromBuffer: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer + .. _PyMemoryView_FromBuffer: + https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer :param ptr: Pointer to the buffer. :param itemsize: Byte size of an element. @@ -1800,7 +1804,8 @@ public: See also: Python C API documentation for `PyMemoryView_FromBuffer`_. - .. _PyMemoryView_FromMemory: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory + .. _PyMemoryView_FromMemory: + https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory \endrst */ static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) { PyObject* ptr = PyMemoryView_FromMemory( diff --git a/include/pybind11/stl_bind.h b/include/pybind11/stl_bind.h index 6db1faf40..2f997d6b0 100644 --- a/include/pybind11/stl_bind.h +++ b/include/pybind11/stl_bind.h @@ -44,7 +44,8 @@ struct is_comparable< container_traits::is_comparable>> : std::true_type { }; -/* For a vector/map data structure, recursively check the value type (which is std::pair for maps) */ +/* For a vector/map data structure, recursively check the value type + (which is std::pair for maps) */ template struct is_comparable::is_vector>> { static constexpr const bool value = @@ -384,7 +385,8 @@ template auto vector_if_insertion_operator(Cl } // Provide the buffer interface for vectors if we have data() and we have a format for it -// GCC seems to have "void std::vector::data()" - doing SFINAE on the existence of data() is insufficient, we need to check it returns an appropriate pointer +// GCC seems to have "void std::vector::data()" - doing SFINAE on the existence of data() +// is insufficient, we need to check it returns an appropriate pointer template struct vector_has_data_and_format : std::false_type {}; template @@ -408,7 +410,8 @@ void vector_buffer_impl(Class_& cl, std::true_type) { static_assert(vector_has_data_and_format::value, "There is not an appropriate format descriptor for this vector"); - // numpy.h declares this for arbitrary types, but it may raise an exception and crash hard at runtime if PYBIND11_NUMPY_DTYPE hasn't been called, so check here + // numpy.h declares this for arbitrary types, but it may raise an exception and crash hard + // at runtime if PYBIND11_NUMPY_DTYPE hasn't been called, so check here format_descriptor::format(); cl.def_buffer([](Vector& v) -> buffer_info { diff --git a/tests/constructor_stats.h b/tests/constructor_stats.h index 8ee404792..ccb623e1c 100644 --- a/tests/constructor_stats.h +++ b/tests/constructor_stats.h @@ -72,8 +72,10 @@ inspection/testing in python) by using the functions with `print_` replaced with class ConstructorStats { protected: - std::unordered_map _instances; // Need a map rather than set because members can shared address with parents - std::list _values; // Used to track values (e.g. of value constructors) + std::unordered_map _instances; // Need a map rather than set because members can + // shared address with parents + std::list _values; // Used to track values + // (e.g. of value constructors) public: int default_constructions = 0; int copy_constructions = 0; diff --git a/tests/pybind11_tests.h b/tests/pybind11_tests.h index 9b9992323..f6e1a6523 100644 --- a/tests/pybind11_tests.h +++ b/tests/pybind11_tests.h @@ -5,8 +5,7 @@ #if defined(_MSC_VER) && _MSC_VER < 1910 // We get some really long type names here which causes MSVC 2015 to emit warnings -# pragma warning( \ - disable : 4503) // warning C4503: decorated name length exceeded, name was truncated +# pragma warning(disable : 4503) // NOLINT: warning C4503: decorated name length exceeded, name was truncated #endif namespace py = pybind11; diff --git a/tests/test_class.cpp b/tests/test_class.cpp index 7445b3c02..851bc00ca 100644 --- a/tests/test_class.cpp +++ b/tests/test_class.cpp @@ -22,7 +22,8 @@ #include #if defined(_MSC_VER) -# pragma warning(disable: 4324) // warning C4324: structure was padded due to alignment specifier +# pragma warning(disable: 4324) +// warning C4324: structure was padded due to alignment specifier #endif // test_brace_initialization @@ -534,22 +535,24 @@ CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared); #define CHECK_BROKEN(N) static_assert(std::is_same>::value, \ "Breaks1 has wrong type!"); -//// Two holder classes: -//typedef py::class_, std::unique_ptr>, std::unique_ptr>> Breaks1; -//CHECK_BROKEN(1); -//// Two aliases: -//typedef py::class_, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2; -//CHECK_BROKEN(2); -//// Holder + 2 aliases -//typedef py::class_, std::unique_ptr>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3; -//CHECK_BROKEN(3); -//// Alias + 2 holders -//typedef py::class_, std::unique_ptr>, BreaksTramp<-4>, std::shared_ptr>> Breaks4; -//CHECK_BROKEN(4); -//// Invalid option (not a subclass or holder) -//typedef py::class_, BreaksTramp<-4>> Breaks5; -//CHECK_BROKEN(5); -//// Invalid option: multiple inheritance not supported: -//template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {}; -//typedef py::class_, BreaksBase<-6>, BreaksBase<-7>> Breaks8; -//CHECK_BROKEN(8); +#ifdef PYBIND11_NEVER_DEFINED_EVER +// Two holder classes: +typedef py::class_, std::unique_ptr>, std::unique_ptr>> Breaks1; +CHECK_BROKEN(1); +// Two aliases: +typedef py::class_, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2; +CHECK_BROKEN(2); +// Holder + 2 aliases +typedef py::class_, std::unique_ptr>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3; +CHECK_BROKEN(3); +// Alias + 2 holders +typedef py::class_, std::unique_ptr>, BreaksTramp<-4>, std::shared_ptr>> Breaks4; +CHECK_BROKEN(4); +// Invalid option (not a subclass or holder) +typedef py::class_, BreaksTramp<-4>> Breaks5; +CHECK_BROKEN(5); +// Invalid option: multiple inheritance not supported: +template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {}; +typedef py::class_, BreaksBase<-6>, BreaksBase<-7>> Breaks8; +CHECK_BROKEN(8); +#endif diff --git a/tests/test_kwargs_and_defaults.cpp b/tests/test_kwargs_and_defaults.cpp index 0e262dad2..d09630a8c 100644 --- a/tests/test_kwargs_and_defaults.cpp +++ b/tests/test_kwargs_and_defaults.cpp @@ -153,10 +153,12 @@ TEST_SUBMODULE(kwargs_and_defaults, m) { // These should fail to compile: +#ifdef PYBIND11_NEVER_DEFINED_EVER // argument annotations are required when using kw_only -// m.def("bad_kw_only1", [](int) {}, py::kw_only()); + m.def("bad_kw_only1", [](int) {}, py::kw_only()); // can't specify both `py::kw_only` and a `py::args` argument -// m.def("bad_kw_only2", [](int i, py::args) {}, py::kw_only(), "i"_a); + m.def("bad_kw_only2", [](int i, py::args) {}, py::kw_only(), "i"_a); +#endif // test_function_signatures (along with most of the above) struct KWClass { void foo(int, float) {} }; diff --git a/tests/test_modules.cpp b/tests/test_modules.cpp index ce61c1a25..ba80a64c9 100644 --- a/tests/test_modules.cpp +++ b/tests/test_modules.cpp @@ -49,7 +49,8 @@ TEST_SUBMODULE(modules, m) { .def(py::init<>()) .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal) .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal) - .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default + .def_readwrite("a1", &B::a1) // def_readonly uses an internal + // reference return policy by default .def_readwrite("a2", &B::a2); // This is intentionally "py::module" to verify it still can be used in place of "py::module_" diff --git a/tests/test_numpy_array.cpp b/tests/test_numpy_array.cpp index bc1797845..17fc4de2e 100644 --- a/tests/test_numpy_array.cpp +++ b/tests/test_numpy_array.cpp @@ -399,7 +399,8 @@ TEST_SUBMODULE(numpy_array, sm) { // test_initializer_list // Issue (unnumbered; reported in #788): regression: initializer lists can be ambiguous - sm.def("array_initializer_list1", []() { return py::array_t(1); }); // { 1 } also works, but clang warns about it + sm.def("array_initializer_list1", []() { return py::array_t(1); }); + // { 1 } also works for the above, but clang warns about it sm.def("array_initializer_list2", []() { return py::array_t({ 1, 2 }); }); sm.def("array_initializer_list3", []() { return py::array_t({ 1, 2, 3 }); }); sm.def("array_initializer_list4", []() { return py::array_t({ 1, 2, 3, 4 }); }); diff --git a/tests/test_numpy_dtypes.cpp b/tests/test_numpy_dtypes.cpp index 468a89a3c..a6566c5c6 100644 --- a/tests/test_numpy_dtypes.cpp +++ b/tests/test_numpy_dtypes.cpp @@ -308,10 +308,12 @@ TEST_SUBMODULE(numpy_dtypes, m) { PYBIND11_NUMPY_DTYPE_EX(StructWithUglyNames, __x__, "x", __y__, "y"); - // If uncommented, this should produce a static_assert failure telling the user that the struct +#ifdef PYBIND11_NEVER_DEFINED_EVER + // If enabled, this should produce a static_assert failure telling the user that the struct // is not a POD type -// struct NotPOD { std::string v; NotPOD() : v("hi") {}; }; -// PYBIND11_NUMPY_DTYPE(NotPOD, v); + struct NotPOD { std::string v; NotPOD() : v("hi") {}; }; + PYBIND11_NUMPY_DTYPE(NotPOD, v); +#endif // Check that dtypes can be registered programmatically, both from // initializer lists of field descriptors and from other containers. diff --git a/tests/test_virtual_functions.cpp b/tests/test_virtual_functions.cpp index 558cd9440..1e47b367d 100644 --- a/tests/test_virtual_functions.cpp +++ b/tests/test_virtual_functions.cpp @@ -370,9 +370,12 @@ TEST_SUBMODULE(virtual_functions, m) { public: using OverrideTest::OverrideTest; std::string str_value() override { PYBIND11_OVERRIDE(std::string, OverrideTest, str_value); } - // Not allowed (uncommenting should hit a static_assert failure): we can't get a reference - // to a python numeric value, since we only copy values in the numeric type caster: -// std::string &str_ref() override { PYBIND11_OVERRIDE(std::string &, OverrideTest, str_ref); } + // Not allowed (enabling the below should hit a static_assert failure): we can't get a + // reference to a python numeric value, since we only copy values in the numeric type + // caster: +#ifdef PYBIND11_NEVER_DEFINED_EVER + std::string &str_ref() override { PYBIND11_OVERRIDE(std::string &, OverrideTest, str_ref); } +#endif // But we can work around it like this: private: std::string _tmp; @@ -389,7 +392,9 @@ TEST_SUBMODULE(virtual_functions, m) { py::class_(m, "OverrideTest") .def(py::init()) .def("str_value", &OverrideTest::str_value) -// .def("str_ref", &OverrideTest::str_ref) +#ifdef PYBIND11_NEVER_DEFINED_EVER + .def("str_ref", &OverrideTest::str_ref) +#endif .def("A_value", &OverrideTest::A_value) .def("A_ref", &OverrideTest::A_ref); @@ -492,11 +497,11 @@ public: // Inheritance approach 2: templated trampoline classes. // // Advantages: -// - we have only 2 (template) class and 4 method declarations (one per virtual method, plus one for -// any override of a pure virtual method), versus 4 classes and 6 methods (MI) or 4 classes and 11 -// methods (repeat). -// - Compared to MI, we also don't have to change the non-trampoline inheritance to virtual, and can -// properly inherit constructors. +// - we have only 2 (template) class and 4 method declarations (one per virtual method, plus one +// for any override of a pure virtual method), versus 4 classes and 6 methods (MI) or 4 classes +// and 11 methods (repeat). +// - Compared to MI, we also don't have to change the non-trampoline inheritance to virtual, and +// can properly inherit constructors. // // Disadvantage: // - the compiler must still generate and compile 14 different methods (more, even, than the 11 @@ -518,8 +523,8 @@ public: int unlucky_number() override { PYBIND11_OVERRIDE(int, Base, unlucky_number, ); } double lucky_number() override { PYBIND11_OVERRIDE(double, Base, lucky_number, ); } }; -// Since C_Tpl and D_Tpl don't declare any new virtual methods, we don't actually need these (we can -// use PyB_Tpl and PyB_Tpl for the trampoline classes instead): +// Since C_Tpl and D_Tpl don't declare any new virtual methods, we don't actually need these +// (we can use PyB_Tpl and PyB_Tpl for the trampoline classes instead): /* template class PyC_Tpl : public PyB_Tpl { public: