Commit Graph

1581 Commits

Author SHA1 Message Date
Aaron Gokaslan
9c04c7b0f1
chore: Delete copy ctor/assign for GIL RAIIs (#4183)
* chore: Delete copy ctor/assign for GIL RAIIs

* Fix typo

* Delete copy ops for local gil scoped acquire
2022-09-19 12:56:31 -04:00
Ralf W. Grosse-Kunstleve
e5a5a83c61 Merge branch 'master' into sh_merge_master 2022-09-15 05:35:19 -07:00
Sergei Izmailov
8524b20c3c
fix: Python-3.12 compatibility (#4168)
* fix: Python-3.12 compatibility

Enable dynamic attributes for `pybind11_static_property`

* Add future-notice comment
2022-09-14 13:56:40 -07:00
Ralf W. Grosse-Kunstleve
fac23b6f65
error_fetch_and_normalize: PyPy 7.3.10+ does not need the PR #4079 workaround anymore. (#4154) 2022-08-24 13:08:24 -07:00
Brad Messer
a48ec3e882
Words matter updates (#4155)
* Remove sanity check from code base.

* Use main over master.

* Better alternative that doesn't collide with language keywords/frequent usage words.
2022-08-24 07:34:31 -07:00
Ralf W. Grosse-Kunstleve
6df86934c2 Merge branch 'master' into sh_merge_master 2022-08-21 19:32:35 -07:00
Ralf W. Grosse-Kunstleve
68e6fdaa90
embed.h Python 3.11 config.use_environment=1 + PYTHONPATH test (#4119)
* Add debug fprintf to test_interpreter.cpp

* Update `sys.path` from `PYTHONPATH` in Python >= 3.11 branch of `initialize_interpreter()`

* Use `config.isolated = 0; config.use_environment = 1;`

As suggsted by @vstinner here: https://github.com/pybind/pybind11/pull/4119#issuecomment-1219442853

* Add `TEST_CASE("PYTHONPATH is used to update sys.path")`

* Fix clang-tidy error.

* Use `_putenv_s()` under Windows.

* Fix clang-tidy error: argument name ... in comment does not match parameter name

* Remove slash from PYTHONPATH addition, to work around Windows slash-vs-backslash issue.

* Use `py::str(...)` instead of `.attr("__str__")` as suggested by @skylion007

Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>

Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
2022-08-21 09:44:01 -07:00
Aaron Gokaslan
81f35d29c6
chore: Mark detail:forward_like as constexpr (#4147) 2022-08-20 17:05:07 -04:00
Stephan T. Lavavej
2d59b43cbf
Qualify detail::forward_like to avoid conflict. (#4136)
C++23 feature: P2445R1 forward_like()
2022-08-11 21:19:39 -07:00
Aaron Gokaslan
6abb7de6cd
chore: Use PyObject_GenericGetDict and PyObject_GenericSetDict functions (#4106)
* Try to update getset_dict APIs for 3.11

* Update API for all Python versions

* Test ifdef for forward explicit forward compat

* Fix ifdef
2022-08-08 14:28:33 -04:00
Ralf W. Grosse-Kunstleve
e654460418 Disable mingw warning.
```
cd /d D:\a\pybind11\pybind11\build3\tests && D:\a\_temp\msys64\mingw64\bin\c++.exe -DPYBIND11_ENABLE_TYPE_CASTER_ODR_GUARD_IF_AVAILABLE -DPYBIND11_TEST_BOOST -DPYBIND11_TEST_EIGEN -Dpybind11_tests_EXPORTS @CMakeFiles/pybind11_tests.dir/includes_CXX.rsp -Os -DNDEBUG -fvisibility=hidden -Wall -Wextra -Wconversion -Wcast-qual -Wdeprecated -Wundef -Wnon-virtual-dtor -Werror -std=c++17 -MD -MT tests/CMakeFiles/pybind11_tests.dir/test_stl.cpp.obj -MF CMakeFiles\pybind11_tests.dir\test_stl.cpp.obj.d -o CMakeFiles\pybind11_tests.dir\test_stl.cpp.obj -c D:\a\pybind11\pybind11\tests\test_stl.cpp
In file included from D:/a/pybind11/pybind11/include/pybind11/stl.h:32,
                 from D:\a\pybind11\pybind11\tests\test_stl.cpp:10:
In member function 'std::enable_if_t<((__exactly_once<std::variant<_Types>::__accepted_type<_Tp&&, typename std::enable_if<__not_self<_Tp&&>, void>::type> > && is_constructible_v<std::variant<_Types>::__accepted_type<_Tp&&, typename std::enable_if<__not_self<_Tp&&>, void>::type>, _Tp>) && is_assignable_v<std::variant<_Types>::__accepted_type<_Tp&&, typename std::enable_if<__not_self<_Tp&&>, void>::type>&, _Tp>), std::variant<_Types>&> std::variant<_Types>::operator=(_Tp&&) [with _Tp = std::nullptr_t; _Types = {int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}]',
    inlined from 'std::enable_if_t<((__exactly_once<std::variant<_Types>::__accepted_type<_Tp&&, typename std::enable_if<__not_self<_Tp&&>, void>::type> > && is_constructible_v<std::variant<_Types>::__accepted_type<_Tp&&, typename std::enable_if<__not_self<_Tp&&>, void>::type>, _Tp>) && is_assignable_v<std::variant<_Types>::__accepted_type<_Tp&&, typename std::enable_if<__not_self<_Tp&&>, void>::type>&, _Tp>), std::variant<_Types>&> std::variant<_Types>::operator=(_Tp&&) [with _Tp = std::nullptr_t; _Types = {int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}]' at D:/a/_temp/msys64/mingw64/include/c++/12.1.0/variant:1469:2,
    inlined from 'bool pybind11::detail::variant_caster<V<Ts ...> >::load_alternative(pybind11::handle, bool, pybind11::detail::type_list<U, Us ...>) [with U = std::nullptr_t; Us = {}; V = std::variant; Ts = {int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}]' at D:/a/pybind11/pybind11/include/pybind11/stl.h:375:19,
    inlined from 'bool pybind11::detail::variant_caster<V<Ts ...> >::load_alternative(pybind11::handle, bool, pybind11::detail::type_list<U, Us ...>) [with U = double; Us = {std::nullptr_t}; V = std::variant; Ts = {int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}]' at D:/a/pybind11/pybind11/include/pybind11/stl.h:378:32,
    inlined from 'bool pybind11::detail::variant_caster<V<Ts ...> >::load_alternative(pybind11::handle, bool, pybind11::detail::type_list<U, Us ...>) [with U = std::__cxx11::basic_string<char>; Us = {double, std::nullptr_t}; V = std::variant; Ts = {int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}]' at D:/a/pybind11/pybind11/include/pybind11/stl.h:378:32,
    inlined from 'bool pybind11::detail::variant_caster<V<Ts ...> >::load_alternative(pybind11::handle, bool, pybind11::detail::type_list<U, Us ...>) [with U = int; Us = {std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}; V = std::variant; Ts = {int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}]' at D:/a/pybind11/pybind11/include/pybind11/stl.h:378:32:
D:/a/_temp/msys64/mingw64/include/c++/12.1.0/variant:1475:38: error: 'caster.pybind11::detail::type_caster_odr_guard<std::nullptr_t, pybind11::detail::type_caster<std::nullptr_t, void> >::<unnamed>.pybind11::detail::type_caster<std::nullptr_t, void>::<unnamed>.pybind11::detail::void_caster<std::nullptr_t>::value' may be used uninitialized [-Werror=maybe-uninitialized]
 1475 |             std::get<__index>(*this) = std::forward<_Tp>(__rhs);
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~
D:/a/pybind11/pybind11/include/pybind11/stl.h: In function 'bool pybind11::detail::variant_caster<V<Ts ...> >::load_alternative(pybind11::handle, bool, pybind11::detail::type_list<U, Us ...>) [with U = int; Us = {std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}; V = std::variant; Ts = {int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::nullptr_t}]':
D:/a/pybind11/pybind11/include/pybind11/stl.h:373:14: note: 'caster.pybind11::detail::type_caster_odr_guard<std::nullptr_t, pybind11::detail::type_caster<std::nullptr_t, void> >::<unnamed>.pybind11::detail::type_caster<std::nullptr_t, void>::<unnamed>.pybind11::detail::void_caster<std::nullptr_t>::value' was declared here
  373 |         auto caster = make_caster<U>();
      |              ^~~~~~
cc1plus.exe: all warnings being treated as errors
```
2022-08-07 21:49:37 -07:00
Ralf W. Grosse-Kunstleve
1f6e9a8945 Merge branch 'master' into sh_merge_master 2022-08-07 15:43:25 -07:00
Aaron Gokaslan
88a1bb9260
chore: remove unnecessary temporary std::pair (#4103) 2022-08-01 15:48:44 -04:00
Ralf W. Grosse-Kunstleve
3665530264
Add -DPYBIND11_WERROR=ON to mingw cmake commands (#4073)
* Add `-DPYBIND11_WERROR=ON` to mingw cmake commands (and `-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON`).

* Using no-destructor idiom to side-step overzealous MINGW warning.

* Add __MINGW32__ pragma GCC diagnostic ignored in eigen.h

* Add another no-destructor workaround.

* Temporarily add -k (keep-going) flags to hopefully speed up finding all warnings.

* Revert "Temporarily add -k (keep-going) flags to hopefully speed up finding all warnings."

This reverts commit f36b0af8f9.

* Very minor shuffle to avoid MSVC warnings.

* Remove all `:BOOL` as suggested by @henryiii
2022-08-01 06:18:48 -07:00
Aaron Gokaslan
b07975f492
Fix missing undef in pytypes (#4087) 2022-07-22 11:52:01 -04:00
Ralf W. Grosse-Kunstleve
4d774ec218 Merge branch 'master' into sh_merge_master 2022-07-21 06:53:22 -07:00
Ralf W. Grosse-Kunstleve
9a2963734d
More systematic gcc & clang coverage (#4083)
* More systematic gcc coverage, based on https://github.com/pybind/pybind11/pull/4074#issuecomment-1188385580

* Fix complete fail.

* Resolve GCC 11 & 12 "redundant move in return statement" warnings.

* Also add clang 11, 12, 13 (to gather info for warning suppressions).

* Add & use `PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING`
2022-07-21 06:40:34 -07:00
Ralf W. Grosse-Kunstleve
c557f9a3ad
[smart_holder] type_caster ODR guard (#4022)
* Insert type_caster_odr_guard<> (an empty struct to start with).

* Add odr_guard_registry() used in type_caster_odr_guard() default constructor.

* Add minimal_real_caster (from PR #3862) to test_async, test_buffers

* VERY MESSY SNAPSHOT of WIP, this was the starting point for cl/454658864, which has more changes on top.

* Restore original test_async, test_buffers from current smart_holder HEAD

* Copy from cl/454991845 snapshot Jun 14, 5:08 PM

* Cleanup of tests. Systematically insert `if (make_caster<T>::translation_unit_local) {`

* Small simplification of odr_guard_impl()

* WIP

* Add PYBIND11_SOURCE_FILE_LINE macro.

* Replace PYBIND11_TYPE_CASTER_UNIQUE_IDENTIFIER with PYBIND11_TYPE_CASTER_SOURCE_FILE_LINE, baked into PYBIND11_TYPE_CASTER macro.

* Add more PYBIND11_DETAIL_TYPE_CASTER_ACCESS_TRANSLATION_UNIT_LOCAL; resolves "unused" warning when compiling test_custom_type_casters.cpp

* load_type fixes & follow-on cleanup

* Strip ./ from source_file_line

* Add new tests to CMakeLists.txt, disable PYBIND11_WERROR

* Replace C++17 syntax. Compiles with Debian clang 13 C++11 mode, but fails to link. Trying GitHub Actions anyway to see if there are any platforms that support https://en.cppreference.com/w/cpp/language/tu_local before C++20. Note that Debian clang 13 C++17 works locally.

* Show C++ version along with ODR VIOLATION DETECTED message.

* Add source_file_line_basename()

* Introduce PYBIND11_TYPE_CASTER_ODR_GUARD_ON (but not set automatically).

* Minor cleanup.

* Set PYBIND11_TYPE_CASTER_ODR_GUARD_ON automatically.

* Resolve clang-tidy error.

* Compatibility with old compilers.

* Fix off-by-one in source_file_line_basename()

* Report PYBIND11_INTERNALS_ID & C++ Version from pytest_configure()

* Restore use of PYBIND11_WERROR

* Move cpp_version_in_use() from cast.h to pybind11_tests.cpp

* define PYBIND11_DETAIL_ODR_GUARD_IMPL_THROW_DISABLED true in test_odr_guard_1,2.cpp

* IWYU cleanup of detail/type_caster_odr_guard.h

* Replace `throw err;` to resolve clang-tidy error.

* Add new header filename to CMakeLists.txt, test_files.py

* Experiment: Try any C++17 compiler.

* Fix ifdef for pragma GCC diagnostic.

* type_caster_odr_guard_impl() cleanup

* Move type_caster_odr_guard to type_caster_odr_guard.h

* Rename test_odr_guard* to test_type_caster_odr_guard*

* Remove comments that are (now) more distracting than helpful.

* Mark tu_local_no_data_always_false operator bool as explicit (clang-tidy). See also: https://stackoverflow.com/questions/39995573/when-can-i-use-explicit-operator-bool-without-a-cast

* New PYBIND11_TYPE_CASTER_ODR_GUARD_STRICT option (current on by default).

* Add test_type_caster_odr_registry_values(), test_type_caster_odr_violation_detected_counter()

* Report UNEXPECTED: test_type_caster_odr_guard_2.cpp prevailed (but do not fail).

* Apply clang-tidy suggestion.

* Attempt to handle valgrind behavior.

* Another attempt to handle valgrind behavior.

* Yet another attempt to handle valgrind behavior.

* Trying a new direction: show compiler info & std for UNEXPECTED: type_caster_odr_violation_detected_count() == 0

* compiler_info MSVC fix. num_violations == 0 condition.

* assert pybind11_tests.compiler_info is not None

* Introduce `make_caster_intrinsic<T>`, to be able to undo the 2 changes from `load_type` to `load_type<T>`. This is to avoid breaking 2 `pybind11::detail::load_type()` calls found in the wild (Google global testing).

One of the breakages in the wild was: 0f0f600767/python/tensorstore/subscript_method.h (L61)

* Add test for stl.h / stl_bind.h mix.

Manually verified that the ODR guard detects the ODR violation:

```
C++ Info: Debian Clang 13.0.1 C++17 __pybind11_internals_v4_clang_libstdcpp_cxxabi1002_sh_def__
=========================================================== test session starts ============================================================
platform linux -- Python 3.9.12, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 -- /usr/bin/python3
...
================================================================= FAILURES =================================================================
_____________________________________________ test_type_caster_odr_violation_detected_counter ______________________________________________

    def test_type_caster_odr_violation_detected_counter():
        ...
        else:
>           assert num_violations == 1
E           assert 2 == 1
E             +2
E             -1

num_violations = 2

test_type_caster_odr_guard_1.py:51: AssertionError
========================================================= short test summary info ==========================================================
FAILED test_type_caster_odr_guard_1.py::test_type_caster_odr_violation_detected_counter - assert 2 == 1
======================================================= 1 failed, 5 passed in 0.08s ========================================================
```

* Eliminate need for `PYBIND11_DETAIL_TYPE_CASTER_ACCESS_TRANSLATION_UNIT_LOCAL` macro.

Copying code first developed by @amauryfa. I tried this at an earlier stage, but by itself this was insufficient. In the meantime I added in the TU-local mechanisms: trying again.

Passes local testing:
```
DISABLED std::system_error: ODR VIOLATION DETECTED: pybind11::detail::type_caster<mrc_ns::type_mrc>: SourceLocation1="/usr/local/google/home/rwgk/forked/pybind11/tests/test_type_caster_odr_guard_1.cpp:18", SourceLocation2="/usr/local/google/home/rwgk/forked/pybind11/tests/test_type_caster_odr_guard_2.cpp:19"
C++ Info: Debian Clang 13.0.1 C++17 __pybind11_internals_v4_clang_libstdcpp_cxxabi1002_sh_def__
=========================================================== test session starts ============================================================
platform linux -- Python 3.9.12, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /usr/local/google/home/rwgk/forked/pybind11/tests, configfile: pytest.ini
collected 6 items

test_type_caster_odr_guard_1.py::test_type_mrc_to_python PASSED
test_type_caster_odr_guard_1.py::test_type_mrc_from_python PASSED
test_type_caster_odr_guard_1.py::test_type_caster_odr_registry_values PASSED
test_type_caster_odr_guard_1.py::test_type_caster_odr_violation_detected_counter PASSED
test_type_caster_odr_guard_2.py::test_type_mrc_to_python PASSED
test_type_caster_odr_guard_2.py::test_type_mrc_from_python PASSED

============================================================ 6 passed in 0.01s =============================================================
```

* tu_local_descr with src_loc experiment

* clang-tidy suggested fixes

* Use source_file_line_from_sloc in type_caster_odr_guard_registry

* Disable type_caster ODR guard for __INTEL_COMPILER (see comment). Also turn off printf.

* Add missing include (discovered via google-internal testing).

* Work `scr_loc` into `descr`

* Use `TypeCasterType::name.sloc` instead of `source_file_line.sloc`

Manual re-verification:

```
+++ b/tests/test_type_caster_odr_guard_2.cpp
-    // m.def("pass_vector_type_mrc", mrc_ns::pass_vector_type_mrc);
+    m.def("pass_vector_type_mrc", mrc_ns::pass_vector_type_mrc);
```

```
>           assert num_violations == 1
E           assert 2 == 1

num_violations = 2

test_type_caster_odr_guard_1.py:51: AssertionError
```

* Fix small oversight (src_loc::here() -> src_loc{nullptr, 0}).

* Remove PYBIND11_DETAIL_TYPE_CASTER_ACCESS_TRANSLATION_UNIT_LOCAL macro completely.

* Remove PYBIND11_TYPE_CASTER_SOURCE_FILE_LINE macro completely. Some small extra cleanup.

* Minor tweaks looking at the PR with a fresh eye.

* src_loc comments

* Add new test_descr_src_loc & and fix descr.h `concat()` `src_loc` bug discovered while working on the test.

* Some more work on source code comments.

* Fully document the ODR violations in the ODR guard itself and introduce `PYBIND11_TYPE_CASTER_ODR_GUARD_ON_IF_AVAILABLE`

* Update comment (incl. mention of deadsnakes known to not work as intended).

* Use no-destructor idiom for type_caster_odr_guard_registry, as suggested by @laramiel

* Fix clang-tidy error: 'auto reg' can be declared as 'auto *reg' [readability-qualified-auto,-warnings-as-errors]

* WIP

* Revert "WIP" (tu_local_no_data_always_false_base experiment).

This reverts commit 31e8ac562f.

* Change `PYBIND11_TYPE_CASTER_ODR_GUARD_ON` to `PYBIND11_ENABLE_TYPE_CASTER_ODR_GUARD`, based on a suggestion by @rainwoodman

* Improved `#if` determining `PYBIND11_ENABLE_TYPE_CASTER_ODR_GUARD`, based on suggestion by @laramiel

* Make `descr::sloc` `const`, as suggested by @rainwoodman

* Rename macro to `PYBIND11_DETAIL_TYPE_CASTER_ODR_GUARD_IMPL_DEBUG`, as suggested by @laramiel

* Tweak comments some more (add "white hat hacker" analogy).

* Bring back `PYBIND11_CPP17` in determining `PYBIND11_ENABLE_TYPE_CASTER_ODR_GUARD`, to hopefully resolve most if not all of the many CI failures (89 failing, 32 successful: https://github.com/pybind/pybind11/runs/7430295771).

* Try another workaround for `__has_builtin`-related breakages (https://github.com/pybind/pybind11/runs/7430720321).

* Remove `defined(__has_builtin)` and subconditions.

* Update "known to not work" expectation in test and comment.

* `pytest.skip` `num_violations == 0` only `#ifdef __NO_INLINE__` (irrespective of the compiler)

* Systematically change all new `#ifdef` to `#if defined` (review suggestion).

* Bring back MSVC comment that got lost while experimenting.
2022-07-21 06:38:21 -07:00
Ralf W. Grosse-Kunstleve
cb35a3c143
For PyPy only, re-enable old behavior (runs the risk of masking bugs) (#4079)
* For PyPy only, re-enable old behavior (likely to mask bugs), to avoid segfault with unknown root cause.

Change prompted by https://github.com/pybind/pybind11/issues/4075

* Undo the change in tests/test_exceptions.py

I turns out (I forgot) that PyPy segfaults in `test_flaky_exception_failure_point_init` already before the `MISMATCH` code path is reached:

https://github.com/pybind/pybind11/runs/7383663596

```
RPython traceback:
test_exceptions.py .......X.........Error in cpyext, CPython compatibility layer:
  File "pypy_module_cpyext.c", line 14052, in wrapper_second_level__star_3_1
  File "pypy_module_cpyext_1.c", line 35750, in not_supposed_to_fail
Fatal Python error: Segmentation fault
Stack (most recent call first, approximate line numbers):
  File "/home/runner/work/pybind11/pybind11/tests/test_exceptions.py", line 306 in test_flaky_exception_failure_point_init
The function PyErr_NormalizeException was not supposed to fail
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/python.py", line 185 in pytest_pyfunc_call
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_callers.py", line 9 in _multicall
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_manager.py", line 77 in _hookexec
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_hooks.py", line 244 in __call__
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/python.py", line 1716 in runtest
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/runner.py", line 159 in pytest_runtest_call
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_callers.py", line 9 in _multicall
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_manager.py", line 77 in _hookexec
Fatal error in cpyext, CPython compatibility layer, calling PyErr_NormalizeException
Either report a bug or consider not using this particular extension
<SystemError object at 0x7fcc8cea6868>
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_hooks.py", line 244 in __call__
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/runner.py", line 261 in <lambda>
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/runner.py", line 317 in from_call
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/runner.py", line 246 in call_runtest_hook
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/runner.py", line 218 in call_and_report
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/runner.py", line 118 in runtestprotocol
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/runner.py", line 110 in pytest_runtest_protocol
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_callers.py", line 9 in _multicall
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_manager.py", line 77 in _hookexec
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_hooks.py", line 244 in __call__
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/main.py", line 335 in pytest_runtestloop
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_callers.py", line 9 in _multicall
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_manager.py", line 77 in _hookexec
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_hooks.py", line 244 in __call__
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/main.py", line 318 in _main
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/main.py", line 255 in wrap_session
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/main.py", line 314 in pytest_cmdline_main
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_callers.py", line 9 in _multicall
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_manager.py", line 77 in _hookexec
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pluggy/_hooks.py", line 244 in __call__
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/config/__init__.py", line 133 in main
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/_pytest/config/__init__.py", line 181 in console_main
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/site-packages/pytest/__main__.py", line 1 in <module>
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/lib-python/3/runpy.py", line 62 in _run_code
  File "/opt/hostedtoolcache/PyPy/3.7.13/x64/lib-python/3/runpy.py", line 170 in _run_module_as_main
  File "<builtin>/app_main.py", line 109 in run_toplevel
  File "<builtin>/app_main.py", line 652 in run_command_line
  File "<builtin>/app_main.py", line 996 in entry_point
Segmentation fault (core dumped)
```

* Add test_pypy_oserror_normalization

* Disable new `PYPY_VERSION` `#if`, to verify that the new test actually fails.

* Restore PYPY_VERSION workaround and update comment to reflect what was learned.

* [ci skip] Fix trivial oversight in comment.
2022-07-21 06:38:00 -07:00
Aaron Gokaslan
42b54507ea
chore: use explicit defaulting in pyobject macros (#4017)
* Use equals default in pyobject macros

* Remove extra semicolon

* Update clang-tidy equals-default rule to not ignore macros

* Fix formatting

* One last formatting change
2022-07-20 12:02:20 -04:00
Aaron Gokaslan
f47f1edfe8
Fix #3812 and fix const of inplace assignments (#4065)
* Fix #3812 and fix const of inplace assignments

* Fix missing tests

* Revert operator overloading changes

* calculate answer first for tests

* Simplify tests

* Add more tests

* Add a couple more tests

* Add test_inplace_lshift, test_inplace_rshift for completeness.

* Update tests

* Shortcircuit on self assigment and address reviewer comment

* broaden skip for self assignment

* One more reviewer comment

* Document opt behavior and make consistent

* Revert unnecessary change

* Clarify comment

Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
2022-07-20 11:42:24 -04:00
Henry Schreiner
8d82f29887 chore: back to work
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
2022-07-15 22:22:51 -05:00
Henry Schreiner
aa304c9c7d
chore: preapre for 2.10.0 release (#4068)
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
2022-07-15 15:47:47 -05:00
Ralf W. Grosse-Kunstleve
1d81191077
Disable implicit conversion of 0 to pybind11::handle. (#4008)
* Disable implicit conversion from `0` to `pybind11::handle`.

* Reverse or-ed condition in an attempt to resolve GCC 8.3.0 errors (i386/debian:buster).

* Trying the simpler `std::is_same<T, PyObject *>`

* Add implicit_conversion_from_pytorch_THPObjectPtr_to_handle test.

* Accommodate types with implicit conversions to `PyObject *`, other than `handle` & `handle` subclasses, or integral types.

* Fix copy-paste mishap (picked wrong name).

* Revamp SFINAE construct to actually fix the pytorch issue (already validated against pytorch proper).

The first version of the reduced pytorch code was critically missing the move ctor. The first version of the accompanying test was meaningless.

Note: It turns out the `!std::is_arithmetic<T>` condition is not needed: `int` is not in general implicitly convertible to `PyObject *`, only the literal `0` is.

* Use `NOLINT(performance-noexcept-move-constructor)` for reduced code from the wild (rather than changing the code).

* Use any_of, all_of, negation. It turns out to clang-format nicer.

* Clean up comments for changed code.

* Reduce pytorch situation further, add test for operator ... const.

* Use `none_of` as suggested by @skylion007

* Add `pure_compile_tests_for_handle_from_PyObject_pointers()`

* Fix inconsequential oversight (retested).

* Factor our `is_pyobj_ptr_or_nullptr_t` to make the SFINAE conditions more readable.

* Remove stray line (oversight).

* Make the `pure_compile_tests_for_handle_from_PyObject_pointers()` "rhs-const-complete", too.

* Remove the temporary PYBIND11_UNDO_PR4008 `#ifdef`.
2022-07-14 09:53:39 -07:00
Aaron Gokaslan
bc9315fe38
chore: optimize sparse matrix casting with python tuple (#4064)
* optimize casting of sparse Eigen arrays

* move array

* Revert for safety
2022-07-13 19:27:00 -04:00
Ralf W. Grosse-Kunstleve
0ec9e31bbf Merge branch 'master' into sh_merge_master 2022-07-12 18:37:15 -07:00
Ralf W. Grosse-Kunstleve
023b3f32c8
Undo accidental one-line change under PR #3913 (#4060) 2022-07-12 12:02:20 -07:00
Ralf W. Grosse-Kunstleve
27ce64fc43 Merge branch 'master' into sh_merge_master 2022-07-09 21:47:49 -07:00
Aaron Gokaslan
f9f00495a3
Properly visit self in >=3.9 traverse (#4051)
* Properly visit self in >=3.9 traverse

* Add comment about 3.9 behavior
2022-07-09 21:43:53 -07:00
Ralf W. Grosse-Kunstleve
432bc5cfb5
Add std::string clean_type_id(const char *typeid_name) overload (in namespace detail). (#4049)
Very minor refactoring to ease development and debugging.

Having to declare a local `std::string` has bugged me many times. Nice to get this little nuisance out of the way.

Extracted from PR #4022, where it is used like this:

```
    std::fprintf(stdout,
                 "\nTYPE_CASTER_ODR_GUARD_IMPL %s %s\n",
                 clean_type_id(intrinsic_type_info.name()).c_str(),
                 source_file_line_from_sloc.c_str());
```
2022-07-07 19:08:10 -07:00
Ralf W. Grosse-Kunstleve
85bc088441
Report C++ Info: via pytest_report_header() (#4046)
* Report `C++ Info:` from `pytest_configure()`

* Use pytest_report_header() as suggested by @skylion007
2022-07-07 17:51:44 -07:00
Ralf W. Grosse-Kunstleve
cd08869df1
PYBIND11_NAMESPACE consistency fixes. (#4043) 2022-07-06 14:29:20 -07:00
Aaron Gokaslan
2af163d9c7
Fix: 3.11 beta support (#3923)
* Placeholder commit for 3.11 testing

* Does this fix it?

* Try suggestion

* Placeholder commit for 3.11 testing

* Does this fix it?

* Try suggestion

* fix: try using modern init for embedded interp

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>

* fix: error message changed in 3.11

* fix: apply logic in Python manually

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>

* fix autodetect dynamic attrs in 3.11

* fix: include error message if possible in error

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>

* ci: enable standard Python 3.11 testing

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>

* Make dynamic attrs condtiion exclusive to ver.

Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
2022-07-06 16:35:12 -04:00
Matthew Woehlke
479e9a50f3
Fix arrays with zero-size dimensions (#4038)
When converting an array to an Eigen matrix, ignore the strides if any
dimension size is 0. If the array is empty, the strides aren't relevant,
and especially numpy ≥ 1.23 explicitly sets the strides to 0 in this
case. (See numpy commit dd5ab7b11520.)

Update tests to verify that this works, and continues to work.
2022-06-29 11:37:16 -07:00
Ralf W. Grosse-Kunstleve
cad2609381 Merge branch 'master' into smart_holder 2022-06-27 22:24:23 -07:00
Xiaofei Wang
c0cfe95b1b
Support loading unique_ptr<Derived> as unique_ptr<Base>. (#4031)
* Support loading unique_ptr<derived> as unique_ptr<base>.

* Fix incorrect test

* pre commit fix

* Fix clang tidy

* Resolve comments

* Resolve comments
2022-06-27 22:21:28 -07:00
Aaron Gokaslan
0964a9093a
Add a missing std::move in numpy.h (#4005) 2022-06-14 14:20:26 -04:00
Aaron Gokaslan
e2dcd95407
chore: optimize dictionary access in strip_padding numpy (#3994)
* emplace field descriptors

* reserve sufficient capacity

* remove std::move

* properly iterate through dict

* make handle casting more explicit

* Revert to old dict api
2022-06-06 22:33:28 -04:00
Maarten Baert
918892b97e
Make dtype::num() return type consistent with other functions (#3995) 2022-06-06 19:41:38 -04:00
Aaron Gokaslan
42a41bf3e7
remove useless ctor (#3989) 2022-06-03 15:18:06 -04:00
Ralf W. Grosse-Kunstleve
cf2c307e7b Merge branch 'master' into sh_merge_master 2022-06-02 16:26:40 -07:00
Sergei Lebedev
a05bc3d235
error_already_set::what() is now constructed lazily (#1895)
* error_already_set::what() is now constructed lazily

Prior to this commit throwing error_already_set was expensive due to the
eager construction of the error string (which required traversing the
Python stack). See #1853 for more context and an alternative take on the
issue.

Note that error_already_set no longer inherits from std::runtime_error
because the latter has no default constructor.

* Do not attempt to normalize if no exception occurred

This is not supported on PyPy-2.7 5.8.0.

* Extract exception name via tp_name

This is faster than dynamically looking up __name__ via GetAttrString.
Note though that the runtime of the code throwing an error_already_set
will be dominated by stack unwinding so the improvement will not be
noticeable.

Before:

396 ns ± 0.913 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

After:

277 ns ± 0.549 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Benchmark:

const std::string foo() {
    PyErr_SetString(PyExc_KeyError, "");
    const std::string &s = py::detail::error_string();
    PyErr_Clear();
    return s;
}

PYBIND11_MODULE(foo, m) {
    m.def("foo", &::foo);
}

* Reverted error_already_set to subclass std::runtime_error

* Revert "Extract exception name via tp_name"

The implementation of __name__ is slightly more complex than that.
It handles the module name prefix, and heap-allocated types. We could
port it to pybind11 later on but for now it seems like an overkill.

This reverts commit f1435c7e6b.

* Cosmit following @YannickJadoul's comments

Note that detail::error_string() no longer calls PyException_SetTraceback
as it is unncessary for pretty-printing the exception.

* Fixed PyPy build

* Moved normalization to error_already_set ctor

* Fix merge bugs

* Fix more merge errors

* Improve formatting

* Improve error message in rare case

* Revert back if statements

* Fix clang-tidy

* Try removing mutable

* Does build_mode release fix it

* Set to Debug to expose segfault

* Fix remove set error string

* Do not run error_string() more than once

* Trying setting the tracebackk to the value

* guard if m_type is null

* Try to debug PGI

* One last try for PGI

* Does reverting this fix PyPy

* Reviewer suggestions

* Remove unnecessary initialization

* Add noexcept move and explicit fail throw

* Optimize error_string creation

* Fix typo

* Revert noexcept

* Fix merge conflict error

* Abuse assignment operator

* Revert operator abuse

* See if we still need debug

* Remove unnecessary mutable

* Report "FATAL failure building pybind11::error_already_set error_string" and terminate process.

* Try specifying noexcept again

* Try explicit ctor

* default ctor is noexcept too

* Apply reviewer suggestions, simplify code, and make helper method private

* Remove unnecessary include

* Clang-Tidy fix

* detail::obj_class_name(), fprintf with [STDERR], [STDOUT] tags, polish comments

* consistently check m_lazy_what.empty() also in production builds

* Make a comment slightly less ambiguous.

* Bug fix: Remove `what();` from `restore()`.

It sure would need to be guarded by `if (m_type)`, otherwise `what()` fails and masks that no error was set (see update unit test). But since `error_already_set` is copyable, there is no point in releasing m_type, m_value, m_trace, therefore we can just as well avoid the runtime overhead of force-building `m_lazy_what`, it may never be used.

* Replace extremely opaque (unhelpful) error message with a truthful reflection of what we know.

* Fix clang-tidy error [performance-move-constructor-init].

* Make expected error message less specific.

* Various changes.

* bug fix: error_string(PyObject **, ...)

* Putting back the two eager PyErr_NormalizeException() calls.

* Change error_already_set() to call pybind11_fail() if the Python error indicator not set. The net result is that a std::runtime_error is thrown instead of error_already_set, but all tests pass as is.

* Remove mutable (fixes oversight in the previous commit).

* Normalize the exception only locally in error_string(). Python 3.6 & 3.7 test failures expected. This is meant for benchmarking, to determine if it is worth the trouble looking into the failures.

* clang-tidy: use auto

* Use `gil_scoped_acquire_local` in `error_already_set` destructor. See long comment.

* For Python < 3.8: `PyErr_NormalizeException` before `PyErr_WriteUnraisable`

* Go back to replacing the held Python exception with then normalized exception, if & when needed. Consistently document the side-effect.

* Slightly rewording comment. (There were also other failures.)

* Add 1-line comment for obj_class_name()

* Benchmark code, with results in this commit message.

          function                   #calls  test time [s]  μs / call
master    pure_unwind                729540      1.061      14.539876
          err_set_unwind_err_clear   681476      1.040      15.260282
          err_set_error_already_set  508038      1.049      20.640525
          error_already_set_restore  555578      1.052      18.933288
          pr1895_original_foo        244113      1.050      43.018168
                                                                       PR / master
PR #1895  pure_unwind                736981      1.054      14.295685       98.32%
          err_set_unwind_err_clear   685820      1.045      15.237399       99.85%
          err_set_error_already_set  661374      1.046      15.811879       76.61%
          error_already_set_restore  669881      1.048      15.645176       82.63%
          pr1895_original_foo        318243      1.059      33.290806       77.39%

master @ commit ad146b2a18

Running tests in directory "/usr/local/google/home/rwgk/forked/pybind11/tests":
============================= test session starts ==============================
platform linux -- Python 3.9.10, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /usr/local/google/home/rwgk/forked/pybind11/tests, configfile: pytest.ini
collecting ... collected 5 items

test_perf_error_already_set.py::test_perf[pure_unwind]
PERF pure_unwind,729540,1.061,14.539876
PASSED
test_perf_error_already_set.py::test_perf[err_set_unwind_err_clear]
PERF err_set_unwind_err_clear,681476,1.040,15.260282
PASSED
test_perf_error_already_set.py::test_perf[err_set_error_already_set]
PERF err_set_error_already_set,508038,1.049,20.640525
PASSED
test_perf_error_already_set.py::test_perf[error_already_set_restore]
PERF error_already_set_restore,555578,1.052,18.933288
PASSED
test_perf_error_already_set.py::test_perf[pr1895_original_foo]
PERF pr1895_original_foo,244113,1.050,43.018168
PASSED

============================== 5 passed in 12.38s ==============================

pr1895 @ commit 8dff51d12e

Running tests in directory "/usr/local/google/home/rwgk/forked/pybind11/tests":
============================= test session starts ==============================
platform linux -- Python 3.9.10, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /usr/local/google/home/rwgk/forked/pybind11/tests, configfile: pytest.ini
collecting ... collected 5 items

test_perf_error_already_set.py::test_perf[pure_unwind]
PERF pure_unwind,736981,1.054,14.295685
PASSED
test_perf_error_already_set.py::test_perf[err_set_unwind_err_clear]
PERF err_set_unwind_err_clear,685820,1.045,15.237399
PASSED
test_perf_error_already_set.py::test_perf[err_set_error_already_set]
PERF err_set_error_already_set,661374,1.046,15.811879
PASSED
test_perf_error_already_set.py::test_perf[error_already_set_restore]
PERF error_already_set_restore,669881,1.048,15.645176
PASSED
test_perf_error_already_set.py::test_perf[pr1895_original_foo]
PERF pr1895_original_foo,318243,1.059,33.290806
PASSED

============================== 5 passed in 12.40s ==============================

clang++ -o pybind11/tests/test_perf_error_already_set.os -c -std=c++17 -fPIC -fvisibility=hidden -Os -flto -Wall -Wextra -Wconversion -Wcast-qual -Wdeprecated -Wnon-virtual-dtor -Wunused-result -isystem /usr/include/python3.9 -isystem /usr/include/eigen3 -DPYBIND11_STRICT_ASSERTS_CLASS_HOLDER_VS_TYPE_CASTER_MIX -DPYBIND11_TEST_BOOST -Ipybind11/include -I/usr/local/google/home/rwgk/forked/pybind11/include -I/usr/local/google/home/rwgk/clone/pybind11/include /usr/local/google/home/rwgk/forked/pybind11/tests/test_perf_error_already_set.cpp

clang++ -o lib/pybind11_tests.so -shared -fPIC -Os -flto -shared ...

Debian clang version 13.0.1-3+build2
Target: x86_64-pc-linux-gnu
Thread model: posix

* Changing call_repetitions_target_elapsed_secs to 0.1 for regular unit testing.

* Adding in `recursion_depth`

* Optimized ctor

* Fix silly bug in recurse_first_then_call()

* Add tests that have equivalent PyErr_Fetch(), PyErr_Restore() but no try-catch.

* Add call_error_string to tests. Sample only recursion_depth 0, 100.

* Show lazy-what speed-up in percent.

* Include real_work in benchmarks.

* Replace all PyErr_SetString() with generate_python_exception_with_traceback()

* Better organization of test loops.

* Add test_error_already_set_copy_move

* Fix bug in newly added test (discovered by clang-tidy): actually use move ctor

* MSVC detects the unreachable return

* change test_perf_error_already_set.py back to quick mode

* Inherit from std::exception (instead of std::runtime_error, which does not make sense anymore with the lazy what)

* Special handling under Windows.

* print with leading newline

* Removing test_perf_error_already_set (copies are under 7765113fbb).

* Avoid gil and scope overhead if there is nothing to release.

* Restore default move ctor. "member function" instead of "function" (note that "method" is Python terminology).

* Delete error_already_set copy ctor.

* Make restore() non-const again to resolve clang-tidy failure (still experimenting).

* Bring back error_already_set copy ctor, to see if that resolves the 4 MSVC test failures.

* Add noexcept to error_already_set copy & move ctors (as suggested by @skylion007 IIUC).

* Trying one-by-one noexcept copy ctor for old compilers.

* Add back test covering copy ctor. Add another simple test that exercises the copy ctor.

* Exclude more older compilers from using the noexcept = default ctors. (The tests in the previous commit exposed that those are broken.)

* Factor out & reuse gil_scoped_acquire_local as gil_scoped_acquire_simple

* Guard gil_scoped_acquire_simple by _Py_IsFinalizing() check.

* what() GIL safety

* clang-tidy & Python 3.6 fixes

* Use `gil_scoped_acquire` in dtor, copy ctor, `what()`. Remove `_Py_IsFinalizing()` checks (they are racy: https://github.com/python/cpython/pull/28525).

* Remove error_scope from copy ctor.

* Add `error_scope` to `get_internals()`, to cover the situation that `get_internals()` is called from the `error_already_set` dtor while a new Python error is in flight already. Also backing out `gil_scoped_acquire_simple` change.

* Add `FlakyException` tests with failure triggers in `__init__` and `__str__`

THIS IS STILL A WORK IN PROGRESS. This commit is only an important resting point.

This commit is a first attempt at addressing the observation that `PyErr_NormalizeException()` completely replaces the original exception if `__init__` fails. This can be very confusing even in small applications, and extremely confusing in large ones.

* Tweaks to resolve Py 3.6 and PyPy CI failures.

* Normalize Python exception immediately in error_already_set ctor.

For background see: https://github.com/pybind/pybind11/pull/1895#issuecomment-1135304081

* Fix oversights based on CI failures (copy & move ctor initialization).

* Move @pytest.mark.xfail("env.PYPY") after @pytest.mark.parametrize(...)

* Use @pytest.mark.skipif (xfail does not work for segfaults, of course).

* Remove unused obj_class_name_or() function (it was added only under this PR).

* Remove already obsolete C++ comments and code that were added only under this PR.

* Slightly better (newly added) comments.

* Factor out detail::error_fetch_and_normalize. Preparation for producing identical results from error_already_set::what() and detail::error_string(). Note that this is a very conservative refactoring. It would be much better to first move detail::error_string into detail/error_string.h

* Copy most of error_string() code to new error_fetch_and_normalize::complete_lazy_error_string()

* Remove all error_string() code from detail/type_caster_base.h. Note that this commit includes a subtle bug fix: previously error_string() restored the Python error, which will upset pybind11_fail(). This never was a problem in practice because the two PyType_Ready() calls in detail/class.h do not usually fail.

* Return const std::string& instead of const char * and move error_string() to pytypes.h

* Remove gil_scope_acquire from error_fetch_and_normalize, add back to error_already_set

* Better handling of FlakyException __str__ failure.

* Move error_fetch_and_normalize::complete_lazy_error_string() implementation from pybind11.h to pytypes.h

* Add error_fetch_and_normalize::release_py_object_references() and use from error_already_set dtor.

* Use shared_ptr for m_fetched_error => 1. non-racy, copy ctor that does not need the GIL; 2. enables guard against duplicate restore() calls.

* Add comments.

* Trivial renaming of a newly introduced member function.

* Workaround for PyPy

* Bug fix (oversight). Only valgrind got this one.

* Use shared_ptr custom deleter for m_fetched_error in error_already_set. This enables removing the dtor, copy ctor, move ctor completely.

* Further small simplification. With the GIL held, simply deleting the raw_ptr takes care of everything.

* IWYU cleanup

```
iwyu version: include-what-you-use 0.17 based on Debian clang version 13.0.1-3+build2
```

Command used:

```
iwyu -c -std=c++17 -DPYBIND11_TEST_BOOST -Iinclude/pybind11 -I/usr/include/python3.9 -I/usr/include/eigen3 include/pybind11/pytypes.cpp
```

pytypes.cpp is a temporary file: `#include "pytypes.h"`

The raw output is very long and noisy.

I decided to use `#include <cstddef>` instead of `#include <cstdio>` for `std::size_t` (iwyu sticks to the manual choice).

I ignored all iwyu suggestions that are indirectly covered by `#include <Python.h>`.

I manually verified that all added includes are actually needed.

Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
2022-06-02 16:17:38 -07:00
Ralf W. Grosse-Kunstleve
485dacef6a Merge branch 'master' into sh_merge_master 2022-06-01 14:39:51 -07:00
Aaron Gokaslan
58802de41b
perf: Add object rvalue overload for accessors. Enables reference stealing (#3970)
* Add object rvalue overload for accessors. Enables reference stealing

* Fix comments

* Fix more comment typos

* Fix bug

* reorder declarations for clarity

* fix another perf bug

* should be static

* future proof operator overloads

* Fix perfect forwarding

* Add a couple of tests

* Remove errant include

* Improve test documentation

* Add dict test

* add object attr tests

* Optimize STL map caster and cleanup enum

* Reorder to match declarations

* adjust increfs

* Remove comment

* revert value change

* add missing move
2022-06-01 15:19:13 -04:00
Ralf W. Grosse-Kunstleve
9f7b3f735a
addl unit tests for PR #3970 (#3977)
* Add test_perf_accessors (to be merged into test_pytypes).

* Python < 3.8 f-string compatibility

* Use thread_local in inc_ref_counter()

* Intentional breakage, brute-force way to quickly find out how many platforms reach the PYBIND11_HANDLE_REF_DEBUG code, with and without threads.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Remove Intentional breakage

* Drop perf test, move inc_refs tests to test_pytypes

* Fold in PR #3970 with `#ifdef`s

* Complete test coverage for all newly added code.

* Condense new unit tests via a simple local helper macro.

* Remove PYBIND11_PR3970 define. See https://github.com/pybind/pybind11/pull/3977#issuecomment-1142526417

* Move static keyword first (fixes silly oversight).

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-05-31 12:59:19 -07:00
Ralf W. Grosse-Kunstleve
b24c5ed204
Replace "Unknown internal error occurred" with a more helpful message. (#3982) 2022-05-31 11:54:33 -07:00
Ralf W. Grosse-Kunstleve
de4ba92c9f
Add error_scope to detail::get_internals() (#3981)
* Add `error_scope` to `detail::get_internals()`

* Adjust test to tolerate macOS PyPy behavior.
2022-05-31 11:51:13 -07:00
Aaron Gokaslan
8da58da539
chore: perfectly forward all make_iterator args (#3980)
* Perfectly forward all make_iterator args

* Try emplace back
2022-05-28 19:58:15 -04:00
Ralf W. Grosse-Kunstleve
748ae2270b
Add missing error handling to module_::def_submodule (#3973)
* Add missing error handling to module_::def_submodule

* Add test_def_submodule_failures

* PyPy only: Skip test with trigger for PyModule_GetName() failure.

* Reapply minor fix that accidentally got lost in transfer from PR #3964
2022-05-28 16:40:57 -07:00
Aaron Gokaslan
68f8010500
chore: add err guard to capsule destructor and add a move to iostream (#3958)
* Add err guard to capsule destructor

* only uses ostream currently

* can these be noexcept

* Add back header

* fix for older compilers

* This should at least be noexcept

* Add missing move

* Apparently not noexcept for old llvm
2022-05-27 14:32:57 -04:00
Ralf W. Grosse-Kunstleve
2c549eb7aa
Move PyErr_NormalizeException() up a few lines (#3971)
* Add error_already_set_what what tests, asserting the status quo.

* Move PyErr_NormalizeException() up a few lines.

* @pytest.mark.skipif("env.PYPY") from PR #1895 is required even for this much simpler PR

* Move PyException_SetTraceback() with PyErr_NormalizeException() as suggested by @skylion007

* Insert a std::move() as suggested by @skylion007
2022-05-25 21:44:55 -07:00
Aaron Gokaslan
2d4a20c8cb
chore: add missing moves for buffer_func and staticmethod in pybind11.h (#3969)
* Use move converting ctor when making class staticmethod

* Add missing caster move in buffer func

* fix use after move

* add back move to staticmethod

* avoid shadowing with varname
2022-05-25 12:14:07 -04:00
Aaron Gokaslan
c42414db86
(perf): use a rvalue cast in func_wrapper (#3966)
* (perf): use an rvalue cast in func_wrapper

* Try to clarify comment

* Fix comment typo
2022-05-23 12:26:53 -04:00
Ralf W. Grosse-Kunstleve
bdf22c8ee7 Merge branch 'master' into sh_merge_master 2022-05-17 16:37:59 -07:00
Ralf W. Grosse-Kunstleve
d28c3a5da7
[smart_holder] .def_readonly, .def_readwrite adaptors (continuation of PR #3581). (#3844)
* Transferred net diff from PR #3581, as-is.

* Automatic `pre-commit run --all-files` fixes. NO manual changes.

* Removing trailing `//` (originally added to manipulate clang-format), as suggested by @charlesbeattie back in Jan/Feb under PR #3581.

* Renaming `xetter_cpp_function` to `property_cpp_function` as suggested by @rainwoodman

* Fully explain the terse variable naming scheme in test_class_sh_property (as suggested by @rainwoodman)

* Also use parametrize for readonly, readwrite (as suggested by @rainwoodman)

* Apply change suggested by @skylion007 (with clang-format).
2022-05-17 16:35:43 -07:00
Aaron Gokaslan
a8b3ff30f9
chore: add a couple of moves in pybind11.h (#3941)
* Add missing std::moves in enum_base methods

* Remove useless move

* Add one more std::move in print

* Further optimize print

* Some more misc optimizations
2022-05-17 11:29:49 -04:00
Maarten Baert
72eea20afd
Fix py::cast from pytype rvalue to pytype (#3949)
* Fix py::cast from pytype rvalue to pytype

Previously, py::cast blindly assumed that the destination type was a C++
type rather than a python type when the source type was an rvalue.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-05-16 13:51:01 -07:00
Ralf W. Grosse-Kunstleve
48c7be4a56 Undoing previous accidental commit. Sorry I forgot to git branch. 2022-05-16 04:31:01 -07:00
Ralf W. Grosse-Kunstleve
5621ab853a Do we have a unit test for the traceback code in error_string()? 2022-05-16 04:26:35 -07:00
Tomi Valkeinen
aebdf00cd0
Fix "extra ';' outside of a function" warning (#3929)
Fix the following warning seen with clang:

include/pybind11/detail/smart_holder_poc.h:109:2: error: extra ';' outside of a function is incompatible with C++98 [-Werror,-Wc++98-compat-extra-semi]

Signed-off-by: Tomi Valkeinen <tomi.valkeinen@ideasonboard.com>
2022-05-07 02:18:13 -07:00
Aaron Gokaslan
2e331308d3
chore: remove unused include from stl.h (#3928)
* change iostream include to ostream include
2022-05-06 16:57:39 -04:00
Ralf W. Grosse-Kunstleve
72f51e1d89 Use PYBIND11_DETAILED_ERROR_MESSAGES in smart_holder_type_casters.h (follow-on to https://github.com/pybind/pybind11/pull/3913) 2022-05-05 16:47:29 -07:00
Ralf W. Grosse-Kunstleve
d5125eaf1e Merge branch 'master' into sh_merge_master 2022-05-05 16:12:58 -07:00
Ed Catmur
68a0b2dfd8
Add anyset & frozenset, enable copying (cast) to std::set (#3901)
* Add frozenset, and allow it cast to std::set

For the reverse direction, std::set still casts to set. This is in concordance with the behavior for sequence containers, where e.g. tuple casts to std::vector but std::vector casts to list.

Extracted from #3886.

* Rename set_base to any_set to match Python C API

since this will be part of pybind11 public API

* PR: static_cast, anyset

* Add tests for frozenset

and rename anyset methods

* Remove frozenset default ctor, add tests

Making frozenset non-default constructible means that we need to adjust pyobject_caster to not require that its value is default constructible, by initializing value to a nil handle.  This also allows writing C++ functions taking anyset, and is arguably a performance improvement, since there is no need to allocate an object that will just be replaced by load.

Add some more tests, including anyset::empty, anyset::size, set::add and set::clear.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add rationale to `pyobject_caster` default ctor

* Remove ineffectual protected: access control

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-05-05 12:09:56 -07:00
Ralf W. Grosse-Kunstleve
2ee1e6445d Merge branch 'master' into sh_merge_master 2022-05-02 12:41:48 -07:00
Michael Voznesensky
f0b9f755e4
Replace error printing code gated by NDEBUG with a new flag: PYBIND11_DETAILED_ERROR_MESSAGES (#3913)
* Update cast.h

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Move definition to detail/common, change name, apply everywhere

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Rename debug_enabled in tests to detailed_error_messages_enabled
2022-05-02 15:30:19 -04:00
Aaron Gokaslan
75007dda72
chore: rule of 3 for strdup guard (#3905) 2022-04-26 15:49:24 -04:00
Aaron Gokaslan
82455a41fd
Minor opt to cache tuple casting (#3894) 2022-04-24 14:46:39 -04:00
Aaron Gokaslan
1c636f4dce
chore: Change numpy dtype from_args call sig to const ref (#3878)
* Change numpy from_args call signature to avoid copy

* Reorder ctors

* Rename arg

* Fix unnecessary move

* Fix clang-tidy and Add a few missing moves to memory_view pytype
2022-04-18 11:11:24 -04:00
Aaron Gokaslan
fbcde3f0af
chore: enable clang-tidy check modernize-use-nullptr (#3881)
* Enable clang-tidy check modernize-use-nullptr

* Sort clang-tidy

* Sorted again
2022-04-18 11:09:45 -04:00
Ralf W. Grosse-Kunstleve
d6d3fe857b Merge branch 'master' into sh_merge_master 2022-04-17 22:20:02 -07:00
Ralf W. Grosse-Kunstleve
3d1cb7be83 Merge branch 'master' into sh_merge_master 2022-04-17 22:16:08 -07:00
Ralf W. Grosse-Kunstleve
30716c67a1
Also add error_scope assignment operator to complete the rule-of-3 (follow-on to PR #3870). (#3872) 2022-04-15 14:44:48 -04:00
Xiaofei Wang
7064d43bc9
[smart_holder] Add a new return value policy return_as_bytes (#3838)
* Add return_as_bytes policy

* Fix format

* Fix test failures

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix std::variant

* Resolve comments

* Note this policy experimental

* Add tests for `return_as_bytes` with `def_property`.

* Change comment for the new return_as_bytes enum to note that the policy is not available on master.

* Applying pr3838_sh.patch (exactly as used Google-internally since 2022-03-31).

* Add `case return_as_bytes` to `switch`es in detail/type_caster_base.h and eigen.h

Based on systematic review under https://github.com/pybind/pybind11/pull/3838#issuecomment-1094390333

* Add missing break (clang-tidy).

* More clang-tidy fixes (this time around clang-tidy was run interactively to pre-empt repeat trips through the CI).

* Underscore prefix: _return_as_bytes

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
2022-04-15 10:17:34 -07:00
Aaron Gokaslan
3829b7624c
chore: simplify numpy dtype ctor (#3869)
* Simplify numpy dtype ctor

* Simplify c_str ctor

* Remove compat macro for str in numpy
2022-04-14 14:12:44 -07:00
Oleksandr Pavlyk
45164c1fcb
Added deleted copy constructor for error_scope to comply with rule of 3. (#3870)
* Added deleted copy constructor for error_scope to comply with rule of 3.
2022-04-14 12:16:58 -04:00
Oleksandr Pavlyk
ba7a0fac73
Expand dtype accessors (#3868)
* Added constructor based on typenum, based on PyArray_DescrFromType

Added accessors for typenum, alignment, byteorder and flags fields of
PyArray_Descr struct.

* Added tests for new py::dtype constructor, and for accessors

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fixed the comment for alignment method

* Update include/pybind11/numpy.h

Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
2022-04-14 10:53:16 -04:00
Oleksandr Pavlyk
fa98804a07
Adds set_name method of pybind11::capsule class (#3866)
* Adds set_name method of pybind11::capsule class

This calls PyCapsule_SetName on the underlying capsule object.

modified destructors to query capsules's Name

[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Handle possible exception thrown by PyCapsule_GetName

Also removed accidentally reintroduced use of `const char *&`.

[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Fixed function name

* Introduced private static function to reuse get_name_or_throw

* added tests for capsule renaming

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* handle python error in flight

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Initialized PyObject * variables to nullptr

* use write-unraisable if PyCapsule_GetName raises

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* get_name_or_throw->get_name_no_throw

If PyCapsule_GetName raises an error we should write as unraisable
to consume it and notify user, and then restore the error in flight if any.
This way this method called from destructor would not modify interpreter
error state.

* used error_scope struct

* Renamed get_name_no_throw->get_name_in_error_scope

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-04-14 10:51:27 -04:00
Ralf W. Grosse-Kunstleve
ab41fa281c Merge branch 'master' into sh_merge_master 2022-04-12 15:48:59 -07:00
Laramie Leavitt
088ad4f298
Cleanup cast_safe<void> specialization (#3861)
* Cleanup cast_safe<void> specialization

Replace explicit specialization of cast_safe<void> with SFINAE.
It's better for SFINAE cases to cover all type-sets rather than mixing SFINAE and explicit specialization.

Extracted from #3674

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update cast.h

Use detail::none_of<> as suggested

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update cast.h

Reorder:
If TEMP_REF
If VOID
if (!VOID && !TEMP_REF)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-04-11 11:57:05 -07:00
Aaron Gokaslan
e3aa215b02
Add perfect forwarding to make_iterator calls (#3860) 2022-04-11 14:03:43 -04:00
Aaron Gokaslan
1b27b744c1
chore: Make stl_bind take slice as const_ref (#3852)
* Make stl_bind take slice as const_ref

* Change eval order if

* Silence MSVC warning
2022-04-11 13:53:30 -04:00
Laramie Leavitt
ab59f45d2e
Prefer make_caster<T> to type_caster<T> (#3859) 2022-04-11 10:36:24 -07:00
Aaron Gokaslan
c4e295287b
perf: Add more moves and optimize (#3845)
* Make slice constructor consistent

* Add more missing std::move for ref steals

* Add missing perfect forwarding for arg_v ctor

* Add missing move in arg_v constructor

* Revert "Add missing move in arg_v constructor"

This reverts commit 126fc7c524.

* Add another missing move in cast.h

* Optimize object move ctor

* Don't do useless move

* Make move ctor same as nb

* Make obj move ctor same as nb

* Revert changes which break MSVC
2022-04-05 14:36:39 -04:00
Lonnie L. Souder II
b3ebd11d98
feature: support compilers that use std::experimental::filesystem (#3840)
* feature: support compilers that use std::experimental::filesystem such as gcc7

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* only use this feature if cpp17

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* more specific namespace alias + style

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* move to pybind11 namespace

* no namespace alias

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: Lonnie Souder II <lonnie.souder@g6labs.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-03-31 22:16:10 -07:00
Ralf W. Grosse-Kunstleve
4db19272cb Merge branch 'master' into sh_merge_master 2022-03-30 19:33:07 -07:00
Aaron Gokaslan
3a183d4b58
fix: improve str exceptions and consistency with python (#3826)
* Improve str exceptions

* Revert macro change just in case

* Make clang-tidy happy

* Fix one more clang-tidy issue

* Refactor duplicate method
2022-03-25 16:01:34 -04:00
Aaron Gokaslan
146695a904
fix: better exception and error handling for capsules (#3825)
* Make capsule errors better match python
2022-03-25 10:55:13 -04:00
Aaron Gokaslan
47079b9e7b
(perf): Add missing move in sp matrix caster and microopt char concats (#3823)
* Add missing move in sp matrix caster and microopt char concat

* Remove useless move

* Add a couple more std::move

* Missed one char

* Improve error_string

* Ensure no temp reallocs in errorString concat

* Remove useless move
2022-03-24 12:57:37 -04:00
Ralf W. Grosse-Kunstleve
08ea85b0ac Merge branch 'master' into sh_merge_master 2022-03-21 22:59:39 -07:00
Laramie Leavitt
b22ee64c73
Add type_caster<std::monostate> (#3818)
* Add type_caster<std::monostate> for std::variant

Add type_caster<std::monostate>, allowing std::variant<std::monostate, ...>

* Add  variant<std::monostate, ...> test methods

* Add std::monostate tests

* Update test_stl.py

Remove erroneous extra tests

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update test fn name

* And update the doc() test

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-03-21 22:58:04 -07:00
Ralf W. Grosse-Kunstleve
2a93b34145 Merge branch 'master' into sh_merge_master 2022-03-18 11:16:24 -07:00
Oleksandr Pavlyk
6bbc5a464b PYBIND11_OBJECT_CVT should use namespace for error_already_set() (#3797)
* PYBIND11_OBJECT_CVT should use namespace for error_already_set()

This change makes the macro usable outside of pybind11 namespace.

* added test for use of PYBIND11_OBJECT_CVT for classes in external to pybind11 namespaces

* Extended test_pytypes.cpp and test_pytest.py

The added test defines a dummy function that takes a custom-defined class external::float_
that uses PYBIND11_OBJECT_CVT

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fixed issues pointed out by CI

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fixed memory leak in default constructor

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-03-18 11:15:52 -07:00
Laramie Leavitt
b3a43d137c
Use rvalue reference for std::variant cast_op<T> (#3811)
Nearly every call site of cast_op<T> uses an r-value reference.

Except stl.h variant_caster::load_alternative for handling std::variant.

Fix that.
2022-03-18 11:10:31 -07:00
Xiaofei Wang
7405976aa4
Fixes issue #3801 (#3807)
* Fixes issue

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix lint error

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix flake8

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix test

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix clang tidy

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix again

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix test

* Add comments

* Try fix Valgrind

* Resolve comments

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-03-18 11:08:20 -07:00
Oleksandr Pavlyk
91a6e129d9
PYBIND11_OBJECT_CVT should use namespace for error_already_set() (#3797)
* PYBIND11_OBJECT_CVT should use namespace for error_already_set()

This change makes the macro usable outside of pybind11 namespace.

* added test for use of PYBIND11_OBJECT_CVT for classes in external to pybind11 namespaces

* Extended test_pytypes.cpp and test_pytest.py

The added test defines a dummy function that takes a custom-defined class external::float_
that uses PYBIND11_OBJECT_CVT

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fixed issues pointed out by CI

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fixed memory leak in default constructor

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-03-11 12:18:25 -08:00
Xiaofei Wang
9d4b4dffce
Fixes issue #3788 (#3796)
* Reproducer for https://github.com/pybind/pybind11/issues/3788

Expected to build & run as-is. Uncommenting reproduces the infinite recursion.

* Moving try_as_void_ptr_capsule() to the end of load_impl()

* Moving new test into the existing test_class_sh_void_ptr_capsule

* Experiment

* Remove comments and simplify the test cases.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-03-10 16:18:24 -08:00
Ralf W. Grosse-Kunstleve
eb6edd9fac Merge branch 'master' into sh_merge_master 2022-03-10 10:32:48 -08:00
Aaron Gokaslan
2dd5254494
fix: missing move in eval.h (#3775) 2022-03-02 15:25:43 -05:00
Aaron Gokaslan
af08a95b56
fix: potential memory leak in pypy (#3774) 2022-03-02 14:14:52 -05:00