Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/INSTALLER +1 -0
- env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/LICENSE +13 -0
- env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/METADATA +131 -0
- env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/RECORD +10 -0
- env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/WHEEL +5 -0
- env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/top_level.txt +1 -0
- env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/zip-safe +1 -0
- env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/INSTALLER +1 -0
- env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/LICENSE +21 -0
- env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/METADATA +683 -0
- env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/RECORD +35 -0
- env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/WHEEL +6 -0
- env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/entry_points.txt +2 -0
- env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/top_level.txt +1 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/environment.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/loaders.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/optimizer.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/runtime.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/__init__.py +13 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/__init__.py +17 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/_version.py +12 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/commands.py +37 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h +690 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h +208 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h +1837 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h +225 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/common.h +2 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/complex.h +74 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/class.h +748 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/common.h +1267 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/descr.h +171 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/init.h +434 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/internals.h +667 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/type_caster_base.h +1218 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/typeid.h +65 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen.h +12 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/common.h +9 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/matrix.h +714 -0
- env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/tensor.h +517 -0
env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/LICENSE
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright 2016-2020 aio-libs collaboration.
|
2 |
+
|
3 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
you may not use this file except in compliance with the License.
|
5 |
+
You may obtain a copy of the License at
|
6 |
+
|
7 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
|
9 |
+
Unless required by applicable law or agreed to in writing, software
|
10 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
See the License for the specific language governing permissions and
|
13 |
+
limitations under the License.
|
env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/METADATA
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: async-timeout
|
3 |
+
Version: 4.0.3
|
4 |
+
Summary: Timeout context manager for asyncio programs
|
5 |
+
Home-page: https://github.com/aio-libs/async-timeout
|
6 |
+
Author: Andrew Svetlov <[email protected]>
|
7 |
+
Author-email: [email protected]
|
8 |
+
License: Apache 2
|
9 |
+
Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby
|
10 |
+
Project-URL: CI: GitHub Actions, https://github.com/aio-libs/async-timeout/actions
|
11 |
+
Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/async-timeout
|
12 |
+
Project-URL: GitHub: issues, https://github.com/aio-libs/async-timeout/issues
|
13 |
+
Project-URL: GitHub: repo, https://github.com/aio-libs/async-timeout
|
14 |
+
Classifier: Development Status :: 5 - Production/Stable
|
15 |
+
Classifier: Topic :: Software Development :: Libraries
|
16 |
+
Classifier: Framework :: AsyncIO
|
17 |
+
Classifier: Intended Audience :: Developers
|
18 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
19 |
+
Classifier: Programming Language :: Python
|
20 |
+
Classifier: Programming Language :: Python :: 3
|
21 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
22 |
+
Classifier: Programming Language :: Python :: 3.7
|
23 |
+
Classifier: Programming Language :: Python :: 3.8
|
24 |
+
Classifier: Programming Language :: Python :: 3.9
|
25 |
+
Classifier: Programming Language :: Python :: 3.10
|
26 |
+
Classifier: Programming Language :: Python :: 3.11
|
27 |
+
Requires-Python: >=3.7
|
28 |
+
Description-Content-Type: text/x-rst
|
29 |
+
License-File: LICENSE
|
30 |
+
Requires-Dist: typing-extensions >=3.6.5 ; python_version < "3.8"
|
31 |
+
|
32 |
+
async-timeout
|
33 |
+
=============
|
34 |
+
.. image:: https://travis-ci.com/aio-libs/async-timeout.svg?branch=master
|
35 |
+
:target: https://travis-ci.com/aio-libs/async-timeout
|
36 |
+
.. image:: https://codecov.io/gh/aio-libs/async-timeout/branch/master/graph/badge.svg
|
37 |
+
:target: https://codecov.io/gh/aio-libs/async-timeout
|
38 |
+
.. image:: https://img.shields.io/pypi/v/async-timeout.svg
|
39 |
+
:target: https://pypi.python.org/pypi/async-timeout
|
40 |
+
.. image:: https://badges.gitter.im/Join%20Chat.svg
|
41 |
+
:target: https://gitter.im/aio-libs/Lobby
|
42 |
+
:alt: Chat on Gitter
|
43 |
+
|
44 |
+
asyncio-compatible timeout context manager.
|
45 |
+
|
46 |
+
|
47 |
+
Usage example
|
48 |
+
-------------
|
49 |
+
|
50 |
+
|
51 |
+
The context manager is useful in cases when you want to apply timeout
|
52 |
+
logic around block of code or in cases when ``asyncio.wait_for()`` is
|
53 |
+
not suitable. Also it's much faster than ``asyncio.wait_for()``
|
54 |
+
because ``timeout`` doesn't create a new task.
|
55 |
+
|
56 |
+
The ``timeout(delay, *, loop=None)`` call returns a context manager
|
57 |
+
that cancels a block on *timeout* expiring::
|
58 |
+
|
59 |
+
from async_timeout import timeout
|
60 |
+
async with timeout(1.5):
|
61 |
+
await inner()
|
62 |
+
|
63 |
+
1. If ``inner()`` is executed faster than in ``1.5`` seconds nothing
|
64 |
+
happens.
|
65 |
+
2. Otherwise ``inner()`` is cancelled internally by sending
|
66 |
+
``asyncio.CancelledError`` into but ``asyncio.TimeoutError`` is
|
67 |
+
raised outside of context manager scope.
|
68 |
+
|
69 |
+
*timeout* parameter could be ``None`` for skipping timeout functionality.
|
70 |
+
|
71 |
+
|
72 |
+
Alternatively, ``timeout_at(when)`` can be used for scheduling
|
73 |
+
at the absolute time::
|
74 |
+
|
75 |
+
loop = asyncio.get_event_loop()
|
76 |
+
now = loop.time()
|
77 |
+
|
78 |
+
async with timeout_at(now + 1.5):
|
79 |
+
await inner()
|
80 |
+
|
81 |
+
|
82 |
+
Please note: it is not POSIX time but a time with
|
83 |
+
undefined starting base, e.g. the time of the system power on.
|
84 |
+
|
85 |
+
|
86 |
+
Context manager has ``.expired`` property for check if timeout happens
|
87 |
+
exactly in context manager::
|
88 |
+
|
89 |
+
async with timeout(1.5) as cm:
|
90 |
+
await inner()
|
91 |
+
print(cm.expired)
|
92 |
+
|
93 |
+
The property is ``True`` if ``inner()`` execution is cancelled by
|
94 |
+
timeout context manager.
|
95 |
+
|
96 |
+
If ``inner()`` call explicitly raises ``TimeoutError`` ``cm.expired``
|
97 |
+
is ``False``.
|
98 |
+
|
99 |
+
The scheduled deadline time is available as ``.deadline`` property::
|
100 |
+
|
101 |
+
async with timeout(1.5) as cm:
|
102 |
+
cm.deadline
|
103 |
+
|
104 |
+
Not finished yet timeout can be rescheduled by ``shift_by()``
|
105 |
+
or ``shift_to()`` methods::
|
106 |
+
|
107 |
+
async with timeout(1.5) as cm:
|
108 |
+
cm.shift(1) # add another second on waiting
|
109 |
+
cm.update(loop.time() + 5) # reschedule to now+5 seconds
|
110 |
+
|
111 |
+
Rescheduling is forbidden if the timeout is expired or after exit from ``async with``
|
112 |
+
code block.
|
113 |
+
|
114 |
+
|
115 |
+
Installation
|
116 |
+
------------
|
117 |
+
|
118 |
+
::
|
119 |
+
|
120 |
+
$ pip install async-timeout
|
121 |
+
|
122 |
+
The library is Python 3 only!
|
123 |
+
|
124 |
+
|
125 |
+
|
126 |
+
Authors and License
|
127 |
+
-------------------
|
128 |
+
|
129 |
+
The module is written by Andrew Svetlov.
|
130 |
+
|
131 |
+
It's *Apache 2* licensed and freely available.
|
env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/RECORD
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
async_timeout-4.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
async_timeout-4.0.3.dist-info/LICENSE,sha256=4Y17uPUT4sRrtYXJS1hb0wcg3TzLId2weG9y0WZY-Sw,568
|
3 |
+
async_timeout-4.0.3.dist-info/METADATA,sha256=WQVcnDIXQ2ntebcm-vYjhNLg_VMeTWw13_ReT-U36J4,4209
|
4 |
+
async_timeout-4.0.3.dist-info/RECORD,,
|
5 |
+
async_timeout-4.0.3.dist-info/WHEEL,sha256=5sUXSg9e4bi7lTLOHcm6QEYwO5TIF1TNbTSVFVjcJcc,92
|
6 |
+
async_timeout-4.0.3.dist-info/top_level.txt,sha256=9oM4e7Twq8iD_7_Q3Mz0E6GPIB6vJvRFo-UBwUQtBDU,14
|
7 |
+
async_timeout-4.0.3.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
8 |
+
async_timeout/__init__.py,sha256=A0VOqDGQ3cCPFp0NZJKIbx_VRP1Y2xPtQOZebVIUB88,7242
|
9 |
+
async_timeout/__pycache__/__init__.cpython-310.pyc,,
|
10 |
+
async_timeout/py.typed,sha256=tyozzRT1fziXETDxokmuyt6jhOmtjUbnVNJdZcG7ik0,12
|
env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/WHEEL
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.41.1)
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py3-none-any
|
5 |
+
|
env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
async_timeout
|
env-llmeval/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/zip-safe
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2019 TAHRI Ahmed R.
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/METADATA
ADDED
@@ -0,0 +1,683 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: charset-normalizer
|
3 |
+
Version: 3.3.2
|
4 |
+
Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet.
|
5 |
+
Home-page: https://github.com/Ousret/charset_normalizer
|
6 |
+
Author: Ahmed TAHRI
|
7 |
+
Author-email: [email protected]
|
8 |
+
License: MIT
|
9 |
+
Project-URL: Bug Reports, https://github.com/Ousret/charset_normalizer/issues
|
10 |
+
Project-URL: Documentation, https://charset-normalizer.readthedocs.io/en/latest
|
11 |
+
Keywords: encoding,charset,charset-detector,detector,normalization,unicode,chardet,detect
|
12 |
+
Classifier: Development Status :: 5 - Production/Stable
|
13 |
+
Classifier: License :: OSI Approved :: MIT License
|
14 |
+
Classifier: Intended Audience :: Developers
|
15 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
16 |
+
Classifier: Operating System :: OS Independent
|
17 |
+
Classifier: Programming Language :: Python
|
18 |
+
Classifier: Programming Language :: Python :: 3
|
19 |
+
Classifier: Programming Language :: Python :: 3.7
|
20 |
+
Classifier: Programming Language :: Python :: 3.8
|
21 |
+
Classifier: Programming Language :: Python :: 3.9
|
22 |
+
Classifier: Programming Language :: Python :: 3.10
|
23 |
+
Classifier: Programming Language :: Python :: 3.11
|
24 |
+
Classifier: Programming Language :: Python :: 3.12
|
25 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
26 |
+
Classifier: Topic :: Text Processing :: Linguistic
|
27 |
+
Classifier: Topic :: Utilities
|
28 |
+
Classifier: Typing :: Typed
|
29 |
+
Requires-Python: >=3.7.0
|
30 |
+
Description-Content-Type: text/markdown
|
31 |
+
License-File: LICENSE
|
32 |
+
Provides-Extra: unicode_backport
|
33 |
+
|
34 |
+
<h1 align="center">Charset Detection, for Everyone 👋</h1>
|
35 |
+
|
36 |
+
<p align="center">
|
37 |
+
<sup>The Real First Universal Charset Detector</sup><br>
|
38 |
+
<a href="https://pypi.org/project/charset-normalizer">
|
39 |
+
<img src="https://img.shields.io/pypi/pyversions/charset_normalizer.svg?orange=blue" />
|
40 |
+
</a>
|
41 |
+
<a href="https://pepy.tech/project/charset-normalizer/">
|
42 |
+
<img alt="Download Count Total" src="https://static.pepy.tech/badge/charset-normalizer/month" />
|
43 |
+
</a>
|
44 |
+
<a href="https://bestpractices.coreinfrastructure.org/projects/7297">
|
45 |
+
<img src="https://bestpractices.coreinfrastructure.org/projects/7297/badge">
|
46 |
+
</a>
|
47 |
+
</p>
|
48 |
+
<p align="center">
|
49 |
+
<sup><i>Featured Packages</i></sup><br>
|
50 |
+
<a href="https://github.com/jawah/niquests">
|
51 |
+
<img alt="Static Badge" src="https://img.shields.io/badge/Niquests-HTTP_1.1%2C%202%2C_and_3_Client-cyan">
|
52 |
+
</a>
|
53 |
+
<a href="https://github.com/jawah/wassima">
|
54 |
+
<img alt="Static Badge" src="https://img.shields.io/badge/Wassima-Certifi_Killer-cyan">
|
55 |
+
</a>
|
56 |
+
</p>
|
57 |
+
<p align="center">
|
58 |
+
<sup><i>In other language (unofficial port - by the community)</i></sup><br>
|
59 |
+
<a href="https://github.com/nickspring/charset-normalizer-rs">
|
60 |
+
<img alt="Static Badge" src="https://img.shields.io/badge/Rust-red">
|
61 |
+
</a>
|
62 |
+
</p>
|
63 |
+
|
64 |
+
> A library that helps you read text from an unknown charset encoding.<br /> Motivated by `chardet`,
|
65 |
+
> I'm trying to resolve the issue by taking a new approach.
|
66 |
+
> All IANA character set names for which the Python core library provides codecs are supported.
|
67 |
+
|
68 |
+
<p align="center">
|
69 |
+
>>>>> <a href="https://charsetnormalizerweb.ousret.now.sh" target="_blank">👉 Try Me Online Now, Then Adopt Me 👈 </a> <<<<<
|
70 |
+
</p>
|
71 |
+
|
72 |
+
This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**.
|
73 |
+
|
74 |
+
| Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) |
|
75 |
+
|--------------------------------------------------|:---------------------------------------------:|:--------------------------------------------------------------------------------------------------:|:-----------------------------------------------:|
|
76 |
+
| `Fast` | ❌ | ✅ | ✅ |
|
77 |
+
| `Universal**` | ❌ | ✅ | ❌ |
|
78 |
+
| `Reliable` **without** distinguishable standards | ❌ | ✅ | ✅ |
|
79 |
+
| `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ |
|
80 |
+
| `License` | LGPL-2.1<br>_restrictive_ | MIT | MPL-1.1<br>_restrictive_ |
|
81 |
+
| `Native Python` | ✅ | ✅ | ❌ |
|
82 |
+
| `Detect spoken language` | ❌ | ✅ | N/A |
|
83 |
+
| `UnicodeDecodeError Safety` | ❌ | ✅ | ❌ |
|
84 |
+
| `Whl Size (min)` | 193.6 kB | 42 kB | ~200 kB |
|
85 |
+
| `Supported Encoding` | 33 | 🎉 [99](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 |
|
86 |
+
|
87 |
+
<p align="center">
|
88 |
+
<img src="https://i.imgflip.com/373iay.gif" alt="Reading Normalized Text" width="226"/><img src="https://media.tenor.com/images/c0180f70732a18b4965448d33adba3d0/tenor.gif" alt="Cat Reading Text" width="200"/>
|
89 |
+
</p>
|
90 |
+
|
91 |
+
*\*\* : They are clearly using specific code for a specific encoding even if covering most of used one*<br>
|
92 |
+
Did you got there because of the logs? See [https://charset-normalizer.readthedocs.io/en/latest/user/miscellaneous.html](https://charset-normalizer.readthedocs.io/en/latest/user/miscellaneous.html)
|
93 |
+
|
94 |
+
## ⚡ Performance
|
95 |
+
|
96 |
+
This package offer better performance than its counterpart Chardet. Here are some numbers.
|
97 |
+
|
98 |
+
| Package | Accuracy | Mean per file (ms) | File per sec (est) |
|
99 |
+
|-----------------------------------------------|:--------:|:------------------:|:------------------:|
|
100 |
+
| [chardet](https://github.com/chardet/chardet) | 86 % | 200 ms | 5 file/sec |
|
101 |
+
| charset-normalizer | **98 %** | **10 ms** | 100 file/sec |
|
102 |
+
|
103 |
+
| Package | 99th percentile | 95th percentile | 50th percentile |
|
104 |
+
|-----------------------------------------------|:---------------:|:---------------:|:---------------:|
|
105 |
+
| [chardet](https://github.com/chardet/chardet) | 1200 ms | 287 ms | 23 ms |
|
106 |
+
| charset-normalizer | 100 ms | 50 ms | 5 ms |
|
107 |
+
|
108 |
+
Chardet's performance on larger file (1MB+) are very poor. Expect huge difference on large payload.
|
109 |
+
|
110 |
+
> Stats are generated using 400+ files using default parameters. More details on used files, see GHA workflows.
|
111 |
+
> And yes, these results might change at any time. The dataset can be updated to include more files.
|
112 |
+
> The actual delays heavily depends on your CPU capabilities. The factors should remain the same.
|
113 |
+
> Keep in mind that the stats are generous and that Chardet accuracy vs our is measured using Chardet initial capability
|
114 |
+
> (eg. Supported Encoding) Challenge-them if you want.
|
115 |
+
|
116 |
+
## ✨ Installation
|
117 |
+
|
118 |
+
Using pip:
|
119 |
+
|
120 |
+
```sh
|
121 |
+
pip install charset-normalizer -U
|
122 |
+
```
|
123 |
+
|
124 |
+
## 🚀 Basic Usage
|
125 |
+
|
126 |
+
### CLI
|
127 |
+
This package comes with a CLI.
|
128 |
+
|
129 |
+
```
|
130 |
+
usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD]
|
131 |
+
file [file ...]
|
132 |
+
|
133 |
+
The Real First Universal Charset Detector. Discover originating encoding used
|
134 |
+
on text file. Normalize text to unicode.
|
135 |
+
|
136 |
+
positional arguments:
|
137 |
+
files File(s) to be analysed
|
138 |
+
|
139 |
+
optional arguments:
|
140 |
+
-h, --help show this help message and exit
|
141 |
+
-v, --verbose Display complementary information about file if any.
|
142 |
+
Stdout will contain logs about the detection process.
|
143 |
+
-a, --with-alternative
|
144 |
+
Output complementary possibilities if any. Top-level
|
145 |
+
JSON WILL be a list.
|
146 |
+
-n, --normalize Permit to normalize input file. If not set, program
|
147 |
+
does not write anything.
|
148 |
+
-m, --minimal Only output the charset detected to STDOUT. Disabling
|
149 |
+
JSON output.
|
150 |
+
-r, --replace Replace file when trying to normalize it instead of
|
151 |
+
creating a new one.
|
152 |
+
-f, --force Replace file without asking if you are sure, use this
|
153 |
+
flag with caution.
|
154 |
+
-t THRESHOLD, --threshold THRESHOLD
|
155 |
+
Define a custom maximum amount of chaos allowed in
|
156 |
+
decoded content. 0. <= chaos <= 1.
|
157 |
+
--version Show version information and exit.
|
158 |
+
```
|
159 |
+
|
160 |
+
```bash
|
161 |
+
normalizer ./data/sample.1.fr.srt
|
162 |
+
```
|
163 |
+
|
164 |
+
or
|
165 |
+
|
166 |
+
```bash
|
167 |
+
python -m charset_normalizer ./data/sample.1.fr.srt
|
168 |
+
```
|
169 |
+
|
170 |
+
🎉 Since version 1.4.0 the CLI produce easily usable stdout result in JSON format.
|
171 |
+
|
172 |
+
```json
|
173 |
+
{
|
174 |
+
"path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt",
|
175 |
+
"encoding": "cp1252",
|
176 |
+
"encoding_aliases": [
|
177 |
+
"1252",
|
178 |
+
"windows_1252"
|
179 |
+
],
|
180 |
+
"alternative_encodings": [
|
181 |
+
"cp1254",
|
182 |
+
"cp1256",
|
183 |
+
"cp1258",
|
184 |
+
"iso8859_14",
|
185 |
+
"iso8859_15",
|
186 |
+
"iso8859_16",
|
187 |
+
"iso8859_3",
|
188 |
+
"iso8859_9",
|
189 |
+
"latin_1",
|
190 |
+
"mbcs"
|
191 |
+
],
|
192 |
+
"language": "French",
|
193 |
+
"alphabets": [
|
194 |
+
"Basic Latin",
|
195 |
+
"Latin-1 Supplement"
|
196 |
+
],
|
197 |
+
"has_sig_or_bom": false,
|
198 |
+
"chaos": 0.149,
|
199 |
+
"coherence": 97.152,
|
200 |
+
"unicode_path": null,
|
201 |
+
"is_preferred": true
|
202 |
+
}
|
203 |
+
```
|
204 |
+
|
205 |
+
### Python
|
206 |
+
*Just print out normalized text*
|
207 |
+
```python
|
208 |
+
from charset_normalizer import from_path
|
209 |
+
|
210 |
+
results = from_path('./my_subtitle.srt')
|
211 |
+
|
212 |
+
print(str(results.best()))
|
213 |
+
```
|
214 |
+
|
215 |
+
*Upgrade your code without effort*
|
216 |
+
```python
|
217 |
+
from charset_normalizer import detect
|
218 |
+
```
|
219 |
+
|
220 |
+
The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible.
|
221 |
+
|
222 |
+
See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/)
|
223 |
+
|
224 |
+
## 😇 Why
|
225 |
+
|
226 |
+
When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a
|
227 |
+
reliable alternative using a completely different method. Also! I never back down on a good challenge!
|
228 |
+
|
229 |
+
I **don't care** about the **originating charset** encoding, because **two different tables** can
|
230 |
+
produce **two identical rendered string.**
|
231 |
+
What I want is to get readable text, the best I can.
|
232 |
+
|
233 |
+
In a way, **I'm brute forcing text decoding.** How cool is that ? 😎
|
234 |
+
|
235 |
+
Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode.
|
236 |
+
|
237 |
+
## 🍰 How
|
238 |
+
|
239 |
+
- Discard all charset encoding table that could not fit the binary content.
|
240 |
+
- Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding.
|
241 |
+
- Extract matches with the lowest mess detected.
|
242 |
+
- Additionally, we measure coherence / probe for a language.
|
243 |
+
|
244 |
+
**Wait a minute**, what is noise/mess and coherence according to **YOU ?**
|
245 |
+
|
246 |
+
*Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then
|
247 |
+
**I established** some ground rules about **what is obvious** when **it seems like** a mess.
|
248 |
+
I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to
|
249 |
+
improve or rewrite it.
|
250 |
+
|
251 |
+
*Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought
|
252 |
+
that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design.
|
253 |
+
|
254 |
+
## ⚡ Known limitations
|
255 |
+
|
256 |
+
- Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters))
|
257 |
+
- Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content.
|
258 |
+
|
259 |
+
## ⚠️ About Python EOLs
|
260 |
+
|
261 |
+
**If you are running:**
|
262 |
+
|
263 |
+
- Python >=2.7,<3.5: Unsupported
|
264 |
+
- Python 3.5: charset-normalizer < 2.1
|
265 |
+
- Python 3.6: charset-normalizer < 3.1
|
266 |
+
- Python 3.7: charset-normalizer < 4.0
|
267 |
+
|
268 |
+
Upgrade your Python interpreter as soon as possible.
|
269 |
+
|
270 |
+
## 👤 Contributing
|
271 |
+
|
272 |
+
Contributions, issues and feature requests are very much welcome.<br />
|
273 |
+
Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute.
|
274 |
+
|
275 |
+
## 📝 License
|
276 |
+
|
277 |
+
Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret).<br />
|
278 |
+
This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed.
|
279 |
+
|
280 |
+
Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/)
|
281 |
+
|
282 |
+
## 💼 For Enterprise
|
283 |
+
|
284 |
+
Professional support for charset-normalizer is available as part of the [Tidelift
|
285 |
+
Subscription][1]. Tidelift gives software development teams a single source for
|
286 |
+
purchasing and maintaining their software, with professional grade assurances
|
287 |
+
from the experts who know it best, while seamlessly integrating with existing
|
288 |
+
tools.
|
289 |
+
|
290 |
+
[1]: https://tidelift.com/subscription/pkg/pypi-charset-normalizer?utm_source=pypi-charset-normalizer&utm_medium=readme
|
291 |
+
|
292 |
+
# Changelog
|
293 |
+
All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
294 |
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
295 |
+
|
296 |
+
## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31)
|
297 |
+
|
298 |
+
### Fixed
|
299 |
+
- Unintentional memory usage regression when using large payload that match several encoding (#376)
|
300 |
+
- Regression on some detection case showcased in the documentation (#371)
|
301 |
+
|
302 |
+
### Added
|
303 |
+
- Noise (md) probe that identify malformed arabic representation due to the presence of letters in isolated form (credit to my wife)
|
304 |
+
|
305 |
+
## [3.3.1](https://github.com/Ousret/charset_normalizer/compare/3.3.0...3.3.1) (2023-10-22)
|
306 |
+
|
307 |
+
### Changed
|
308 |
+
- Optional mypyc compilation upgraded to version 1.6.1 for Python >= 3.8
|
309 |
+
- Improved the general detection reliability based on reports from the community
|
310 |
+
|
311 |
+
## [3.3.0](https://github.com/Ousret/charset_normalizer/compare/3.2.0...3.3.0) (2023-09-30)
|
312 |
+
|
313 |
+
### Added
|
314 |
+
- Allow to execute the CLI (e.g. normalizer) through `python -m charset_normalizer.cli` or `python -m charset_normalizer`
|
315 |
+
- Support for 9 forgotten encoding that are supported by Python but unlisted in `encoding.aliases` as they have no alias (#323)
|
316 |
+
|
317 |
+
### Removed
|
318 |
+
- (internal) Redundant utils.is_ascii function and unused function is_private_use_only
|
319 |
+
- (internal) charset_normalizer.assets is moved inside charset_normalizer.constant
|
320 |
+
|
321 |
+
### Changed
|
322 |
+
- (internal) Unicode code blocks in constants are updated using the latest v15.0.0 definition to improve detection
|
323 |
+
- Optional mypyc compilation upgraded to version 1.5.1 for Python >= 3.8
|
324 |
+
|
325 |
+
### Fixed
|
326 |
+
- Unable to properly sort CharsetMatch when both chaos/noise and coherence were close due to an unreachable condition in \_\_lt\_\_ (#350)
|
327 |
+
|
328 |
+
## [3.2.0](https://github.com/Ousret/charset_normalizer/compare/3.1.0...3.2.0) (2023-06-07)
|
329 |
+
|
330 |
+
### Changed
|
331 |
+
- Typehint for function `from_path` no longer enforce `PathLike` as its first argument
|
332 |
+
- Minor improvement over the global detection reliability
|
333 |
+
|
334 |
+
### Added
|
335 |
+
- Introduce function `is_binary` that relies on main capabilities, and optimized to detect binaries
|
336 |
+
- Propagate `enable_fallback` argument throughout `from_bytes`, `from_path`, and `from_fp` that allow a deeper control over the detection (default True)
|
337 |
+
- Explicit support for Python 3.12
|
338 |
+
|
339 |
+
### Fixed
|
340 |
+
- Edge case detection failure where a file would contain 'very-long' camel cased word (Issue #289)
|
341 |
+
|
342 |
+
## [3.1.0](https://github.com/Ousret/charset_normalizer/compare/3.0.1...3.1.0) (2023-03-06)
|
343 |
+
|
344 |
+
### Added
|
345 |
+
- Argument `should_rename_legacy` for legacy function `detect` and disregard any new arguments without errors (PR #262)
|
346 |
+
|
347 |
+
### Removed
|
348 |
+
- Support for Python 3.6 (PR #260)
|
349 |
+
|
350 |
+
### Changed
|
351 |
+
- Optional speedup provided by mypy/c 1.0.1
|
352 |
+
|
353 |
+
## [3.0.1](https://github.com/Ousret/charset_normalizer/compare/3.0.0...3.0.1) (2022-11-18)
|
354 |
+
|
355 |
+
### Fixed
|
356 |
+
- Multi-bytes cutter/chunk generator did not always cut correctly (PR #233)
|
357 |
+
|
358 |
+
### Changed
|
359 |
+
- Speedup provided by mypy/c 0.990 on Python >= 3.7
|
360 |
+
|
361 |
+
## [3.0.0](https://github.com/Ousret/charset_normalizer/compare/2.1.1...3.0.0) (2022-10-20)
|
362 |
+
|
363 |
+
### Added
|
364 |
+
- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results
|
365 |
+
- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES
|
366 |
+
- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio
|
367 |
+
- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl)
|
368 |
+
|
369 |
+
### Changed
|
370 |
+
- Build with static metadata using 'build' frontend
|
371 |
+
- Make the language detection stricter
|
372 |
+
- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1
|
373 |
+
|
374 |
+
### Fixed
|
375 |
+
- CLI with opt --normalize fail when using full path for files
|
376 |
+
- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it
|
377 |
+
- Sphinx warnings when generating the documentation
|
378 |
+
|
379 |
+
### Removed
|
380 |
+
- Coherence detector no longer return 'Simple English' instead return 'English'
|
381 |
+
- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese'
|
382 |
+
- Breaking: Method `first()` and `best()` from CharsetMatch
|
383 |
+
- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII)
|
384 |
+
- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches
|
385 |
+
- Breaking: Top-level function `normalize`
|
386 |
+
- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch
|
387 |
+
- Support for the backport `unicodedata2`
|
388 |
+
|
389 |
+
## [3.0.0rc1](https://github.com/Ousret/charset_normalizer/compare/3.0.0b2...3.0.0rc1) (2022-10-18)
|
390 |
+
|
391 |
+
### Added
|
392 |
+
- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results
|
393 |
+
- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES
|
394 |
+
- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio
|
395 |
+
|
396 |
+
### Changed
|
397 |
+
- Build with static metadata using 'build' frontend
|
398 |
+
- Make the language detection stricter
|
399 |
+
|
400 |
+
### Fixed
|
401 |
+
- CLI with opt --normalize fail when using full path for files
|
402 |
+
- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it
|
403 |
+
|
404 |
+
### Removed
|
405 |
+
- Coherence detector no longer return 'Simple English' instead return 'English'
|
406 |
+
- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese'
|
407 |
+
|
408 |
+
## [3.0.0b2](https://github.com/Ousret/charset_normalizer/compare/3.0.0b1...3.0.0b2) (2022-08-21)
|
409 |
+
|
410 |
+
### Added
|
411 |
+
- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl)
|
412 |
+
|
413 |
+
### Removed
|
414 |
+
- Breaking: Method `first()` and `best()` from CharsetMatch
|
415 |
+
- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII)
|
416 |
+
|
417 |
+
### Fixed
|
418 |
+
- Sphinx warnings when generating the documentation
|
419 |
+
|
420 |
+
## [3.0.0b1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...3.0.0b1) (2022-08-15)
|
421 |
+
|
422 |
+
### Changed
|
423 |
+
- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1
|
424 |
+
|
425 |
+
### Removed
|
426 |
+
- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches
|
427 |
+
- Breaking: Top-level function `normalize`
|
428 |
+
- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch
|
429 |
+
- Support for the backport `unicodedata2`
|
430 |
+
|
431 |
+
## [2.1.1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...2.1.1) (2022-08-19)
|
432 |
+
|
433 |
+
### Deprecated
|
434 |
+
- Function `normalize` scheduled for removal in 3.0
|
435 |
+
|
436 |
+
### Changed
|
437 |
+
- Removed useless call to decode in fn is_unprintable (#206)
|
438 |
+
|
439 |
+
### Fixed
|
440 |
+
- Third-party library (i18n xgettext) crashing not recognizing utf_8 (PEP 263) with underscore from [@aleksandernovikov](https://github.com/aleksandernovikov) (#204)
|
441 |
+
|
442 |
+
## [2.1.0](https://github.com/Ousret/charset_normalizer/compare/2.0.12...2.1.0) (2022-06-19)
|
443 |
+
|
444 |
+
### Added
|
445 |
+
- Output the Unicode table version when running the CLI with `--version` (PR #194)
|
446 |
+
|
447 |
+
### Changed
|
448 |
+
- Re-use decoded buffer for single byte character sets from [@nijel](https://github.com/nijel) (PR #175)
|
449 |
+
- Fixing some performance bottlenecks from [@deedy5](https://github.com/deedy5) (PR #183)
|
450 |
+
|
451 |
+
### Fixed
|
452 |
+
- Workaround potential bug in cpython with Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space (PR #175)
|
453 |
+
- CLI default threshold aligned with the API threshold from [@oleksandr-kuzmenko](https://github.com/oleksandr-kuzmenko) (PR #181)
|
454 |
+
|
455 |
+
### Removed
|
456 |
+
- Support for Python 3.5 (PR #192)
|
457 |
+
|
458 |
+
### Deprecated
|
459 |
+
- Use of backport unicodedata from `unicodedata2` as Python is quickly catching up, scheduled for removal in 3.0 (PR #194)
|
460 |
+
|
461 |
+
## [2.0.12](https://github.com/Ousret/charset_normalizer/compare/2.0.11...2.0.12) (2022-02-12)
|
462 |
+
|
463 |
+
### Fixed
|
464 |
+
- ASCII miss-detection on rare cases (PR #170)
|
465 |
+
|
466 |
+
## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30)
|
467 |
+
|
468 |
+
### Added
|
469 |
+
- Explicit support for Python 3.11 (PR #164)
|
470 |
+
|
471 |
+
### Changed
|
472 |
+
- The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165)
|
473 |
+
|
474 |
+
## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04)
|
475 |
+
|
476 |
+
### Fixed
|
477 |
+
- Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154)
|
478 |
+
|
479 |
+
### Changed
|
480 |
+
- Skipping the language-detection (CD) on ASCII (PR #155)
|
481 |
+
|
482 |
+
## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03)
|
483 |
+
|
484 |
+
### Changed
|
485 |
+
- Moderating the logging impact (since 2.0.8) for specific environments (PR #147)
|
486 |
+
|
487 |
+
### Fixed
|
488 |
+
- Wrong logging level applied when setting kwarg `explain` to True (PR #146)
|
489 |
+
|
490 |
+
## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24)
|
491 |
+
### Changed
|
492 |
+
- Improvement over Vietnamese detection (PR #126)
|
493 |
+
- MD improvement on trailing data and long foreign (non-pure latin) data (PR #124)
|
494 |
+
- Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122)
|
495 |
+
- call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129)
|
496 |
+
- Code style as refactored by Sourcery-AI (PR #131)
|
497 |
+
- Minor adjustment on the MD around european words (PR #133)
|
498 |
+
- Remove and replace SRTs from assets / tests (PR #139)
|
499 |
+
- Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135)
|
500 |
+
- Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135)
|
501 |
+
|
502 |
+
### Fixed
|
503 |
+
- Fix large (misleading) sequence giving UnicodeDecodeError (PR #137)
|
504 |
+
- Avoid using too insignificant chunk (PR #137)
|
505 |
+
|
506 |
+
### Added
|
507 |
+
- Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135)
|
508 |
+
- Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141)
|
509 |
+
|
510 |
+
## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11)
|
511 |
+
### Added
|
512 |
+
- Add support for Kazakh (Cyrillic) language detection (PR #109)
|
513 |
+
|
514 |
+
### Changed
|
515 |
+
- Further, improve inferring the language from a given single-byte code page (PR #112)
|
516 |
+
- Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116)
|
517 |
+
- Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113)
|
518 |
+
- Various detection improvement (MD+CD) (PR #117)
|
519 |
+
|
520 |
+
### Removed
|
521 |
+
- Remove redundant logging entry about detected language(s) (PR #115)
|
522 |
+
|
523 |
+
### Fixed
|
524 |
+
- Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102)
|
525 |
+
|
526 |
+
## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18)
|
527 |
+
### Fixed
|
528 |
+
- Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100)
|
529 |
+
- Fix CLI crash when using --minimal output in certain cases (PR #103)
|
530 |
+
|
531 |
+
### Changed
|
532 |
+
- Minor improvement to the detection efficiency (less than 1%) (PR #106 #101)
|
533 |
+
|
534 |
+
## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14)
|
535 |
+
### Changed
|
536 |
+
- The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81)
|
537 |
+
- The BC-support with v1.x was improved, the old staticmethods are restored (PR #82)
|
538 |
+
- The Unicode detection is slightly improved (PR #93)
|
539 |
+
- Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91)
|
540 |
+
|
541 |
+
### Removed
|
542 |
+
- The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92)
|
543 |
+
|
544 |
+
### Fixed
|
545 |
+
- In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95)
|
546 |
+
- Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96)
|
547 |
+
- The MANIFEST.in was not exhaustive (PR #78)
|
548 |
+
|
549 |
+
## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30)
|
550 |
+
### Fixed
|
551 |
+
- The CLI no longer raise an unexpected exception when no encoding has been found (PR #70)
|
552 |
+
- Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68)
|
553 |
+
- The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72)
|
554 |
+
- Submatch factoring could be wrong in rare edge cases (PR #72)
|
555 |
+
- Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72)
|
556 |
+
- Fix line endings from CRLF to LF for certain project files (PR #67)
|
557 |
+
|
558 |
+
### Changed
|
559 |
+
- Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76)
|
560 |
+
- Allow fallback on specified encoding if any (PR #71)
|
561 |
+
|
562 |
+
## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16)
|
563 |
+
### Changed
|
564 |
+
- Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63)
|
565 |
+
- According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64)
|
566 |
+
|
567 |
+
## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15)
|
568 |
+
### Fixed
|
569 |
+
- Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59)
|
570 |
+
|
571 |
+
### Changed
|
572 |
+
- Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57)
|
573 |
+
|
574 |
+
## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13)
|
575 |
+
### Fixed
|
576 |
+
- Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55)
|
577 |
+
- Using explain=False permanently disable the verbose output in the current runtime (PR #47)
|
578 |
+
- One log entry (language target preemptive) was not show in logs when using explain=True (PR #47)
|
579 |
+
- Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52)
|
580 |
+
|
581 |
+
### Changed
|
582 |
+
- Public function normalize default args values were not aligned with from_bytes (PR #53)
|
583 |
+
|
584 |
+
### Added
|
585 |
+
- You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47)
|
586 |
+
|
587 |
+
## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02)
|
588 |
+
### Changed
|
589 |
+
- 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet.
|
590 |
+
- Accent has been made on UTF-8 detection, should perform rather instantaneous.
|
591 |
+
- The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible.
|
592 |
+
- The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time)
|
593 |
+
- The program has been rewritten to ease the readability and maintainability. (+Using static typing)+
|
594 |
+
- utf_7 detection has been reinstated.
|
595 |
+
|
596 |
+
### Removed
|
597 |
+
- This package no longer require anything when used with Python 3.5 (Dropped cached_property)
|
598 |
+
- Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian.
|
599 |
+
- The exception hook on UnicodeDecodeError has been removed.
|
600 |
+
|
601 |
+
### Deprecated
|
602 |
+
- Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0
|
603 |
+
|
604 |
+
### Fixed
|
605 |
+
- The CLI output used the relative path of the file(s). Should be absolute.
|
606 |
+
|
607 |
+
## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28)
|
608 |
+
### Fixed
|
609 |
+
- Logger configuration/usage no longer conflict with others (PR #44)
|
610 |
+
|
611 |
+
## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21)
|
612 |
+
### Removed
|
613 |
+
- Using standard logging instead of using the package loguru.
|
614 |
+
- Dropping nose test framework in favor of the maintained pytest.
|
615 |
+
- Choose to not use dragonmapper package to help with gibberish Chinese/CJK text.
|
616 |
+
- Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version.
|
617 |
+
- Stop support for UTF-7 that does not contain a SIG.
|
618 |
+
- Dropping PrettyTable, replaced with pure JSON output in CLI.
|
619 |
+
|
620 |
+
### Fixed
|
621 |
+
- BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process.
|
622 |
+
- Not searching properly for the BOM when trying utf32/16 parent codec.
|
623 |
+
|
624 |
+
### Changed
|
625 |
+
- Improving the package final size by compressing frequencies.json.
|
626 |
+
- Huge improvement over the larges payload.
|
627 |
+
|
628 |
+
### Added
|
629 |
+
- CLI now produces JSON consumable output.
|
630 |
+
- Return ASCII if given sequences fit. Given reasonable confidence.
|
631 |
+
|
632 |
+
## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13)
|
633 |
+
|
634 |
+
### Fixed
|
635 |
+
- In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40)
|
636 |
+
|
637 |
+
## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12)
|
638 |
+
|
639 |
+
### Fixed
|
640 |
+
- Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39)
|
641 |
+
|
642 |
+
## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12)
|
643 |
+
|
644 |
+
### Fixed
|
645 |
+
- The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38)
|
646 |
+
|
647 |
+
## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09)
|
648 |
+
|
649 |
+
### Changed
|
650 |
+
- Amend the previous release to allow prettytable 2.0 (PR #35)
|
651 |
+
|
652 |
+
## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08)
|
653 |
+
|
654 |
+
### Fixed
|
655 |
+
- Fix error while using the package with a python pre-release interpreter (PR #33)
|
656 |
+
|
657 |
+
### Changed
|
658 |
+
- Dependencies refactoring, constraints revised.
|
659 |
+
|
660 |
+
### Added
|
661 |
+
- Add python 3.9 and 3.10 to the supported interpreters
|
662 |
+
|
663 |
+
MIT License
|
664 |
+
|
665 |
+
Copyright (c) 2019 TAHRI Ahmed R.
|
666 |
+
|
667 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
668 |
+
of this software and associated documentation files (the "Software"), to deal
|
669 |
+
in the Software without restriction, including without limitation the rights
|
670 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
671 |
+
copies of the Software, and to permit persons to whom the Software is
|
672 |
+
furnished to do so, subject to the following conditions:
|
673 |
+
|
674 |
+
The above copyright notice and this permission notice shall be included in all
|
675 |
+
copies or substantial portions of the Software.
|
676 |
+
|
677 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
678 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
679 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
680 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
681 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
682 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
683 |
+
SOFTWARE.
|
env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/RECORD
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
../../../bin/normalizer,sha256=qedt49WER5buUvl2eM7SoBISPEqYe1xwmi74d6Ix1ik,259
|
2 |
+
charset_normalizer-3.3.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
3 |
+
charset_normalizer-3.3.2.dist-info/LICENSE,sha256=6zGgxaT7Cbik4yBV0lweX5w1iidS_vPNcgIT0cz-4kE,1070
|
4 |
+
charset_normalizer-3.3.2.dist-info/METADATA,sha256=cfLhl5A6SI-F0oclm8w8ux9wshL1nipdeCdVnYb4AaA,33550
|
5 |
+
charset_normalizer-3.3.2.dist-info/RECORD,,
|
6 |
+
charset_normalizer-3.3.2.dist-info/WHEEL,sha256=cD39NF6a3hkhaWoPQJng7gnGZRIfQsUCtwcedITCPtg,152
|
7 |
+
charset_normalizer-3.3.2.dist-info/entry_points.txt,sha256=ADSTKrkXZ3hhdOVFi6DcUEHQRS0xfxDIE_pEz4wLIXA,65
|
8 |
+
charset_normalizer-3.3.2.dist-info/top_level.txt,sha256=7ASyzePr8_xuZWJsnqJjIBtyV8vhEo0wBCv1MPRRi3Q,19
|
9 |
+
charset_normalizer/__init__.py,sha256=UzI3xC8PhmcLRMzSgPb6minTmRq0kWznnCBJ8ZCc2XI,1577
|
10 |
+
charset_normalizer/__main__.py,sha256=JxY8bleaENOFlLRb9HfoeZCzAMnn2A1oGR5Xm2eyqg0,73
|
11 |
+
charset_normalizer/__pycache__/__init__.cpython-310.pyc,,
|
12 |
+
charset_normalizer/__pycache__/__main__.cpython-310.pyc,,
|
13 |
+
charset_normalizer/__pycache__/api.cpython-310.pyc,,
|
14 |
+
charset_normalizer/__pycache__/cd.cpython-310.pyc,,
|
15 |
+
charset_normalizer/__pycache__/constant.cpython-310.pyc,,
|
16 |
+
charset_normalizer/__pycache__/legacy.cpython-310.pyc,,
|
17 |
+
charset_normalizer/__pycache__/md.cpython-310.pyc,,
|
18 |
+
charset_normalizer/__pycache__/models.cpython-310.pyc,,
|
19 |
+
charset_normalizer/__pycache__/utils.cpython-310.pyc,,
|
20 |
+
charset_normalizer/__pycache__/version.cpython-310.pyc,,
|
21 |
+
charset_normalizer/api.py,sha256=WOlWjy6wT8SeMYFpaGbXZFN1TMXa-s8vZYfkL4G29iQ,21097
|
22 |
+
charset_normalizer/cd.py,sha256=xwZliZcTQFA3jU0c00PRiu9MNxXTFxQkFLWmMW24ZzI,12560
|
23 |
+
charset_normalizer/cli/__init__.py,sha256=D5ERp8P62llm2FuoMzydZ7d9rs8cvvLXqE-1_6oViPc,100
|
24 |
+
charset_normalizer/cli/__main__.py,sha256=2F-xURZJzo063Ye-2RLJ2wcmURpbKeAzKwpiws65dAs,9744
|
25 |
+
charset_normalizer/cli/__pycache__/__init__.cpython-310.pyc,,
|
26 |
+
charset_normalizer/cli/__pycache__/__main__.cpython-310.pyc,,
|
27 |
+
charset_normalizer/constant.py,sha256=p0IsOVcEbPWYPOdWhnhRbjK1YVBy6fs05C5vKC-zoxU,40481
|
28 |
+
charset_normalizer/legacy.py,sha256=T-QuVMsMeDiQEk8WSszMrzVJg_14AMeSkmHdRYhdl1k,2071
|
29 |
+
charset_normalizer/md.cpython-310-x86_64-linux-gnu.so,sha256=Y7QSLD5QLoSFAWys0-tL7R6QB7oi5864zM6zr7RWek4,16064
|
30 |
+
charset_normalizer/md.py,sha256=NkSuVLK13_a8c7BxZ4cGIQ5vOtGIWOdh22WZEvjp-7U,19624
|
31 |
+
charset_normalizer/md__mypyc.cpython-310-x86_64-linux-gnu.so,sha256=y2N-LgwRp7TCdgRqsmIM8UvKeavC0t8kx_hdRvaSfcY,268472
|
32 |
+
charset_normalizer/models.py,sha256=I5i0s4aKCCgLPY2tUY3pwkgFA-BUbbNxQ7hVkVTt62s,11624
|
33 |
+
charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
34 |
+
charset_normalizer/utils.py,sha256=teiosMqzKjXyAHXnGdjSBOgnBZwx-SkBbCLrx0UXy8M,11894
|
35 |
+
charset_normalizer/version.py,sha256=iHKUfHD3kDRSyrh_BN2ojh43TA5-UZQjvbVIEFfpHDs,79
|
env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/WHEEL
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: bdist_wheel (0.41.2)
|
3 |
+
Root-Is-Purelib: false
|
4 |
+
Tag: cp310-cp310-manylinux_2_17_x86_64
|
5 |
+
Tag: cp310-cp310-manylinux2014_x86_64
|
6 |
+
|
env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/entry_points.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
[console_scripts]
|
2 |
+
normalizer = charset_normalizer.cli:cli_detect
|
env-llmeval/lib/python3.10/site-packages/charset_normalizer-3.3.2.dist-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
charset_normalizer
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc
ADDED
Binary file (1.54 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/environment.cpython-310.pyc
ADDED
Binary file (53.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc
ADDED
Binary file (11.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc
ADDED
Binary file (20.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/loaders.cpython-310.pyc
ADDED
Binary file (20.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc
ADDED
Binary file (5.01 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc
ADDED
Binary file (40.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/optimizer.cpython-310.pyc
ADDED
Binary file (1.96 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/jinja2/__pycache__/runtime.cpython-310.pyc
ADDED
Binary file (32.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/__init__.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List, Optional
|
2 |
+
|
3 |
+
__version__ = "22.0.2"
|
4 |
+
|
5 |
+
|
6 |
+
def main(args: Optional[List[str]] = None) -> int:
|
7 |
+
"""This is an internal API only meant for use by pip's own console scripts.
|
8 |
+
|
9 |
+
For additional details, see https://github.com/pypa/pip/issues/7498.
|
10 |
+
"""
|
11 |
+
from pip._internal.utils.entrypoints import _wrapper
|
12 |
+
|
13 |
+
return _wrapper(args)
|
env-llmeval/lib/python3.10/site-packages/pybind11/__init__.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
|
3 |
+
if sys.version_info < (3, 6): # noqa: UP036
|
4 |
+
msg = "pybind11 does not support Python < 3.6. 2.9 was the last release supporting Python 2.7 and 3.5."
|
5 |
+
raise ImportError(msg)
|
6 |
+
|
7 |
+
|
8 |
+
from ._version import __version__, version_info
|
9 |
+
from .commands import get_cmake_dir, get_include, get_pkgconfig_dir
|
10 |
+
|
11 |
+
__all__ = (
|
12 |
+
"version_info",
|
13 |
+
"__version__",
|
14 |
+
"get_include",
|
15 |
+
"get_cmake_dir",
|
16 |
+
"get_pkgconfig_dir",
|
17 |
+
)
|
env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (553 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc
ADDED
Binary file (1.67 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc
ADDED
Binary file (609 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc
ADDED
Binary file (1.39 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc
ADDED
Binary file (15.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pybind11/_version.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Union
|
2 |
+
|
3 |
+
|
4 |
+
def _to_int(s: str) -> Union[int, str]:
|
5 |
+
try:
|
6 |
+
return int(s)
|
7 |
+
except ValueError:
|
8 |
+
return s
|
9 |
+
|
10 |
+
|
11 |
+
__version__ = "2.12.0"
|
12 |
+
version_info = tuple(_to_int(s) for s in __version__.split("."))
|
env-llmeval/lib/python3.10/site-packages/pybind11/commands.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
DIR = os.path.abspath(os.path.dirname(__file__))
|
4 |
+
|
5 |
+
|
6 |
+
def get_include(user: bool = False) -> str: # noqa: ARG001
|
7 |
+
"""
|
8 |
+
Return the path to the pybind11 include directory. The historical "user"
|
9 |
+
argument is unused, and may be removed.
|
10 |
+
"""
|
11 |
+
installed_path = os.path.join(DIR, "include")
|
12 |
+
source_path = os.path.join(os.path.dirname(DIR), "include")
|
13 |
+
return installed_path if os.path.exists(installed_path) else source_path
|
14 |
+
|
15 |
+
|
16 |
+
def get_cmake_dir() -> str:
|
17 |
+
"""
|
18 |
+
Return the path to the pybind11 CMake module directory.
|
19 |
+
"""
|
20 |
+
cmake_installed_path = os.path.join(DIR, "share", "cmake", "pybind11")
|
21 |
+
if os.path.exists(cmake_installed_path):
|
22 |
+
return cmake_installed_path
|
23 |
+
|
24 |
+
msg = "pybind11 not installed, installation required to access the CMake files"
|
25 |
+
raise ImportError(msg)
|
26 |
+
|
27 |
+
|
28 |
+
def get_pkgconfig_dir() -> str:
|
29 |
+
"""
|
30 |
+
Return the path to the pybind11 pkgconfig directory.
|
31 |
+
"""
|
32 |
+
pkgconfig_installed_path = os.path.join(DIR, "share", "pkgconfig")
|
33 |
+
if os.path.exists(pkgconfig_installed_path):
|
34 |
+
return pkgconfig_installed_path
|
35 |
+
|
36 |
+
msg = "pybind11 not installed, installation required to access the pkgconfig files"
|
37 |
+
raise ImportError(msg)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h
ADDED
@@ -0,0 +1,690 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/attr.h: Infrastructure for processing custom
|
3 |
+
type and function attributes
|
4 |
+
|
5 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
6 |
+
|
7 |
+
All rights reserved. Use of this source code is governed by a
|
8 |
+
BSD-style license that can be found in the LICENSE file.
|
9 |
+
*/
|
10 |
+
|
11 |
+
#pragma once
|
12 |
+
|
13 |
+
#include "detail/common.h"
|
14 |
+
#include "cast.h"
|
15 |
+
|
16 |
+
#include <functional>
|
17 |
+
|
18 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
19 |
+
|
20 |
+
/// \addtogroup annotations
|
21 |
+
/// @{
|
22 |
+
|
23 |
+
/// Annotation for methods
|
24 |
+
struct is_method {
|
25 |
+
handle class_;
|
26 |
+
explicit is_method(const handle &c) : class_(c) {}
|
27 |
+
};
|
28 |
+
|
29 |
+
/// Annotation for setters
|
30 |
+
struct is_setter {};
|
31 |
+
|
32 |
+
/// Annotation for operators
|
33 |
+
struct is_operator {};
|
34 |
+
|
35 |
+
/// Annotation for classes that cannot be subclassed
|
36 |
+
struct is_final {};
|
37 |
+
|
38 |
+
/// Annotation for parent scope
|
39 |
+
struct scope {
|
40 |
+
handle value;
|
41 |
+
explicit scope(const handle &s) : value(s) {}
|
42 |
+
};
|
43 |
+
|
44 |
+
/// Annotation for documentation
|
45 |
+
struct doc {
|
46 |
+
const char *value;
|
47 |
+
explicit doc(const char *value) : value(value) {}
|
48 |
+
};
|
49 |
+
|
50 |
+
/// Annotation for function names
|
51 |
+
struct name {
|
52 |
+
const char *value;
|
53 |
+
explicit name(const char *value) : value(value) {}
|
54 |
+
};
|
55 |
+
|
56 |
+
/// Annotation indicating that a function is an overload associated with a given "sibling"
|
57 |
+
struct sibling {
|
58 |
+
handle value;
|
59 |
+
explicit sibling(const handle &value) : value(value.ptr()) {}
|
60 |
+
};
|
61 |
+
|
62 |
+
/// Annotation indicating that a class derives from another given type
|
63 |
+
template <typename T>
|
64 |
+
struct base {
|
65 |
+
|
66 |
+
PYBIND11_DEPRECATED(
|
67 |
+
"base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
|
68 |
+
base() = default;
|
69 |
+
};
|
70 |
+
|
71 |
+
/// Keep patient alive while nurse lives
|
72 |
+
template <size_t Nurse, size_t Patient>
|
73 |
+
struct keep_alive {};
|
74 |
+
|
75 |
+
/// Annotation indicating that a class is involved in a multiple inheritance relationship
|
76 |
+
struct multiple_inheritance {};
|
77 |
+
|
78 |
+
/// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
|
79 |
+
struct dynamic_attr {};
|
80 |
+
|
81 |
+
/// Annotation which enables the buffer protocol for a type
|
82 |
+
struct buffer_protocol {};
|
83 |
+
|
84 |
+
/// Annotation which requests that a special metaclass is created for a type
|
85 |
+
struct metaclass {
|
86 |
+
handle value;
|
87 |
+
|
88 |
+
PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
|
89 |
+
metaclass() = default;
|
90 |
+
|
91 |
+
/// Override pybind11's default metaclass
|
92 |
+
explicit metaclass(handle value) : value(value) {}
|
93 |
+
};
|
94 |
+
|
95 |
+
/// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that
|
96 |
+
/// may be used to customize the Python type.
|
97 |
+
///
|
98 |
+
/// The callback is invoked immediately before `PyType_Ready`.
|
99 |
+
///
|
100 |
+
/// Note: This is an advanced interface, and uses of it may require changes to
|
101 |
+
/// work with later versions of pybind11. You may wish to consult the
|
102 |
+
/// implementation of `make_new_python_type` in `detail/classes.h` to understand
|
103 |
+
/// the context in which the callback will be run.
|
104 |
+
struct custom_type_setup {
|
105 |
+
using callback = std::function<void(PyHeapTypeObject *heap_type)>;
|
106 |
+
|
107 |
+
explicit custom_type_setup(callback value) : value(std::move(value)) {}
|
108 |
+
|
109 |
+
callback value;
|
110 |
+
};
|
111 |
+
|
112 |
+
/// Annotation that marks a class as local to the module:
|
113 |
+
struct module_local {
|
114 |
+
const bool value;
|
115 |
+
constexpr explicit module_local(bool v = true) : value(v) {}
|
116 |
+
};
|
117 |
+
|
118 |
+
/// Annotation to mark enums as an arithmetic type
|
119 |
+
struct arithmetic {};
|
120 |
+
|
121 |
+
/// Mark a function for addition at the beginning of the existing overload chain instead of the end
|
122 |
+
struct prepend {};
|
123 |
+
|
124 |
+
/** \rst
|
125 |
+
A call policy which places one or more guard variables (``Ts...``) around the function call.
|
126 |
+
|
127 |
+
For example, this definition:
|
128 |
+
|
129 |
+
.. code-block:: cpp
|
130 |
+
|
131 |
+
m.def("foo", foo, py::call_guard<T>());
|
132 |
+
|
133 |
+
is equivalent to the following pseudocode:
|
134 |
+
|
135 |
+
.. code-block:: cpp
|
136 |
+
|
137 |
+
m.def("foo", [](args...) {
|
138 |
+
T scope_guard;
|
139 |
+
return foo(args...); // forwarded arguments
|
140 |
+
});
|
141 |
+
\endrst */
|
142 |
+
template <typename... Ts>
|
143 |
+
struct call_guard;
|
144 |
+
|
145 |
+
template <>
|
146 |
+
struct call_guard<> {
|
147 |
+
using type = detail::void_type;
|
148 |
+
};
|
149 |
+
|
150 |
+
template <typename T>
|
151 |
+
struct call_guard<T> {
|
152 |
+
static_assert(std::is_default_constructible<T>::value,
|
153 |
+
"The guard type must be default constructible");
|
154 |
+
|
155 |
+
using type = T;
|
156 |
+
};
|
157 |
+
|
158 |
+
template <typename T, typename... Ts>
|
159 |
+
struct call_guard<T, Ts...> {
|
160 |
+
struct type {
|
161 |
+
T guard{}; // Compose multiple guard types with left-to-right default-constructor order
|
162 |
+
typename call_guard<Ts...>::type next{};
|
163 |
+
};
|
164 |
+
};
|
165 |
+
|
166 |
+
/// @} annotations
|
167 |
+
|
168 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
169 |
+
/* Forward declarations */
|
170 |
+
enum op_id : int;
|
171 |
+
enum op_type : int;
|
172 |
+
struct undefined_t;
|
173 |
+
template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>
|
174 |
+
struct op_;
|
175 |
+
void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
|
176 |
+
|
177 |
+
/// Internal data structure which holds metadata about a keyword argument
|
178 |
+
struct argument_record {
|
179 |
+
const char *name; ///< Argument name
|
180 |
+
const char *descr; ///< Human-readable version of the argument value
|
181 |
+
handle value; ///< Associated Python object
|
182 |
+
bool convert : 1; ///< True if the argument is allowed to convert when loading
|
183 |
+
bool none : 1; ///< True if None is allowed when loading
|
184 |
+
|
185 |
+
argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
|
186 |
+
: name(name), descr(descr), value(value), convert(convert), none(none) {}
|
187 |
+
};
|
188 |
+
|
189 |
+
/// Internal data structure which holds metadata about a bound function (signature, overloads,
|
190 |
+
/// etc.)
|
191 |
+
struct function_record {
|
192 |
+
function_record()
|
193 |
+
: is_constructor(false), is_new_style_constructor(false), is_stateless(false),
|
194 |
+
is_operator(false), is_method(false), is_setter(false), has_args(false),
|
195 |
+
has_kwargs(false), prepend(false) {}
|
196 |
+
|
197 |
+
/// Function name
|
198 |
+
char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
|
199 |
+
|
200 |
+
// User-specified documentation string
|
201 |
+
char *doc = nullptr;
|
202 |
+
|
203 |
+
/// Human-readable version of the function signature
|
204 |
+
char *signature = nullptr;
|
205 |
+
|
206 |
+
/// List of registered keyword arguments
|
207 |
+
std::vector<argument_record> args;
|
208 |
+
|
209 |
+
/// Pointer to lambda function which converts arguments and performs the actual call
|
210 |
+
handle (*impl)(function_call &) = nullptr;
|
211 |
+
|
212 |
+
/// Storage for the wrapped function pointer and captured data, if any
|
213 |
+
void *data[3] = {};
|
214 |
+
|
215 |
+
/// Pointer to custom destructor for 'data' (if needed)
|
216 |
+
void (*free_data)(function_record *ptr) = nullptr;
|
217 |
+
|
218 |
+
/// Return value policy associated with this function
|
219 |
+
return_value_policy policy = return_value_policy::automatic;
|
220 |
+
|
221 |
+
/// True if name == '__init__'
|
222 |
+
bool is_constructor : 1;
|
223 |
+
|
224 |
+
/// True if this is a new-style `__init__` defined in `detail/init.h`
|
225 |
+
bool is_new_style_constructor : 1;
|
226 |
+
|
227 |
+
/// True if this is a stateless function pointer
|
228 |
+
bool is_stateless : 1;
|
229 |
+
|
230 |
+
/// True if this is an operator (__add__), etc.
|
231 |
+
bool is_operator : 1;
|
232 |
+
|
233 |
+
/// True if this is a method
|
234 |
+
bool is_method : 1;
|
235 |
+
|
236 |
+
/// True if this is a setter
|
237 |
+
bool is_setter : 1;
|
238 |
+
|
239 |
+
/// True if the function has a '*args' argument
|
240 |
+
bool has_args : 1;
|
241 |
+
|
242 |
+
/// True if the function has a '**kwargs' argument
|
243 |
+
bool has_kwargs : 1;
|
244 |
+
|
245 |
+
/// True if this function is to be inserted at the beginning of the overload resolution chain
|
246 |
+
bool prepend : 1;
|
247 |
+
|
248 |
+
/// Number of arguments (including py::args and/or py::kwargs, if present)
|
249 |
+
std::uint16_t nargs;
|
250 |
+
|
251 |
+
/// Number of leading positional arguments, which are terminated by a py::args or py::kwargs
|
252 |
+
/// argument or by a py::kw_only annotation.
|
253 |
+
std::uint16_t nargs_pos = 0;
|
254 |
+
|
255 |
+
/// Number of leading arguments (counted in `nargs`) that are positional-only
|
256 |
+
std::uint16_t nargs_pos_only = 0;
|
257 |
+
|
258 |
+
/// Python method object
|
259 |
+
PyMethodDef *def = nullptr;
|
260 |
+
|
261 |
+
/// Python handle to the parent scope (a class or a module)
|
262 |
+
handle scope;
|
263 |
+
|
264 |
+
/// Python handle to the sibling function representing an overload chain
|
265 |
+
handle sibling;
|
266 |
+
|
267 |
+
/// Pointer to next overload
|
268 |
+
function_record *next = nullptr;
|
269 |
+
};
|
270 |
+
|
271 |
+
/// Special data structure which (temporarily) holds metadata about a bound class
|
272 |
+
struct type_record {
|
273 |
+
PYBIND11_NOINLINE type_record()
|
274 |
+
: multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
|
275 |
+
default_holder(true), module_local(false), is_final(false) {}
|
276 |
+
|
277 |
+
/// Handle to the parent scope
|
278 |
+
handle scope;
|
279 |
+
|
280 |
+
/// Name of the class
|
281 |
+
const char *name = nullptr;
|
282 |
+
|
283 |
+
// Pointer to RTTI type_info data structure
|
284 |
+
const std::type_info *type = nullptr;
|
285 |
+
|
286 |
+
/// How large is the underlying C++ type?
|
287 |
+
size_t type_size = 0;
|
288 |
+
|
289 |
+
/// What is the alignment of the underlying C++ type?
|
290 |
+
size_t type_align = 0;
|
291 |
+
|
292 |
+
/// How large is the type's holder?
|
293 |
+
size_t holder_size = 0;
|
294 |
+
|
295 |
+
/// The global operator new can be overridden with a class-specific variant
|
296 |
+
void *(*operator_new)(size_t) = nullptr;
|
297 |
+
|
298 |
+
/// Function pointer to class_<..>::init_instance
|
299 |
+
void (*init_instance)(instance *, const void *) = nullptr;
|
300 |
+
|
301 |
+
/// Function pointer to class_<..>::dealloc
|
302 |
+
void (*dealloc)(detail::value_and_holder &) = nullptr;
|
303 |
+
|
304 |
+
/// List of base classes of the newly created type
|
305 |
+
list bases;
|
306 |
+
|
307 |
+
/// Optional docstring
|
308 |
+
const char *doc = nullptr;
|
309 |
+
|
310 |
+
/// Custom metaclass (optional)
|
311 |
+
handle metaclass;
|
312 |
+
|
313 |
+
/// Custom type setup.
|
314 |
+
custom_type_setup::callback custom_type_setup_callback;
|
315 |
+
|
316 |
+
/// Multiple inheritance marker
|
317 |
+
bool multiple_inheritance : 1;
|
318 |
+
|
319 |
+
/// Does the class manage a __dict__?
|
320 |
+
bool dynamic_attr : 1;
|
321 |
+
|
322 |
+
/// Does the class implement the buffer protocol?
|
323 |
+
bool buffer_protocol : 1;
|
324 |
+
|
325 |
+
/// Is the default (unique_ptr) holder type used?
|
326 |
+
bool default_holder : 1;
|
327 |
+
|
328 |
+
/// Is the class definition local to the module shared object?
|
329 |
+
bool module_local : 1;
|
330 |
+
|
331 |
+
/// Is the class inheritable from python classes?
|
332 |
+
bool is_final : 1;
|
333 |
+
|
334 |
+
PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {
|
335 |
+
auto *base_info = detail::get_type_info(base, false);
|
336 |
+
if (!base_info) {
|
337 |
+
std::string tname(base.name());
|
338 |
+
detail::clean_type_id(tname);
|
339 |
+
pybind11_fail("generic_type: type \"" + std::string(name)
|
340 |
+
+ "\" referenced unknown base type \"" + tname + "\"");
|
341 |
+
}
|
342 |
+
|
343 |
+
if (default_holder != base_info->default_holder) {
|
344 |
+
std::string tname(base.name());
|
345 |
+
detail::clean_type_id(tname);
|
346 |
+
pybind11_fail("generic_type: type \"" + std::string(name) + "\" "
|
347 |
+
+ (default_holder ? "does not have" : "has")
|
348 |
+
+ " a non-default holder type while its base \"" + tname + "\" "
|
349 |
+
+ (base_info->default_holder ? "does not" : "does"));
|
350 |
+
}
|
351 |
+
|
352 |
+
bases.append((PyObject *) base_info->type);
|
353 |
+
|
354 |
+
#if PY_VERSION_HEX < 0x030B0000
|
355 |
+
dynamic_attr |= base_info->type->tp_dictoffset != 0;
|
356 |
+
#else
|
357 |
+
dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0;
|
358 |
+
#endif
|
359 |
+
|
360 |
+
if (caster) {
|
361 |
+
base_info->implicit_casts.emplace_back(type, caster);
|
362 |
+
}
|
363 |
+
}
|
364 |
+
};
|
365 |
+
|
366 |
+
inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {
|
367 |
+
args.reserve(f.nargs);
|
368 |
+
args_convert.reserve(f.nargs);
|
369 |
+
}
|
370 |
+
|
371 |
+
/// Tag for a new-style `__init__` defined in `detail/init.h`
|
372 |
+
struct is_new_style_constructor {};
|
373 |
+
|
374 |
+
/**
|
375 |
+
* Partial template specializations to process custom attributes provided to
|
376 |
+
* cpp_function_ and class_. These are either used to initialize the respective
|
377 |
+
* fields in the type_record and function_record data structures or executed at
|
378 |
+
* runtime to deal with custom call policies (e.g. keep_alive).
|
379 |
+
*/
|
380 |
+
template <typename T, typename SFINAE = void>
|
381 |
+
struct process_attribute;
|
382 |
+
|
383 |
+
template <typename T>
|
384 |
+
struct process_attribute_default {
|
385 |
+
/// Default implementation: do nothing
|
386 |
+
static void init(const T &, function_record *) {}
|
387 |
+
static void init(const T &, type_record *) {}
|
388 |
+
static void precall(function_call &) {}
|
389 |
+
static void postcall(function_call &, handle) {}
|
390 |
+
};
|
391 |
+
|
392 |
+
/// Process an attribute specifying the function's name
|
393 |
+
template <>
|
394 |
+
struct process_attribute<name> : process_attribute_default<name> {
|
395 |
+
static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
|
396 |
+
};
|
397 |
+
|
398 |
+
/// Process an attribute specifying the function's docstring
|
399 |
+
template <>
|
400 |
+
struct process_attribute<doc> : process_attribute_default<doc> {
|
401 |
+
static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
|
402 |
+
};
|
403 |
+
|
404 |
+
/// Process an attribute specifying the function's docstring (provided as a C-style string)
|
405 |
+
template <>
|
406 |
+
struct process_attribute<const char *> : process_attribute_default<const char *> {
|
407 |
+
static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
|
408 |
+
static void init(const char *d, type_record *r) { r->doc = d; }
|
409 |
+
};
|
410 |
+
template <>
|
411 |
+
struct process_attribute<char *> : process_attribute<const char *> {};
|
412 |
+
|
413 |
+
/// Process an attribute indicating the function's return value policy
|
414 |
+
template <>
|
415 |
+
struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
|
416 |
+
static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
|
417 |
+
};
|
418 |
+
|
419 |
+
/// Process an attribute which indicates that this is an overloaded function associated with a
|
420 |
+
/// given sibling
|
421 |
+
template <>
|
422 |
+
struct process_attribute<sibling> : process_attribute_default<sibling> {
|
423 |
+
static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
|
424 |
+
};
|
425 |
+
|
426 |
+
/// Process an attribute which indicates that this function is a method
|
427 |
+
template <>
|
428 |
+
struct process_attribute<is_method> : process_attribute_default<is_method> {
|
429 |
+
static void init(const is_method &s, function_record *r) {
|
430 |
+
r->is_method = true;
|
431 |
+
r->scope = s.class_;
|
432 |
+
}
|
433 |
+
};
|
434 |
+
|
435 |
+
/// Process an attribute which indicates that this function is a setter
|
436 |
+
template <>
|
437 |
+
struct process_attribute<is_setter> : process_attribute_default<is_setter> {
|
438 |
+
static void init(const is_setter &, function_record *r) { r->is_setter = true; }
|
439 |
+
};
|
440 |
+
|
441 |
+
/// Process an attribute which indicates the parent scope of a method
|
442 |
+
template <>
|
443 |
+
struct process_attribute<scope> : process_attribute_default<scope> {
|
444 |
+
static void init(const scope &s, function_record *r) { r->scope = s.value; }
|
445 |
+
};
|
446 |
+
|
447 |
+
/// Process an attribute which indicates that this function is an operator
|
448 |
+
template <>
|
449 |
+
struct process_attribute<is_operator> : process_attribute_default<is_operator> {
|
450 |
+
static void init(const is_operator &, function_record *r) { r->is_operator = true; }
|
451 |
+
};
|
452 |
+
|
453 |
+
template <>
|
454 |
+
struct process_attribute<is_new_style_constructor>
|
455 |
+
: process_attribute_default<is_new_style_constructor> {
|
456 |
+
static void init(const is_new_style_constructor &, function_record *r) {
|
457 |
+
r->is_new_style_constructor = true;
|
458 |
+
}
|
459 |
+
};
|
460 |
+
|
461 |
+
inline void check_kw_only_arg(const arg &a, function_record *r) {
|
462 |
+
if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) {
|
463 |
+
pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or "
|
464 |
+
"args() argument");
|
465 |
+
}
|
466 |
+
}
|
467 |
+
|
468 |
+
inline void append_self_arg_if_needed(function_record *r) {
|
469 |
+
if (r->is_method && r->args.empty()) {
|
470 |
+
r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false);
|
471 |
+
}
|
472 |
+
}
|
473 |
+
|
474 |
+
/// Process a keyword argument attribute (*without* a default value)
|
475 |
+
template <>
|
476 |
+
struct process_attribute<arg> : process_attribute_default<arg> {
|
477 |
+
static void init(const arg &a, function_record *r) {
|
478 |
+
append_self_arg_if_needed(r);
|
479 |
+
r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
|
480 |
+
|
481 |
+
check_kw_only_arg(a, r);
|
482 |
+
}
|
483 |
+
};
|
484 |
+
|
485 |
+
/// Process a keyword argument attribute (*with* a default value)
|
486 |
+
template <>
|
487 |
+
struct process_attribute<arg_v> : process_attribute_default<arg_v> {
|
488 |
+
static void init(const arg_v &a, function_record *r) {
|
489 |
+
if (r->is_method && r->args.empty()) {
|
490 |
+
r->args.emplace_back(
|
491 |
+
"self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);
|
492 |
+
}
|
493 |
+
|
494 |
+
if (!a.value) {
|
495 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
496 |
+
std::string descr("'");
|
497 |
+
if (a.name) {
|
498 |
+
descr += std::string(a.name) + ": ";
|
499 |
+
}
|
500 |
+
descr += a.type + "'";
|
501 |
+
if (r->is_method) {
|
502 |
+
if (r->name) {
|
503 |
+
descr += " in method '" + (std::string) str(r->scope) + "."
|
504 |
+
+ (std::string) r->name + "'";
|
505 |
+
} else {
|
506 |
+
descr += " in method of '" + (std::string) str(r->scope) + "'";
|
507 |
+
}
|
508 |
+
} else if (r->name) {
|
509 |
+
descr += " in function '" + (std::string) r->name + "'";
|
510 |
+
}
|
511 |
+
pybind11_fail("arg(): could not convert default argument " + descr
|
512 |
+
+ " into a Python object (type not registered yet?)");
|
513 |
+
#else
|
514 |
+
pybind11_fail("arg(): could not convert default argument "
|
515 |
+
"into a Python object (type not registered yet?). "
|
516 |
+
"#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
|
517 |
+
"more information.");
|
518 |
+
#endif
|
519 |
+
}
|
520 |
+
r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
|
521 |
+
|
522 |
+
check_kw_only_arg(a, r);
|
523 |
+
}
|
524 |
+
};
|
525 |
+
|
526 |
+
/// Process a keyword-only-arguments-follow pseudo argument
|
527 |
+
template <>
|
528 |
+
struct process_attribute<kw_only> : process_attribute_default<kw_only> {
|
529 |
+
static void init(const kw_only &, function_record *r) {
|
530 |
+
append_self_arg_if_needed(r);
|
531 |
+
if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
|
532 |
+
pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
|
533 |
+
"argument location (or omit kw_only() entirely)");
|
534 |
+
}
|
535 |
+
r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
|
536 |
+
}
|
537 |
+
};
|
538 |
+
|
539 |
+
/// Process a positional-only-argument maker
|
540 |
+
template <>
|
541 |
+
struct process_attribute<pos_only> : process_attribute_default<pos_only> {
|
542 |
+
static void init(const pos_only &, function_record *r) {
|
543 |
+
append_self_arg_if_needed(r);
|
544 |
+
r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
|
545 |
+
if (r->nargs_pos_only > r->nargs_pos) {
|
546 |
+
pybind11_fail("pos_only(): cannot follow a py::args() argument");
|
547 |
+
}
|
548 |
+
// It also can't follow a kw_only, but a static_assert in pybind11.h checks that
|
549 |
+
}
|
550 |
+
};
|
551 |
+
|
552 |
+
/// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
|
553 |
+
/// that)
|
554 |
+
template <typename T>
|
555 |
+
struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
|
556 |
+
: process_attribute_default<handle> {
|
557 |
+
static void init(const handle &h, type_record *r) { r->bases.append(h); }
|
558 |
+
};
|
559 |
+
|
560 |
+
/// Process a parent class attribute (deprecated, does not support multiple inheritance)
|
561 |
+
template <typename T>
|
562 |
+
struct process_attribute<base<T>> : process_attribute_default<base<T>> {
|
563 |
+
static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
|
564 |
+
};
|
565 |
+
|
566 |
+
/// Process a multiple inheritance attribute
|
567 |
+
template <>
|
568 |
+
struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
|
569 |
+
static void init(const multiple_inheritance &, type_record *r) {
|
570 |
+
r->multiple_inheritance = true;
|
571 |
+
}
|
572 |
+
};
|
573 |
+
|
574 |
+
template <>
|
575 |
+
struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
|
576 |
+
static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
|
577 |
+
};
|
578 |
+
|
579 |
+
template <>
|
580 |
+
struct process_attribute<custom_type_setup> {
|
581 |
+
static void init(const custom_type_setup &value, type_record *r) {
|
582 |
+
r->custom_type_setup_callback = value.value;
|
583 |
+
}
|
584 |
+
};
|
585 |
+
|
586 |
+
template <>
|
587 |
+
struct process_attribute<is_final> : process_attribute_default<is_final> {
|
588 |
+
static void init(const is_final &, type_record *r) { r->is_final = true; }
|
589 |
+
};
|
590 |
+
|
591 |
+
template <>
|
592 |
+
struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
|
593 |
+
static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
|
594 |
+
};
|
595 |
+
|
596 |
+
template <>
|
597 |
+
struct process_attribute<metaclass> : process_attribute_default<metaclass> {
|
598 |
+
static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
|
599 |
+
};
|
600 |
+
|
601 |
+
template <>
|
602 |
+
struct process_attribute<module_local> : process_attribute_default<module_local> {
|
603 |
+
static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
|
604 |
+
};
|
605 |
+
|
606 |
+
/// Process a 'prepend' attribute, putting this at the beginning of the overload chain
|
607 |
+
template <>
|
608 |
+
struct process_attribute<prepend> : process_attribute_default<prepend> {
|
609 |
+
static void init(const prepend &, function_record *r) { r->prepend = true; }
|
610 |
+
};
|
611 |
+
|
612 |
+
/// Process an 'arithmetic' attribute for enums (does nothing here)
|
613 |
+
template <>
|
614 |
+
struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
|
615 |
+
|
616 |
+
template <typename... Ts>
|
617 |
+
struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
|
618 |
+
|
619 |
+
/**
|
620 |
+
* Process a keep_alive call policy -- invokes keep_alive_impl during the
|
621 |
+
* pre-call handler if both Nurse, Patient != 0 and use the post-call handler
|
622 |
+
* otherwise
|
623 |
+
*/
|
624 |
+
template <size_t Nurse, size_t Patient>
|
625 |
+
struct process_attribute<keep_alive<Nurse, Patient>>
|
626 |
+
: public process_attribute_default<keep_alive<Nurse, Patient>> {
|
627 |
+
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
|
628 |
+
static void precall(function_call &call) {
|
629 |
+
keep_alive_impl(Nurse, Patient, call, handle());
|
630 |
+
}
|
631 |
+
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
|
632 |
+
static void postcall(function_call &, handle) {}
|
633 |
+
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
|
634 |
+
static void precall(function_call &) {}
|
635 |
+
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
|
636 |
+
static void postcall(function_call &call, handle ret) {
|
637 |
+
keep_alive_impl(Nurse, Patient, call, ret);
|
638 |
+
}
|
639 |
+
};
|
640 |
+
|
641 |
+
/// Recursively iterate over variadic template arguments
|
642 |
+
template <typename... Args>
|
643 |
+
struct process_attributes {
|
644 |
+
static void init(const Args &...args, function_record *r) {
|
645 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
|
646 |
+
PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
|
647 |
+
using expander = int[];
|
648 |
+
(void) expander{
|
649 |
+
0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
|
650 |
+
}
|
651 |
+
static void init(const Args &...args, type_record *r) {
|
652 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
|
653 |
+
PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
|
654 |
+
using expander = int[];
|
655 |
+
(void) expander{0,
|
656 |
+
(process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
|
657 |
+
}
|
658 |
+
static void precall(function_call &call) {
|
659 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
|
660 |
+
using expander = int[];
|
661 |
+
(void) expander{0,
|
662 |
+
(process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
|
663 |
+
}
|
664 |
+
static void postcall(function_call &call, handle fn_ret) {
|
665 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
|
666 |
+
PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
|
667 |
+
using expander = int[];
|
668 |
+
(void) expander{
|
669 |
+
0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
|
670 |
+
}
|
671 |
+
};
|
672 |
+
|
673 |
+
template <typename T>
|
674 |
+
using is_call_guard = is_instantiation<call_guard, T>;
|
675 |
+
|
676 |
+
/// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
|
677 |
+
template <typename... Extra>
|
678 |
+
using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
|
679 |
+
|
680 |
+
/// Check the number of named arguments at compile time
|
681 |
+
template <typename... Extra,
|
682 |
+
size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
|
683 |
+
size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
|
684 |
+
constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
|
685 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
|
686 |
+
return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
|
687 |
+
}
|
688 |
+
|
689 |
+
PYBIND11_NAMESPACE_END(detail)
|
690 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h
ADDED
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/buffer_info.h: Python buffer object interface
|
3 |
+
|
4 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "detail/common.h"
|
13 |
+
|
14 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
15 |
+
|
16 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
17 |
+
|
18 |
+
// Default, C-style strides
|
19 |
+
inline std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
|
20 |
+
auto ndim = shape.size();
|
21 |
+
std::vector<ssize_t> strides(ndim, itemsize);
|
22 |
+
if (ndim > 0) {
|
23 |
+
for (size_t i = ndim - 1; i > 0; --i) {
|
24 |
+
strides[i - 1] = strides[i] * shape[i];
|
25 |
+
}
|
26 |
+
}
|
27 |
+
return strides;
|
28 |
+
}
|
29 |
+
|
30 |
+
// F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
|
31 |
+
inline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
|
32 |
+
auto ndim = shape.size();
|
33 |
+
std::vector<ssize_t> strides(ndim, itemsize);
|
34 |
+
for (size_t i = 1; i < ndim; ++i) {
|
35 |
+
strides[i] = strides[i - 1] * shape[i - 1];
|
36 |
+
}
|
37 |
+
return strides;
|
38 |
+
}
|
39 |
+
|
40 |
+
template <typename T, typename SFINAE = void>
|
41 |
+
struct compare_buffer_info;
|
42 |
+
|
43 |
+
PYBIND11_NAMESPACE_END(detail)
|
44 |
+
|
45 |
+
/// Information record describing a Python buffer object
|
46 |
+
struct buffer_info {
|
47 |
+
void *ptr = nullptr; // Pointer to the underlying storage
|
48 |
+
ssize_t itemsize = 0; // Size of individual items in bytes
|
49 |
+
ssize_t size = 0; // Total number of entries
|
50 |
+
std::string format; // For homogeneous buffers, this should be set to
|
51 |
+
// format_descriptor<T>::format()
|
52 |
+
ssize_t ndim = 0; // Number of dimensions
|
53 |
+
std::vector<ssize_t> shape; // Shape of the tensor (1 entry per dimension)
|
54 |
+
std::vector<ssize_t> strides; // Number of bytes between adjacent entries
|
55 |
+
// (for each per dimension)
|
56 |
+
bool readonly = false; // flag to indicate if the underlying storage may be written to
|
57 |
+
|
58 |
+
buffer_info() = default;
|
59 |
+
|
60 |
+
buffer_info(void *ptr,
|
61 |
+
ssize_t itemsize,
|
62 |
+
const std::string &format,
|
63 |
+
ssize_t ndim,
|
64 |
+
detail::any_container<ssize_t> shape_in,
|
65 |
+
detail::any_container<ssize_t> strides_in,
|
66 |
+
bool readonly = false)
|
67 |
+
: ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),
|
68 |
+
shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) {
|
69 |
+
if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) {
|
70 |
+
pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length");
|
71 |
+
}
|
72 |
+
for (size_t i = 0; i < (size_t) ndim; ++i) {
|
73 |
+
size *= shape[i];
|
74 |
+
}
|
75 |
+
}
|
76 |
+
|
77 |
+
template <typename T>
|
78 |
+
buffer_info(T *ptr,
|
79 |
+
detail::any_container<ssize_t> shape_in,
|
80 |
+
detail::any_container<ssize_t> strides_in,
|
81 |
+
bool readonly = false)
|
82 |
+
: buffer_info(private_ctr_tag(),
|
83 |
+
ptr,
|
84 |
+
sizeof(T),
|
85 |
+
format_descriptor<T>::format(),
|
86 |
+
static_cast<ssize_t>(shape_in->size()),
|
87 |
+
std::move(shape_in),
|
88 |
+
std::move(strides_in),
|
89 |
+
readonly) {}
|
90 |
+
|
91 |
+
buffer_info(void *ptr,
|
92 |
+
ssize_t itemsize,
|
93 |
+
const std::string &format,
|
94 |
+
ssize_t size,
|
95 |
+
bool readonly = false)
|
96 |
+
: buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {}
|
97 |
+
|
98 |
+
template <typename T>
|
99 |
+
buffer_info(T *ptr, ssize_t size, bool readonly = false)
|
100 |
+
: buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) {}
|
101 |
+
|
102 |
+
template <typename T>
|
103 |
+
buffer_info(const T *ptr, ssize_t size, bool readonly = true)
|
104 |
+
: buffer_info(
|
105 |
+
const_cast<T *>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) {}
|
106 |
+
|
107 |
+
explicit buffer_info(Py_buffer *view, bool ownview = true)
|
108 |
+
: buffer_info(
|
109 |
+
view->buf,
|
110 |
+
view->itemsize,
|
111 |
+
view->format,
|
112 |
+
view->ndim,
|
113 |
+
{view->shape, view->shape + view->ndim},
|
114 |
+
/* Though buffer::request() requests PyBUF_STRIDES, ctypes objects
|
115 |
+
* ignore this flag and return a view with NULL strides.
|
116 |
+
* When strides are NULL, build them manually. */
|
117 |
+
view->strides
|
118 |
+
? std::vector<ssize_t>(view->strides, view->strides + view->ndim)
|
119 |
+
: detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize),
|
120 |
+
(view->readonly != 0)) {
|
121 |
+
// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
|
122 |
+
this->m_view = view;
|
123 |
+
// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
|
124 |
+
this->ownview = ownview;
|
125 |
+
}
|
126 |
+
|
127 |
+
buffer_info(const buffer_info &) = delete;
|
128 |
+
buffer_info &operator=(const buffer_info &) = delete;
|
129 |
+
|
130 |
+
buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); }
|
131 |
+
|
132 |
+
buffer_info &operator=(buffer_info &&rhs) noexcept {
|
133 |
+
ptr = rhs.ptr;
|
134 |
+
itemsize = rhs.itemsize;
|
135 |
+
size = rhs.size;
|
136 |
+
format = std::move(rhs.format);
|
137 |
+
ndim = rhs.ndim;
|
138 |
+
shape = std::move(rhs.shape);
|
139 |
+
strides = std::move(rhs.strides);
|
140 |
+
std::swap(m_view, rhs.m_view);
|
141 |
+
std::swap(ownview, rhs.ownview);
|
142 |
+
readonly = rhs.readonly;
|
143 |
+
return *this;
|
144 |
+
}
|
145 |
+
|
146 |
+
~buffer_info() {
|
147 |
+
if (m_view && ownview) {
|
148 |
+
PyBuffer_Release(m_view);
|
149 |
+
delete m_view;
|
150 |
+
}
|
151 |
+
}
|
152 |
+
|
153 |
+
Py_buffer *view() const { return m_view; }
|
154 |
+
Py_buffer *&view() { return m_view; }
|
155 |
+
|
156 |
+
/* True if the buffer item type is equivalent to `T`. */
|
157 |
+
// To define "equivalent" by example:
|
158 |
+
// `buffer_info::item_type_is_equivalent_to<int>(b)` and
|
159 |
+
// `buffer_info::item_type_is_equivalent_to<long>(b)` may both be true
|
160 |
+
// on some platforms, but `int` and `unsigned` will never be equivalent.
|
161 |
+
// For the ground truth, please inspect `detail::compare_buffer_info<>`.
|
162 |
+
template <typename T>
|
163 |
+
bool item_type_is_equivalent_to() const {
|
164 |
+
return detail::compare_buffer_info<T>::compare(*this);
|
165 |
+
}
|
166 |
+
|
167 |
+
private:
|
168 |
+
struct private_ctr_tag {};
|
169 |
+
|
170 |
+
buffer_info(private_ctr_tag,
|
171 |
+
void *ptr,
|
172 |
+
ssize_t itemsize,
|
173 |
+
const std::string &format,
|
174 |
+
ssize_t ndim,
|
175 |
+
detail::any_container<ssize_t> &&shape_in,
|
176 |
+
detail::any_container<ssize_t> &&strides_in,
|
177 |
+
bool readonly)
|
178 |
+
: buffer_info(
|
179 |
+
ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {}
|
180 |
+
|
181 |
+
Py_buffer *m_view = nullptr;
|
182 |
+
bool ownview = false;
|
183 |
+
};
|
184 |
+
|
185 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
186 |
+
|
187 |
+
template <typename T, typename SFINAE>
|
188 |
+
struct compare_buffer_info {
|
189 |
+
static bool compare(const buffer_info &b) {
|
190 |
+
// NOLINTNEXTLINE(bugprone-sizeof-expression) Needed for `PyObject *`
|
191 |
+
return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T);
|
192 |
+
}
|
193 |
+
};
|
194 |
+
|
195 |
+
template <typename T>
|
196 |
+
struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
|
197 |
+
static bool compare(const buffer_info &b) {
|
198 |
+
return (size_t) b.itemsize == sizeof(T)
|
199 |
+
&& (b.format == format_descriptor<T>::value
|
200 |
+
|| ((sizeof(T) == sizeof(long))
|
201 |
+
&& b.format == (std::is_unsigned<T>::value ? "L" : "l"))
|
202 |
+
|| ((sizeof(T) == sizeof(size_t))
|
203 |
+
&& b.format == (std::is_unsigned<T>::value ? "N" : "n")));
|
204 |
+
}
|
205 |
+
};
|
206 |
+
|
207 |
+
PYBIND11_NAMESPACE_END(detail)
|
208 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h
ADDED
@@ -0,0 +1,1837 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/cast.h: Partial template specializations to cast between
|
3 |
+
C++ and Python types
|
4 |
+
|
5 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
6 |
+
|
7 |
+
All rights reserved. Use of this source code is governed by a
|
8 |
+
BSD-style license that can be found in the LICENSE file.
|
9 |
+
*/
|
10 |
+
|
11 |
+
#pragma once
|
12 |
+
|
13 |
+
#include "detail/common.h"
|
14 |
+
#include "detail/descr.h"
|
15 |
+
#include "detail/type_caster_base.h"
|
16 |
+
#include "detail/typeid.h"
|
17 |
+
#include "pytypes.h"
|
18 |
+
|
19 |
+
#include <array>
|
20 |
+
#include <cstring>
|
21 |
+
#include <functional>
|
22 |
+
#include <iosfwd>
|
23 |
+
#include <iterator>
|
24 |
+
#include <memory>
|
25 |
+
#include <string>
|
26 |
+
#include <tuple>
|
27 |
+
#include <type_traits>
|
28 |
+
#include <utility>
|
29 |
+
#include <vector>
|
30 |
+
|
31 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
32 |
+
|
33 |
+
PYBIND11_WARNING_DISABLE_MSVC(4127)
|
34 |
+
|
35 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
36 |
+
|
37 |
+
template <typename type, typename SFINAE = void>
|
38 |
+
class type_caster : public type_caster_base<type> {};
|
39 |
+
template <typename type>
|
40 |
+
using make_caster = type_caster<intrinsic_t<type>>;
|
41 |
+
|
42 |
+
// Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
|
43 |
+
template <typename T>
|
44 |
+
typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
|
45 |
+
using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893
|
46 |
+
return caster.operator result_t();
|
47 |
+
}
|
48 |
+
template <typename T>
|
49 |
+
typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
|
50 |
+
cast_op(make_caster<T> &&caster) {
|
51 |
+
using result_t = typename make_caster<T>::template cast_op_type<
|
52 |
+
typename std::add_rvalue_reference<T>::type>; // See PR #4893
|
53 |
+
return std::move(caster).operator result_t();
|
54 |
+
}
|
55 |
+
|
56 |
+
template <typename type>
|
57 |
+
class type_caster<std::reference_wrapper<type>> {
|
58 |
+
private:
|
59 |
+
using caster_t = make_caster<type>;
|
60 |
+
caster_t subcaster;
|
61 |
+
using reference_t = type &;
|
62 |
+
using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
|
63 |
+
|
64 |
+
static_assert(
|
65 |
+
std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
|
66 |
+
|| std::is_same<reference_t, subcaster_cast_op_type>::value,
|
67 |
+
"std::reference_wrapper<T> caster requires T to have a caster with an "
|
68 |
+
"`operator T &()` or `operator const T &()`");
|
69 |
+
|
70 |
+
public:
|
71 |
+
bool load(handle src, bool convert) { return subcaster.load(src, convert); }
|
72 |
+
static constexpr auto name = caster_t::name;
|
73 |
+
static handle
|
74 |
+
cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
|
75 |
+
// It is definitely wrong to take ownership of this pointer, so mask that rvp
|
76 |
+
if (policy == return_value_policy::take_ownership
|
77 |
+
|| policy == return_value_policy::automatic) {
|
78 |
+
policy = return_value_policy::automatic_reference;
|
79 |
+
}
|
80 |
+
return caster_t::cast(&src.get(), policy, parent);
|
81 |
+
}
|
82 |
+
template <typename T>
|
83 |
+
using cast_op_type = std::reference_wrapper<type>;
|
84 |
+
explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
|
85 |
+
};
|
86 |
+
|
87 |
+
#define PYBIND11_TYPE_CASTER(type, py_name) \
|
88 |
+
protected: \
|
89 |
+
type value; \
|
90 |
+
\
|
91 |
+
public: \
|
92 |
+
static constexpr auto name = py_name; \
|
93 |
+
template <typename T_, \
|
94 |
+
::pybind11::detail::enable_if_t< \
|
95 |
+
std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
|
96 |
+
int> \
|
97 |
+
= 0> \
|
98 |
+
static ::pybind11::handle cast( \
|
99 |
+
T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
|
100 |
+
if (!src) \
|
101 |
+
return ::pybind11::none().release(); \
|
102 |
+
if (policy == ::pybind11::return_value_policy::take_ownership) { \
|
103 |
+
auto h = cast(std::move(*src), policy, parent); \
|
104 |
+
delete src; \
|
105 |
+
return h; \
|
106 |
+
} \
|
107 |
+
return cast(*src, policy, parent); \
|
108 |
+
} \
|
109 |
+
operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
|
110 |
+
operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
|
111 |
+
operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
|
112 |
+
template <typename T_> \
|
113 |
+
using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
|
114 |
+
|
115 |
+
template <typename CharT>
|
116 |
+
using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
|
117 |
+
#if defined(PYBIND11_HAS_U8STRING)
|
118 |
+
std::is_same<CharT, char8_t>, /* std::u8string */
|
119 |
+
#endif
|
120 |
+
std::is_same<CharT, char16_t>, /* std::u16string */
|
121 |
+
std::is_same<CharT, char32_t>, /* std::u32string */
|
122 |
+
std::is_same<CharT, wchar_t> /* std::wstring */
|
123 |
+
>;
|
124 |
+
|
125 |
+
template <typename T>
|
126 |
+
struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
|
127 |
+
using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
|
128 |
+
using _py_type_1 = conditional_t<std::is_signed<T>::value,
|
129 |
+
_py_type_0,
|
130 |
+
typename std::make_unsigned<_py_type_0>::type>;
|
131 |
+
using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
|
132 |
+
|
133 |
+
public:
|
134 |
+
bool load(handle src, bool convert) {
|
135 |
+
py_type py_value;
|
136 |
+
|
137 |
+
if (!src) {
|
138 |
+
return false;
|
139 |
+
}
|
140 |
+
|
141 |
+
#if !defined(PYPY_VERSION)
|
142 |
+
auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
|
143 |
+
#else
|
144 |
+
// In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
|
145 |
+
// while CPython only considers the existence of `nb_index`/`__index__`.
|
146 |
+
auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
|
147 |
+
#endif
|
148 |
+
|
149 |
+
if (std::is_floating_point<T>::value) {
|
150 |
+
if (convert || PyFloat_Check(src.ptr())) {
|
151 |
+
py_value = (py_type) PyFloat_AsDouble(src.ptr());
|
152 |
+
} else {
|
153 |
+
return false;
|
154 |
+
}
|
155 |
+
} else if (PyFloat_Check(src.ptr())
|
156 |
+
|| (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
|
157 |
+
return false;
|
158 |
+
} else {
|
159 |
+
handle src_or_index = src;
|
160 |
+
// PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
|
161 |
+
#if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
|
162 |
+
object index;
|
163 |
+
if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
|
164 |
+
index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
|
165 |
+
if (!index) {
|
166 |
+
PyErr_Clear();
|
167 |
+
if (!convert)
|
168 |
+
return false;
|
169 |
+
} else {
|
170 |
+
src_or_index = index;
|
171 |
+
}
|
172 |
+
}
|
173 |
+
#endif
|
174 |
+
if (std::is_unsigned<py_type>::value) {
|
175 |
+
py_value = as_unsigned<py_type>(src_or_index.ptr());
|
176 |
+
} else { // signed integer:
|
177 |
+
py_value = sizeof(T) <= sizeof(long)
|
178 |
+
? (py_type) PyLong_AsLong(src_or_index.ptr())
|
179 |
+
: (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
|
180 |
+
}
|
181 |
+
}
|
182 |
+
|
183 |
+
// Python API reported an error
|
184 |
+
bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
|
185 |
+
|
186 |
+
// Check to see if the conversion is valid (integers should match exactly)
|
187 |
+
// Signed/unsigned checks happen elsewhere
|
188 |
+
if (py_err
|
189 |
+
|| (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
|
190 |
+
&& py_value != (py_type) (T) py_value)) {
|
191 |
+
PyErr_Clear();
|
192 |
+
if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
|
193 |
+
auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
|
194 |
+
? PyNumber_Float(src.ptr())
|
195 |
+
: PyNumber_Long(src.ptr()));
|
196 |
+
PyErr_Clear();
|
197 |
+
return load(tmp, false);
|
198 |
+
}
|
199 |
+
return false;
|
200 |
+
}
|
201 |
+
|
202 |
+
value = (T) py_value;
|
203 |
+
return true;
|
204 |
+
}
|
205 |
+
|
206 |
+
template <typename U = T>
|
207 |
+
static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
|
208 |
+
cast(U src, return_value_policy /* policy */, handle /* parent */) {
|
209 |
+
return PyFloat_FromDouble((double) src);
|
210 |
+
}
|
211 |
+
|
212 |
+
template <typename U = T>
|
213 |
+
static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
|
214 |
+
&& (sizeof(U) <= sizeof(long)),
|
215 |
+
handle>::type
|
216 |
+
cast(U src, return_value_policy /* policy */, handle /* parent */) {
|
217 |
+
return PYBIND11_LONG_FROM_SIGNED((long) src);
|
218 |
+
}
|
219 |
+
|
220 |
+
template <typename U = T>
|
221 |
+
static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
|
222 |
+
&& (sizeof(U) <= sizeof(unsigned long)),
|
223 |
+
handle>::type
|
224 |
+
cast(U src, return_value_policy /* policy */, handle /* parent */) {
|
225 |
+
return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
|
226 |
+
}
|
227 |
+
|
228 |
+
template <typename U = T>
|
229 |
+
static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
|
230 |
+
&& (sizeof(U) > sizeof(long)),
|
231 |
+
handle>::type
|
232 |
+
cast(U src, return_value_policy /* policy */, handle /* parent */) {
|
233 |
+
return PyLong_FromLongLong((long long) src);
|
234 |
+
}
|
235 |
+
|
236 |
+
template <typename U = T>
|
237 |
+
static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
|
238 |
+
&& (sizeof(U) > sizeof(unsigned long)),
|
239 |
+
handle>::type
|
240 |
+
cast(U src, return_value_policy /* policy */, handle /* parent */) {
|
241 |
+
return PyLong_FromUnsignedLongLong((unsigned long long) src);
|
242 |
+
}
|
243 |
+
|
244 |
+
PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
|
245 |
+
};
|
246 |
+
|
247 |
+
template <typename T>
|
248 |
+
struct void_caster {
|
249 |
+
public:
|
250 |
+
bool load(handle src, bool) {
|
251 |
+
if (src && src.is_none()) {
|
252 |
+
return true;
|
253 |
+
}
|
254 |
+
return false;
|
255 |
+
}
|
256 |
+
static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
|
257 |
+
return none().release();
|
258 |
+
}
|
259 |
+
PYBIND11_TYPE_CASTER(T, const_name("None"));
|
260 |
+
};
|
261 |
+
|
262 |
+
template <>
|
263 |
+
class type_caster<void_type> : public void_caster<void_type> {};
|
264 |
+
|
265 |
+
template <>
|
266 |
+
class type_caster<void> : public type_caster<void_type> {
|
267 |
+
public:
|
268 |
+
using type_caster<void_type>::cast;
|
269 |
+
|
270 |
+
bool load(handle h, bool) {
|
271 |
+
if (!h) {
|
272 |
+
return false;
|
273 |
+
}
|
274 |
+
if (h.is_none()) {
|
275 |
+
value = nullptr;
|
276 |
+
return true;
|
277 |
+
}
|
278 |
+
|
279 |
+
/* Check if this is a capsule */
|
280 |
+
if (isinstance<capsule>(h)) {
|
281 |
+
value = reinterpret_borrow<capsule>(h);
|
282 |
+
return true;
|
283 |
+
}
|
284 |
+
|
285 |
+
/* Check if this is a C++ type */
|
286 |
+
const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
|
287 |
+
if (bases.size() == 1) { // Only allowing loading from a single-value type
|
288 |
+
value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
|
289 |
+
return true;
|
290 |
+
}
|
291 |
+
|
292 |
+
/* Fail */
|
293 |
+
return false;
|
294 |
+
}
|
295 |
+
|
296 |
+
static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
|
297 |
+
if (ptr) {
|
298 |
+
return capsule(ptr).release();
|
299 |
+
}
|
300 |
+
return none().release();
|
301 |
+
}
|
302 |
+
|
303 |
+
template <typename T>
|
304 |
+
using cast_op_type = void *&;
|
305 |
+
explicit operator void *&() { return value; }
|
306 |
+
static constexpr auto name = const_name("capsule");
|
307 |
+
|
308 |
+
private:
|
309 |
+
void *value = nullptr;
|
310 |
+
};
|
311 |
+
|
312 |
+
template <>
|
313 |
+
class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
|
314 |
+
|
315 |
+
template <>
|
316 |
+
class type_caster<bool> {
|
317 |
+
public:
|
318 |
+
bool load(handle src, bool convert) {
|
319 |
+
if (!src) {
|
320 |
+
return false;
|
321 |
+
}
|
322 |
+
if (src.ptr() == Py_True) {
|
323 |
+
value = true;
|
324 |
+
return true;
|
325 |
+
}
|
326 |
+
if (src.ptr() == Py_False) {
|
327 |
+
value = false;
|
328 |
+
return true;
|
329 |
+
}
|
330 |
+
if (convert || is_numpy_bool(src)) {
|
331 |
+
// (allow non-implicit conversion for numpy booleans), use strncmp
|
332 |
+
// since NumPy 1.x had an additional trailing underscore.
|
333 |
+
|
334 |
+
Py_ssize_t res = -1;
|
335 |
+
if (src.is_none()) {
|
336 |
+
res = 0; // None is implicitly converted to False
|
337 |
+
}
|
338 |
+
#if defined(PYPY_VERSION)
|
339 |
+
// On PyPy, check that "__bool__" attr exists
|
340 |
+
else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
|
341 |
+
res = PyObject_IsTrue(src.ptr());
|
342 |
+
}
|
343 |
+
#else
|
344 |
+
// Alternate approach for CPython: this does the same as the above, but optimized
|
345 |
+
// using the CPython API so as to avoid an unneeded attribute lookup.
|
346 |
+
else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
|
347 |
+
if (PYBIND11_NB_BOOL(tp_as_number)) {
|
348 |
+
res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
|
349 |
+
}
|
350 |
+
}
|
351 |
+
#endif
|
352 |
+
if (res == 0 || res == 1) {
|
353 |
+
value = (res != 0);
|
354 |
+
return true;
|
355 |
+
}
|
356 |
+
PyErr_Clear();
|
357 |
+
}
|
358 |
+
return false;
|
359 |
+
}
|
360 |
+
static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
|
361 |
+
return handle(src ? Py_True : Py_False).inc_ref();
|
362 |
+
}
|
363 |
+
PYBIND11_TYPE_CASTER(bool, const_name("bool"));
|
364 |
+
|
365 |
+
private:
|
366 |
+
// Test if an object is a NumPy boolean (without fetching the type).
|
367 |
+
static inline bool is_numpy_bool(handle object) {
|
368 |
+
const char *type_name = Py_TYPE(object.ptr())->tp_name;
|
369 |
+
// Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support
|
370 |
+
return std::strcmp("numpy.bool", type_name) == 0
|
371 |
+
|| std::strcmp("numpy.bool_", type_name) == 0;
|
372 |
+
}
|
373 |
+
};
|
374 |
+
|
375 |
+
// Helper class for UTF-{8,16,32} C++ stl strings:
|
376 |
+
template <typename StringType, bool IsView = false>
|
377 |
+
struct string_caster {
|
378 |
+
using CharT = typename StringType::value_type;
|
379 |
+
|
380 |
+
// Simplify life by being able to assume standard char sizes (the standard only guarantees
|
381 |
+
// minimums, but Python requires exact sizes)
|
382 |
+
static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
|
383 |
+
"Unsupported char size != 1");
|
384 |
+
#if defined(PYBIND11_HAS_U8STRING)
|
385 |
+
static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
|
386 |
+
"Unsupported char8_t size != 1");
|
387 |
+
#endif
|
388 |
+
static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
|
389 |
+
"Unsupported char16_t size != 2");
|
390 |
+
static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
|
391 |
+
"Unsupported char32_t size != 4");
|
392 |
+
// wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
|
393 |
+
static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
|
394 |
+
"Unsupported wchar_t size != 2/4");
|
395 |
+
static constexpr size_t UTF_N = 8 * sizeof(CharT);
|
396 |
+
|
397 |
+
bool load(handle src, bool) {
|
398 |
+
handle load_src = src;
|
399 |
+
if (!src) {
|
400 |
+
return false;
|
401 |
+
}
|
402 |
+
if (!PyUnicode_Check(load_src.ptr())) {
|
403 |
+
return load_raw(load_src);
|
404 |
+
}
|
405 |
+
|
406 |
+
// For UTF-8 we avoid the need for a temporary `bytes` object by using
|
407 |
+
// `PyUnicode_AsUTF8AndSize`.
|
408 |
+
if (UTF_N == 8) {
|
409 |
+
Py_ssize_t size = -1;
|
410 |
+
const auto *buffer
|
411 |
+
= reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
|
412 |
+
if (!buffer) {
|
413 |
+
PyErr_Clear();
|
414 |
+
return false;
|
415 |
+
}
|
416 |
+
value = StringType(buffer, static_cast<size_t>(size));
|
417 |
+
return true;
|
418 |
+
}
|
419 |
+
|
420 |
+
auto utfNbytes
|
421 |
+
= reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
|
422 |
+
UTF_N == 8 ? "utf-8"
|
423 |
+
: UTF_N == 16 ? "utf-16"
|
424 |
+
: "utf-32",
|
425 |
+
nullptr));
|
426 |
+
if (!utfNbytes) {
|
427 |
+
PyErr_Clear();
|
428 |
+
return false;
|
429 |
+
}
|
430 |
+
|
431 |
+
const auto *buffer
|
432 |
+
= reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
|
433 |
+
size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
|
434 |
+
// Skip BOM for UTF-16/32
|
435 |
+
if (UTF_N > 8) {
|
436 |
+
buffer++;
|
437 |
+
length--;
|
438 |
+
}
|
439 |
+
value = StringType(buffer, length);
|
440 |
+
|
441 |
+
// If we're loading a string_view we need to keep the encoded Python object alive:
|
442 |
+
if (IsView) {
|
443 |
+
loader_life_support::add_patient(utfNbytes);
|
444 |
+
}
|
445 |
+
|
446 |
+
return true;
|
447 |
+
}
|
448 |
+
|
449 |
+
static handle
|
450 |
+
cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
|
451 |
+
const char *buffer = reinterpret_cast<const char *>(src.data());
|
452 |
+
auto nbytes = ssize_t(src.size() * sizeof(CharT));
|
453 |
+
handle s = decode_utfN(buffer, nbytes);
|
454 |
+
if (!s) {
|
455 |
+
throw error_already_set();
|
456 |
+
}
|
457 |
+
return s;
|
458 |
+
}
|
459 |
+
|
460 |
+
PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
|
461 |
+
|
462 |
+
private:
|
463 |
+
static handle decode_utfN(const char *buffer, ssize_t nbytes) {
|
464 |
+
#if !defined(PYPY_VERSION)
|
465 |
+
return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
|
466 |
+
: UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
|
467 |
+
: PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
|
468 |
+
#else
|
469 |
+
// PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
|
470 |
+
// well), so bypass the whole thing by just passing the encoding as a string value, which
|
471 |
+
// works properly:
|
472 |
+
return PyUnicode_Decode(buffer,
|
473 |
+
nbytes,
|
474 |
+
UTF_N == 8 ? "utf-8"
|
475 |
+
: UTF_N == 16 ? "utf-16"
|
476 |
+
: "utf-32",
|
477 |
+
nullptr);
|
478 |
+
#endif
|
479 |
+
}
|
480 |
+
|
481 |
+
// When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
|
482 |
+
// without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
|
483 |
+
// which supports loading a unicode from a str, doesn't take this path.
|
484 |
+
template <typename C = CharT>
|
485 |
+
bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
|
486 |
+
if (PYBIND11_BYTES_CHECK(src.ptr())) {
|
487 |
+
// We were passed raw bytes; accept it into a std::string or char*
|
488 |
+
// without any encoding attempt.
|
489 |
+
const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
|
490 |
+
if (!bytes) {
|
491 |
+
pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
|
492 |
+
}
|
493 |
+
value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
|
494 |
+
return true;
|
495 |
+
}
|
496 |
+
if (PyByteArray_Check(src.ptr())) {
|
497 |
+
// We were passed a bytearray; accept it into a std::string or char*
|
498 |
+
// without any encoding attempt.
|
499 |
+
const char *bytearray = PyByteArray_AsString(src.ptr());
|
500 |
+
if (!bytearray) {
|
501 |
+
pybind11_fail("Unexpected PyByteArray_AsString() failure.");
|
502 |
+
}
|
503 |
+
value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
|
504 |
+
return true;
|
505 |
+
}
|
506 |
+
|
507 |
+
return false;
|
508 |
+
}
|
509 |
+
|
510 |
+
template <typename C = CharT>
|
511 |
+
bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
|
512 |
+
return false;
|
513 |
+
}
|
514 |
+
};
|
515 |
+
|
516 |
+
template <typename CharT, class Traits, class Allocator>
|
517 |
+
struct type_caster<std::basic_string<CharT, Traits, Allocator>,
|
518 |
+
enable_if_t<is_std_char_type<CharT>::value>>
|
519 |
+
: string_caster<std::basic_string<CharT, Traits, Allocator>> {};
|
520 |
+
|
521 |
+
#ifdef PYBIND11_HAS_STRING_VIEW
|
522 |
+
template <typename CharT, class Traits>
|
523 |
+
struct type_caster<std::basic_string_view<CharT, Traits>,
|
524 |
+
enable_if_t<is_std_char_type<CharT>::value>>
|
525 |
+
: string_caster<std::basic_string_view<CharT, Traits>, true> {};
|
526 |
+
#endif
|
527 |
+
|
528 |
+
// Type caster for C-style strings. We basically use a std::string type caster, but also add the
|
529 |
+
// ability to use None as a nullptr char* (which the string caster doesn't allow).
|
530 |
+
template <typename CharT>
|
531 |
+
struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
|
532 |
+
using StringType = std::basic_string<CharT>;
|
533 |
+
using StringCaster = make_caster<StringType>;
|
534 |
+
StringCaster str_caster;
|
535 |
+
bool none = false;
|
536 |
+
CharT one_char = 0;
|
537 |
+
|
538 |
+
public:
|
539 |
+
bool load(handle src, bool convert) {
|
540 |
+
if (!src) {
|
541 |
+
return false;
|
542 |
+
}
|
543 |
+
if (src.is_none()) {
|
544 |
+
// Defer accepting None to other overloads (if we aren't in convert mode):
|
545 |
+
if (!convert) {
|
546 |
+
return false;
|
547 |
+
}
|
548 |
+
none = true;
|
549 |
+
return true;
|
550 |
+
}
|
551 |
+
return str_caster.load(src, convert);
|
552 |
+
}
|
553 |
+
|
554 |
+
static handle cast(const CharT *src, return_value_policy policy, handle parent) {
|
555 |
+
if (src == nullptr) {
|
556 |
+
return pybind11::none().release();
|
557 |
+
}
|
558 |
+
return StringCaster::cast(StringType(src), policy, parent);
|
559 |
+
}
|
560 |
+
|
561 |
+
static handle cast(CharT src, return_value_policy policy, handle parent) {
|
562 |
+
if (std::is_same<char, CharT>::value) {
|
563 |
+
handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
|
564 |
+
if (!s) {
|
565 |
+
throw error_already_set();
|
566 |
+
}
|
567 |
+
return s;
|
568 |
+
}
|
569 |
+
return StringCaster::cast(StringType(1, src), policy, parent);
|
570 |
+
}
|
571 |
+
|
572 |
+
explicit operator CharT *() {
|
573 |
+
return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
|
574 |
+
}
|
575 |
+
explicit operator CharT &() {
|
576 |
+
if (none) {
|
577 |
+
throw value_error("Cannot convert None to a character");
|
578 |
+
}
|
579 |
+
|
580 |
+
auto &value = static_cast<StringType &>(str_caster);
|
581 |
+
size_t str_len = value.size();
|
582 |
+
if (str_len == 0) {
|
583 |
+
throw value_error("Cannot convert empty string to a character");
|
584 |
+
}
|
585 |
+
|
586 |
+
// If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
|
587 |
+
// is too high, and one for multiple unicode characters (caught later), so we need to
|
588 |
+
// figure out how long the first encoded character is in bytes to distinguish between these
|
589 |
+
// two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
|
590 |
+
// those can fit into a single char value.
|
591 |
+
if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
|
592 |
+
auto v0 = static_cast<unsigned char>(value[0]);
|
593 |
+
// low bits only: 0-127
|
594 |
+
// 0b110xxxxx - start of 2-byte sequence
|
595 |
+
// 0b1110xxxx - start of 3-byte sequence
|
596 |
+
// 0b11110xxx - start of 4-byte sequence
|
597 |
+
size_t char0_bytes = (v0 & 0x80) == 0 ? 1
|
598 |
+
: (v0 & 0xE0) == 0xC0 ? 2
|
599 |
+
: (v0 & 0xF0) == 0xE0 ? 3
|
600 |
+
: 4;
|
601 |
+
|
602 |
+
if (char0_bytes == str_len) {
|
603 |
+
// If we have a 128-255 value, we can decode it into a single char:
|
604 |
+
if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
|
605 |
+
one_char = static_cast<CharT>(((v0 & 3) << 6)
|
606 |
+
+ (static_cast<unsigned char>(value[1]) & 0x3F));
|
607 |
+
return one_char;
|
608 |
+
}
|
609 |
+
// Otherwise we have a single character, but it's > U+00FF
|
610 |
+
throw value_error("Character code point not in range(0x100)");
|
611 |
+
}
|
612 |
+
}
|
613 |
+
|
614 |
+
// UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
|
615 |
+
// surrogate pair with total length 2 instantly indicates a range error (but not a "your
|
616 |
+
// string was too long" error).
|
617 |
+
else if (StringCaster::UTF_N == 16 && str_len == 2) {
|
618 |
+
one_char = static_cast<CharT>(value[0]);
|
619 |
+
if (one_char >= 0xD800 && one_char < 0xE000) {
|
620 |
+
throw value_error("Character code point not in range(0x10000)");
|
621 |
+
}
|
622 |
+
}
|
623 |
+
|
624 |
+
if (str_len != 1) {
|
625 |
+
throw value_error("Expected a character, but multi-character string found");
|
626 |
+
}
|
627 |
+
|
628 |
+
one_char = value[0];
|
629 |
+
return one_char;
|
630 |
+
}
|
631 |
+
|
632 |
+
static constexpr auto name = const_name(PYBIND11_STRING_NAME);
|
633 |
+
template <typename _T>
|
634 |
+
using cast_op_type = pybind11::detail::cast_op_type<_T>;
|
635 |
+
};
|
636 |
+
|
637 |
+
// Base implementation for std::tuple and std::pair
|
638 |
+
template <template <typename...> class Tuple, typename... Ts>
|
639 |
+
class tuple_caster {
|
640 |
+
using type = Tuple<Ts...>;
|
641 |
+
static constexpr auto size = sizeof...(Ts);
|
642 |
+
using indices = make_index_sequence<size>;
|
643 |
+
|
644 |
+
public:
|
645 |
+
bool load(handle src, bool convert) {
|
646 |
+
if (!isinstance<sequence>(src)) {
|
647 |
+
return false;
|
648 |
+
}
|
649 |
+
const auto seq = reinterpret_borrow<sequence>(src);
|
650 |
+
if (seq.size() != size) {
|
651 |
+
return false;
|
652 |
+
}
|
653 |
+
return load_impl(seq, convert, indices{});
|
654 |
+
}
|
655 |
+
|
656 |
+
template <typename T>
|
657 |
+
static handle cast(T &&src, return_value_policy policy, handle parent) {
|
658 |
+
return cast_impl(std::forward<T>(src), policy, parent, indices{});
|
659 |
+
}
|
660 |
+
|
661 |
+
// copied from the PYBIND11_TYPE_CASTER macro
|
662 |
+
template <typename T>
|
663 |
+
static handle cast(T *src, return_value_policy policy, handle parent) {
|
664 |
+
if (!src) {
|
665 |
+
return none().release();
|
666 |
+
}
|
667 |
+
if (policy == return_value_policy::take_ownership) {
|
668 |
+
auto h = cast(std::move(*src), policy, parent);
|
669 |
+
delete src;
|
670 |
+
return h;
|
671 |
+
}
|
672 |
+
return cast(*src, policy, parent);
|
673 |
+
}
|
674 |
+
|
675 |
+
static constexpr auto name = const_name("tuple[")
|
676 |
+
+ ::pybind11::detail::concat(make_caster<Ts>::name...)
|
677 |
+
+ const_name("]");
|
678 |
+
|
679 |
+
template <typename T>
|
680 |
+
using cast_op_type = type;
|
681 |
+
|
682 |
+
explicit operator type() & { return implicit_cast(indices{}); }
|
683 |
+
explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
|
684 |
+
|
685 |
+
protected:
|
686 |
+
template <size_t... Is>
|
687 |
+
type implicit_cast(index_sequence<Is...>) & {
|
688 |
+
return type(cast_op<Ts>(std::get<Is>(subcasters))...);
|
689 |
+
}
|
690 |
+
template <size_t... Is>
|
691 |
+
type implicit_cast(index_sequence<Is...>) && {
|
692 |
+
return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
|
693 |
+
}
|
694 |
+
|
695 |
+
static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
|
696 |
+
|
697 |
+
template <size_t... Is>
|
698 |
+
bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
|
699 |
+
#ifdef __cpp_fold_expressions
|
700 |
+
if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
|
701 |
+
return false;
|
702 |
+
}
|
703 |
+
#else
|
704 |
+
for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
|
705 |
+
if (!r) {
|
706 |
+
return false;
|
707 |
+
}
|
708 |
+
}
|
709 |
+
#endif
|
710 |
+
return true;
|
711 |
+
}
|
712 |
+
|
713 |
+
/* Implementation: Convert a C++ tuple into a Python tuple */
|
714 |
+
template <typename T, size_t... Is>
|
715 |
+
static handle
|
716 |
+
cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
|
717 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
|
718 |
+
PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
|
719 |
+
std::array<object, size> entries{{reinterpret_steal<object>(
|
720 |
+
make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
|
721 |
+
for (const auto &entry : entries) {
|
722 |
+
if (!entry) {
|
723 |
+
return handle();
|
724 |
+
}
|
725 |
+
}
|
726 |
+
tuple result(size);
|
727 |
+
int counter = 0;
|
728 |
+
for (auto &entry : entries) {
|
729 |
+
PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
|
730 |
+
}
|
731 |
+
return result.release();
|
732 |
+
}
|
733 |
+
|
734 |
+
Tuple<make_caster<Ts>...> subcasters;
|
735 |
+
};
|
736 |
+
|
737 |
+
template <typename T1, typename T2>
|
738 |
+
class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
|
739 |
+
|
740 |
+
template <typename... Ts>
|
741 |
+
class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
|
742 |
+
|
743 |
+
/// Helper class which abstracts away certain actions. Users can provide specializations for
|
744 |
+
/// custom holders, but it's only necessary if the type has a non-standard interface.
|
745 |
+
template <typename T>
|
746 |
+
struct holder_helper {
|
747 |
+
static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
|
748 |
+
};
|
749 |
+
|
750 |
+
/// Type caster for holder types like std::shared_ptr, etc.
|
751 |
+
/// The SFINAE hook is provided to help work around the current lack of support
|
752 |
+
/// for smart-pointer interoperability. Please consider it an implementation
|
753 |
+
/// detail that may change in the future, as formal support for smart-pointer
|
754 |
+
/// interoperability is added into pybind11.
|
755 |
+
template <typename type, typename holder_type, typename SFINAE = void>
|
756 |
+
struct copyable_holder_caster : public type_caster_base<type> {
|
757 |
+
public:
|
758 |
+
using base = type_caster_base<type>;
|
759 |
+
static_assert(std::is_base_of<base, type_caster<type>>::value,
|
760 |
+
"Holder classes are only supported for custom types");
|
761 |
+
using base::base;
|
762 |
+
using base::cast;
|
763 |
+
using base::typeinfo;
|
764 |
+
using base::value;
|
765 |
+
|
766 |
+
bool load(handle src, bool convert) {
|
767 |
+
return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
|
768 |
+
}
|
769 |
+
|
770 |
+
explicit operator type *() { return this->value; }
|
771 |
+
// static_cast works around compiler error with MSVC 17 and CUDA 10.2
|
772 |
+
// see issue #2180
|
773 |
+
explicit operator type &() { return *(static_cast<type *>(this->value)); }
|
774 |
+
explicit operator holder_type *() { return std::addressof(holder); }
|
775 |
+
explicit operator holder_type &() { return holder; }
|
776 |
+
|
777 |
+
static handle cast(const holder_type &src, return_value_policy, handle) {
|
778 |
+
const auto *ptr = holder_helper<holder_type>::get(src);
|
779 |
+
return type_caster_base<type>::cast_holder(ptr, &src);
|
780 |
+
}
|
781 |
+
|
782 |
+
protected:
|
783 |
+
friend class type_caster_generic;
|
784 |
+
void check_holder_compat() {
|
785 |
+
if (typeinfo->default_holder) {
|
786 |
+
throw cast_error("Unable to load a custom holder type from a default-holder instance");
|
787 |
+
}
|
788 |
+
}
|
789 |
+
|
790 |
+
bool load_value(value_and_holder &&v_h) {
|
791 |
+
if (v_h.holder_constructed()) {
|
792 |
+
value = v_h.value_ptr();
|
793 |
+
holder = v_h.template holder<holder_type>();
|
794 |
+
return true;
|
795 |
+
}
|
796 |
+
throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
|
797 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
798 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
|
799 |
+
"type information)");
|
800 |
+
#else
|
801 |
+
"of type '"
|
802 |
+
+ type_id<holder_type>() + "''");
|
803 |
+
#endif
|
804 |
+
}
|
805 |
+
|
806 |
+
template <typename T = holder_type,
|
807 |
+
detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
|
808 |
+
bool try_implicit_casts(handle, bool) {
|
809 |
+
return false;
|
810 |
+
}
|
811 |
+
|
812 |
+
template <typename T = holder_type,
|
813 |
+
detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
|
814 |
+
bool try_implicit_casts(handle src, bool convert) {
|
815 |
+
for (auto &cast : typeinfo->implicit_casts) {
|
816 |
+
copyable_holder_caster sub_caster(*cast.first);
|
817 |
+
if (sub_caster.load(src, convert)) {
|
818 |
+
value = cast.second(sub_caster.value);
|
819 |
+
holder = holder_type(sub_caster.holder, (type *) value);
|
820 |
+
return true;
|
821 |
+
}
|
822 |
+
}
|
823 |
+
return false;
|
824 |
+
}
|
825 |
+
|
826 |
+
static bool try_direct_conversions(handle) { return false; }
|
827 |
+
|
828 |
+
holder_type holder;
|
829 |
+
};
|
830 |
+
|
831 |
+
/// Specialize for the common std::shared_ptr, so users don't need to
|
832 |
+
template <typename T>
|
833 |
+
class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
|
834 |
+
|
835 |
+
/// Type caster for holder types like std::unique_ptr.
|
836 |
+
/// Please consider the SFINAE hook an implementation detail, as explained
|
837 |
+
/// in the comment for the copyable_holder_caster.
|
838 |
+
template <typename type, typename holder_type, typename SFINAE = void>
|
839 |
+
struct move_only_holder_caster {
|
840 |
+
static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
|
841 |
+
"Holder classes are only supported for custom types");
|
842 |
+
|
843 |
+
static handle cast(holder_type &&src, return_value_policy, handle) {
|
844 |
+
auto *ptr = holder_helper<holder_type>::get(src);
|
845 |
+
return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
|
846 |
+
}
|
847 |
+
static constexpr auto name = type_caster_base<type>::name;
|
848 |
+
};
|
849 |
+
|
850 |
+
template <typename type, typename deleter>
|
851 |
+
class type_caster<std::unique_ptr<type, deleter>>
|
852 |
+
: public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
|
853 |
+
|
854 |
+
template <typename type, typename holder_type>
|
855 |
+
using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
|
856 |
+
copyable_holder_caster<type, holder_type>,
|
857 |
+
move_only_holder_caster<type, holder_type>>;
|
858 |
+
|
859 |
+
template <typename T, bool Value = false>
|
860 |
+
struct always_construct_holder {
|
861 |
+
static constexpr bool value = Value;
|
862 |
+
};
|
863 |
+
|
864 |
+
/// Create a specialization for custom holder types (silently ignores std::shared_ptr)
|
865 |
+
#define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
|
866 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
|
867 |
+
namespace detail { \
|
868 |
+
template <typename type> \
|
869 |
+
struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
|
870 |
+
}; \
|
871 |
+
template <typename type> \
|
872 |
+
class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
|
873 |
+
: public type_caster_holder<type, holder_type> {}; \
|
874 |
+
} \
|
875 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
876 |
+
|
877 |
+
// PYBIND11_DECLARE_HOLDER_TYPE holder types:
|
878 |
+
template <typename base, typename holder>
|
879 |
+
struct is_holder_type
|
880 |
+
: std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
|
881 |
+
// Specialization for always-supported unique_ptr holders:
|
882 |
+
template <typename base, typename deleter>
|
883 |
+
struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
|
884 |
+
|
885 |
+
#ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
|
886 |
+
|
887 |
+
// This leads to compilation errors if a specialization is missing.
|
888 |
+
template <typename T>
|
889 |
+
struct handle_type_name;
|
890 |
+
|
891 |
+
#else
|
892 |
+
|
893 |
+
template <typename T>
|
894 |
+
struct handle_type_name {
|
895 |
+
static constexpr auto name = const_name<T>();
|
896 |
+
};
|
897 |
+
|
898 |
+
#endif
|
899 |
+
|
900 |
+
template <>
|
901 |
+
struct handle_type_name<object> {
|
902 |
+
static constexpr auto name = const_name("object");
|
903 |
+
};
|
904 |
+
template <>
|
905 |
+
struct handle_type_name<list> {
|
906 |
+
static constexpr auto name = const_name("list");
|
907 |
+
};
|
908 |
+
template <>
|
909 |
+
struct handle_type_name<dict> {
|
910 |
+
static constexpr auto name = const_name("dict");
|
911 |
+
};
|
912 |
+
template <>
|
913 |
+
struct handle_type_name<anyset> {
|
914 |
+
static constexpr auto name = const_name("Union[set, frozenset]");
|
915 |
+
};
|
916 |
+
template <>
|
917 |
+
struct handle_type_name<set> {
|
918 |
+
static constexpr auto name = const_name("set");
|
919 |
+
};
|
920 |
+
template <>
|
921 |
+
struct handle_type_name<frozenset> {
|
922 |
+
static constexpr auto name = const_name("frozenset");
|
923 |
+
};
|
924 |
+
template <>
|
925 |
+
struct handle_type_name<str> {
|
926 |
+
static constexpr auto name = const_name("str");
|
927 |
+
};
|
928 |
+
template <>
|
929 |
+
struct handle_type_name<tuple> {
|
930 |
+
static constexpr auto name = const_name("tuple");
|
931 |
+
};
|
932 |
+
template <>
|
933 |
+
struct handle_type_name<bool_> {
|
934 |
+
static constexpr auto name = const_name("bool");
|
935 |
+
};
|
936 |
+
template <>
|
937 |
+
struct handle_type_name<bytes> {
|
938 |
+
static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
|
939 |
+
};
|
940 |
+
template <>
|
941 |
+
struct handle_type_name<buffer> {
|
942 |
+
static constexpr auto name = const_name("Buffer");
|
943 |
+
};
|
944 |
+
template <>
|
945 |
+
struct handle_type_name<int_> {
|
946 |
+
static constexpr auto name = const_name("int");
|
947 |
+
};
|
948 |
+
template <>
|
949 |
+
struct handle_type_name<iterable> {
|
950 |
+
static constexpr auto name = const_name("Iterable");
|
951 |
+
};
|
952 |
+
template <>
|
953 |
+
struct handle_type_name<iterator> {
|
954 |
+
static constexpr auto name = const_name("Iterator");
|
955 |
+
};
|
956 |
+
template <>
|
957 |
+
struct handle_type_name<float_> {
|
958 |
+
static constexpr auto name = const_name("float");
|
959 |
+
};
|
960 |
+
template <>
|
961 |
+
struct handle_type_name<function> {
|
962 |
+
static constexpr auto name = const_name("Callable");
|
963 |
+
};
|
964 |
+
template <>
|
965 |
+
struct handle_type_name<handle> {
|
966 |
+
static constexpr auto name = handle_type_name<object>::name;
|
967 |
+
};
|
968 |
+
template <>
|
969 |
+
struct handle_type_name<none> {
|
970 |
+
static constexpr auto name = const_name("None");
|
971 |
+
};
|
972 |
+
template <>
|
973 |
+
struct handle_type_name<sequence> {
|
974 |
+
static constexpr auto name = const_name("Sequence");
|
975 |
+
};
|
976 |
+
template <>
|
977 |
+
struct handle_type_name<bytearray> {
|
978 |
+
static constexpr auto name = const_name("bytearray");
|
979 |
+
};
|
980 |
+
template <>
|
981 |
+
struct handle_type_name<memoryview> {
|
982 |
+
static constexpr auto name = const_name("memoryview");
|
983 |
+
};
|
984 |
+
template <>
|
985 |
+
struct handle_type_name<slice> {
|
986 |
+
static constexpr auto name = const_name("slice");
|
987 |
+
};
|
988 |
+
template <>
|
989 |
+
struct handle_type_name<type> {
|
990 |
+
static constexpr auto name = const_name("type");
|
991 |
+
};
|
992 |
+
template <>
|
993 |
+
struct handle_type_name<capsule> {
|
994 |
+
static constexpr auto name = const_name("capsule");
|
995 |
+
};
|
996 |
+
template <>
|
997 |
+
struct handle_type_name<ellipsis> {
|
998 |
+
static constexpr auto name = const_name("ellipsis");
|
999 |
+
};
|
1000 |
+
template <>
|
1001 |
+
struct handle_type_name<weakref> {
|
1002 |
+
static constexpr auto name = const_name("weakref");
|
1003 |
+
};
|
1004 |
+
template <>
|
1005 |
+
struct handle_type_name<args> {
|
1006 |
+
static constexpr auto name = const_name("*args");
|
1007 |
+
};
|
1008 |
+
template <>
|
1009 |
+
struct handle_type_name<kwargs> {
|
1010 |
+
static constexpr auto name = const_name("**kwargs");
|
1011 |
+
};
|
1012 |
+
template <>
|
1013 |
+
struct handle_type_name<obj_attr_accessor> {
|
1014 |
+
static constexpr auto name = const_name<obj_attr_accessor>();
|
1015 |
+
};
|
1016 |
+
template <>
|
1017 |
+
struct handle_type_name<str_attr_accessor> {
|
1018 |
+
static constexpr auto name = const_name<str_attr_accessor>();
|
1019 |
+
};
|
1020 |
+
template <>
|
1021 |
+
struct handle_type_name<item_accessor> {
|
1022 |
+
static constexpr auto name = const_name<item_accessor>();
|
1023 |
+
};
|
1024 |
+
template <>
|
1025 |
+
struct handle_type_name<sequence_accessor> {
|
1026 |
+
static constexpr auto name = const_name<sequence_accessor>();
|
1027 |
+
};
|
1028 |
+
template <>
|
1029 |
+
struct handle_type_name<list_accessor> {
|
1030 |
+
static constexpr auto name = const_name<list_accessor>();
|
1031 |
+
};
|
1032 |
+
template <>
|
1033 |
+
struct handle_type_name<tuple_accessor> {
|
1034 |
+
static constexpr auto name = const_name<tuple_accessor>();
|
1035 |
+
};
|
1036 |
+
|
1037 |
+
template <typename type>
|
1038 |
+
struct pyobject_caster {
|
1039 |
+
template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
|
1040 |
+
pyobject_caster() : value() {}
|
1041 |
+
|
1042 |
+
// `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
|
1043 |
+
// to a nil handle is safe since it will only be accessed if `load` succeeds.
|
1044 |
+
template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
|
1045 |
+
pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
|
1046 |
+
|
1047 |
+
template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
|
1048 |
+
bool load(handle src, bool /* convert */) {
|
1049 |
+
value = src;
|
1050 |
+
return static_cast<bool>(value);
|
1051 |
+
}
|
1052 |
+
|
1053 |
+
template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
|
1054 |
+
bool load(handle src, bool /* convert */) {
|
1055 |
+
if (!isinstance<type>(src)) {
|
1056 |
+
return false;
|
1057 |
+
}
|
1058 |
+
value = reinterpret_borrow<type>(src);
|
1059 |
+
return true;
|
1060 |
+
}
|
1061 |
+
|
1062 |
+
static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
|
1063 |
+
return src.inc_ref();
|
1064 |
+
}
|
1065 |
+
PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
|
1066 |
+
};
|
1067 |
+
|
1068 |
+
template <typename T>
|
1069 |
+
class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
|
1070 |
+
|
1071 |
+
// Our conditions for enabling moving are quite restrictive:
|
1072 |
+
// At compile time:
|
1073 |
+
// - T needs to be a non-const, non-pointer, non-reference type
|
1074 |
+
// - type_caster<T>::operator T&() must exist
|
1075 |
+
// - the type must be move constructible (obviously)
|
1076 |
+
// At run-time:
|
1077 |
+
// - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
|
1078 |
+
// must have ref_count() == 1)h
|
1079 |
+
// If any of the above are not satisfied, we fall back to copying.
|
1080 |
+
template <typename T>
|
1081 |
+
using move_is_plain_type
|
1082 |
+
= satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
|
1083 |
+
template <typename T, typename SFINAE = void>
|
1084 |
+
struct move_always : std::false_type {};
|
1085 |
+
template <typename T>
|
1086 |
+
struct move_always<
|
1087 |
+
T,
|
1088 |
+
enable_if_t<
|
1089 |
+
all_of<move_is_plain_type<T>,
|
1090 |
+
negation<is_copy_constructible<T>>,
|
1091 |
+
is_move_constructible<T>,
|
1092 |
+
std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
|
1093 |
+
: std::true_type {};
|
1094 |
+
template <typename T, typename SFINAE = void>
|
1095 |
+
struct move_if_unreferenced : std::false_type {};
|
1096 |
+
template <typename T>
|
1097 |
+
struct move_if_unreferenced<
|
1098 |
+
T,
|
1099 |
+
enable_if_t<
|
1100 |
+
all_of<move_is_plain_type<T>,
|
1101 |
+
negation<move_always<T>>,
|
1102 |
+
is_move_constructible<T>,
|
1103 |
+
std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
|
1104 |
+
: std::true_type {};
|
1105 |
+
template <typename T>
|
1106 |
+
using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
|
1107 |
+
|
1108 |
+
// Detect whether returning a `type` from a cast on type's type_caster is going to result in a
|
1109 |
+
// reference or pointer to a local variable of the type_caster. Basically, only
|
1110 |
+
// non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
|
1111 |
+
// everything else returns a reference/pointer to a local variable.
|
1112 |
+
template <typename type>
|
1113 |
+
using cast_is_temporary_value_reference
|
1114 |
+
= bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
|
1115 |
+
&& !std::is_base_of<type_caster_generic, make_caster<type>>::value
|
1116 |
+
&& !std::is_same<intrinsic_t<type>, void>::value>;
|
1117 |
+
|
1118 |
+
// When a value returned from a C++ function is being cast back to Python, we almost always want to
|
1119 |
+
// force `policy = move`, regardless of the return value policy the function/method was declared
|
1120 |
+
// with.
|
1121 |
+
template <typename Return, typename SFINAE = void>
|
1122 |
+
struct return_value_policy_override {
|
1123 |
+
static return_value_policy policy(return_value_policy p) { return p; }
|
1124 |
+
};
|
1125 |
+
|
1126 |
+
template <typename Return>
|
1127 |
+
struct return_value_policy_override<
|
1128 |
+
Return,
|
1129 |
+
detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
|
1130 |
+
static return_value_policy policy(return_value_policy p) {
|
1131 |
+
return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
|
1132 |
+
? return_value_policy::move
|
1133 |
+
: p;
|
1134 |
+
}
|
1135 |
+
};
|
1136 |
+
|
1137 |
+
// Basic python -> C++ casting; throws if casting fails
|
1138 |
+
template <typename T, typename SFINAE>
|
1139 |
+
type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
|
1140 |
+
static_assert(!detail::is_pyobject<T>::value,
|
1141 |
+
"Internal error: type_caster should only be used for C++ types");
|
1142 |
+
if (!conv.load(handle, true)) {
|
1143 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1144 |
+
throw cast_error(
|
1145 |
+
"Unable to cast Python instance of type "
|
1146 |
+
+ str(type::handle_of(handle)).cast<std::string>()
|
1147 |
+
+ " to C++ type '?' (#define "
|
1148 |
+
"PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1149 |
+
#else
|
1150 |
+
throw cast_error("Unable to cast Python instance of type "
|
1151 |
+
+ str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
|
1152 |
+
+ type_id<T>() + "'");
|
1153 |
+
#endif
|
1154 |
+
}
|
1155 |
+
return conv;
|
1156 |
+
}
|
1157 |
+
// Wrapper around the above that also constructs and returns a type_caster
|
1158 |
+
template <typename T>
|
1159 |
+
make_caster<T> load_type(const handle &handle) {
|
1160 |
+
make_caster<T> conv;
|
1161 |
+
load_type(conv, handle);
|
1162 |
+
return conv;
|
1163 |
+
}
|
1164 |
+
|
1165 |
+
PYBIND11_NAMESPACE_END(detail)
|
1166 |
+
|
1167 |
+
// pytype -> C++ type
|
1168 |
+
template <typename T,
|
1169 |
+
detail::enable_if_t<!detail::is_pyobject<T>::value
|
1170 |
+
&& !detail::is_same_ignoring_cvref<T, PyObject *>::value,
|
1171 |
+
int>
|
1172 |
+
= 0>
|
1173 |
+
T cast(const handle &handle) {
|
1174 |
+
using namespace detail;
|
1175 |
+
static_assert(!cast_is_temporary_value_reference<T>::value,
|
1176 |
+
"Unable to cast type to reference: value is local to type caster");
|
1177 |
+
return cast_op<T>(load_type<T>(handle));
|
1178 |
+
}
|
1179 |
+
|
1180 |
+
// pytype -> pytype (calls converting constructor)
|
1181 |
+
template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
|
1182 |
+
T cast(const handle &handle) {
|
1183 |
+
return T(reinterpret_borrow<object>(handle));
|
1184 |
+
}
|
1185 |
+
|
1186 |
+
// Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
|
1187 |
+
// This is necessary for the case that `obj` is a temporary, and could
|
1188 |
+
// not possibly be different, given
|
1189 |
+
// 1. the established convention that the passed `handle` is borrowed, and
|
1190 |
+
// 2. we don't want to force all generic code using `cast<T>()` to special-case
|
1191 |
+
// handling of `T` = `PyObject *` (to increment the reference count there).
|
1192 |
+
// It is the responsibility of the caller to ensure that the reference count
|
1193 |
+
// is decremented.
|
1194 |
+
template <typename T,
|
1195 |
+
typename Handle,
|
1196 |
+
detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
|
1197 |
+
&& detail::is_same_ignoring_cvref<Handle, handle>::value,
|
1198 |
+
int>
|
1199 |
+
= 0>
|
1200 |
+
T cast(Handle &&handle) {
|
1201 |
+
return handle.inc_ref().ptr();
|
1202 |
+
}
|
1203 |
+
// To optimize way an inc_ref/dec_ref cycle:
|
1204 |
+
template <typename T,
|
1205 |
+
typename Object,
|
1206 |
+
detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
|
1207 |
+
&& detail::is_same_ignoring_cvref<Object, object>::value,
|
1208 |
+
int>
|
1209 |
+
= 0>
|
1210 |
+
T cast(Object &&obj) {
|
1211 |
+
return obj.release().ptr();
|
1212 |
+
}
|
1213 |
+
|
1214 |
+
// C++ type -> py::object
|
1215 |
+
template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
|
1216 |
+
object cast(T &&value,
|
1217 |
+
return_value_policy policy = return_value_policy::automatic_reference,
|
1218 |
+
handle parent = handle()) {
|
1219 |
+
using no_ref_T = typename std::remove_reference<T>::type;
|
1220 |
+
if (policy == return_value_policy::automatic) {
|
1221 |
+
policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
|
1222 |
+
: std::is_lvalue_reference<T>::value ? return_value_policy::copy
|
1223 |
+
: return_value_policy::move;
|
1224 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
1225 |
+
policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
|
1226 |
+
: std::is_lvalue_reference<T>::value ? return_value_policy::copy
|
1227 |
+
: return_value_policy::move;
|
1228 |
+
}
|
1229 |
+
return reinterpret_steal<object>(
|
1230 |
+
detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
|
1231 |
+
}
|
1232 |
+
|
1233 |
+
template <typename T>
|
1234 |
+
T handle::cast() const {
|
1235 |
+
return pybind11::cast<T>(*this);
|
1236 |
+
}
|
1237 |
+
template <>
|
1238 |
+
inline void handle::cast() const {
|
1239 |
+
return;
|
1240 |
+
}
|
1241 |
+
|
1242 |
+
template <typename T>
|
1243 |
+
detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
|
1244 |
+
if (obj.ref_count() > 1) {
|
1245 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1246 |
+
throw cast_error(
|
1247 |
+
"Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
|
1248 |
+
+ " instance to C++ rvalue: instance has multiple references"
|
1249 |
+
" (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1250 |
+
#else
|
1251 |
+
throw cast_error("Unable to move from Python "
|
1252 |
+
+ str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
|
1253 |
+
+ type_id<T>() + " instance: instance has multiple references");
|
1254 |
+
#endif
|
1255 |
+
}
|
1256 |
+
|
1257 |
+
// Move into a temporary and return that, because the reference may be a local value of `conv`
|
1258 |
+
T ret = std::move(detail::load_type<T>(obj).operator T &());
|
1259 |
+
return ret;
|
1260 |
+
}
|
1261 |
+
|
1262 |
+
// Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
|
1263 |
+
// - If we have to move (because T has no copy constructor), do it. This will fail if the moved
|
1264 |
+
// object has multiple references, but trying to copy will fail to compile.
|
1265 |
+
// - If both movable and copyable, check ref count: if 1, move; otherwise copy
|
1266 |
+
// - Otherwise (not movable), copy.
|
1267 |
+
template <typename T>
|
1268 |
+
detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
|
1269 |
+
cast(object &&object) {
|
1270 |
+
return move<T>(std::move(object));
|
1271 |
+
}
|
1272 |
+
template <typename T>
|
1273 |
+
detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
|
1274 |
+
cast(object &&object) {
|
1275 |
+
if (object.ref_count() > 1) {
|
1276 |
+
return cast<T>(object);
|
1277 |
+
}
|
1278 |
+
return move<T>(std::move(object));
|
1279 |
+
}
|
1280 |
+
template <typename T>
|
1281 |
+
detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
|
1282 |
+
cast(object &&object) {
|
1283 |
+
return cast<T>(object);
|
1284 |
+
}
|
1285 |
+
|
1286 |
+
// pytype rvalue -> pytype (calls converting constructor)
|
1287 |
+
template <typename T>
|
1288 |
+
detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
|
1289 |
+
return T(std::move(object));
|
1290 |
+
}
|
1291 |
+
|
1292 |
+
template <typename T>
|
1293 |
+
T object::cast() const & {
|
1294 |
+
return pybind11::cast<T>(*this);
|
1295 |
+
}
|
1296 |
+
template <typename T>
|
1297 |
+
T object::cast() && {
|
1298 |
+
return pybind11::cast<T>(std::move(*this));
|
1299 |
+
}
|
1300 |
+
template <>
|
1301 |
+
inline void object::cast() const & {
|
1302 |
+
return;
|
1303 |
+
}
|
1304 |
+
template <>
|
1305 |
+
inline void object::cast() && {
|
1306 |
+
return;
|
1307 |
+
}
|
1308 |
+
|
1309 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1310 |
+
|
1311 |
+
// Declared in pytypes.h:
|
1312 |
+
template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
|
1313 |
+
object object_or_cast(T &&o) {
|
1314 |
+
return pybind11::cast(std::forward<T>(o));
|
1315 |
+
}
|
1316 |
+
|
1317 |
+
// Placeholder type for the unneeded (and dead code) static variable in the
|
1318 |
+
// PYBIND11_OVERRIDE_OVERRIDE macro
|
1319 |
+
struct override_unused {};
|
1320 |
+
template <typename ret_type>
|
1321 |
+
using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
|
1322 |
+
make_caster<ret_type>,
|
1323 |
+
override_unused>;
|
1324 |
+
|
1325 |
+
// Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
|
1326 |
+
// store the result in the given variable. For other types, this is a no-op.
|
1327 |
+
template <typename T>
|
1328 |
+
enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
|
1329 |
+
make_caster<T> &caster) {
|
1330 |
+
return cast_op<T>(load_type(caster, o));
|
1331 |
+
}
|
1332 |
+
template <typename T>
|
1333 |
+
enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
|
1334 |
+
override_unused &) {
|
1335 |
+
pybind11_fail("Internal error: cast_ref fallback invoked");
|
1336 |
+
}
|
1337 |
+
|
1338 |
+
// Trampoline use: Having a pybind11::cast with an invalid reference type is going to
|
1339 |
+
// static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
|
1340 |
+
// that only does anything in cases where pybind11::cast is valid.
|
1341 |
+
template <typename T>
|
1342 |
+
enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
|
1343 |
+
pybind11_fail("Internal error: cast_safe fallback invoked");
|
1344 |
+
}
|
1345 |
+
template <typename T>
|
1346 |
+
enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
|
1347 |
+
template <typename T>
|
1348 |
+
enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>, std::is_void<T>>::value, T>
|
1349 |
+
cast_safe(object &&o) {
|
1350 |
+
return pybind11::cast<T>(std::move(o));
|
1351 |
+
}
|
1352 |
+
|
1353 |
+
PYBIND11_NAMESPACE_END(detail)
|
1354 |
+
|
1355 |
+
// The overloads could coexist, i.e. the #if is not strictly speaking needed,
|
1356 |
+
// but it is an easy minor optimization.
|
1357 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1358 |
+
inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
|
1359 |
+
return cast_error("Unable to convert call argument '" + name
|
1360 |
+
+ "' to Python object (#define "
|
1361 |
+
"PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1362 |
+
}
|
1363 |
+
#else
|
1364 |
+
inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
|
1365 |
+
const std::string &type) {
|
1366 |
+
return cast_error("Unable to convert call argument '" + name + "' of type '" + type
|
1367 |
+
+ "' to Python object");
|
1368 |
+
}
|
1369 |
+
#endif
|
1370 |
+
|
1371 |
+
template <return_value_policy policy = return_value_policy::automatic_reference>
|
1372 |
+
tuple make_tuple() {
|
1373 |
+
return tuple(0);
|
1374 |
+
}
|
1375 |
+
|
1376 |
+
template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
|
1377 |
+
tuple make_tuple(Args &&...args_) {
|
1378 |
+
constexpr size_t size = sizeof...(Args);
|
1379 |
+
std::array<object, size> args{{reinterpret_steal<object>(
|
1380 |
+
detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
|
1381 |
+
for (size_t i = 0; i < args.size(); i++) {
|
1382 |
+
if (!args[i]) {
|
1383 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1384 |
+
throw cast_error_unable_to_convert_call_arg(std::to_string(i));
|
1385 |
+
#else
|
1386 |
+
std::array<std::string, size> argtypes{{type_id<Args>()...}};
|
1387 |
+
throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
|
1388 |
+
#endif
|
1389 |
+
}
|
1390 |
+
}
|
1391 |
+
tuple result(size);
|
1392 |
+
int counter = 0;
|
1393 |
+
for (auto &arg_value : args) {
|
1394 |
+
PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
|
1395 |
+
}
|
1396 |
+
return result;
|
1397 |
+
}
|
1398 |
+
|
1399 |
+
/// \ingroup annotations
|
1400 |
+
/// Annotation for arguments
|
1401 |
+
struct arg {
|
1402 |
+
/// Constructs an argument with the name of the argument; if null or omitted, this is a
|
1403 |
+
/// positional argument.
|
1404 |
+
constexpr explicit arg(const char *name = nullptr)
|
1405 |
+
: name(name), flag_noconvert(false), flag_none(true) {}
|
1406 |
+
/// Assign a value to this argument
|
1407 |
+
template <typename T>
|
1408 |
+
arg_v operator=(T &&value) const;
|
1409 |
+
/// Indicate that the type should not be converted in the type caster
|
1410 |
+
arg &noconvert(bool flag = true) {
|
1411 |
+
flag_noconvert = flag;
|
1412 |
+
return *this;
|
1413 |
+
}
|
1414 |
+
/// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
|
1415 |
+
arg &none(bool flag = true) {
|
1416 |
+
flag_none = flag;
|
1417 |
+
return *this;
|
1418 |
+
}
|
1419 |
+
|
1420 |
+
const char *name; ///< If non-null, this is a named kwargs argument
|
1421 |
+
bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
|
1422 |
+
///< caster!)
|
1423 |
+
bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
|
1424 |
+
};
|
1425 |
+
|
1426 |
+
/// \ingroup annotations
|
1427 |
+
/// Annotation for arguments with values
|
1428 |
+
struct arg_v : arg {
|
1429 |
+
private:
|
1430 |
+
template <typename T>
|
1431 |
+
arg_v(arg &&base, T &&x, const char *descr = nullptr)
|
1432 |
+
: arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
|
1433 |
+
std::forward<T>(x), return_value_policy::automatic, {}))),
|
1434 |
+
descr(descr)
|
1435 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1436 |
+
,
|
1437 |
+
type(type_id<T>())
|
1438 |
+
#endif
|
1439 |
+
{
|
1440 |
+
// Workaround! See:
|
1441 |
+
// https://github.com/pybind/pybind11/issues/2336
|
1442 |
+
// https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
|
1443 |
+
if (PyErr_Occurred()) {
|
1444 |
+
PyErr_Clear();
|
1445 |
+
}
|
1446 |
+
}
|
1447 |
+
|
1448 |
+
public:
|
1449 |
+
/// Direct construction with name, default, and description
|
1450 |
+
template <typename T>
|
1451 |
+
arg_v(const char *name, T &&x, const char *descr = nullptr)
|
1452 |
+
: arg_v(arg(name), std::forward<T>(x), descr) {}
|
1453 |
+
|
1454 |
+
/// Called internally when invoking `py::arg("a") = value`
|
1455 |
+
template <typename T>
|
1456 |
+
arg_v(const arg &base, T &&x, const char *descr = nullptr)
|
1457 |
+
: arg_v(arg(base), std::forward<T>(x), descr) {}
|
1458 |
+
|
1459 |
+
/// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
|
1460 |
+
arg_v &noconvert(bool flag = true) {
|
1461 |
+
arg::noconvert(flag);
|
1462 |
+
return *this;
|
1463 |
+
}
|
1464 |
+
|
1465 |
+
/// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
|
1466 |
+
arg_v &none(bool flag = true) {
|
1467 |
+
arg::none(flag);
|
1468 |
+
return *this;
|
1469 |
+
}
|
1470 |
+
|
1471 |
+
/// The default value
|
1472 |
+
object value;
|
1473 |
+
/// The (optional) description of the default value
|
1474 |
+
const char *descr;
|
1475 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1476 |
+
/// The C++ type name of the default value (only available when compiled in debug mode)
|
1477 |
+
std::string type;
|
1478 |
+
#endif
|
1479 |
+
};
|
1480 |
+
|
1481 |
+
/// \ingroup annotations
|
1482 |
+
/// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
|
1483 |
+
/// an unnamed '*' argument
|
1484 |
+
struct kw_only {};
|
1485 |
+
|
1486 |
+
/// \ingroup annotations
|
1487 |
+
/// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
|
1488 |
+
/// an unnamed '/' argument (in Python 3.8)
|
1489 |
+
struct pos_only {};
|
1490 |
+
|
1491 |
+
template <typename T>
|
1492 |
+
arg_v arg::operator=(T &&value) const {
|
1493 |
+
return {*this, std::forward<T>(value)};
|
1494 |
+
}
|
1495 |
+
|
1496 |
+
/// Alias for backward compatibility -- to be removed in version 2.0
|
1497 |
+
template <typename /*unused*/>
|
1498 |
+
using arg_t = arg_v;
|
1499 |
+
|
1500 |
+
inline namespace literals {
|
1501 |
+
/** \rst
|
1502 |
+
String literal version of `arg`
|
1503 |
+
\endrst */
|
1504 |
+
constexpr arg
|
1505 |
+
#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
|
1506 |
+
operator"" _a // gcc 4.8.5 insists on having a space (hard error).
|
1507 |
+
#else
|
1508 |
+
operator""_a // clang 17 generates a deprecation warning if there is a space.
|
1509 |
+
#endif
|
1510 |
+
(const char *name, size_t) {
|
1511 |
+
return arg(name);
|
1512 |
+
}
|
1513 |
+
} // namespace literals
|
1514 |
+
|
1515 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1516 |
+
|
1517 |
+
template <typename T>
|
1518 |
+
using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
|
1519 |
+
template <typename T>
|
1520 |
+
using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
|
1521 |
+
|
1522 |
+
// forward declaration (definition in attr.h)
|
1523 |
+
struct function_record;
|
1524 |
+
|
1525 |
+
/// Internal data associated with a single function call
|
1526 |
+
struct function_call {
|
1527 |
+
function_call(const function_record &f, handle p); // Implementation in attr.h
|
1528 |
+
|
1529 |
+
/// The function data:
|
1530 |
+
const function_record &func;
|
1531 |
+
|
1532 |
+
/// Arguments passed to the function:
|
1533 |
+
std::vector<handle> args;
|
1534 |
+
|
1535 |
+
/// The `convert` value the arguments should be loaded with
|
1536 |
+
std::vector<bool> args_convert;
|
1537 |
+
|
1538 |
+
/// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
|
1539 |
+
/// present, are also in `args` but without a reference).
|
1540 |
+
object args_ref, kwargs_ref;
|
1541 |
+
|
1542 |
+
/// The parent, if any
|
1543 |
+
handle parent;
|
1544 |
+
|
1545 |
+
/// If this is a call to an initializer, this argument contains `self`
|
1546 |
+
handle init_self;
|
1547 |
+
};
|
1548 |
+
|
1549 |
+
/// Helper class which loads arguments for C++ functions called from Python
|
1550 |
+
template <typename... Args>
|
1551 |
+
class argument_loader {
|
1552 |
+
using indices = make_index_sequence<sizeof...(Args)>;
|
1553 |
+
|
1554 |
+
template <typename Arg>
|
1555 |
+
using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
|
1556 |
+
template <typename Arg>
|
1557 |
+
using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
|
1558 |
+
// Get kwargs argument position, or -1 if not present:
|
1559 |
+
static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
|
1560 |
+
|
1561 |
+
static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
|
1562 |
+
"py::kwargs is only permitted as the last argument of a function");
|
1563 |
+
|
1564 |
+
public:
|
1565 |
+
static constexpr bool has_kwargs = kwargs_pos != -1;
|
1566 |
+
|
1567 |
+
// py::args argument position; -1 if not present.
|
1568 |
+
static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
|
1569 |
+
|
1570 |
+
static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
|
1571 |
+
"py::args cannot be specified more than once");
|
1572 |
+
|
1573 |
+
static constexpr auto arg_names
|
1574 |
+
= ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
|
1575 |
+
|
1576 |
+
bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
|
1577 |
+
|
1578 |
+
template <typename Return, typename Guard, typename Func>
|
1579 |
+
// NOLINTNEXTLINE(readability-const-return-type)
|
1580 |
+
enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
|
1581 |
+
return std::move(*this).template call_impl<remove_cv_t<Return>>(
|
1582 |
+
std::forward<Func>(f), indices{}, Guard{});
|
1583 |
+
}
|
1584 |
+
|
1585 |
+
template <typename Return, typename Guard, typename Func>
|
1586 |
+
enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
|
1587 |
+
std::move(*this).template call_impl<remove_cv_t<Return>>(
|
1588 |
+
std::forward<Func>(f), indices{}, Guard{});
|
1589 |
+
return void_type();
|
1590 |
+
}
|
1591 |
+
|
1592 |
+
private:
|
1593 |
+
static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
|
1594 |
+
|
1595 |
+
template <size_t... Is>
|
1596 |
+
bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
|
1597 |
+
#ifdef __cpp_fold_expressions
|
1598 |
+
if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
|
1599 |
+
return false;
|
1600 |
+
}
|
1601 |
+
#else
|
1602 |
+
for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
|
1603 |
+
if (!r) {
|
1604 |
+
return false;
|
1605 |
+
}
|
1606 |
+
}
|
1607 |
+
#endif
|
1608 |
+
return true;
|
1609 |
+
}
|
1610 |
+
|
1611 |
+
template <typename Return, typename Func, size_t... Is, typename Guard>
|
1612 |
+
Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
|
1613 |
+
return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
|
1614 |
+
}
|
1615 |
+
|
1616 |
+
std::tuple<make_caster<Args>...> argcasters;
|
1617 |
+
};
|
1618 |
+
|
1619 |
+
/// Helper class which collects only positional arguments for a Python function call.
|
1620 |
+
/// A fancier version below can collect any argument, but this one is optimal for simple calls.
|
1621 |
+
template <return_value_policy policy>
|
1622 |
+
class simple_collector {
|
1623 |
+
public:
|
1624 |
+
template <typename... Ts>
|
1625 |
+
explicit simple_collector(Ts &&...values)
|
1626 |
+
: m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
|
1627 |
+
|
1628 |
+
const tuple &args() const & { return m_args; }
|
1629 |
+
dict kwargs() const { return {}; }
|
1630 |
+
|
1631 |
+
tuple args() && { return std::move(m_args); }
|
1632 |
+
|
1633 |
+
/// Call a Python function and pass the collected arguments
|
1634 |
+
object call(PyObject *ptr) const {
|
1635 |
+
PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
|
1636 |
+
if (!result) {
|
1637 |
+
throw error_already_set();
|
1638 |
+
}
|
1639 |
+
return reinterpret_steal<object>(result);
|
1640 |
+
}
|
1641 |
+
|
1642 |
+
private:
|
1643 |
+
tuple m_args;
|
1644 |
+
};
|
1645 |
+
|
1646 |
+
/// Helper class which collects positional, keyword, * and ** arguments for a Python function call
|
1647 |
+
template <return_value_policy policy>
|
1648 |
+
class unpacking_collector {
|
1649 |
+
public:
|
1650 |
+
template <typename... Ts>
|
1651 |
+
explicit unpacking_collector(Ts &&...values) {
|
1652 |
+
// Tuples aren't (easily) resizable so a list is needed for collection,
|
1653 |
+
// but the actual function call strictly requires a tuple.
|
1654 |
+
auto args_list = list();
|
1655 |
+
using expander = int[];
|
1656 |
+
(void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
|
1657 |
+
|
1658 |
+
m_args = std::move(args_list);
|
1659 |
+
}
|
1660 |
+
|
1661 |
+
const tuple &args() const & { return m_args; }
|
1662 |
+
const dict &kwargs() const & { return m_kwargs; }
|
1663 |
+
|
1664 |
+
tuple args() && { return std::move(m_args); }
|
1665 |
+
dict kwargs() && { return std::move(m_kwargs); }
|
1666 |
+
|
1667 |
+
/// Call a Python function and pass the collected arguments
|
1668 |
+
object call(PyObject *ptr) const {
|
1669 |
+
PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
|
1670 |
+
if (!result) {
|
1671 |
+
throw error_already_set();
|
1672 |
+
}
|
1673 |
+
return reinterpret_steal<object>(result);
|
1674 |
+
}
|
1675 |
+
|
1676 |
+
private:
|
1677 |
+
template <typename T>
|
1678 |
+
void process(list &args_list, T &&x) {
|
1679 |
+
auto o = reinterpret_steal<object>(
|
1680 |
+
detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
|
1681 |
+
if (!o) {
|
1682 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1683 |
+
throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()));
|
1684 |
+
#else
|
1685 |
+
throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
|
1686 |
+
type_id<T>());
|
1687 |
+
#endif
|
1688 |
+
}
|
1689 |
+
args_list.append(std::move(o));
|
1690 |
+
}
|
1691 |
+
|
1692 |
+
void process(list &args_list, detail::args_proxy ap) {
|
1693 |
+
for (auto a : ap) {
|
1694 |
+
args_list.append(a);
|
1695 |
+
}
|
1696 |
+
}
|
1697 |
+
|
1698 |
+
void process(list & /*args_list*/, arg_v a) {
|
1699 |
+
if (!a.name) {
|
1700 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1701 |
+
nameless_argument_error();
|
1702 |
+
#else
|
1703 |
+
nameless_argument_error(a.type);
|
1704 |
+
#endif
|
1705 |
+
}
|
1706 |
+
if (m_kwargs.contains(a.name)) {
|
1707 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1708 |
+
multiple_values_error();
|
1709 |
+
#else
|
1710 |
+
multiple_values_error(a.name);
|
1711 |
+
#endif
|
1712 |
+
}
|
1713 |
+
if (!a.value) {
|
1714 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1715 |
+
throw cast_error_unable_to_convert_call_arg(a.name);
|
1716 |
+
#else
|
1717 |
+
throw cast_error_unable_to_convert_call_arg(a.name, a.type);
|
1718 |
+
#endif
|
1719 |
+
}
|
1720 |
+
m_kwargs[a.name] = std::move(a.value);
|
1721 |
+
}
|
1722 |
+
|
1723 |
+
void process(list & /*args_list*/, detail::kwargs_proxy kp) {
|
1724 |
+
if (!kp) {
|
1725 |
+
return;
|
1726 |
+
}
|
1727 |
+
for (auto k : reinterpret_borrow<dict>(kp)) {
|
1728 |
+
if (m_kwargs.contains(k.first)) {
|
1729 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
1730 |
+
multiple_values_error();
|
1731 |
+
#else
|
1732 |
+
multiple_values_error(str(k.first));
|
1733 |
+
#endif
|
1734 |
+
}
|
1735 |
+
m_kwargs[k.first] = k.second;
|
1736 |
+
}
|
1737 |
+
}
|
1738 |
+
|
1739 |
+
[[noreturn]] static void nameless_argument_error() {
|
1740 |
+
throw type_error(
|
1741 |
+
"Got kwargs without a name; only named arguments "
|
1742 |
+
"may be passed via py::arg() to a python function call. "
|
1743 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1744 |
+
}
|
1745 |
+
[[noreturn]] static void nameless_argument_error(const std::string &type) {
|
1746 |
+
throw type_error("Got kwargs without a name of type '" + type
|
1747 |
+
+ "'; only named "
|
1748 |
+
"arguments may be passed via py::arg() to a python function call. ");
|
1749 |
+
}
|
1750 |
+
[[noreturn]] static void multiple_values_error() {
|
1751 |
+
throw type_error(
|
1752 |
+
"Got multiple values for keyword argument "
|
1753 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
|
1754 |
+
}
|
1755 |
+
|
1756 |
+
[[noreturn]] static void multiple_values_error(const std::string &name) {
|
1757 |
+
throw type_error("Got multiple values for keyword argument '" + name + "'");
|
1758 |
+
}
|
1759 |
+
|
1760 |
+
private:
|
1761 |
+
tuple m_args;
|
1762 |
+
dict m_kwargs;
|
1763 |
+
};
|
1764 |
+
|
1765 |
+
// [workaround(intel)] Separate function required here
|
1766 |
+
// We need to put this into a separate function because the Intel compiler
|
1767 |
+
// fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
|
1768 |
+
// (tested with ICC 2021.1 Beta 20200827).
|
1769 |
+
template <typename... Args>
|
1770 |
+
constexpr bool args_are_all_positional() {
|
1771 |
+
return all_of<is_positional<Args>...>::value;
|
1772 |
+
}
|
1773 |
+
|
1774 |
+
/// Collect only positional arguments for a Python function call
|
1775 |
+
template <return_value_policy policy,
|
1776 |
+
typename... Args,
|
1777 |
+
typename = enable_if_t<args_are_all_positional<Args...>()>>
|
1778 |
+
simple_collector<policy> collect_arguments(Args &&...args) {
|
1779 |
+
return simple_collector<policy>(std::forward<Args>(args)...);
|
1780 |
+
}
|
1781 |
+
|
1782 |
+
/// Collect all arguments, including keywords and unpacking (only instantiated when needed)
|
1783 |
+
template <return_value_policy policy,
|
1784 |
+
typename... Args,
|
1785 |
+
typename = enable_if_t<!args_are_all_positional<Args...>()>>
|
1786 |
+
unpacking_collector<policy> collect_arguments(Args &&...args) {
|
1787 |
+
// Following argument order rules for generalized unpacking according to PEP 448
|
1788 |
+
static_assert(constexpr_last<is_positional, Args...>()
|
1789 |
+
< constexpr_first<is_keyword_or_ds, Args...>()
|
1790 |
+
&& constexpr_last<is_s_unpacking, Args...>()
|
1791 |
+
< constexpr_first<is_ds_unpacking, Args...>(),
|
1792 |
+
"Invalid function call: positional args must precede keywords and ** unpacking; "
|
1793 |
+
"* unpacking must precede ** unpacking");
|
1794 |
+
return unpacking_collector<policy>(std::forward<Args>(args)...);
|
1795 |
+
}
|
1796 |
+
|
1797 |
+
template <typename Derived>
|
1798 |
+
template <return_value_policy policy, typename... Args>
|
1799 |
+
object object_api<Derived>::operator()(Args &&...args) const {
|
1800 |
+
#ifndef NDEBUG
|
1801 |
+
if (!PyGILState_Check()) {
|
1802 |
+
pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
|
1803 |
+
}
|
1804 |
+
#endif
|
1805 |
+
return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
|
1806 |
+
}
|
1807 |
+
|
1808 |
+
template <typename Derived>
|
1809 |
+
template <return_value_policy policy, typename... Args>
|
1810 |
+
object object_api<Derived>::call(Args &&...args) const {
|
1811 |
+
return operator()<policy>(std::forward<Args>(args)...);
|
1812 |
+
}
|
1813 |
+
|
1814 |
+
PYBIND11_NAMESPACE_END(detail)
|
1815 |
+
|
1816 |
+
template <typename T>
|
1817 |
+
handle type::handle_of() {
|
1818 |
+
static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
|
1819 |
+
"py::type::of<T> only supports the case where T is a registered C++ types.");
|
1820 |
+
|
1821 |
+
return detail::get_type_handle(typeid(T), true);
|
1822 |
+
}
|
1823 |
+
|
1824 |
+
#define PYBIND11_MAKE_OPAQUE(...) \
|
1825 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
|
1826 |
+
namespace detail { \
|
1827 |
+
template <> \
|
1828 |
+
class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
|
1829 |
+
} \
|
1830 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
1831 |
+
|
1832 |
+
/// Lets you pass a type containing a `,` through a macro parameter without needing a separate
|
1833 |
+
/// typedef, e.g.:
|
1834 |
+
/// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
|
1835 |
+
#define PYBIND11_TYPE(...) __VA_ARGS__
|
1836 |
+
|
1837 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h
ADDED
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime
|
3 |
+
|
4 |
+
Copyright (c) 2016 Trent Houliston <[email protected]> and
|
5 |
+
Wenzel Jakob <[email protected]>
|
6 |
+
|
7 |
+
All rights reserved. Use of this source code is governed by a
|
8 |
+
BSD-style license that can be found in the LICENSE file.
|
9 |
+
*/
|
10 |
+
|
11 |
+
#pragma once
|
12 |
+
|
13 |
+
#include "pybind11.h"
|
14 |
+
|
15 |
+
#include <chrono>
|
16 |
+
#include <cmath>
|
17 |
+
#include <ctime>
|
18 |
+
#include <datetime.h>
|
19 |
+
#include <mutex>
|
20 |
+
|
21 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
22 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
23 |
+
|
24 |
+
template <typename type>
|
25 |
+
class duration_caster {
|
26 |
+
public:
|
27 |
+
using rep = typename type::rep;
|
28 |
+
using period = typename type::period;
|
29 |
+
|
30 |
+
// signed 25 bits required by the standard.
|
31 |
+
using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
|
32 |
+
|
33 |
+
bool load(handle src, bool) {
|
34 |
+
using namespace std::chrono;
|
35 |
+
|
36 |
+
// Lazy initialise the PyDateTime import
|
37 |
+
if (!PyDateTimeAPI) {
|
38 |
+
PyDateTime_IMPORT;
|
39 |
+
}
|
40 |
+
|
41 |
+
if (!src) {
|
42 |
+
return false;
|
43 |
+
}
|
44 |
+
// If invoked with datetime.delta object
|
45 |
+
if (PyDelta_Check(src.ptr())) {
|
46 |
+
value = type(duration_cast<duration<rep, period>>(
|
47 |
+
days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
|
48 |
+
+ seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
|
49 |
+
+ microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
|
50 |
+
return true;
|
51 |
+
}
|
52 |
+
// If invoked with a float we assume it is seconds and convert
|
53 |
+
if (PyFloat_Check(src.ptr())) {
|
54 |
+
value = type(duration_cast<duration<rep, period>>(
|
55 |
+
duration<double>(PyFloat_AsDouble(src.ptr()))));
|
56 |
+
return true;
|
57 |
+
}
|
58 |
+
return false;
|
59 |
+
}
|
60 |
+
|
61 |
+
// If this is a duration just return it back
|
62 |
+
static const std::chrono::duration<rep, period> &
|
63 |
+
get_duration(const std::chrono::duration<rep, period> &src) {
|
64 |
+
return src;
|
65 |
+
}
|
66 |
+
|
67 |
+
// If this is a time_point get the time_since_epoch
|
68 |
+
template <typename Clock>
|
69 |
+
static std::chrono::duration<rep, period>
|
70 |
+
get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
|
71 |
+
return src.time_since_epoch();
|
72 |
+
}
|
73 |
+
|
74 |
+
static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
|
75 |
+
using namespace std::chrono;
|
76 |
+
|
77 |
+
// Use overloaded function to get our duration from our source
|
78 |
+
// Works out if it is a duration or time_point and get the duration
|
79 |
+
auto d = get_duration(src);
|
80 |
+
|
81 |
+
// Lazy initialise the PyDateTime import
|
82 |
+
if (!PyDateTimeAPI) {
|
83 |
+
PyDateTime_IMPORT;
|
84 |
+
}
|
85 |
+
|
86 |
+
// Declare these special duration types so the conversions happen with the correct
|
87 |
+
// primitive types (int)
|
88 |
+
using dd_t = duration<int, std::ratio<86400>>;
|
89 |
+
using ss_t = duration<int, std::ratio<1>>;
|
90 |
+
using us_t = duration<int, std::micro>;
|
91 |
+
|
92 |
+
auto dd = duration_cast<dd_t>(d);
|
93 |
+
auto subd = d - dd;
|
94 |
+
auto ss = duration_cast<ss_t>(subd);
|
95 |
+
auto us = duration_cast<us_t>(subd - ss);
|
96 |
+
return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
|
97 |
+
}
|
98 |
+
|
99 |
+
PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
|
100 |
+
};
|
101 |
+
|
102 |
+
inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
|
103 |
+
#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
|
104 |
+
if (localtime_s(buf, time))
|
105 |
+
return nullptr;
|
106 |
+
return buf;
|
107 |
+
#else
|
108 |
+
static std::mutex mtx;
|
109 |
+
std::lock_guard<std::mutex> lock(mtx);
|
110 |
+
std::tm *tm_ptr = std::localtime(time);
|
111 |
+
if (tm_ptr != nullptr) {
|
112 |
+
*buf = *tm_ptr;
|
113 |
+
}
|
114 |
+
return tm_ptr;
|
115 |
+
#endif
|
116 |
+
}
|
117 |
+
|
118 |
+
// This is for casting times on the system clock into datetime.datetime instances
|
119 |
+
template <typename Duration>
|
120 |
+
class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
|
121 |
+
public:
|
122 |
+
using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
|
123 |
+
bool load(handle src, bool) {
|
124 |
+
using namespace std::chrono;
|
125 |
+
|
126 |
+
// Lazy initialise the PyDateTime import
|
127 |
+
if (!PyDateTimeAPI) {
|
128 |
+
PyDateTime_IMPORT;
|
129 |
+
}
|
130 |
+
|
131 |
+
if (!src) {
|
132 |
+
return false;
|
133 |
+
}
|
134 |
+
|
135 |
+
std::tm cal;
|
136 |
+
microseconds msecs;
|
137 |
+
|
138 |
+
if (PyDateTime_Check(src.ptr())) {
|
139 |
+
cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
|
140 |
+
cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
|
141 |
+
cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
|
142 |
+
cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
|
143 |
+
cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
|
144 |
+
cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
|
145 |
+
cal.tm_isdst = -1;
|
146 |
+
msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
|
147 |
+
} else if (PyDate_Check(src.ptr())) {
|
148 |
+
cal.tm_sec = 0;
|
149 |
+
cal.tm_min = 0;
|
150 |
+
cal.tm_hour = 0;
|
151 |
+
cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
|
152 |
+
cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
|
153 |
+
cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
|
154 |
+
cal.tm_isdst = -1;
|
155 |
+
msecs = microseconds(0);
|
156 |
+
} else if (PyTime_Check(src.ptr())) {
|
157 |
+
cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
|
158 |
+
cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
|
159 |
+
cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
|
160 |
+
cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
|
161 |
+
cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
|
162 |
+
cal.tm_year = 70; // earliest available date for Python's datetime
|
163 |
+
cal.tm_isdst = -1;
|
164 |
+
msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
|
165 |
+
} else {
|
166 |
+
return false;
|
167 |
+
}
|
168 |
+
|
169 |
+
value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
|
170 |
+
return true;
|
171 |
+
}
|
172 |
+
|
173 |
+
static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
|
174 |
+
return_value_policy /* policy */,
|
175 |
+
handle /* parent */) {
|
176 |
+
using namespace std::chrono;
|
177 |
+
|
178 |
+
// Lazy initialise the PyDateTime import
|
179 |
+
if (!PyDateTimeAPI) {
|
180 |
+
PyDateTime_IMPORT;
|
181 |
+
}
|
182 |
+
|
183 |
+
// Get out microseconds, and make sure they are positive, to avoid bug in eastern
|
184 |
+
// hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
|
185 |
+
using us_t = duration<int, std::micro>;
|
186 |
+
auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
|
187 |
+
if (us.count() < 0) {
|
188 |
+
us += seconds(1);
|
189 |
+
}
|
190 |
+
|
191 |
+
// Subtract microseconds BEFORE `system_clock::to_time_t`, because:
|
192 |
+
// > If std::time_t has lower precision, it is implementation-defined whether the value is
|
193 |
+
// rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
|
194 |
+
std::time_t tt
|
195 |
+
= system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
|
196 |
+
|
197 |
+
std::tm localtime;
|
198 |
+
std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
|
199 |
+
if (!localtime_ptr) {
|
200 |
+
throw cast_error("Unable to represent system_clock in local time");
|
201 |
+
}
|
202 |
+
return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
|
203 |
+
localtime.tm_mon + 1,
|
204 |
+
localtime.tm_mday,
|
205 |
+
localtime.tm_hour,
|
206 |
+
localtime.tm_min,
|
207 |
+
localtime.tm_sec,
|
208 |
+
us.count());
|
209 |
+
}
|
210 |
+
PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
|
211 |
+
};
|
212 |
+
|
213 |
+
// Other clocks that are not the system clock are not measured as datetime.datetime objects
|
214 |
+
// since they are not measured on calendar time. So instead we just make them timedeltas
|
215 |
+
// Or if they have passed us a time as a float we convert that
|
216 |
+
template <typename Clock, typename Duration>
|
217 |
+
class type_caster<std::chrono::time_point<Clock, Duration>>
|
218 |
+
: public duration_caster<std::chrono::time_point<Clock, Duration>> {};
|
219 |
+
|
220 |
+
template <typename Rep, typename Period>
|
221 |
+
class type_caster<std::chrono::duration<Rep, Period>>
|
222 |
+
: public duration_caster<std::chrono::duration<Rep, Period>> {};
|
223 |
+
|
224 |
+
PYBIND11_NAMESPACE_END(detail)
|
225 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/common.h
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
#include "detail/common.h"
|
2 |
+
#warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'."
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/complex.h
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/complex.h: Complex number support
|
3 |
+
|
4 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "pybind11.h"
|
13 |
+
|
14 |
+
#include <complex>
|
15 |
+
|
16 |
+
/// glibc defines I as a macro which breaks things, e.g., boost template names
|
17 |
+
#ifdef I
|
18 |
+
# undef I
|
19 |
+
#endif
|
20 |
+
|
21 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
22 |
+
|
23 |
+
template <typename T>
|
24 |
+
struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
|
25 |
+
static constexpr const char c = format_descriptor<T>::c;
|
26 |
+
static constexpr const char value[3] = {'Z', c, '\0'};
|
27 |
+
static std::string format() { return std::string(value); }
|
28 |
+
};
|
29 |
+
|
30 |
+
#ifndef PYBIND11_CPP17
|
31 |
+
|
32 |
+
template <typename T>
|
33 |
+
constexpr const char
|
34 |
+
format_descriptor<std::complex<T>,
|
35 |
+
detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
|
36 |
+
|
37 |
+
#endif
|
38 |
+
|
39 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
40 |
+
|
41 |
+
template <typename T>
|
42 |
+
struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
|
43 |
+
static constexpr bool value = true;
|
44 |
+
static constexpr int index = is_fmt_numeric<T>::index + 3;
|
45 |
+
};
|
46 |
+
|
47 |
+
template <typename T>
|
48 |
+
class type_caster<std::complex<T>> {
|
49 |
+
public:
|
50 |
+
bool load(handle src, bool convert) {
|
51 |
+
if (!src) {
|
52 |
+
return false;
|
53 |
+
}
|
54 |
+
if (!convert && !PyComplex_Check(src.ptr())) {
|
55 |
+
return false;
|
56 |
+
}
|
57 |
+
Py_complex result = PyComplex_AsCComplex(src.ptr());
|
58 |
+
if (result.real == -1.0 && PyErr_Occurred()) {
|
59 |
+
PyErr_Clear();
|
60 |
+
return false;
|
61 |
+
}
|
62 |
+
value = std::complex<T>((T) result.real, (T) result.imag);
|
63 |
+
return true;
|
64 |
+
}
|
65 |
+
|
66 |
+
static handle
|
67 |
+
cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
|
68 |
+
return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
|
69 |
+
}
|
70 |
+
|
71 |
+
PYBIND11_TYPE_CASTER(std::complex<T>, const_name("complex"));
|
72 |
+
};
|
73 |
+
PYBIND11_NAMESPACE_END(detail)
|
74 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/class.h
ADDED
@@ -0,0 +1,748 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/detail/class.h: Python C API implementation details for py::class_
|
3 |
+
|
4 |
+
Copyright (c) 2017 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "../attr.h"
|
13 |
+
#include "../options.h"
|
14 |
+
|
15 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
16 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
17 |
+
|
18 |
+
#if !defined(PYPY_VERSION)
|
19 |
+
# define PYBIND11_BUILTIN_QUALNAME
|
20 |
+
# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
|
21 |
+
#else
|
22 |
+
// In PyPy, we still set __qualname__ so that we can produce reliable function type
|
23 |
+
// signatures; in CPython this macro expands to nothing:
|
24 |
+
# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
|
25 |
+
setattr((PyObject *) obj, "__qualname__", nameobj)
|
26 |
+
#endif
|
27 |
+
|
28 |
+
inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
|
29 |
+
#if !defined(PYPY_VERSION)
|
30 |
+
return type->tp_name;
|
31 |
+
#else
|
32 |
+
auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
|
33 |
+
if (module_name == PYBIND11_BUILTINS_MODULE)
|
34 |
+
return type->tp_name;
|
35 |
+
else
|
36 |
+
return std::move(module_name) + "." + type->tp_name;
|
37 |
+
#endif
|
38 |
+
}
|
39 |
+
|
40 |
+
inline PyTypeObject *type_incref(PyTypeObject *type) {
|
41 |
+
Py_INCREF(type);
|
42 |
+
return type;
|
43 |
+
}
|
44 |
+
|
45 |
+
#if !defined(PYPY_VERSION)
|
46 |
+
|
47 |
+
/// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
|
48 |
+
extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
|
49 |
+
return PyProperty_Type.tp_descr_get(self, cls, cls);
|
50 |
+
}
|
51 |
+
|
52 |
+
/// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
|
53 |
+
extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
|
54 |
+
PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
|
55 |
+
return PyProperty_Type.tp_descr_set(self, cls, value);
|
56 |
+
}
|
57 |
+
|
58 |
+
// Forward declaration to use in `make_static_property_type()`
|
59 |
+
inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
|
60 |
+
|
61 |
+
/** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
|
62 |
+
methods are modified to always use the object type instead of a concrete instance.
|
63 |
+
Return value: New reference. */
|
64 |
+
inline PyTypeObject *make_static_property_type() {
|
65 |
+
constexpr auto *name = "pybind11_static_property";
|
66 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
67 |
+
|
68 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
69 |
+
issue no Python C API calls which could potentially invoke the
|
70 |
+
garbage collector (the GC will call type_traverse(), which will in
|
71 |
+
turn find the newly constructed type in an invalid state) */
|
72 |
+
auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
|
73 |
+
if (!heap_type) {
|
74 |
+
pybind11_fail("make_static_property_type(): error allocating type!");
|
75 |
+
}
|
76 |
+
|
77 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
78 |
+
# ifdef PYBIND11_BUILTIN_QUALNAME
|
79 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
80 |
+
# endif
|
81 |
+
|
82 |
+
auto *type = &heap_type->ht_type;
|
83 |
+
type->tp_name = name;
|
84 |
+
type->tp_base = type_incref(&PyProperty_Type);
|
85 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
86 |
+
type->tp_descr_get = pybind11_static_get;
|
87 |
+
type->tp_descr_set = pybind11_static_set;
|
88 |
+
|
89 |
+
# if PY_VERSION_HEX >= 0x030C0000
|
90 |
+
// Since Python-3.12 property-derived types are required to
|
91 |
+
// have dynamic attributes (to set `__doc__`)
|
92 |
+
enable_dynamic_attributes(heap_type);
|
93 |
+
# endif
|
94 |
+
|
95 |
+
if (PyType_Ready(type) < 0) {
|
96 |
+
pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
|
97 |
+
}
|
98 |
+
|
99 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
100 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
101 |
+
|
102 |
+
return type;
|
103 |
+
}
|
104 |
+
|
105 |
+
#else // PYPY
|
106 |
+
|
107 |
+
/** PyPy has some issues with the above C API, so we evaluate Python code instead.
|
108 |
+
This function will only be called once so performance isn't really a concern.
|
109 |
+
Return value: New reference. */
|
110 |
+
inline PyTypeObject *make_static_property_type() {
|
111 |
+
auto d = dict();
|
112 |
+
PyObject *result = PyRun_String(R"(\
|
113 |
+
class pybind11_static_property(property):
|
114 |
+
def __get__(self, obj, cls):
|
115 |
+
return property.__get__(self, cls, cls)
|
116 |
+
|
117 |
+
def __set__(self, obj, value):
|
118 |
+
cls = obj if isinstance(obj, type) else type(obj)
|
119 |
+
property.__set__(self, cls, value)
|
120 |
+
)",
|
121 |
+
Py_file_input,
|
122 |
+
d.ptr(),
|
123 |
+
d.ptr());
|
124 |
+
if (result == nullptr)
|
125 |
+
throw error_already_set();
|
126 |
+
Py_DECREF(result);
|
127 |
+
return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
|
128 |
+
}
|
129 |
+
|
130 |
+
#endif // PYPY
|
131 |
+
|
132 |
+
/** Types with static properties need to handle `Type.static_prop = x` in a specific way.
|
133 |
+
By default, Python replaces the `static_property` itself, but for wrapped C++ types
|
134 |
+
we need to call `static_property.__set__()` in order to propagate the new value to
|
135 |
+
the underlying C++ data structure. */
|
136 |
+
extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
|
137 |
+
// Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
|
138 |
+
// descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
|
139 |
+
PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
|
140 |
+
|
141 |
+
// The following assignment combinations are possible:
|
142 |
+
// 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
|
143 |
+
// 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
|
144 |
+
// 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
|
145 |
+
auto *const static_prop = (PyObject *) get_internals().static_property_type;
|
146 |
+
const auto call_descr_set = (descr != nullptr) && (value != nullptr)
|
147 |
+
&& (PyObject_IsInstance(descr, static_prop) != 0)
|
148 |
+
&& (PyObject_IsInstance(value, static_prop) == 0);
|
149 |
+
if (call_descr_set) {
|
150 |
+
// Call `static_property.__set__()` instead of replacing the `static_property`.
|
151 |
+
#if !defined(PYPY_VERSION)
|
152 |
+
return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
|
153 |
+
#else
|
154 |
+
if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
|
155 |
+
Py_DECREF(result);
|
156 |
+
return 0;
|
157 |
+
} else {
|
158 |
+
return -1;
|
159 |
+
}
|
160 |
+
#endif
|
161 |
+
} else {
|
162 |
+
// Replace existing attribute.
|
163 |
+
return PyType_Type.tp_setattro(obj, name, value);
|
164 |
+
}
|
165 |
+
}
|
166 |
+
|
167 |
+
/**
|
168 |
+
* Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
|
169 |
+
* methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
|
170 |
+
* when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
|
171 |
+
* to do a special case bypass for PyInstanceMethod_Types.
|
172 |
+
*/
|
173 |
+
extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
|
174 |
+
PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
|
175 |
+
if (descr && PyInstanceMethod_Check(descr)) {
|
176 |
+
Py_INCREF(descr);
|
177 |
+
return descr;
|
178 |
+
}
|
179 |
+
return PyType_Type.tp_getattro(obj, name);
|
180 |
+
}
|
181 |
+
|
182 |
+
/// metaclass `__call__` function that is used to create all pybind11 objects.
|
183 |
+
extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
|
184 |
+
|
185 |
+
// use the default metaclass call to create/initialize the object
|
186 |
+
PyObject *self = PyType_Type.tp_call(type, args, kwargs);
|
187 |
+
if (self == nullptr) {
|
188 |
+
return nullptr;
|
189 |
+
}
|
190 |
+
|
191 |
+
// Ensure that the base __init__ function(s) were called
|
192 |
+
values_and_holders vhs(self);
|
193 |
+
for (const auto &vh : vhs) {
|
194 |
+
if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {
|
195 |
+
PyErr_Format(PyExc_TypeError,
|
196 |
+
"%.200s.__init__() must be called when overriding __init__",
|
197 |
+
get_fully_qualified_tp_name(vh.type->type).c_str());
|
198 |
+
Py_DECREF(self);
|
199 |
+
return nullptr;
|
200 |
+
}
|
201 |
+
}
|
202 |
+
|
203 |
+
return self;
|
204 |
+
}
|
205 |
+
|
206 |
+
/// Cleanup the type-info for a pybind11-registered type.
|
207 |
+
extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
|
208 |
+
auto *type = (PyTypeObject *) obj;
|
209 |
+
auto &internals = get_internals();
|
210 |
+
|
211 |
+
// A pybind11-registered type will:
|
212 |
+
// 1) be found in internals.registered_types_py
|
213 |
+
// 2) have exactly one associated `detail::type_info`
|
214 |
+
auto found_type = internals.registered_types_py.find(type);
|
215 |
+
if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
|
216 |
+
&& found_type->second[0]->type == type) {
|
217 |
+
|
218 |
+
auto *tinfo = found_type->second[0];
|
219 |
+
auto tindex = std::type_index(*tinfo->cpptype);
|
220 |
+
internals.direct_conversions.erase(tindex);
|
221 |
+
|
222 |
+
if (tinfo->module_local) {
|
223 |
+
get_local_internals().registered_types_cpp.erase(tindex);
|
224 |
+
} else {
|
225 |
+
internals.registered_types_cpp.erase(tindex);
|
226 |
+
}
|
227 |
+
internals.registered_types_py.erase(tinfo->type);
|
228 |
+
|
229 |
+
// Actually just `std::erase_if`, but that's only available in C++20
|
230 |
+
auto &cache = internals.inactive_override_cache;
|
231 |
+
for (auto it = cache.begin(), last = cache.end(); it != last;) {
|
232 |
+
if (it->first == (PyObject *) tinfo->type) {
|
233 |
+
it = cache.erase(it);
|
234 |
+
} else {
|
235 |
+
++it;
|
236 |
+
}
|
237 |
+
}
|
238 |
+
|
239 |
+
delete tinfo;
|
240 |
+
}
|
241 |
+
|
242 |
+
PyType_Type.tp_dealloc(obj);
|
243 |
+
}
|
244 |
+
|
245 |
+
/** This metaclass is assigned by default to all pybind11 types and is required in order
|
246 |
+
for static properties to function correctly. Users may override this using `py::metaclass`.
|
247 |
+
Return value: New reference. */
|
248 |
+
inline PyTypeObject *make_default_metaclass() {
|
249 |
+
constexpr auto *name = "pybind11_type";
|
250 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
251 |
+
|
252 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
253 |
+
issue no Python C API calls which could potentially invoke the
|
254 |
+
garbage collector (the GC will call type_traverse(), which will in
|
255 |
+
turn find the newly constructed type in an invalid state) */
|
256 |
+
auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
|
257 |
+
if (!heap_type) {
|
258 |
+
pybind11_fail("make_default_metaclass(): error allocating metaclass!");
|
259 |
+
}
|
260 |
+
|
261 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
262 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
263 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
264 |
+
#endif
|
265 |
+
|
266 |
+
auto *type = &heap_type->ht_type;
|
267 |
+
type->tp_name = name;
|
268 |
+
type->tp_base = type_incref(&PyType_Type);
|
269 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
270 |
+
|
271 |
+
type->tp_call = pybind11_meta_call;
|
272 |
+
|
273 |
+
type->tp_setattro = pybind11_meta_setattro;
|
274 |
+
type->tp_getattro = pybind11_meta_getattro;
|
275 |
+
|
276 |
+
type->tp_dealloc = pybind11_meta_dealloc;
|
277 |
+
|
278 |
+
if (PyType_Ready(type) < 0) {
|
279 |
+
pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
|
280 |
+
}
|
281 |
+
|
282 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
283 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
284 |
+
|
285 |
+
return type;
|
286 |
+
}
|
287 |
+
|
288 |
+
/// For multiple inheritance types we need to recursively register/deregister base pointers for any
|
289 |
+
/// base classes with pointers that are difference from the instance value pointer so that we can
|
290 |
+
/// correctly recognize an offset base class pointer. This calls a function with any offset base
|
291 |
+
/// ptrs.
|
292 |
+
inline void traverse_offset_bases(void *valueptr,
|
293 |
+
const detail::type_info *tinfo,
|
294 |
+
instance *self,
|
295 |
+
bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
|
296 |
+
for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
|
297 |
+
if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
|
298 |
+
for (auto &c : parent_tinfo->implicit_casts) {
|
299 |
+
if (c.first == tinfo->cpptype) {
|
300 |
+
auto *parentptr = c.second(valueptr);
|
301 |
+
if (parentptr != valueptr) {
|
302 |
+
f(parentptr, self);
|
303 |
+
}
|
304 |
+
traverse_offset_bases(parentptr, parent_tinfo, self, f);
|
305 |
+
break;
|
306 |
+
}
|
307 |
+
}
|
308 |
+
}
|
309 |
+
}
|
310 |
+
}
|
311 |
+
|
312 |
+
inline bool register_instance_impl(void *ptr, instance *self) {
|
313 |
+
get_internals().registered_instances.emplace(ptr, self);
|
314 |
+
return true; // unused, but gives the same signature as the deregister func
|
315 |
+
}
|
316 |
+
inline bool deregister_instance_impl(void *ptr, instance *self) {
|
317 |
+
auto ®istered_instances = get_internals().registered_instances;
|
318 |
+
auto range = registered_instances.equal_range(ptr);
|
319 |
+
for (auto it = range.first; it != range.second; ++it) {
|
320 |
+
if (self == it->second) {
|
321 |
+
registered_instances.erase(it);
|
322 |
+
return true;
|
323 |
+
}
|
324 |
+
}
|
325 |
+
return false;
|
326 |
+
}
|
327 |
+
|
328 |
+
inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
|
329 |
+
register_instance_impl(valptr, self);
|
330 |
+
if (!tinfo->simple_ancestors) {
|
331 |
+
traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
|
332 |
+
}
|
333 |
+
}
|
334 |
+
|
335 |
+
inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
|
336 |
+
bool ret = deregister_instance_impl(valptr, self);
|
337 |
+
if (!tinfo->simple_ancestors) {
|
338 |
+
traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
|
339 |
+
}
|
340 |
+
return ret;
|
341 |
+
}
|
342 |
+
|
343 |
+
/// Instance creation function for all pybind11 types. It allocates the internal instance layout
|
344 |
+
/// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
|
345 |
+
/// cast to a reference or pointer), and initialization is done by an `__init__` function.
|
346 |
+
inline PyObject *make_new_instance(PyTypeObject *type) {
|
347 |
+
#if defined(PYPY_VERSION)
|
348 |
+
// PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
|
349 |
+
// inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
|
350 |
+
ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
|
351 |
+
if (type->tp_basicsize < instance_size) {
|
352 |
+
type->tp_basicsize = instance_size;
|
353 |
+
}
|
354 |
+
#endif
|
355 |
+
PyObject *self = type->tp_alloc(type, 0);
|
356 |
+
auto *inst = reinterpret_cast<instance *>(self);
|
357 |
+
// Allocate the value/holder internals:
|
358 |
+
inst->allocate_layout();
|
359 |
+
|
360 |
+
return self;
|
361 |
+
}
|
362 |
+
|
363 |
+
/// Instance creation function for all pybind11 types. It only allocates space for the
|
364 |
+
/// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
|
365 |
+
extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
|
366 |
+
return make_new_instance(type);
|
367 |
+
}
|
368 |
+
|
369 |
+
/// An `__init__` function constructs the C++ object. Users should provide at least one
|
370 |
+
/// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
|
371 |
+
/// following default function will be used which simply throws an exception.
|
372 |
+
extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
|
373 |
+
PyTypeObject *type = Py_TYPE(self);
|
374 |
+
std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
|
375 |
+
set_error(PyExc_TypeError, msg.c_str());
|
376 |
+
return -1;
|
377 |
+
}
|
378 |
+
|
379 |
+
inline void add_patient(PyObject *nurse, PyObject *patient) {
|
380 |
+
auto &internals = get_internals();
|
381 |
+
auto *instance = reinterpret_cast<detail::instance *>(nurse);
|
382 |
+
instance->has_patients = true;
|
383 |
+
Py_INCREF(patient);
|
384 |
+
internals.patients[nurse].push_back(patient);
|
385 |
+
}
|
386 |
+
|
387 |
+
inline void clear_patients(PyObject *self) {
|
388 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
389 |
+
auto &internals = get_internals();
|
390 |
+
auto pos = internals.patients.find(self);
|
391 |
+
assert(pos != internals.patients.end());
|
392 |
+
// Clearing the patients can cause more Python code to run, which
|
393 |
+
// can invalidate the iterator. Extract the vector of patients
|
394 |
+
// from the unordered_map first.
|
395 |
+
auto patients = std::move(pos->second);
|
396 |
+
internals.patients.erase(pos);
|
397 |
+
instance->has_patients = false;
|
398 |
+
for (PyObject *&patient : patients) {
|
399 |
+
Py_CLEAR(patient);
|
400 |
+
}
|
401 |
+
}
|
402 |
+
|
403 |
+
/// Clears all internal data from the instance and removes it from registered instances in
|
404 |
+
/// preparation for deallocation.
|
405 |
+
inline void clear_instance(PyObject *self) {
|
406 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
407 |
+
|
408 |
+
// Deallocate any values/holders, if present:
|
409 |
+
for (auto &v_h : values_and_holders(instance)) {
|
410 |
+
if (v_h) {
|
411 |
+
|
412 |
+
// We have to deregister before we call dealloc because, for virtual MI types, we still
|
413 |
+
// need to be able to get the parent pointers.
|
414 |
+
if (v_h.instance_registered()
|
415 |
+
&& !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
|
416 |
+
pybind11_fail(
|
417 |
+
"pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
|
418 |
+
}
|
419 |
+
|
420 |
+
if (instance->owned || v_h.holder_constructed()) {
|
421 |
+
v_h.type->dealloc(v_h);
|
422 |
+
}
|
423 |
+
}
|
424 |
+
}
|
425 |
+
// Deallocate the value/holder layout internals:
|
426 |
+
instance->deallocate_layout();
|
427 |
+
|
428 |
+
if (instance->weakrefs) {
|
429 |
+
PyObject_ClearWeakRefs(self);
|
430 |
+
}
|
431 |
+
|
432 |
+
PyObject **dict_ptr = _PyObject_GetDictPtr(self);
|
433 |
+
if (dict_ptr) {
|
434 |
+
Py_CLEAR(*dict_ptr);
|
435 |
+
}
|
436 |
+
|
437 |
+
if (instance->has_patients) {
|
438 |
+
clear_patients(self);
|
439 |
+
}
|
440 |
+
}
|
441 |
+
|
442 |
+
/// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
|
443 |
+
/// to destroy the C++ object itself, while the rest is Python bookkeeping.
|
444 |
+
extern "C" inline void pybind11_object_dealloc(PyObject *self) {
|
445 |
+
auto *type = Py_TYPE(self);
|
446 |
+
|
447 |
+
// If this is a GC tracked object, untrack it first
|
448 |
+
// Note that the track call is implicitly done by the
|
449 |
+
// default tp_alloc, which we never override.
|
450 |
+
if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
|
451 |
+
PyObject_GC_UnTrack(self);
|
452 |
+
}
|
453 |
+
|
454 |
+
clear_instance(self);
|
455 |
+
|
456 |
+
type->tp_free(self);
|
457 |
+
|
458 |
+
#if PY_VERSION_HEX < 0x03080000
|
459 |
+
// `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
|
460 |
+
// as part of a derived type's dealloc, in which case we're not allowed to decref
|
461 |
+
// the type here. For cross-module compatibility, we shouldn't compare directly
|
462 |
+
// with `pybind11_object_dealloc`, but with the common one stashed in internals.
|
463 |
+
auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
|
464 |
+
if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
|
465 |
+
Py_DECREF(type);
|
466 |
+
#else
|
467 |
+
// This was not needed before Python 3.8 (Python issue 35810)
|
468 |
+
// https://github.com/pybind/pybind11/issues/1946
|
469 |
+
Py_DECREF(type);
|
470 |
+
#endif
|
471 |
+
}
|
472 |
+
|
473 |
+
std::string error_string();
|
474 |
+
|
475 |
+
/** Create the type which can be used as a common base for all classes. This is
|
476 |
+
needed in order to satisfy Python's requirements for multiple inheritance.
|
477 |
+
Return value: New reference. */
|
478 |
+
inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
|
479 |
+
constexpr auto *name = "pybind11_object";
|
480 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
481 |
+
|
482 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
483 |
+
issue no Python C API calls which could potentially invoke the
|
484 |
+
garbage collector (the GC will call type_traverse(), which will in
|
485 |
+
turn find the newly constructed type in an invalid state) */
|
486 |
+
auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
|
487 |
+
if (!heap_type) {
|
488 |
+
pybind11_fail("make_object_base_type(): error allocating type!");
|
489 |
+
}
|
490 |
+
|
491 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
492 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
493 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
494 |
+
#endif
|
495 |
+
|
496 |
+
auto *type = &heap_type->ht_type;
|
497 |
+
type->tp_name = name;
|
498 |
+
type->tp_base = type_incref(&PyBaseObject_Type);
|
499 |
+
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
|
500 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
501 |
+
|
502 |
+
type->tp_new = pybind11_object_new;
|
503 |
+
type->tp_init = pybind11_object_init;
|
504 |
+
type->tp_dealloc = pybind11_object_dealloc;
|
505 |
+
|
506 |
+
/* Support weak references (needed for the keep_alive feature) */
|
507 |
+
type->tp_weaklistoffset = offsetof(instance, weakrefs);
|
508 |
+
|
509 |
+
if (PyType_Ready(type) < 0) {
|
510 |
+
pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
|
511 |
+
}
|
512 |
+
|
513 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
514 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
515 |
+
|
516 |
+
assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
|
517 |
+
return (PyObject *) heap_type;
|
518 |
+
}
|
519 |
+
|
520 |
+
/// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
|
521 |
+
extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
|
522 |
+
#if PY_VERSION_HEX >= 0x030D0000
|
523 |
+
PyObject_VisitManagedDict(self, visit, arg);
|
524 |
+
#else
|
525 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
526 |
+
Py_VISIT(dict);
|
527 |
+
#endif
|
528 |
+
// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
|
529 |
+
#if PY_VERSION_HEX >= 0x03090000
|
530 |
+
Py_VISIT(Py_TYPE(self));
|
531 |
+
#endif
|
532 |
+
return 0;
|
533 |
+
}
|
534 |
+
|
535 |
+
/// dynamic_attr: Allow the GC to clear the dictionary.
|
536 |
+
extern "C" inline int pybind11_clear(PyObject *self) {
|
537 |
+
#if PY_VERSION_HEX >= 0x030D0000
|
538 |
+
PyObject_ClearManagedDict(self);
|
539 |
+
#else
|
540 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
541 |
+
Py_CLEAR(dict);
|
542 |
+
#endif
|
543 |
+
return 0;
|
544 |
+
}
|
545 |
+
|
546 |
+
/// Give instances of this type a `__dict__` and opt into garbage collection.
|
547 |
+
inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
|
548 |
+
auto *type = &heap_type->ht_type;
|
549 |
+
type->tp_flags |= Py_TPFLAGS_HAVE_GC;
|
550 |
+
#if PY_VERSION_HEX < 0x030B0000
|
551 |
+
type->tp_dictoffset = type->tp_basicsize; // place dict at the end
|
552 |
+
type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
|
553 |
+
#else
|
554 |
+
type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
|
555 |
+
#endif
|
556 |
+
type->tp_traverse = pybind11_traverse;
|
557 |
+
type->tp_clear = pybind11_clear;
|
558 |
+
|
559 |
+
static PyGetSetDef getset[] = {{
|
560 |
+
#if PY_VERSION_HEX < 0x03070000
|
561 |
+
const_cast<char *>("__dict__"),
|
562 |
+
#else
|
563 |
+
"__dict__",
|
564 |
+
#endif
|
565 |
+
PyObject_GenericGetDict,
|
566 |
+
PyObject_GenericSetDict,
|
567 |
+
nullptr,
|
568 |
+
nullptr},
|
569 |
+
{nullptr, nullptr, nullptr, nullptr, nullptr}};
|
570 |
+
type->tp_getset = getset;
|
571 |
+
}
|
572 |
+
|
573 |
+
/// buffer_protocol: Fill in the view as specified by flags.
|
574 |
+
extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
|
575 |
+
// Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
|
576 |
+
type_info *tinfo = nullptr;
|
577 |
+
for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
|
578 |
+
tinfo = get_type_info((PyTypeObject *) type.ptr());
|
579 |
+
if (tinfo && tinfo->get_buffer) {
|
580 |
+
break;
|
581 |
+
}
|
582 |
+
}
|
583 |
+
if (view == nullptr || !tinfo || !tinfo->get_buffer) {
|
584 |
+
if (view) {
|
585 |
+
view->obj = nullptr;
|
586 |
+
}
|
587 |
+
set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
|
588 |
+
return -1;
|
589 |
+
}
|
590 |
+
std::memset(view, 0, sizeof(Py_buffer));
|
591 |
+
buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
|
592 |
+
if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
|
593 |
+
delete info;
|
594 |
+
// view->obj = nullptr; // Was just memset to 0, so not necessary
|
595 |
+
set_error(PyExc_BufferError, "Writable buffer requested for readonly storage");
|
596 |
+
return -1;
|
597 |
+
}
|
598 |
+
view->obj = obj;
|
599 |
+
view->ndim = 1;
|
600 |
+
view->internal = info;
|
601 |
+
view->buf = info->ptr;
|
602 |
+
view->itemsize = info->itemsize;
|
603 |
+
view->len = view->itemsize;
|
604 |
+
for (auto s : info->shape) {
|
605 |
+
view->len *= s;
|
606 |
+
}
|
607 |
+
view->readonly = static_cast<int>(info->readonly);
|
608 |
+
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
|
609 |
+
view->format = const_cast<char *>(info->format.c_str());
|
610 |
+
}
|
611 |
+
if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
|
612 |
+
view->ndim = (int) info->ndim;
|
613 |
+
view->strides = info->strides.data();
|
614 |
+
view->shape = info->shape.data();
|
615 |
+
}
|
616 |
+
Py_INCREF(view->obj);
|
617 |
+
return 0;
|
618 |
+
}
|
619 |
+
|
620 |
+
/// buffer_protocol: Release the resources of the buffer.
|
621 |
+
extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
|
622 |
+
delete (buffer_info *) view->internal;
|
623 |
+
}
|
624 |
+
|
625 |
+
/// Give this type a buffer interface.
|
626 |
+
inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
|
627 |
+
heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
|
628 |
+
|
629 |
+
heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
|
630 |
+
heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
|
631 |
+
}
|
632 |
+
|
633 |
+
/** Create a brand new Python type according to the `type_record` specification.
|
634 |
+
Return value: New reference. */
|
635 |
+
inline PyObject *make_new_python_type(const type_record &rec) {
|
636 |
+
auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
|
637 |
+
|
638 |
+
auto qualname = name;
|
639 |
+
if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
|
640 |
+
qualname = reinterpret_steal<object>(
|
641 |
+
PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
|
642 |
+
}
|
643 |
+
|
644 |
+
object module_;
|
645 |
+
if (rec.scope) {
|
646 |
+
if (hasattr(rec.scope, "__module__")) {
|
647 |
+
module_ = rec.scope.attr("__module__");
|
648 |
+
} else if (hasattr(rec.scope, "__name__")) {
|
649 |
+
module_ = rec.scope.attr("__name__");
|
650 |
+
}
|
651 |
+
}
|
652 |
+
|
653 |
+
const auto *full_name = c_str(
|
654 |
+
#if !defined(PYPY_VERSION)
|
655 |
+
module_ ? str(module_).cast<std::string>() + "." + rec.name :
|
656 |
+
#endif
|
657 |
+
rec.name);
|
658 |
+
|
659 |
+
char *tp_doc = nullptr;
|
660 |
+
if (rec.doc && options::show_user_defined_docstrings()) {
|
661 |
+
/* Allocate memory for docstring (using PyObject_MALLOC, since
|
662 |
+
Python will free this later on) */
|
663 |
+
size_t size = std::strlen(rec.doc) + 1;
|
664 |
+
tp_doc = (char *) PyObject_MALLOC(size);
|
665 |
+
std::memcpy((void *) tp_doc, rec.doc, size);
|
666 |
+
}
|
667 |
+
|
668 |
+
auto &internals = get_internals();
|
669 |
+
auto bases = tuple(rec.bases);
|
670 |
+
auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
|
671 |
+
|
672 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
673 |
+
issue no Python C API calls which could potentially invoke the
|
674 |
+
garbage collector (the GC will call type_traverse(), which will in
|
675 |
+
turn find the newly constructed type in an invalid state) */
|
676 |
+
auto *metaclass
|
677 |
+
= rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
|
678 |
+
|
679 |
+
auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
|
680 |
+
if (!heap_type) {
|
681 |
+
pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
|
682 |
+
}
|
683 |
+
|
684 |
+
heap_type->ht_name = name.release().ptr();
|
685 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
686 |
+
heap_type->ht_qualname = qualname.inc_ref().ptr();
|
687 |
+
#endif
|
688 |
+
|
689 |
+
auto *type = &heap_type->ht_type;
|
690 |
+
type->tp_name = full_name;
|
691 |
+
type->tp_doc = tp_doc;
|
692 |
+
type->tp_base = type_incref((PyTypeObject *) base);
|
693 |
+
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
|
694 |
+
if (!bases.empty()) {
|
695 |
+
type->tp_bases = bases.release().ptr();
|
696 |
+
}
|
697 |
+
|
698 |
+
/* Don't inherit base __init__ */
|
699 |
+
type->tp_init = pybind11_object_init;
|
700 |
+
|
701 |
+
/* Supported protocols */
|
702 |
+
type->tp_as_number = &heap_type->as_number;
|
703 |
+
type->tp_as_sequence = &heap_type->as_sequence;
|
704 |
+
type->tp_as_mapping = &heap_type->as_mapping;
|
705 |
+
type->tp_as_async = &heap_type->as_async;
|
706 |
+
|
707 |
+
/* Flags */
|
708 |
+
type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
|
709 |
+
if (!rec.is_final) {
|
710 |
+
type->tp_flags |= Py_TPFLAGS_BASETYPE;
|
711 |
+
}
|
712 |
+
|
713 |
+
if (rec.dynamic_attr) {
|
714 |
+
enable_dynamic_attributes(heap_type);
|
715 |
+
}
|
716 |
+
|
717 |
+
if (rec.buffer_protocol) {
|
718 |
+
enable_buffer_protocol(heap_type);
|
719 |
+
}
|
720 |
+
|
721 |
+
if (rec.custom_type_setup_callback) {
|
722 |
+
rec.custom_type_setup_callback(heap_type);
|
723 |
+
}
|
724 |
+
|
725 |
+
if (PyType_Ready(type) < 0) {
|
726 |
+
pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
|
727 |
+
}
|
728 |
+
|
729 |
+
assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
|
730 |
+
|
731 |
+
/* Register type with the parent scope */
|
732 |
+
if (rec.scope) {
|
733 |
+
setattr(rec.scope, rec.name, (PyObject *) type);
|
734 |
+
} else {
|
735 |
+
Py_INCREF(type); // Keep it alive forever (reference leak)
|
736 |
+
}
|
737 |
+
|
738 |
+
if (module_) { // Needed by pydoc
|
739 |
+
setattr((PyObject *) type, "__module__", module_);
|
740 |
+
}
|
741 |
+
|
742 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
|
743 |
+
|
744 |
+
return (PyObject *) type;
|
745 |
+
}
|
746 |
+
|
747 |
+
PYBIND11_NAMESPACE_END(detail)
|
748 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/common.h
ADDED
@@ -0,0 +1,1267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/detail/common.h -- Basic macros
|
3 |
+
|
4 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#define PYBIND11_VERSION_MAJOR 2
|
13 |
+
#define PYBIND11_VERSION_MINOR 12
|
14 |
+
#define PYBIND11_VERSION_PATCH 0
|
15 |
+
|
16 |
+
// Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
|
17 |
+
// Additional convention: 0xD = dev
|
18 |
+
#define PYBIND11_VERSION_HEX 0x020C0000
|
19 |
+
|
20 |
+
// Define some generic pybind11 helper macros for warning management.
|
21 |
+
//
|
22 |
+
// Note that compiler-specific push/pop pairs are baked into the
|
23 |
+
// PYBIND11_NAMESPACE_BEGIN/PYBIND11_NAMESPACE_END pair of macros. Therefore manual
|
24 |
+
// PYBIND11_WARNING_PUSH/PYBIND11_WARNING_POP are usually only needed in `#include` sections.
|
25 |
+
//
|
26 |
+
// If you find you need to suppress a warning, please try to make the suppression as local as
|
27 |
+
// possible using these macros. Please also be sure to push/pop with the pybind11 macros. Please
|
28 |
+
// only use compiler specifics if you need to check specific versions, e.g. Apple Clang vs. vanilla
|
29 |
+
// Clang.
|
30 |
+
#if defined(_MSC_VER)
|
31 |
+
# define PYBIND11_COMPILER_MSVC
|
32 |
+
# define PYBIND11_PRAGMA(...) __pragma(__VA_ARGS__)
|
33 |
+
# define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning(push))
|
34 |
+
# define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning(pop))
|
35 |
+
#elif defined(__INTEL_COMPILER)
|
36 |
+
# define PYBIND11_COMPILER_INTEL
|
37 |
+
# define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
|
38 |
+
# define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning push)
|
39 |
+
# define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning pop)
|
40 |
+
#elif defined(__clang__)
|
41 |
+
# define PYBIND11_COMPILER_CLANG
|
42 |
+
# define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
|
43 |
+
# define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(clang diagnostic push)
|
44 |
+
# define PYBIND11_WARNING_POP PYBIND11_PRAGMA(clang diagnostic push)
|
45 |
+
#elif defined(__GNUC__)
|
46 |
+
# define PYBIND11_COMPILER_GCC
|
47 |
+
# define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
|
48 |
+
# define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(GCC diagnostic push)
|
49 |
+
# define PYBIND11_WARNING_POP PYBIND11_PRAGMA(GCC diagnostic pop)
|
50 |
+
#endif
|
51 |
+
|
52 |
+
#ifdef PYBIND11_COMPILER_MSVC
|
53 |
+
# define PYBIND11_WARNING_DISABLE_MSVC(name) PYBIND11_PRAGMA(warning(disable : name))
|
54 |
+
#else
|
55 |
+
# define PYBIND11_WARNING_DISABLE_MSVC(name)
|
56 |
+
#endif
|
57 |
+
|
58 |
+
#ifdef PYBIND11_COMPILER_CLANG
|
59 |
+
# define PYBIND11_WARNING_DISABLE_CLANG(name) PYBIND11_PRAGMA(clang diagnostic ignored name)
|
60 |
+
#else
|
61 |
+
# define PYBIND11_WARNING_DISABLE_CLANG(name)
|
62 |
+
#endif
|
63 |
+
|
64 |
+
#ifdef PYBIND11_COMPILER_GCC
|
65 |
+
# define PYBIND11_WARNING_DISABLE_GCC(name) PYBIND11_PRAGMA(GCC diagnostic ignored name)
|
66 |
+
#else
|
67 |
+
# define PYBIND11_WARNING_DISABLE_GCC(name)
|
68 |
+
#endif
|
69 |
+
|
70 |
+
#ifdef PYBIND11_COMPILER_INTEL
|
71 |
+
# define PYBIND11_WARNING_DISABLE_INTEL(name) PYBIND11_PRAGMA(warning disable name)
|
72 |
+
#else
|
73 |
+
# define PYBIND11_WARNING_DISABLE_INTEL(name)
|
74 |
+
#endif
|
75 |
+
|
76 |
+
#define PYBIND11_NAMESPACE_BEGIN(name) \
|
77 |
+
namespace name { \
|
78 |
+
PYBIND11_WARNING_PUSH
|
79 |
+
|
80 |
+
#define PYBIND11_NAMESPACE_END(name) \
|
81 |
+
PYBIND11_WARNING_POP \
|
82 |
+
}
|
83 |
+
|
84 |
+
// Robust support for some features and loading modules compiled against different pybind versions
|
85 |
+
// requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute
|
86 |
+
// on the main `pybind11` namespace.
|
87 |
+
#if !defined(PYBIND11_NAMESPACE)
|
88 |
+
# ifdef __GNUG__
|
89 |
+
# define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
|
90 |
+
# else
|
91 |
+
# define PYBIND11_NAMESPACE pybind11
|
92 |
+
# endif
|
93 |
+
#endif
|
94 |
+
|
95 |
+
#if !(defined(_MSC_VER) && __cplusplus == 199711L)
|
96 |
+
# if __cplusplus >= 201402L
|
97 |
+
# define PYBIND11_CPP14
|
98 |
+
# if __cplusplus >= 201703L
|
99 |
+
# define PYBIND11_CPP17
|
100 |
+
# if __cplusplus >= 202002L
|
101 |
+
# define PYBIND11_CPP20
|
102 |
+
// Please update tests/pybind11_tests.cpp `cpp_std()` when adding a macro here.
|
103 |
+
# endif
|
104 |
+
# endif
|
105 |
+
# endif
|
106 |
+
#elif defined(_MSC_VER) && __cplusplus == 199711L
|
107 |
+
// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully
|
108 |
+
// implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3
|
109 |
+
// or newer.
|
110 |
+
# if _MSVC_LANG >= 201402L
|
111 |
+
# define PYBIND11_CPP14
|
112 |
+
# if _MSVC_LANG > 201402L
|
113 |
+
# define PYBIND11_CPP17
|
114 |
+
# if _MSVC_LANG >= 202002L
|
115 |
+
# define PYBIND11_CPP20
|
116 |
+
# endif
|
117 |
+
# endif
|
118 |
+
# endif
|
119 |
+
#endif
|
120 |
+
|
121 |
+
#if defined(PYBIND11_CPP20)
|
122 |
+
# define PYBIND11_CONSTINIT constinit
|
123 |
+
# define PYBIND11_DTOR_CONSTEXPR constexpr
|
124 |
+
#else
|
125 |
+
# define PYBIND11_CONSTINIT
|
126 |
+
# define PYBIND11_DTOR_CONSTEXPR
|
127 |
+
#endif
|
128 |
+
|
129 |
+
// Compiler version assertions
|
130 |
+
#if defined(__INTEL_COMPILER)
|
131 |
+
# if __INTEL_COMPILER < 1800
|
132 |
+
# error pybind11 requires Intel C++ compiler v18 or newer
|
133 |
+
# elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
|
134 |
+
# error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
|
135 |
+
# endif
|
136 |
+
/* The following pragma cannot be pop'ed:
|
137 |
+
https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
|
138 |
+
# pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
|
139 |
+
#elif defined(__clang__) && !defined(__apple_build_version__)
|
140 |
+
# if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
|
141 |
+
# error pybind11 requires clang 3.3 or newer
|
142 |
+
# endif
|
143 |
+
#elif defined(__clang__)
|
144 |
+
// Apple changes clang version macros to its Xcode version; the first Xcode release based on
|
145 |
+
// (upstream) clang 3.3 was Xcode 5:
|
146 |
+
# if __clang_major__ < 5
|
147 |
+
# error pybind11 requires Xcode/clang 5.0 or newer
|
148 |
+
# endif
|
149 |
+
#elif defined(__GNUG__)
|
150 |
+
# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
|
151 |
+
# error pybind11 requires gcc 4.8 or newer
|
152 |
+
# endif
|
153 |
+
#elif defined(_MSC_VER)
|
154 |
+
# if _MSC_VER < 1910
|
155 |
+
# error pybind11 2.10+ requires MSVC 2017 or newer
|
156 |
+
# endif
|
157 |
+
#endif
|
158 |
+
|
159 |
+
#if !defined(PYBIND11_EXPORT)
|
160 |
+
# if defined(WIN32) || defined(_WIN32)
|
161 |
+
# define PYBIND11_EXPORT __declspec(dllexport)
|
162 |
+
# else
|
163 |
+
# define PYBIND11_EXPORT __attribute__((visibility("default")))
|
164 |
+
# endif
|
165 |
+
#endif
|
166 |
+
|
167 |
+
#if !defined(PYBIND11_EXPORT_EXCEPTION)
|
168 |
+
# if defined(__apple_build_version__)
|
169 |
+
# define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
|
170 |
+
# else
|
171 |
+
# define PYBIND11_EXPORT_EXCEPTION
|
172 |
+
# endif
|
173 |
+
#endif
|
174 |
+
|
175 |
+
// For CUDA, GCC7, GCC8:
|
176 |
+
// PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
|
177 |
+
// When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
|
178 |
+
// However, the measured shared-library size saving when using noinline are only
|
179 |
+
// 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
|
180 |
+
// the default under pybind11/tests).
|
181 |
+
#if !defined(PYBIND11_NOINLINE_FORCED) \
|
182 |
+
&& (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
|
183 |
+
# define PYBIND11_NOINLINE_DISABLED
|
184 |
+
#endif
|
185 |
+
|
186 |
+
// The PYBIND11_NOINLINE macro is for function DEFINITIONS.
|
187 |
+
// In contrast, FORWARD DECLARATIONS should never use this macro:
|
188 |
+
// https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
|
189 |
+
#if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
|
190 |
+
# define PYBIND11_NOINLINE inline
|
191 |
+
#elif defined(_MSC_VER)
|
192 |
+
# define PYBIND11_NOINLINE __declspec(noinline) inline
|
193 |
+
#else
|
194 |
+
# define PYBIND11_NOINLINE __attribute__((noinline)) inline
|
195 |
+
#endif
|
196 |
+
|
197 |
+
#if defined(__MINGW32__)
|
198 |
+
// For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
|
199 |
+
// whether it is used or not
|
200 |
+
# define PYBIND11_DEPRECATED(reason)
|
201 |
+
#elif defined(PYBIND11_CPP14)
|
202 |
+
# define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
|
203 |
+
#else
|
204 |
+
# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
|
205 |
+
#endif
|
206 |
+
|
207 |
+
#if defined(PYBIND11_CPP17)
|
208 |
+
# define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
|
209 |
+
#elif defined(_MSC_VER) && !defined(__clang__)
|
210 |
+
# define PYBIND11_MAYBE_UNUSED
|
211 |
+
#else
|
212 |
+
# define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
|
213 |
+
#endif
|
214 |
+
|
215 |
+
/* Don't let Python.h #define (v)snprintf as macro because they are implemented
|
216 |
+
properly in Visual Studio since 2015. */
|
217 |
+
#if defined(_MSC_VER)
|
218 |
+
# define HAVE_SNPRINTF 1
|
219 |
+
#endif
|
220 |
+
|
221 |
+
/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
|
222 |
+
#if defined(_MSC_VER)
|
223 |
+
PYBIND11_WARNING_PUSH
|
224 |
+
PYBIND11_WARNING_DISABLE_MSVC(4505)
|
225 |
+
// C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
|
226 |
+
# if defined(_DEBUG) && !defined(Py_DEBUG)
|
227 |
+
// Workaround for a VS 2022 issue.
|
228 |
+
// NOTE: This workaround knowingly violates the Python.h include order requirement:
|
229 |
+
// https://docs.python.org/3/c-api/intro.html#include-files
|
230 |
+
// See https://github.com/pybind/pybind11/pull/3497 for full context.
|
231 |
+
# include <yvals.h>
|
232 |
+
# if _MSVC_STL_VERSION >= 143
|
233 |
+
# include <crtdefs.h>
|
234 |
+
# endif
|
235 |
+
# define PYBIND11_DEBUG_MARKER
|
236 |
+
# undef _DEBUG
|
237 |
+
# endif
|
238 |
+
#endif
|
239 |
+
|
240 |
+
// https://en.cppreference.com/w/c/chrono/localtime
|
241 |
+
#if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
|
242 |
+
# define __STDC_WANT_LIB_EXT1__
|
243 |
+
#endif
|
244 |
+
|
245 |
+
#ifdef __has_include
|
246 |
+
// std::optional (but including it in c++14 mode isn't allowed)
|
247 |
+
# if defined(PYBIND11_CPP17) && __has_include(<optional>)
|
248 |
+
# define PYBIND11_HAS_OPTIONAL 1
|
249 |
+
# endif
|
250 |
+
// std::experimental::optional (but not allowed in c++11 mode)
|
251 |
+
# if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
|
252 |
+
!__has_include(<optional>))
|
253 |
+
# define PYBIND11_HAS_EXP_OPTIONAL 1
|
254 |
+
# endif
|
255 |
+
// std::variant
|
256 |
+
# if defined(PYBIND11_CPP17) && __has_include(<variant>)
|
257 |
+
# define PYBIND11_HAS_VARIANT 1
|
258 |
+
# endif
|
259 |
+
#elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
|
260 |
+
# define PYBIND11_HAS_OPTIONAL 1
|
261 |
+
# define PYBIND11_HAS_VARIANT 1
|
262 |
+
#endif
|
263 |
+
|
264 |
+
#if defined(PYBIND11_CPP17)
|
265 |
+
# if defined(__has_include)
|
266 |
+
# if __has_include(<string_view>)
|
267 |
+
# define PYBIND11_HAS_STRING_VIEW
|
268 |
+
# endif
|
269 |
+
# elif defined(_MSC_VER)
|
270 |
+
# define PYBIND11_HAS_STRING_VIEW
|
271 |
+
# endif
|
272 |
+
#endif
|
273 |
+
|
274 |
+
#include <Python.h>
|
275 |
+
// Reminder: WITH_THREAD is always defined if PY_VERSION_HEX >= 0x03070000
|
276 |
+
#if PY_VERSION_HEX < 0x03060000
|
277 |
+
# error "PYTHON < 3.6 IS UNSUPPORTED. pybind11 v2.9 was the last to support Python 2 and 3.5."
|
278 |
+
#endif
|
279 |
+
#include <frameobject.h>
|
280 |
+
#include <pythread.h>
|
281 |
+
|
282 |
+
/* Python #defines overrides on all sorts of core functions, which
|
283 |
+
tends to weak havok in C++ codebases that expect these to work
|
284 |
+
like regular functions (potentially with several overloads) */
|
285 |
+
#if defined(isalnum)
|
286 |
+
# undef isalnum
|
287 |
+
# undef isalpha
|
288 |
+
# undef islower
|
289 |
+
# undef isspace
|
290 |
+
# undef isupper
|
291 |
+
# undef tolower
|
292 |
+
# undef toupper
|
293 |
+
#endif
|
294 |
+
|
295 |
+
#if defined(copysign)
|
296 |
+
# undef copysign
|
297 |
+
#endif
|
298 |
+
|
299 |
+
#if defined(PYBIND11_NUMPY_1_ONLY)
|
300 |
+
# define PYBIND11_INTERNAL_NUMPY_1_ONLY_DETECTED
|
301 |
+
#endif
|
302 |
+
|
303 |
+
#if defined(PYPY_VERSION) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
|
304 |
+
# define PYBIND11_SIMPLE_GIL_MANAGEMENT
|
305 |
+
#endif
|
306 |
+
|
307 |
+
#if defined(_MSC_VER)
|
308 |
+
# if defined(PYBIND11_DEBUG_MARKER)
|
309 |
+
# define _DEBUG
|
310 |
+
# undef PYBIND11_DEBUG_MARKER
|
311 |
+
# endif
|
312 |
+
PYBIND11_WARNING_POP
|
313 |
+
#endif
|
314 |
+
|
315 |
+
#include <cstddef>
|
316 |
+
#include <cstring>
|
317 |
+
#include <exception>
|
318 |
+
#include <forward_list>
|
319 |
+
#include <memory>
|
320 |
+
#include <stdexcept>
|
321 |
+
#include <string>
|
322 |
+
#include <type_traits>
|
323 |
+
#include <typeindex>
|
324 |
+
#include <unordered_map>
|
325 |
+
#include <unordered_set>
|
326 |
+
#include <vector>
|
327 |
+
#if defined(__has_include)
|
328 |
+
# if __has_include(<version>)
|
329 |
+
# include <version>
|
330 |
+
# endif
|
331 |
+
#endif
|
332 |
+
|
333 |
+
// Must be after including <version> or one of the other headers specified by the standard
|
334 |
+
#if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
|
335 |
+
# define PYBIND11_HAS_U8STRING
|
336 |
+
#endif
|
337 |
+
|
338 |
+
// See description of PR #4246:
|
339 |
+
#if !defined(PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF) && !defined(NDEBUG) \
|
340 |
+
&& !defined(PYPY_VERSION) && !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
|
341 |
+
# define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
|
342 |
+
#endif
|
343 |
+
|
344 |
+
// #define PYBIND11_STR_LEGACY_PERMISSIVE
|
345 |
+
// If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
|
346 |
+
// (probably surprising and never documented, but this was the
|
347 |
+
// legacy behavior until and including v2.6.x). As a side-effect,
|
348 |
+
// pybind11::isinstance<str>() is true for both pybind11::str and
|
349 |
+
// pybind11::bytes.
|
350 |
+
// If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
|
351 |
+
// pybind11::isinstance<str>() is true only for pybind11::str.
|
352 |
+
// However, for Python 2 only (!), the pybind11::str caster
|
353 |
+
// implicitly decoded bytes to PyUnicodeObject. This was to ease
|
354 |
+
// the transition from the legacy behavior to the non-permissive
|
355 |
+
// behavior.
|
356 |
+
|
357 |
+
/// Compatibility macros for Python 2 / Python 3 versions TODO: remove
|
358 |
+
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
|
359 |
+
#define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
|
360 |
+
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
|
361 |
+
#define PYBIND11_BYTES_CHECK PyBytes_Check
|
362 |
+
#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
|
363 |
+
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
|
364 |
+
#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
|
365 |
+
#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
|
366 |
+
#define PYBIND11_BYTES_SIZE PyBytes_Size
|
367 |
+
#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
|
368 |
+
#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
|
369 |
+
#define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
|
370 |
+
#define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
|
371 |
+
#define PYBIND11_BYTES_NAME "bytes"
|
372 |
+
#define PYBIND11_STRING_NAME "str"
|
373 |
+
#define PYBIND11_SLICE_OBJECT PyObject
|
374 |
+
#define PYBIND11_FROM_STRING PyUnicode_FromString
|
375 |
+
#define PYBIND11_STR_TYPE ::pybind11::str
|
376 |
+
#define PYBIND11_BOOL_ATTR "__bool__"
|
377 |
+
#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
|
378 |
+
#define PYBIND11_BUILTINS_MODULE "builtins"
|
379 |
+
// Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
|
380 |
+
// See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
|
381 |
+
#define PYBIND11_PLUGIN_IMPL(name) \
|
382 |
+
extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
|
383 |
+
extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
|
384 |
+
|
385 |
+
#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
|
386 |
+
#define PYBIND11_STRINGIFY(x) #x
|
387 |
+
#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
|
388 |
+
#define PYBIND11_CONCAT(first, second) first##second
|
389 |
+
#define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals();
|
390 |
+
|
391 |
+
#define PYBIND11_CHECK_PYTHON_VERSION \
|
392 |
+
{ \
|
393 |
+
const char *compiled_ver \
|
394 |
+
= PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
|
395 |
+
const char *runtime_ver = Py_GetVersion(); \
|
396 |
+
size_t len = std::strlen(compiled_ver); \
|
397 |
+
if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
|
398 |
+
|| (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
|
399 |
+
PyErr_Format(PyExc_ImportError, \
|
400 |
+
"Python version mismatch: module was compiled for Python %s, " \
|
401 |
+
"but the interpreter version is incompatible: %s.", \
|
402 |
+
compiled_ver, \
|
403 |
+
runtime_ver); \
|
404 |
+
return nullptr; \
|
405 |
+
} \
|
406 |
+
}
|
407 |
+
|
408 |
+
#define PYBIND11_CATCH_INIT_EXCEPTIONS \
|
409 |
+
catch (pybind11::error_already_set & e) { \
|
410 |
+
pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
|
411 |
+
return nullptr; \
|
412 |
+
} \
|
413 |
+
catch (const std::exception &e) { \
|
414 |
+
::pybind11::set_error(PyExc_ImportError, e.what()); \
|
415 |
+
return nullptr; \
|
416 |
+
}
|
417 |
+
|
418 |
+
/** \rst
|
419 |
+
***Deprecated in favor of PYBIND11_MODULE***
|
420 |
+
|
421 |
+
This macro creates the entry point that will be invoked when the Python interpreter
|
422 |
+
imports a plugin library. Please create a `module_` in the function body and return
|
423 |
+
the pointer to its underlying Python object at the end.
|
424 |
+
|
425 |
+
.. code-block:: cpp
|
426 |
+
|
427 |
+
PYBIND11_PLUGIN(example) {
|
428 |
+
pybind11::module_ m("example", "pybind11 example plugin");
|
429 |
+
/// Set up bindings here
|
430 |
+
return m.ptr();
|
431 |
+
}
|
432 |
+
\endrst */
|
433 |
+
#define PYBIND11_PLUGIN(name) \
|
434 |
+
PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
|
435 |
+
static PyObject *pybind11_init(); \
|
436 |
+
PYBIND11_PLUGIN_IMPL(name) { \
|
437 |
+
PYBIND11_CHECK_PYTHON_VERSION \
|
438 |
+
PYBIND11_ENSURE_INTERNALS_READY \
|
439 |
+
try { \
|
440 |
+
return pybind11_init(); \
|
441 |
+
} \
|
442 |
+
PYBIND11_CATCH_INIT_EXCEPTIONS \
|
443 |
+
} \
|
444 |
+
PyObject *pybind11_init()
|
445 |
+
|
446 |
+
/** \rst
|
447 |
+
This macro creates the entry point that will be invoked when the Python interpreter
|
448 |
+
imports an extension module. The module name is given as the first argument and it
|
449 |
+
should not be in quotes. The second macro argument defines a variable of type
|
450 |
+
`py::module_` which can be used to initialize the module.
|
451 |
+
|
452 |
+
The entry point is marked as "maybe unused" to aid dead-code detection analysis:
|
453 |
+
since the entry point is typically only looked up at runtime and not referenced
|
454 |
+
during translation, it would otherwise appear as unused ("dead") code.
|
455 |
+
|
456 |
+
.. code-block:: cpp
|
457 |
+
|
458 |
+
PYBIND11_MODULE(example, m) {
|
459 |
+
m.doc() = "pybind11 example module";
|
460 |
+
|
461 |
+
// Add bindings here
|
462 |
+
m.def("foo", []() {
|
463 |
+
return "Hello, World!";
|
464 |
+
});
|
465 |
+
}
|
466 |
+
\endrst */
|
467 |
+
#define PYBIND11_MODULE(name, variable) \
|
468 |
+
static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name) \
|
469 |
+
PYBIND11_MAYBE_UNUSED; \
|
470 |
+
PYBIND11_MAYBE_UNUSED \
|
471 |
+
static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
|
472 |
+
PYBIND11_PLUGIN_IMPL(name) { \
|
473 |
+
PYBIND11_CHECK_PYTHON_VERSION \
|
474 |
+
PYBIND11_ENSURE_INTERNALS_READY \
|
475 |
+
auto m = ::pybind11::module_::create_extension_module( \
|
476 |
+
PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
|
477 |
+
try { \
|
478 |
+
PYBIND11_CONCAT(pybind11_init_, name)(m); \
|
479 |
+
return m.ptr(); \
|
480 |
+
} \
|
481 |
+
PYBIND11_CATCH_INIT_EXCEPTIONS \
|
482 |
+
} \
|
483 |
+
void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
|
484 |
+
|
485 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
486 |
+
|
487 |
+
using ssize_t = Py_ssize_t;
|
488 |
+
using size_t = std::size_t;
|
489 |
+
|
490 |
+
template <typename IntType>
|
491 |
+
inline ssize_t ssize_t_cast(const IntType &val) {
|
492 |
+
static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
|
493 |
+
return static_cast<ssize_t>(val);
|
494 |
+
}
|
495 |
+
|
496 |
+
/// Approach used to cast a previously unknown C++ instance into a Python object
|
497 |
+
enum class return_value_policy : uint8_t {
|
498 |
+
/** This is the default return value policy, which falls back to the policy
|
499 |
+
return_value_policy::take_ownership when the return value is a pointer.
|
500 |
+
Otherwise, it uses return_value::move or return_value::copy for rvalue
|
501 |
+
and lvalue references, respectively. See below for a description of what
|
502 |
+
all of these different policies do. */
|
503 |
+
automatic = 0,
|
504 |
+
|
505 |
+
/** As above, but use policy return_value_policy::reference when the return
|
506 |
+
value is a pointer. This is the default conversion policy for function
|
507 |
+
arguments when calling Python functions manually from C++ code (i.e. via
|
508 |
+
handle::operator()). You probably won't need to use this. */
|
509 |
+
automatic_reference,
|
510 |
+
|
511 |
+
/** Reference an existing object (i.e. do not create a new copy) and take
|
512 |
+
ownership. Python will call the destructor and delete operator when the
|
513 |
+
object's reference count reaches zero. Undefined behavior ensues when
|
514 |
+
the C++ side does the same.. */
|
515 |
+
take_ownership,
|
516 |
+
|
517 |
+
/** Create a new copy of the returned object, which will be owned by
|
518 |
+
Python. This policy is comparably safe because the lifetimes of the two
|
519 |
+
instances are decoupled. */
|
520 |
+
copy,
|
521 |
+
|
522 |
+
/** Use std::move to move the return value contents into a new instance
|
523 |
+
that will be owned by Python. This policy is comparably safe because the
|
524 |
+
lifetimes of the two instances (move source and destination) are
|
525 |
+
decoupled. */
|
526 |
+
move,
|
527 |
+
|
528 |
+
/** Reference an existing object, but do not take ownership. The C++ side
|
529 |
+
is responsible for managing the object's lifetime and deallocating it
|
530 |
+
when it is no longer used. Warning: undefined behavior will ensue when
|
531 |
+
the C++ side deletes an object that is still referenced and used by
|
532 |
+
Python. */
|
533 |
+
reference,
|
534 |
+
|
535 |
+
/** This policy only applies to methods and properties. It references the
|
536 |
+
object without taking ownership similar to the above
|
537 |
+
return_value_policy::reference policy. In contrast to that policy, the
|
538 |
+
function or property's implicit this argument (called the parent) is
|
539 |
+
considered to be the the owner of the return value (the child).
|
540 |
+
pybind11 then couples the lifetime of the parent to the child via a
|
541 |
+
reference relationship that ensures that the parent cannot be garbage
|
542 |
+
collected while Python is still using the child. More advanced
|
543 |
+
variations of this scheme are also possible using combinations of
|
544 |
+
return_value_policy::reference and the keep_alive call policy */
|
545 |
+
reference_internal
|
546 |
+
};
|
547 |
+
|
548 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
549 |
+
|
550 |
+
inline static constexpr int log2(size_t n, int k = 0) {
|
551 |
+
return (n <= 1) ? k : log2(n >> 1, k + 1);
|
552 |
+
}
|
553 |
+
|
554 |
+
// Returns the size as a multiple of sizeof(void *), rounded up.
|
555 |
+
inline static constexpr size_t size_in_ptrs(size_t s) {
|
556 |
+
return 1 + ((s - 1) >> log2(sizeof(void *)));
|
557 |
+
}
|
558 |
+
|
559 |
+
/**
|
560 |
+
* The space to allocate for simple layout instance holders (see below) in multiple of the size of
|
561 |
+
* a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
|
562 |
+
* to holder either a std::unique_ptr or std::shared_ptr (which is almost always
|
563 |
+
* sizeof(std::shared_ptr<T>)).
|
564 |
+
*/
|
565 |
+
constexpr size_t instance_simple_holder_in_ptrs() {
|
566 |
+
static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
|
567 |
+
"pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
|
568 |
+
return size_in_ptrs(sizeof(std::shared_ptr<int>));
|
569 |
+
}
|
570 |
+
|
571 |
+
// Forward declarations
|
572 |
+
struct type_info;
|
573 |
+
struct value_and_holder;
|
574 |
+
|
575 |
+
struct nonsimple_values_and_holders {
|
576 |
+
void **values_and_holders;
|
577 |
+
uint8_t *status;
|
578 |
+
};
|
579 |
+
|
580 |
+
/// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
|
581 |
+
struct instance {
|
582 |
+
PyObject_HEAD
|
583 |
+
/// Storage for pointers and holder; see simple_layout, below, for a description
|
584 |
+
union {
|
585 |
+
void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
|
586 |
+
nonsimple_values_and_holders nonsimple;
|
587 |
+
};
|
588 |
+
/// Weak references
|
589 |
+
PyObject *weakrefs;
|
590 |
+
/// If true, the pointer is owned which means we're free to manage it with a holder.
|
591 |
+
bool owned : 1;
|
592 |
+
/**
|
593 |
+
* An instance has two possible value/holder layouts.
|
594 |
+
*
|
595 |
+
* Simple layout (when this flag is true), means the `simple_value_holder` is set with a
|
596 |
+
* pointer and the holder object governing that pointer, i.e. [val1*][holder]. This layout is
|
597 |
+
* applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
|
598 |
+
* type's holder will fit in the default space (which is large enough to hold either a
|
599 |
+
* std::unique_ptr or std::shared_ptr).
|
600 |
+
*
|
601 |
+
* Non-simple layout applies when using custom holders that require more space than
|
602 |
+
* `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
|
603 |
+
* used on the python side. Non-simple layout allocates the required amount of memory to have
|
604 |
+
* multiple bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is
|
605 |
+
* set to a pointer to allocated space of the required space to hold a sequence of value
|
606 |
+
* pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
|
607 |
+
* [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple
|
608 |
+
* of `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the beginning of
|
609 |
+
* the [bb...] block (but not independently allocated).
|
610 |
+
*
|
611 |
+
* Status bits indicate whether the associated holder is constructed (&
|
612 |
+
* status_holder_constructed) and whether the value pointer is registered (&
|
613 |
+
* status_instance_registered) in `registered_instances`.
|
614 |
+
*/
|
615 |
+
bool simple_layout : 1;
|
616 |
+
/// For simple layout, tracks whether the holder has been constructed
|
617 |
+
bool simple_holder_constructed : 1;
|
618 |
+
/// For simple layout, tracks whether the instance is registered in `registered_instances`
|
619 |
+
bool simple_instance_registered : 1;
|
620 |
+
/// If true, get_internals().patients has an entry for this object
|
621 |
+
bool has_patients : 1;
|
622 |
+
|
623 |
+
/// Initializes all of the above type/values/holders data (but not the instance values
|
624 |
+
/// themselves)
|
625 |
+
void allocate_layout();
|
626 |
+
|
627 |
+
/// Destroys/deallocates all of the above
|
628 |
+
void deallocate_layout();
|
629 |
+
|
630 |
+
/// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
|
631 |
+
/// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
|
632 |
+
/// `throw_if_missing` is false.
|
633 |
+
value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
|
634 |
+
bool throw_if_missing = true);
|
635 |
+
|
636 |
+
/// Bit values for the non-simple status flags
|
637 |
+
static constexpr uint8_t status_holder_constructed = 1;
|
638 |
+
static constexpr uint8_t status_instance_registered = 2;
|
639 |
+
};
|
640 |
+
|
641 |
+
static_assert(std::is_standard_layout<instance>::value,
|
642 |
+
"Internal error: `pybind11::detail::instance` is not standard layout!");
|
643 |
+
|
644 |
+
/// from __cpp_future__ import (convenient aliases from C++14/17)
|
645 |
+
#if defined(PYBIND11_CPP14)
|
646 |
+
using std::conditional_t;
|
647 |
+
using std::enable_if_t;
|
648 |
+
using std::remove_cv_t;
|
649 |
+
using std::remove_reference_t;
|
650 |
+
#else
|
651 |
+
template <bool B, typename T = void>
|
652 |
+
using enable_if_t = typename std::enable_if<B, T>::type;
|
653 |
+
template <bool B, typename T, typename F>
|
654 |
+
using conditional_t = typename std::conditional<B, T, F>::type;
|
655 |
+
template <typename T>
|
656 |
+
using remove_cv_t = typename std::remove_cv<T>::type;
|
657 |
+
template <typename T>
|
658 |
+
using remove_reference_t = typename std::remove_reference<T>::type;
|
659 |
+
#endif
|
660 |
+
|
661 |
+
#if defined(PYBIND11_CPP20)
|
662 |
+
using std::remove_cvref;
|
663 |
+
using std::remove_cvref_t;
|
664 |
+
#else
|
665 |
+
template <class T>
|
666 |
+
struct remove_cvref {
|
667 |
+
using type = remove_cv_t<remove_reference_t<T>>;
|
668 |
+
};
|
669 |
+
template <class T>
|
670 |
+
using remove_cvref_t = typename remove_cvref<T>::type;
|
671 |
+
#endif
|
672 |
+
|
673 |
+
/// Example usage: is_same_ignoring_cvref<T, PyObject *>::value
|
674 |
+
template <typename T, typename U>
|
675 |
+
using is_same_ignoring_cvref = std::is_same<detail::remove_cvref_t<T>, U>;
|
676 |
+
|
677 |
+
/// Index sequences
|
678 |
+
#if defined(PYBIND11_CPP14)
|
679 |
+
using std::index_sequence;
|
680 |
+
using std::make_index_sequence;
|
681 |
+
#else
|
682 |
+
template <size_t...>
|
683 |
+
struct index_sequence {};
|
684 |
+
template <size_t N, size_t... S>
|
685 |
+
struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...> {};
|
686 |
+
template <size_t... S>
|
687 |
+
struct make_index_sequence_impl<0, S...> {
|
688 |
+
using type = index_sequence<S...>;
|
689 |
+
};
|
690 |
+
template <size_t N>
|
691 |
+
using make_index_sequence = typename make_index_sequence_impl<N>::type;
|
692 |
+
#endif
|
693 |
+
|
694 |
+
/// Make an index sequence of the indices of true arguments
|
695 |
+
template <typename ISeq, size_t, bool...>
|
696 |
+
struct select_indices_impl {
|
697 |
+
using type = ISeq;
|
698 |
+
};
|
699 |
+
template <size_t... IPrev, size_t I, bool B, bool... Bs>
|
700 |
+
struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
|
701 |
+
: select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
|
702 |
+
I + 1,
|
703 |
+
Bs...> {};
|
704 |
+
template <bool... Bs>
|
705 |
+
using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
|
706 |
+
|
707 |
+
/// Backports of std::bool_constant and std::negation to accommodate older compilers
|
708 |
+
template <bool B>
|
709 |
+
using bool_constant = std::integral_constant<bool, B>;
|
710 |
+
template <typename T>
|
711 |
+
struct negation : bool_constant<!T::value> {};
|
712 |
+
|
713 |
+
// PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
|
714 |
+
// using the new one (C++14 defect, so generally works on newer compilers, even
|
715 |
+
// if not in C++17 mode)
|
716 |
+
#if defined(__PGIC__) || defined(__INTEL_COMPILER)
|
717 |
+
template <typename...>
|
718 |
+
using void_t = void;
|
719 |
+
#else
|
720 |
+
template <typename...>
|
721 |
+
struct void_t_impl {
|
722 |
+
using type = void;
|
723 |
+
};
|
724 |
+
template <typename... Ts>
|
725 |
+
using void_t = typename void_t_impl<Ts...>::type;
|
726 |
+
#endif
|
727 |
+
|
728 |
+
/// Compile-time all/any/none of that check the boolean value of all template types
|
729 |
+
#if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
|
730 |
+
template <class... Ts>
|
731 |
+
using all_of = bool_constant<(Ts::value && ...)>;
|
732 |
+
template <class... Ts>
|
733 |
+
using any_of = bool_constant<(Ts::value || ...)>;
|
734 |
+
#elif !defined(_MSC_VER)
|
735 |
+
template <bool...>
|
736 |
+
struct bools {};
|
737 |
+
template <class... Ts>
|
738 |
+
using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
|
739 |
+
template <class... Ts>
|
740 |
+
using any_of = negation<all_of<negation<Ts>...>>;
|
741 |
+
#else
|
742 |
+
// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
|
743 |
+
// at a slight loss of compilation efficiency).
|
744 |
+
template <class... Ts>
|
745 |
+
using all_of = std::conjunction<Ts...>;
|
746 |
+
template <class... Ts>
|
747 |
+
using any_of = std::disjunction<Ts...>;
|
748 |
+
#endif
|
749 |
+
template <class... Ts>
|
750 |
+
using none_of = negation<any_of<Ts...>>;
|
751 |
+
|
752 |
+
template <class T, template <class> class... Predicates>
|
753 |
+
using satisfies_all_of = all_of<Predicates<T>...>;
|
754 |
+
template <class T, template <class> class... Predicates>
|
755 |
+
using satisfies_any_of = any_of<Predicates<T>...>;
|
756 |
+
template <class T, template <class> class... Predicates>
|
757 |
+
using satisfies_none_of = none_of<Predicates<T>...>;
|
758 |
+
|
759 |
+
/// Strip the class from a method type
|
760 |
+
template <typename T>
|
761 |
+
struct remove_class {};
|
762 |
+
template <typename C, typename R, typename... A>
|
763 |
+
struct remove_class<R (C::*)(A...)> {
|
764 |
+
using type = R(A...);
|
765 |
+
};
|
766 |
+
template <typename C, typename R, typename... A>
|
767 |
+
struct remove_class<R (C::*)(A...) const> {
|
768 |
+
using type = R(A...);
|
769 |
+
};
|
770 |
+
#ifdef __cpp_noexcept_function_type
|
771 |
+
template <typename C, typename R, typename... A>
|
772 |
+
struct remove_class<R (C::*)(A...) noexcept> {
|
773 |
+
using type = R(A...);
|
774 |
+
};
|
775 |
+
template <typename C, typename R, typename... A>
|
776 |
+
struct remove_class<R (C::*)(A...) const noexcept> {
|
777 |
+
using type = R(A...);
|
778 |
+
};
|
779 |
+
#endif
|
780 |
+
/// Helper template to strip away type modifiers
|
781 |
+
template <typename T>
|
782 |
+
struct intrinsic_type {
|
783 |
+
using type = T;
|
784 |
+
};
|
785 |
+
template <typename T>
|
786 |
+
struct intrinsic_type<const T> {
|
787 |
+
using type = typename intrinsic_type<T>::type;
|
788 |
+
};
|
789 |
+
template <typename T>
|
790 |
+
struct intrinsic_type<T *> {
|
791 |
+
using type = typename intrinsic_type<T>::type;
|
792 |
+
};
|
793 |
+
template <typename T>
|
794 |
+
struct intrinsic_type<T &> {
|
795 |
+
using type = typename intrinsic_type<T>::type;
|
796 |
+
};
|
797 |
+
template <typename T>
|
798 |
+
struct intrinsic_type<T &&> {
|
799 |
+
using type = typename intrinsic_type<T>::type;
|
800 |
+
};
|
801 |
+
template <typename T, size_t N>
|
802 |
+
struct intrinsic_type<const T[N]> {
|
803 |
+
using type = typename intrinsic_type<T>::type;
|
804 |
+
};
|
805 |
+
template <typename T, size_t N>
|
806 |
+
struct intrinsic_type<T[N]> {
|
807 |
+
using type = typename intrinsic_type<T>::type;
|
808 |
+
};
|
809 |
+
template <typename T>
|
810 |
+
using intrinsic_t = typename intrinsic_type<T>::type;
|
811 |
+
|
812 |
+
/// Helper type to replace 'void' in some expressions
|
813 |
+
struct void_type {};
|
814 |
+
|
815 |
+
/// Helper template which holds a list of types
|
816 |
+
template <typename...>
|
817 |
+
struct type_list {};
|
818 |
+
|
819 |
+
/// Compile-time integer sum
|
820 |
+
#ifdef __cpp_fold_expressions
|
821 |
+
template <typename... Ts>
|
822 |
+
constexpr size_t constexpr_sum(Ts... ns) {
|
823 |
+
return (0 + ... + size_t{ns});
|
824 |
+
}
|
825 |
+
#else
|
826 |
+
constexpr size_t constexpr_sum() { return 0; }
|
827 |
+
template <typename T, typename... Ts>
|
828 |
+
constexpr size_t constexpr_sum(T n, Ts... ns) {
|
829 |
+
return size_t{n} + constexpr_sum(ns...);
|
830 |
+
}
|
831 |
+
#endif
|
832 |
+
|
833 |
+
PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
|
834 |
+
/// Implementation details for constexpr functions
|
835 |
+
constexpr int first(int i) { return i; }
|
836 |
+
template <typename T, typename... Ts>
|
837 |
+
constexpr int first(int i, T v, Ts... vs) {
|
838 |
+
return v ? i : first(i + 1, vs...);
|
839 |
+
}
|
840 |
+
|
841 |
+
constexpr int last(int /*i*/, int result) { return result; }
|
842 |
+
template <typename T, typename... Ts>
|
843 |
+
constexpr int last(int i, int result, T v, Ts... vs) {
|
844 |
+
return last(i + 1, v ? i : result, vs...);
|
845 |
+
}
|
846 |
+
PYBIND11_NAMESPACE_END(constexpr_impl)
|
847 |
+
|
848 |
+
/// Return the index of the first type in Ts which satisfies Predicate<T>.
|
849 |
+
/// Returns sizeof...(Ts) if none match.
|
850 |
+
template <template <typename> class Predicate, typename... Ts>
|
851 |
+
constexpr int constexpr_first() {
|
852 |
+
return constexpr_impl::first(0, Predicate<Ts>::value...);
|
853 |
+
}
|
854 |
+
|
855 |
+
/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
|
856 |
+
template <template <typename> class Predicate, typename... Ts>
|
857 |
+
constexpr int constexpr_last() {
|
858 |
+
return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
|
859 |
+
}
|
860 |
+
|
861 |
+
/// Return the Nth element from the parameter pack
|
862 |
+
template <size_t N, typename T, typename... Ts>
|
863 |
+
struct pack_element {
|
864 |
+
using type = typename pack_element<N - 1, Ts...>::type;
|
865 |
+
};
|
866 |
+
template <typename T, typename... Ts>
|
867 |
+
struct pack_element<0, T, Ts...> {
|
868 |
+
using type = T;
|
869 |
+
};
|
870 |
+
|
871 |
+
/// Return the one and only type which matches the predicate, or Default if none match.
|
872 |
+
/// If more than one type matches the predicate, fail at compile-time.
|
873 |
+
template <template <typename> class Predicate, typename Default, typename... Ts>
|
874 |
+
struct exactly_one {
|
875 |
+
static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
|
876 |
+
static_assert(found <= 1, "Found more than one type matching the predicate");
|
877 |
+
|
878 |
+
static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
|
879 |
+
using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
|
880 |
+
};
|
881 |
+
template <template <typename> class P, typename Default>
|
882 |
+
struct exactly_one<P, Default> {
|
883 |
+
using type = Default;
|
884 |
+
};
|
885 |
+
|
886 |
+
template <template <typename> class Predicate, typename Default, typename... Ts>
|
887 |
+
using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
|
888 |
+
|
889 |
+
/// Defer the evaluation of type T until types Us are instantiated
|
890 |
+
template <typename T, typename... /*Us*/>
|
891 |
+
struct deferred_type {
|
892 |
+
using type = T;
|
893 |
+
};
|
894 |
+
template <typename T, typename... Us>
|
895 |
+
using deferred_t = typename deferred_type<T, Us...>::type;
|
896 |
+
|
897 |
+
/// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
|
898 |
+
/// unlike `std::is_base_of`)
|
899 |
+
template <typename Base, typename Derived>
|
900 |
+
using is_strict_base_of
|
901 |
+
= bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
|
902 |
+
|
903 |
+
/// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
|
904 |
+
/// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
|
905 |
+
/// we need to check `is_same` as well.
|
906 |
+
template <typename Base, typename Derived>
|
907 |
+
using is_accessible_base_of
|
908 |
+
= bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
|
909 |
+
&& std::is_convertible<Derived *, Base *>::value>;
|
910 |
+
|
911 |
+
template <template <typename...> class Base>
|
912 |
+
struct is_template_base_of_impl {
|
913 |
+
template <typename... Us>
|
914 |
+
static std::true_type check(Base<Us...> *);
|
915 |
+
static std::false_type check(...);
|
916 |
+
};
|
917 |
+
|
918 |
+
/// Check if a template is the base of a type. For example:
|
919 |
+
/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
|
920 |
+
template <template <typename...> class Base, typename T>
|
921 |
+
// Sadly, all MSVC versions incl. 2022 need the workaround, even in C++20 mode.
|
922 |
+
// See also: https://github.com/pybind/pybind11/pull/3741
|
923 |
+
#if !defined(_MSC_VER)
|
924 |
+
using is_template_base_of
|
925 |
+
= decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
|
926 |
+
#else
|
927 |
+
struct is_template_base_of
|
928 |
+
: decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)) {
|
929 |
+
};
|
930 |
+
#endif
|
931 |
+
|
932 |
+
/// Check if T is an instantiation of the template `Class`. For example:
|
933 |
+
/// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
|
934 |
+
template <template <typename...> class Class, typename T>
|
935 |
+
struct is_instantiation : std::false_type {};
|
936 |
+
template <template <typename...> class Class, typename... Us>
|
937 |
+
struct is_instantiation<Class, Class<Us...>> : std::true_type {};
|
938 |
+
|
939 |
+
/// Check if T is std::shared_ptr<U> where U can be anything
|
940 |
+
template <typename T>
|
941 |
+
using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
|
942 |
+
|
943 |
+
/// Check if T looks like an input iterator
|
944 |
+
template <typename T, typename = void>
|
945 |
+
struct is_input_iterator : std::false_type {};
|
946 |
+
template <typename T>
|
947 |
+
struct is_input_iterator<T,
|
948 |
+
void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
|
949 |
+
: std::true_type {};
|
950 |
+
|
951 |
+
template <typename T>
|
952 |
+
using is_function_pointer
|
953 |
+
= bool_constant<std::is_pointer<T>::value
|
954 |
+
&& std::is_function<typename std::remove_pointer<T>::type>::value>;
|
955 |
+
|
956 |
+
template <typename F>
|
957 |
+
struct strip_function_object {
|
958 |
+
// If you are encountering an
|
959 |
+
// 'error: name followed by "::" must be a class or namespace name'
|
960 |
+
// with the Intel compiler and a noexcept function here,
|
961 |
+
// try to use noexcept(true) instead of plain noexcept.
|
962 |
+
using type = typename remove_class<decltype(&F::operator())>::type;
|
963 |
+
};
|
964 |
+
|
965 |
+
// Extracts the function signature from a function, function pointer or lambda.
|
966 |
+
template <typename Function, typename F = remove_reference_t<Function>>
|
967 |
+
using function_signature_t = conditional_t<
|
968 |
+
std::is_function<F>::value,
|
969 |
+
F,
|
970 |
+
typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
|
971 |
+
std::remove_pointer<F>,
|
972 |
+
strip_function_object<F>>::type>;
|
973 |
+
|
974 |
+
/// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
|
975 |
+
/// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
|
976 |
+
/// in a place where passing a lambda makes sense.
|
977 |
+
template <typename T>
|
978 |
+
using is_lambda = satisfies_none_of<remove_reference_t<T>,
|
979 |
+
std::is_function,
|
980 |
+
std::is_pointer,
|
981 |
+
std::is_member_pointer>;
|
982 |
+
|
983 |
+
// [workaround(intel)] Internal error on fold expression
|
984 |
+
/// Apply a function over each element of a parameter pack
|
985 |
+
#if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
|
986 |
+
// Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
|
987 |
+
# define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
|
988 |
+
#else
|
989 |
+
using expand_side_effects = bool[];
|
990 |
+
# define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) \
|
991 |
+
(void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
|
992 |
+
#endif
|
993 |
+
|
994 |
+
PYBIND11_NAMESPACE_END(detail)
|
995 |
+
|
996 |
+
/// C++ bindings of builtin Python exceptions
|
997 |
+
class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
|
998 |
+
public:
|
999 |
+
using std::runtime_error::runtime_error;
|
1000 |
+
/// Set the error using the Python C API
|
1001 |
+
virtual void set_error() const = 0;
|
1002 |
+
};
|
1003 |
+
|
1004 |
+
#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
|
1005 |
+
class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { \
|
1006 |
+
public: \
|
1007 |
+
using builtin_exception::builtin_exception; \
|
1008 |
+
name() : name("") {} \
|
1009 |
+
void set_error() const override { PyErr_SetString(type, what()); } \
|
1010 |
+
};
|
1011 |
+
|
1012 |
+
PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
|
1013 |
+
PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
|
1014 |
+
PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
|
1015 |
+
PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
|
1016 |
+
PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
|
1017 |
+
PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
|
1018 |
+
PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
|
1019 |
+
PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
|
1020 |
+
PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
|
1021 |
+
/// handle::call fail due to a type
|
1022 |
+
/// casting error
|
1023 |
+
PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
|
1024 |
+
|
1025 |
+
[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
|
1026 |
+
assert(!PyErr_Occurred());
|
1027 |
+
throw std::runtime_error(reason);
|
1028 |
+
}
|
1029 |
+
[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
|
1030 |
+
assert(!PyErr_Occurred());
|
1031 |
+
throw std::runtime_error(reason);
|
1032 |
+
}
|
1033 |
+
|
1034 |
+
template <typename T, typename SFINAE = void>
|
1035 |
+
struct format_descriptor {};
|
1036 |
+
|
1037 |
+
template <typename T>
|
1038 |
+
struct format_descriptor<
|
1039 |
+
T,
|
1040 |
+
detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value>> {
|
1041 |
+
static constexpr const char c = 'O';
|
1042 |
+
static constexpr const char value[2] = {c, '\0'};
|
1043 |
+
static std::string format() { return std::string(1, c); }
|
1044 |
+
};
|
1045 |
+
|
1046 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1047 |
+
// Returns the index of the given type in the type char array below, and in the list in numpy.h
|
1048 |
+
// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
|
1049 |
+
// complex float,double,long double. Note that the long double types only participate when long
|
1050 |
+
// double is actually longer than double (it isn't under MSVC).
|
1051 |
+
// NB: not only the string below but also complex.h and numpy.h rely on this order.
|
1052 |
+
template <typename T, typename SFINAE = void>
|
1053 |
+
struct is_fmt_numeric {
|
1054 |
+
static constexpr bool value = false;
|
1055 |
+
};
|
1056 |
+
template <typename T>
|
1057 |
+
struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
|
1058 |
+
static constexpr bool value = true;
|
1059 |
+
static constexpr int index
|
1060 |
+
= std::is_same<T, bool>::value
|
1061 |
+
? 0
|
1062 |
+
: 1
|
1063 |
+
+ (std::is_integral<T>::value
|
1064 |
+
? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
|
1065 |
+
: 8
|
1066 |
+
+ (std::is_same<T, double>::value ? 1
|
1067 |
+
: std::is_same<T, long double>::value ? 2
|
1068 |
+
: 0));
|
1069 |
+
};
|
1070 |
+
PYBIND11_NAMESPACE_END(detail)
|
1071 |
+
|
1072 |
+
template <typename T>
|
1073 |
+
struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
|
1074 |
+
static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
|
1075 |
+
static constexpr const char value[2] = {c, '\0'};
|
1076 |
+
static std::string format() { return std::string(1, c); }
|
1077 |
+
};
|
1078 |
+
|
1079 |
+
#if !defined(PYBIND11_CPP17)
|
1080 |
+
|
1081 |
+
template <typename T>
|
1082 |
+
constexpr const char
|
1083 |
+
format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
|
1084 |
+
|
1085 |
+
#endif
|
1086 |
+
|
1087 |
+
/// RAII wrapper that temporarily clears any Python error state
|
1088 |
+
struct error_scope {
|
1089 |
+
PyObject *type, *value, *trace;
|
1090 |
+
error_scope() { PyErr_Fetch(&type, &value, &trace); }
|
1091 |
+
error_scope(const error_scope &) = delete;
|
1092 |
+
error_scope &operator=(const error_scope &) = delete;
|
1093 |
+
~error_scope() { PyErr_Restore(type, value, trace); }
|
1094 |
+
};
|
1095 |
+
|
1096 |
+
/// Dummy destructor wrapper that can be used to expose classes with a private destructor
|
1097 |
+
struct nodelete {
|
1098 |
+
template <typename T>
|
1099 |
+
void operator()(T *) {}
|
1100 |
+
};
|
1101 |
+
|
1102 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1103 |
+
template <typename... Args>
|
1104 |
+
struct overload_cast_impl {
|
1105 |
+
template <typename Return>
|
1106 |
+
constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
|
1107 |
+
return pf;
|
1108 |
+
}
|
1109 |
+
|
1110 |
+
template <typename Return, typename Class>
|
1111 |
+
constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
|
1112 |
+
-> decltype(pmf) {
|
1113 |
+
return pmf;
|
1114 |
+
}
|
1115 |
+
|
1116 |
+
template <typename Return, typename Class>
|
1117 |
+
constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
|
1118 |
+
-> decltype(pmf) {
|
1119 |
+
return pmf;
|
1120 |
+
}
|
1121 |
+
};
|
1122 |
+
PYBIND11_NAMESPACE_END(detail)
|
1123 |
+
|
1124 |
+
// overload_cast requires variable templates: C++14
|
1125 |
+
#if defined(PYBIND11_CPP14)
|
1126 |
+
# define PYBIND11_OVERLOAD_CAST 1
|
1127 |
+
/// Syntax sugar for resolving overloaded function pointers:
|
1128 |
+
/// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
|
1129 |
+
/// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
|
1130 |
+
template <typename... Args>
|
1131 |
+
static constexpr detail::overload_cast_impl<Args...> overload_cast{};
|
1132 |
+
#endif
|
1133 |
+
|
1134 |
+
/// Const member function selector for overload_cast
|
1135 |
+
/// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
|
1136 |
+
/// - sweet: overload_cast<Arg>(&Class::func, const_)
|
1137 |
+
static constexpr auto const_ = std::true_type{};
|
1138 |
+
|
1139 |
+
#if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
|
1140 |
+
template <typename... Args>
|
1141 |
+
struct overload_cast {
|
1142 |
+
static_assert(detail::deferred_t<std::false_type, Args...>::value,
|
1143 |
+
"pybind11::overload_cast<...> requires compiling in C++14 mode");
|
1144 |
+
};
|
1145 |
+
#endif // overload_cast
|
1146 |
+
|
1147 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1148 |
+
|
1149 |
+
// Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
|
1150 |
+
// any standard container (or C-style array) supporting std::begin/std::end, any singleton
|
1151 |
+
// arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
|
1152 |
+
template <typename T>
|
1153 |
+
class any_container {
|
1154 |
+
std::vector<T> v;
|
1155 |
+
|
1156 |
+
public:
|
1157 |
+
any_container() = default;
|
1158 |
+
|
1159 |
+
// Can construct from a pair of iterators
|
1160 |
+
template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
|
1161 |
+
any_container(It first, It last) : v(first, last) {}
|
1162 |
+
|
1163 |
+
// Implicit conversion constructor from any arbitrary container type
|
1164 |
+
// with values convertible to T
|
1165 |
+
template <typename Container,
|
1166 |
+
typename = enable_if_t<
|
1167 |
+
std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
|
1168 |
+
T>::value>>
|
1169 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
1170 |
+
any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
|
1171 |
+
|
1172 |
+
// initializer_list's aren't deducible, so don't get matched by the above template;
|
1173 |
+
// we need this to explicitly allow implicit conversion from one:
|
1174 |
+
template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
|
1175 |
+
any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
|
1176 |
+
|
1177 |
+
// Avoid copying if given an rvalue vector of the correct type.
|
1178 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
1179 |
+
any_container(std::vector<T> &&v) : v(std::move(v)) {}
|
1180 |
+
|
1181 |
+
// Moves the vector out of an rvalue any_container
|
1182 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
1183 |
+
operator std::vector<T> &&() && { return std::move(v); }
|
1184 |
+
|
1185 |
+
// Dereferencing obtains a reference to the underlying vector
|
1186 |
+
std::vector<T> &operator*() { return v; }
|
1187 |
+
const std::vector<T> &operator*() const { return v; }
|
1188 |
+
|
1189 |
+
// -> lets you call methods on the underlying vector
|
1190 |
+
std::vector<T> *operator->() { return &v; }
|
1191 |
+
const std::vector<T> *operator->() const { return &v; }
|
1192 |
+
};
|
1193 |
+
|
1194 |
+
// Forward-declaration; see detail/class.h
|
1195 |
+
std::string get_fully_qualified_tp_name(PyTypeObject *);
|
1196 |
+
|
1197 |
+
template <typename T>
|
1198 |
+
inline static std::shared_ptr<T>
|
1199 |
+
try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
|
1200 |
+
// Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
|
1201 |
+
// Use at your own risk!
|
1202 |
+
// See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
|
1203 |
+
// the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
|
1204 |
+
#if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
|
1205 |
+
return holder_value_ptr->weak_from_this().lock();
|
1206 |
+
#else
|
1207 |
+
try {
|
1208 |
+
return holder_value_ptr->shared_from_this();
|
1209 |
+
} catch (const std::bad_weak_ptr &) {
|
1210 |
+
return nullptr;
|
1211 |
+
}
|
1212 |
+
#endif
|
1213 |
+
}
|
1214 |
+
|
1215 |
+
// For silencing "unused" compiler warnings in special situations.
|
1216 |
+
template <typename... Args>
|
1217 |
+
#if defined(_MSC_VER) && _MSC_VER < 1920 // MSVC 2017
|
1218 |
+
constexpr
|
1219 |
+
#endif
|
1220 |
+
inline void
|
1221 |
+
silence_unused_warnings(Args &&...) {
|
1222 |
+
}
|
1223 |
+
|
1224 |
+
// MSVC warning C4100: Unreferenced formal parameter
|
1225 |
+
#if defined(_MSC_VER) && _MSC_VER <= 1916
|
1226 |
+
# define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...) \
|
1227 |
+
detail::silence_unused_warnings(__VA_ARGS__)
|
1228 |
+
#else
|
1229 |
+
# define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
|
1230 |
+
#endif
|
1231 |
+
|
1232 |
+
// GCC -Wunused-but-set-parameter All GCC versions (as of July 2021).
|
1233 |
+
#if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
|
1234 |
+
# define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...) \
|
1235 |
+
detail::silence_unused_warnings(__VA_ARGS__)
|
1236 |
+
#else
|
1237 |
+
# define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
|
1238 |
+
#endif
|
1239 |
+
|
1240 |
+
#if defined(__clang__) \
|
1241 |
+
&& (defined(__apple_build_version__) /* AppleClang 13.0.0.13000029 was the only data point \
|
1242 |
+
available. */ \
|
1243 |
+
|| (__clang_major__ >= 7 \
|
1244 |
+
&& __clang_major__ <= 12) /* Clang 3, 5, 13, 14, 15 do not generate the warning. */ \
|
1245 |
+
)
|
1246 |
+
# define PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
|
1247 |
+
// Example:
|
1248 |
+
// tests/test_kwargs_and_defaults.cpp:46:68: error: local variable 'args' will be copied despite
|
1249 |
+
// being returned by name [-Werror,-Wreturn-std-move]
|
1250 |
+
// m.def("args_function", [](py::args args) -> py::tuple { return args; });
|
1251 |
+
// ^~~~
|
1252 |
+
// test_kwargs_and_defaults.cpp:46:68: note: call 'std::move' explicitly to avoid copying
|
1253 |
+
// m.def("args_function", [](py::args args) -> py::tuple { return args; });
|
1254 |
+
// ^~~~
|
1255 |
+
// std::move(args)
|
1256 |
+
#endif
|
1257 |
+
|
1258 |
+
// Pybind offers detailed error messages by default for all builts that are debug (through the
|
1259 |
+
// negation of NDEBUG). This can also be manually enabled by users, for any builds, through
|
1260 |
+
// defining PYBIND11_DETAILED_ERROR_MESSAGES. This information is primarily useful for those
|
1261 |
+
// who are writing (as opposed to merely using) libraries that use pybind11.
|
1262 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(NDEBUG)
|
1263 |
+
# define PYBIND11_DETAILED_ERROR_MESSAGES
|
1264 |
+
#endif
|
1265 |
+
|
1266 |
+
PYBIND11_NAMESPACE_END(detail)
|
1267 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/descr.h
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time
|
3 |
+
|
4 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "common.h"
|
13 |
+
|
14 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
15 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
16 |
+
|
17 |
+
#if !defined(_MSC_VER)
|
18 |
+
# define PYBIND11_DESCR_CONSTEXPR static constexpr
|
19 |
+
#else
|
20 |
+
# define PYBIND11_DESCR_CONSTEXPR const
|
21 |
+
#endif
|
22 |
+
|
23 |
+
/* Concatenate type signatures at compile time */
|
24 |
+
template <size_t N, typename... Ts>
|
25 |
+
struct descr {
|
26 |
+
char text[N + 1]{'\0'};
|
27 |
+
|
28 |
+
constexpr descr() = default;
|
29 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
30 |
+
constexpr descr(char const (&s)[N + 1]) : descr(s, make_index_sequence<N>()) {}
|
31 |
+
|
32 |
+
template <size_t... Is>
|
33 |
+
constexpr descr(char const (&s)[N + 1], index_sequence<Is...>) : text{s[Is]..., '\0'} {}
|
34 |
+
|
35 |
+
template <typename... Chars>
|
36 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
37 |
+
constexpr descr(char c, Chars... cs) : text{c, static_cast<char>(cs)..., '\0'} {}
|
38 |
+
|
39 |
+
static constexpr std::array<const std::type_info *, sizeof...(Ts) + 1> types() {
|
40 |
+
return {{&typeid(Ts)..., nullptr}};
|
41 |
+
}
|
42 |
+
};
|
43 |
+
|
44 |
+
template <size_t N1, size_t N2, typename... Ts1, typename... Ts2, size_t... Is1, size_t... Is2>
|
45 |
+
constexpr descr<N1 + N2, Ts1..., Ts2...> plus_impl(const descr<N1, Ts1...> &a,
|
46 |
+
const descr<N2, Ts2...> &b,
|
47 |
+
index_sequence<Is1...>,
|
48 |
+
index_sequence<Is2...>) {
|
49 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(b);
|
50 |
+
return {a.text[Is1]..., b.text[Is2]...};
|
51 |
+
}
|
52 |
+
|
53 |
+
template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
|
54 |
+
constexpr descr<N1 + N2, Ts1..., Ts2...> operator+(const descr<N1, Ts1...> &a,
|
55 |
+
const descr<N2, Ts2...> &b) {
|
56 |
+
return plus_impl(a, b, make_index_sequence<N1>(), make_index_sequence<N2>());
|
57 |
+
}
|
58 |
+
|
59 |
+
template <size_t N>
|
60 |
+
constexpr descr<N - 1> const_name(char const (&text)[N]) {
|
61 |
+
return descr<N - 1>(text);
|
62 |
+
}
|
63 |
+
constexpr descr<0> const_name(char const (&)[1]) { return {}; }
|
64 |
+
|
65 |
+
template <size_t Rem, size_t... Digits>
|
66 |
+
struct int_to_str : int_to_str<Rem / 10, Rem % 10, Digits...> {};
|
67 |
+
template <size_t... Digits>
|
68 |
+
struct int_to_str<0, Digits...> {
|
69 |
+
// WARNING: This only works with C++17 or higher.
|
70 |
+
static constexpr auto digits = descr<sizeof...(Digits)>(('0' + Digits)...);
|
71 |
+
};
|
72 |
+
|
73 |
+
// Ternary description (like std::conditional)
|
74 |
+
template <bool B, size_t N1, size_t N2>
|
75 |
+
constexpr enable_if_t<B, descr<N1 - 1>> const_name(char const (&text1)[N1], char const (&)[N2]) {
|
76 |
+
return const_name(text1);
|
77 |
+
}
|
78 |
+
template <bool B, size_t N1, size_t N2>
|
79 |
+
constexpr enable_if_t<!B, descr<N2 - 1>> const_name(char const (&)[N1], char const (&text2)[N2]) {
|
80 |
+
return const_name(text2);
|
81 |
+
}
|
82 |
+
|
83 |
+
template <bool B, typename T1, typename T2>
|
84 |
+
constexpr enable_if_t<B, T1> const_name(const T1 &d, const T2 &) {
|
85 |
+
return d;
|
86 |
+
}
|
87 |
+
template <bool B, typename T1, typename T2>
|
88 |
+
constexpr enable_if_t<!B, T2> const_name(const T1 &, const T2 &d) {
|
89 |
+
return d;
|
90 |
+
}
|
91 |
+
|
92 |
+
template <size_t Size>
|
93 |
+
auto constexpr const_name() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
|
94 |
+
return int_to_str<Size / 10, Size % 10>::digits;
|
95 |
+
}
|
96 |
+
|
97 |
+
template <typename Type>
|
98 |
+
constexpr descr<1, Type> const_name() {
|
99 |
+
return {'%'};
|
100 |
+
}
|
101 |
+
|
102 |
+
// If "_" is defined as a macro, py::detail::_ cannot be provided.
|
103 |
+
// It is therefore best to use py::detail::const_name universally.
|
104 |
+
// This block is for backward compatibility only.
|
105 |
+
// (The const_name code is repeated to avoid introducing a "_" #define ourselves.)
|
106 |
+
#ifndef _
|
107 |
+
# define PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY
|
108 |
+
template <size_t N>
|
109 |
+
constexpr descr<N - 1> _(char const (&text)[N]) {
|
110 |
+
return const_name<N>(text);
|
111 |
+
}
|
112 |
+
template <bool B, size_t N1, size_t N2>
|
113 |
+
constexpr enable_if_t<B, descr<N1 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
|
114 |
+
return const_name<B, N1, N2>(text1, text2);
|
115 |
+
}
|
116 |
+
template <bool B, size_t N1, size_t N2>
|
117 |
+
constexpr enable_if_t<!B, descr<N2 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
|
118 |
+
return const_name<B, N1, N2>(text1, text2);
|
119 |
+
}
|
120 |
+
template <bool B, typename T1, typename T2>
|
121 |
+
constexpr enable_if_t<B, T1> _(const T1 &d1, const T2 &d2) {
|
122 |
+
return const_name<B, T1, T2>(d1, d2);
|
123 |
+
}
|
124 |
+
template <bool B, typename T1, typename T2>
|
125 |
+
constexpr enable_if_t<!B, T2> _(const T1 &d1, const T2 &d2) {
|
126 |
+
return const_name<B, T1, T2>(d1, d2);
|
127 |
+
}
|
128 |
+
|
129 |
+
template <size_t Size>
|
130 |
+
auto constexpr _() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
|
131 |
+
return const_name<Size>();
|
132 |
+
}
|
133 |
+
template <typename Type>
|
134 |
+
constexpr descr<1, Type> _() {
|
135 |
+
return const_name<Type>();
|
136 |
+
}
|
137 |
+
#endif // #ifndef _
|
138 |
+
|
139 |
+
constexpr descr<0> concat() { return {}; }
|
140 |
+
|
141 |
+
template <size_t N, typename... Ts>
|
142 |
+
constexpr descr<N, Ts...> concat(const descr<N, Ts...> &descr) {
|
143 |
+
return descr;
|
144 |
+
}
|
145 |
+
|
146 |
+
#ifdef __cpp_fold_expressions
|
147 |
+
template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
|
148 |
+
constexpr descr<N1 + N2 + 2, Ts1..., Ts2...> operator,(const descr<N1, Ts1...> &a,
|
149 |
+
const descr<N2, Ts2...> &b) {
|
150 |
+
return a + const_name(", ") + b;
|
151 |
+
}
|
152 |
+
|
153 |
+
template <size_t N, typename... Ts, typename... Args>
|
154 |
+
constexpr auto concat(const descr<N, Ts...> &d, const Args &...args) {
|
155 |
+
return (d, ..., args);
|
156 |
+
}
|
157 |
+
#else
|
158 |
+
template <size_t N, typename... Ts, typename... Args>
|
159 |
+
constexpr auto concat(const descr<N, Ts...> &d, const Args &...args)
|
160 |
+
-> decltype(std::declval<descr<N + 2, Ts...>>() + concat(args...)) {
|
161 |
+
return d + const_name(", ") + concat(args...);
|
162 |
+
}
|
163 |
+
#endif
|
164 |
+
|
165 |
+
template <size_t N, typename... Ts>
|
166 |
+
constexpr descr<N + 2, Ts...> type_descr(const descr<N, Ts...> &descr) {
|
167 |
+
return const_name("{") + descr + const_name("}");
|
168 |
+
}
|
169 |
+
|
170 |
+
PYBIND11_NAMESPACE_END(detail)
|
171 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/init.h
ADDED
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/detail/init.h: init factory function implementation and support code.
|
3 |
+
|
4 |
+
Copyright (c) 2017 Jason Rhinelander <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "class.h"
|
13 |
+
|
14 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
15 |
+
|
16 |
+
PYBIND11_WARNING_DISABLE_MSVC(4127)
|
17 |
+
|
18 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
19 |
+
|
20 |
+
template <>
|
21 |
+
class type_caster<value_and_holder> {
|
22 |
+
public:
|
23 |
+
bool load(handle h, bool) {
|
24 |
+
value = reinterpret_cast<value_and_holder *>(h.ptr());
|
25 |
+
return true;
|
26 |
+
}
|
27 |
+
|
28 |
+
template <typename>
|
29 |
+
using cast_op_type = value_and_holder &;
|
30 |
+
explicit operator value_and_holder &() { return *value; }
|
31 |
+
static constexpr auto name = const_name<value_and_holder>();
|
32 |
+
|
33 |
+
private:
|
34 |
+
value_and_holder *value = nullptr;
|
35 |
+
};
|
36 |
+
|
37 |
+
PYBIND11_NAMESPACE_BEGIN(initimpl)
|
38 |
+
|
39 |
+
inline void no_nullptr(void *ptr) {
|
40 |
+
if (!ptr) {
|
41 |
+
throw type_error("pybind11::init(): factory function returned nullptr");
|
42 |
+
}
|
43 |
+
}
|
44 |
+
|
45 |
+
// Implementing functions for all forms of py::init<...> and py::init(...)
|
46 |
+
template <typename Class>
|
47 |
+
using Cpp = typename Class::type;
|
48 |
+
template <typename Class>
|
49 |
+
using Alias = typename Class::type_alias;
|
50 |
+
template <typename Class>
|
51 |
+
using Holder = typename Class::holder_type;
|
52 |
+
|
53 |
+
template <typename Class>
|
54 |
+
using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
|
55 |
+
|
56 |
+
// Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.
|
57 |
+
template <typename Class, enable_if_t<Class::has_alias, int> = 0>
|
58 |
+
bool is_alias(Cpp<Class> *ptr) {
|
59 |
+
return dynamic_cast<Alias<Class> *>(ptr) != nullptr;
|
60 |
+
}
|
61 |
+
// Failing fallback version of the above for a no-alias class (always returns false)
|
62 |
+
template <typename /*Class*/>
|
63 |
+
constexpr bool is_alias(void *) {
|
64 |
+
return false;
|
65 |
+
}
|
66 |
+
|
67 |
+
// Constructs and returns a new object; if the given arguments don't map to a constructor, we fall
|
68 |
+
// back to brace aggregate initialization so that for aggregate initialization can be used with
|
69 |
+
// py::init, e.g. `py::init<int, int>` to initialize a `struct T { int a; int b; }`. For
|
70 |
+
// non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually
|
71 |
+
// works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).
|
72 |
+
template <typename Class,
|
73 |
+
typename... Args,
|
74 |
+
detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
|
75 |
+
inline Class *construct_or_initialize(Args &&...args) {
|
76 |
+
return new Class(std::forward<Args>(args)...);
|
77 |
+
}
|
78 |
+
template <typename Class,
|
79 |
+
typename... Args,
|
80 |
+
detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
|
81 |
+
inline Class *construct_or_initialize(Args &&...args) {
|
82 |
+
return new Class{std::forward<Args>(args)...};
|
83 |
+
}
|
84 |
+
|
85 |
+
// Attempts to constructs an alias using a `Alias(Cpp &&)` constructor. This allows types with
|
86 |
+
// an alias to provide only a single Cpp factory function as long as the Alias can be
|
87 |
+
// constructed from an rvalue reference of the base Cpp type. This means that Alias classes
|
88 |
+
// can, when appropriate, simply define a `Alias(Cpp &&)` constructor rather than needing to
|
89 |
+
// inherit all the base class constructors.
|
90 |
+
template <typename Class>
|
91 |
+
void construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,
|
92 |
+
value_and_holder &v_h,
|
93 |
+
Cpp<Class> &&base) {
|
94 |
+
v_h.value_ptr() = new Alias<Class>(std::move(base));
|
95 |
+
}
|
96 |
+
template <typename Class>
|
97 |
+
[[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,
|
98 |
+
value_and_holder &,
|
99 |
+
Cpp<Class> &&) {
|
100 |
+
throw type_error("pybind11::init(): unable to convert returned instance to required "
|
101 |
+
"alias class: no `Alias<Class>(Class &&)` constructor available");
|
102 |
+
}
|
103 |
+
|
104 |
+
// Error-generating fallback for factories that don't match one of the below construction
|
105 |
+
// mechanisms.
|
106 |
+
template <typename Class>
|
107 |
+
void construct(...) {
|
108 |
+
static_assert(!std::is_same<Class, Class>::value /* always false */,
|
109 |
+
"pybind11::init(): init function must return a compatible pointer, "
|
110 |
+
"holder, or value");
|
111 |
+
}
|
112 |
+
|
113 |
+
// Pointer return v1: the factory function returns a class pointer for a registered class.
|
114 |
+
// If we don't need an alias (because this class doesn't have one, or because the final type is
|
115 |
+
// inherited on the Python side) we can simply take over ownership. Otherwise we need to try to
|
116 |
+
// construct an Alias from the returned base instance.
|
117 |
+
template <typename Class>
|
118 |
+
void construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {
|
119 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
|
120 |
+
no_nullptr(ptr);
|
121 |
+
if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
|
122 |
+
// We're going to try to construct an alias by moving the cpp type. Whether or not
|
123 |
+
// that succeeds, we still need to destroy the original cpp pointer (either the
|
124 |
+
// moved away leftover, if the alias construction works, or the value itself if we
|
125 |
+
// throw an error), but we can't just call `delete ptr`: it might have a special
|
126 |
+
// deleter, or might be shared_from_this. So we construct a holder around it as if
|
127 |
+
// it was a normal instance, then steal the holder away into a local variable; thus
|
128 |
+
// the holder and destruction happens when we leave the C++ scope, and the holder
|
129 |
+
// class gets to handle the destruction however it likes.
|
130 |
+
v_h.value_ptr() = ptr;
|
131 |
+
v_h.set_instance_registered(true); // To prevent init_instance from registering it
|
132 |
+
v_h.type->init_instance(v_h.inst, nullptr); // Set up the holder
|
133 |
+
Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder
|
134 |
+
v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null
|
135 |
+
v_h.set_instance_registered(false);
|
136 |
+
|
137 |
+
construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(*ptr));
|
138 |
+
} else {
|
139 |
+
// Otherwise the type isn't inherited, so we don't need an Alias
|
140 |
+
v_h.value_ptr() = ptr;
|
141 |
+
}
|
142 |
+
}
|
143 |
+
|
144 |
+
// Pointer return v2: a factory that always returns an alias instance ptr. We simply take over
|
145 |
+
// ownership of the pointer.
|
146 |
+
template <typename Class, enable_if_t<Class::has_alias, int> = 0>
|
147 |
+
void construct(value_and_holder &v_h, Alias<Class> *alias_ptr, bool) {
|
148 |
+
no_nullptr(alias_ptr);
|
149 |
+
v_h.value_ptr() = static_cast<Cpp<Class> *>(alias_ptr);
|
150 |
+
}
|
151 |
+
|
152 |
+
// Holder return: copy its pointer, and move or copy the returned holder into the new instance's
|
153 |
+
// holder. This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a
|
154 |
+
// derived type (through those holder's implicit conversion from derived class holder
|
155 |
+
// constructors).
|
156 |
+
template <typename Class>
|
157 |
+
void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
|
158 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
|
159 |
+
auto *ptr = holder_helper<Holder<Class>>::get(holder);
|
160 |
+
no_nullptr(ptr);
|
161 |
+
// If we need an alias, check that the held pointer is actually an alias instance
|
162 |
+
if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
|
163 |
+
throw type_error("pybind11::init(): construction failed: returned holder-wrapped instance "
|
164 |
+
"is not an alias instance");
|
165 |
+
}
|
166 |
+
|
167 |
+
v_h.value_ptr() = ptr;
|
168 |
+
v_h.type->init_instance(v_h.inst, &holder);
|
169 |
+
}
|
170 |
+
|
171 |
+
// return-by-value version 1: returning a cpp class by value. If the class has an alias and an
|
172 |
+
// alias is required the alias must have an `Alias(Cpp &&)` constructor so that we can construct
|
173 |
+
// the alias from the base when needed (i.e. because of Python-side inheritance). When we don't
|
174 |
+
// need it, we simply move-construct the cpp value into a new instance.
|
175 |
+
template <typename Class>
|
176 |
+
void construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {
|
177 |
+
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
|
178 |
+
static_assert(is_move_constructible<Cpp<Class>>::value,
|
179 |
+
"pybind11::init() return-by-value factory function requires a movable class");
|
180 |
+
if (Class::has_alias && need_alias) {
|
181 |
+
construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));
|
182 |
+
} else {
|
183 |
+
v_h.value_ptr() = new Cpp<Class>(std::move(result));
|
184 |
+
}
|
185 |
+
}
|
186 |
+
|
187 |
+
// return-by-value version 2: returning a value of the alias type itself. We move-construct an
|
188 |
+
// Alias instance (even if no the python-side inheritance is involved). The is intended for
|
189 |
+
// cases where Alias initialization is always desired.
|
190 |
+
template <typename Class>
|
191 |
+
void construct(value_and_holder &v_h, Alias<Class> &&result, bool) {
|
192 |
+
static_assert(
|
193 |
+
is_move_constructible<Alias<Class>>::value,
|
194 |
+
"pybind11::init() return-by-alias-value factory function requires a movable alias class");
|
195 |
+
v_h.value_ptr() = new Alias<Class>(std::move(result));
|
196 |
+
}
|
197 |
+
|
198 |
+
// Implementing class for py::init<...>()
|
199 |
+
template <typename... Args>
|
200 |
+
struct constructor {
|
201 |
+
template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
|
202 |
+
static void execute(Class &cl, const Extra &...extra) {
|
203 |
+
cl.def(
|
204 |
+
"__init__",
|
205 |
+
[](value_and_holder &v_h, Args... args) {
|
206 |
+
v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
|
207 |
+
},
|
208 |
+
is_new_style_constructor(),
|
209 |
+
extra...);
|
210 |
+
}
|
211 |
+
|
212 |
+
template <
|
213 |
+
typename Class,
|
214 |
+
typename... Extra,
|
215 |
+
enable_if_t<Class::has_alias && std::is_constructible<Cpp<Class>, Args...>::value, int>
|
216 |
+
= 0>
|
217 |
+
static void execute(Class &cl, const Extra &...extra) {
|
218 |
+
cl.def(
|
219 |
+
"__init__",
|
220 |
+
[](value_and_holder &v_h, Args... args) {
|
221 |
+
if (Py_TYPE(v_h.inst) == v_h.type->type) {
|
222 |
+
v_h.value_ptr()
|
223 |
+
= construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
|
224 |
+
} else {
|
225 |
+
v_h.value_ptr()
|
226 |
+
= construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
|
227 |
+
}
|
228 |
+
},
|
229 |
+
is_new_style_constructor(),
|
230 |
+
extra...);
|
231 |
+
}
|
232 |
+
|
233 |
+
template <
|
234 |
+
typename Class,
|
235 |
+
typename... Extra,
|
236 |
+
enable_if_t<Class::has_alias && !std::is_constructible<Cpp<Class>, Args...>::value, int>
|
237 |
+
= 0>
|
238 |
+
static void execute(Class &cl, const Extra &...extra) {
|
239 |
+
cl.def(
|
240 |
+
"__init__",
|
241 |
+
[](value_and_holder &v_h, Args... args) {
|
242 |
+
v_h.value_ptr()
|
243 |
+
= construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
|
244 |
+
},
|
245 |
+
is_new_style_constructor(),
|
246 |
+
extra...);
|
247 |
+
}
|
248 |
+
};
|
249 |
+
|
250 |
+
// Implementing class for py::init_alias<...>()
|
251 |
+
template <typename... Args>
|
252 |
+
struct alias_constructor {
|
253 |
+
template <
|
254 |
+
typename Class,
|
255 |
+
typename... Extra,
|
256 |
+
enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value, int>
|
257 |
+
= 0>
|
258 |
+
static void execute(Class &cl, const Extra &...extra) {
|
259 |
+
cl.def(
|
260 |
+
"__init__",
|
261 |
+
[](value_and_holder &v_h, Args... args) {
|
262 |
+
v_h.value_ptr()
|
263 |
+
= construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
|
264 |
+
},
|
265 |
+
is_new_style_constructor(),
|
266 |
+
extra...);
|
267 |
+
}
|
268 |
+
};
|
269 |
+
|
270 |
+
// Implementation class for py::init(Func) and py::init(Func, AliasFunc)
|
271 |
+
template <typename CFunc,
|
272 |
+
typename AFunc = void_type (*)(),
|
273 |
+
typename = function_signature_t<CFunc>,
|
274 |
+
typename = function_signature_t<AFunc>>
|
275 |
+
struct factory;
|
276 |
+
|
277 |
+
// Specialization for py::init(Func)
|
278 |
+
template <typename Func, typename Return, typename... Args>
|
279 |
+
struct factory<Func, void_type (*)(), Return(Args...)> {
|
280 |
+
remove_reference_t<Func> class_factory;
|
281 |
+
|
282 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
283 |
+
factory(Func &&f) : class_factory(std::forward<Func>(f)) {}
|
284 |
+
|
285 |
+
// The given class either has no alias or has no separate alias factory;
|
286 |
+
// this always constructs the class itself. If the class is registered with an alias
|
287 |
+
// type and an alias instance is needed (i.e. because the final type is a Python class
|
288 |
+
// inheriting from the C++ type) the returned value needs to either already be an alias
|
289 |
+
// instance, or the alias needs to be constructible from a `Class &&` argument.
|
290 |
+
template <typename Class, typename... Extra>
|
291 |
+
void execute(Class &cl, const Extra &...extra) && {
|
292 |
+
#if defined(PYBIND11_CPP14)
|
293 |
+
cl.def(
|
294 |
+
"__init__",
|
295 |
+
[func = std::move(class_factory)]
|
296 |
+
#else
|
297 |
+
auto &func = class_factory;
|
298 |
+
cl.def(
|
299 |
+
"__init__",
|
300 |
+
[func]
|
301 |
+
#endif
|
302 |
+
(value_and_holder &v_h, Args... args) {
|
303 |
+
construct<Class>(
|
304 |
+
v_h, func(std::forward<Args>(args)...), Py_TYPE(v_h.inst) != v_h.type->type);
|
305 |
+
},
|
306 |
+
is_new_style_constructor(),
|
307 |
+
extra...);
|
308 |
+
}
|
309 |
+
};
|
310 |
+
|
311 |
+
// Specialization for py::init(Func, AliasFunc)
|
312 |
+
template <typename CFunc,
|
313 |
+
typename AFunc,
|
314 |
+
typename CReturn,
|
315 |
+
typename... CArgs,
|
316 |
+
typename AReturn,
|
317 |
+
typename... AArgs>
|
318 |
+
struct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {
|
319 |
+
static_assert(sizeof...(CArgs) == sizeof...(AArgs),
|
320 |
+
"pybind11::init(class_factory, alias_factory): class and alias factories "
|
321 |
+
"must have identical argument signatures");
|
322 |
+
static_assert(all_of<std::is_same<CArgs, AArgs>...>::value,
|
323 |
+
"pybind11::init(class_factory, alias_factory): class and alias factories "
|
324 |
+
"must have identical argument signatures");
|
325 |
+
|
326 |
+
remove_reference_t<CFunc> class_factory;
|
327 |
+
remove_reference_t<AFunc> alias_factory;
|
328 |
+
|
329 |
+
factory(CFunc &&c, AFunc &&a)
|
330 |
+
: class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) {}
|
331 |
+
|
332 |
+
// The class factory is called when the `self` type passed to `__init__` is the direct
|
333 |
+
// class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.
|
334 |
+
template <typename Class, typename... Extra>
|
335 |
+
void execute(Class &cl, const Extra &...extra) && {
|
336 |
+
static_assert(Class::has_alias,
|
337 |
+
"The two-argument version of `py::init()` can "
|
338 |
+
"only be used if the class has an alias");
|
339 |
+
#if defined(PYBIND11_CPP14)
|
340 |
+
cl.def(
|
341 |
+
"__init__",
|
342 |
+
[class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
|
343 |
+
#else
|
344 |
+
auto &class_func = class_factory;
|
345 |
+
auto &alias_func = alias_factory;
|
346 |
+
cl.def(
|
347 |
+
"__init__",
|
348 |
+
[class_func, alias_func]
|
349 |
+
#endif
|
350 |
+
(value_and_holder &v_h, CArgs... args) {
|
351 |
+
if (Py_TYPE(v_h.inst) == v_h.type->type) {
|
352 |
+
// If the instance type equals the registered type we don't have inheritance,
|
353 |
+
// so don't need the alias and can construct using the class function:
|
354 |
+
construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
|
355 |
+
} else {
|
356 |
+
construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
|
357 |
+
}
|
358 |
+
},
|
359 |
+
is_new_style_constructor(),
|
360 |
+
extra...);
|
361 |
+
}
|
362 |
+
};
|
363 |
+
|
364 |
+
/// Set just the C++ state. Same as `__init__`.
|
365 |
+
template <typename Class, typename T>
|
366 |
+
void setstate(value_and_holder &v_h, T &&result, bool need_alias) {
|
367 |
+
construct<Class>(v_h, std::forward<T>(result), need_alias);
|
368 |
+
}
|
369 |
+
|
370 |
+
/// Set both the C++ and Python states
|
371 |
+
template <typename Class,
|
372 |
+
typename T,
|
373 |
+
typename O,
|
374 |
+
enable_if_t<std::is_convertible<O, handle>::value, int> = 0>
|
375 |
+
void setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {
|
376 |
+
construct<Class>(v_h, std::move(result.first), need_alias);
|
377 |
+
auto d = handle(result.second);
|
378 |
+
if (PyDict_Check(d.ptr()) && PyDict_Size(d.ptr()) == 0) {
|
379 |
+
// Skipping setattr below, to not force use of py::dynamic_attr() for Class unnecessarily.
|
380 |
+
// See PR #2972 for details.
|
381 |
+
return;
|
382 |
+
}
|
383 |
+
setattr((PyObject *) v_h.inst, "__dict__", d);
|
384 |
+
}
|
385 |
+
|
386 |
+
/// Implementation for py::pickle(GetState, SetState)
|
387 |
+
template <typename Get,
|
388 |
+
typename Set,
|
389 |
+
typename = function_signature_t<Get>,
|
390 |
+
typename = function_signature_t<Set>>
|
391 |
+
struct pickle_factory;
|
392 |
+
|
393 |
+
template <typename Get,
|
394 |
+
typename Set,
|
395 |
+
typename RetState,
|
396 |
+
typename Self,
|
397 |
+
typename NewInstance,
|
398 |
+
typename ArgState>
|
399 |
+
struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
|
400 |
+
static_assert(std::is_same<intrinsic_t<RetState>, intrinsic_t<ArgState>>::value,
|
401 |
+
"The type returned by `__getstate__` must be the same "
|
402 |
+
"as the argument accepted by `__setstate__`");
|
403 |
+
|
404 |
+
remove_reference_t<Get> get;
|
405 |
+
remove_reference_t<Set> set;
|
406 |
+
|
407 |
+
pickle_factory(Get get, Set set) : get(std::forward<Get>(get)), set(std::forward<Set>(set)) {}
|
408 |
+
|
409 |
+
template <typename Class, typename... Extra>
|
410 |
+
void execute(Class &cl, const Extra &...extra) && {
|
411 |
+
cl.def("__getstate__", std::move(get));
|
412 |
+
|
413 |
+
#if defined(PYBIND11_CPP14)
|
414 |
+
cl.def(
|
415 |
+
"__setstate__",
|
416 |
+
[func = std::move(set)]
|
417 |
+
#else
|
418 |
+
auto &func = set;
|
419 |
+
cl.def(
|
420 |
+
"__setstate__",
|
421 |
+
[func]
|
422 |
+
#endif
|
423 |
+
(value_and_holder &v_h, ArgState state) {
|
424 |
+
setstate<Class>(
|
425 |
+
v_h, func(std::forward<ArgState>(state)), Py_TYPE(v_h.inst) != v_h.type->type);
|
426 |
+
},
|
427 |
+
is_new_style_constructor(),
|
428 |
+
extra...);
|
429 |
+
}
|
430 |
+
};
|
431 |
+
|
432 |
+
PYBIND11_NAMESPACE_END(initimpl)
|
433 |
+
PYBIND11_NAMESPACE_END(detail)
|
434 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/internals.h
ADDED
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/detail/internals.h: Internal data structure and related functions
|
3 |
+
|
4 |
+
Copyright (c) 2017 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "common.h"
|
13 |
+
|
14 |
+
#if defined(WITH_THREAD) && defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
|
15 |
+
# include "../gil.h"
|
16 |
+
#endif
|
17 |
+
|
18 |
+
#include "../pytypes.h"
|
19 |
+
|
20 |
+
#include <exception>
|
21 |
+
|
22 |
+
/// Tracks the `internals` and `type_info` ABI version independent of the main library version.
|
23 |
+
///
|
24 |
+
/// Some portions of the code use an ABI that is conditional depending on this
|
25 |
+
/// version number. That allows ABI-breaking changes to be "pre-implemented".
|
26 |
+
/// Once the default version number is incremented, the conditional logic that
|
27 |
+
/// no longer applies can be removed. Additionally, users that need not
|
28 |
+
/// maintain ABI compatibility can increase the version number in order to take
|
29 |
+
/// advantage of any functionality/efficiency improvements that depend on the
|
30 |
+
/// newer ABI.
|
31 |
+
///
|
32 |
+
/// WARNING: If you choose to manually increase the ABI version, note that
|
33 |
+
/// pybind11 may not be tested as thoroughly with a non-default ABI version, and
|
34 |
+
/// further ABI-incompatible changes may be made before the ABI is officially
|
35 |
+
/// changed to the new version.
|
36 |
+
#ifndef PYBIND11_INTERNALS_VERSION
|
37 |
+
# if PY_VERSION_HEX >= 0x030C0000 || defined(_MSC_VER)
|
38 |
+
// Version bump for Python 3.12+, before first 3.12 beta release.
|
39 |
+
// Version bump for MSVC piggy-backed on PR #4779. See comments there.
|
40 |
+
# define PYBIND11_INTERNALS_VERSION 5
|
41 |
+
# else
|
42 |
+
# define PYBIND11_INTERNALS_VERSION 4
|
43 |
+
# endif
|
44 |
+
#endif
|
45 |
+
|
46 |
+
// This requirement is mainly to reduce the support burden (see PR #4570).
|
47 |
+
static_assert(PY_VERSION_HEX < 0x030C0000 || PYBIND11_INTERNALS_VERSION >= 5,
|
48 |
+
"pybind11 ABI version 5 is the minimum for Python 3.12+");
|
49 |
+
|
50 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
51 |
+
|
52 |
+
using ExceptionTranslator = void (*)(std::exception_ptr);
|
53 |
+
|
54 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
55 |
+
|
56 |
+
constexpr const char *internals_function_record_capsule_name = "pybind11_function_record_capsule";
|
57 |
+
|
58 |
+
// Forward declarations
|
59 |
+
inline PyTypeObject *make_static_property_type();
|
60 |
+
inline PyTypeObject *make_default_metaclass();
|
61 |
+
inline PyObject *make_object_base_type(PyTypeObject *metaclass);
|
62 |
+
|
63 |
+
// The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
|
64 |
+
// Thread Specific Storage (TSS) API.
|
65 |
+
#if PY_VERSION_HEX >= 0x03070000
|
66 |
+
// Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
|
67 |
+
// `Py_LIMITED_API` anyway.
|
68 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
69 |
+
# define PYBIND11_TLS_KEY_REF Py_tss_t &
|
70 |
+
# if defined(__clang__)
|
71 |
+
# define PYBIND11_TLS_KEY_INIT(var) \
|
72 |
+
_Pragma("clang diagnostic push") /**/ \
|
73 |
+
_Pragma("clang diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
|
74 |
+
Py_tss_t var \
|
75 |
+
= Py_tss_NEEDS_INIT; \
|
76 |
+
_Pragma("clang diagnostic pop")
|
77 |
+
# elif defined(__GNUC__) && !defined(__INTEL_COMPILER)
|
78 |
+
# define PYBIND11_TLS_KEY_INIT(var) \
|
79 |
+
_Pragma("GCC diagnostic push") /**/ \
|
80 |
+
_Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
|
81 |
+
Py_tss_t var \
|
82 |
+
= Py_tss_NEEDS_INIT; \
|
83 |
+
_Pragma("GCC diagnostic pop")
|
84 |
+
# else
|
85 |
+
# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;
|
86 |
+
# endif
|
87 |
+
# define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
|
88 |
+
# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
|
89 |
+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
|
90 |
+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
|
91 |
+
# define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
|
92 |
+
# else
|
93 |
+
# define PYBIND11_TLS_KEY_REF Py_tss_t *
|
94 |
+
# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr;
|
95 |
+
# define PYBIND11_TLS_KEY_CREATE(var) \
|
96 |
+
(((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
|
97 |
+
# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
|
98 |
+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
|
99 |
+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
|
100 |
+
# define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
|
101 |
+
# endif
|
102 |
+
#else
|
103 |
+
// Usually an int but a long on Cygwin64 with Python 3.x
|
104 |
+
# define PYBIND11_TLS_KEY_REF decltype(PyThread_create_key())
|
105 |
+
# define PYBIND11_TLS_KEY_INIT(var) PYBIND11_TLS_KEY_REF var = 0;
|
106 |
+
# define PYBIND11_TLS_KEY_CREATE(var) (((var) = PyThread_create_key()) != -1)
|
107 |
+
# define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
|
108 |
+
# if defined(PYPY_VERSION)
|
109 |
+
// On CPython < 3.4 and on PyPy, `PyThread_set_key_value` strangely does not set
|
110 |
+
// the value if it has already been set. Instead, it must first be deleted and
|
111 |
+
// then set again.
|
112 |
+
inline void tls_replace_value(PYBIND11_TLS_KEY_REF key, void *value) {
|
113 |
+
PyThread_delete_key_value(key);
|
114 |
+
PyThread_set_key_value(key, value);
|
115 |
+
}
|
116 |
+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_delete_key_value(key)
|
117 |
+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) \
|
118 |
+
::pybind11::detail::tls_replace_value((key), (value))
|
119 |
+
# else
|
120 |
+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_set_key_value((key), nullptr)
|
121 |
+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_set_key_value((key), (value))
|
122 |
+
# endif
|
123 |
+
# define PYBIND11_TLS_FREE(key) (void) key
|
124 |
+
#endif
|
125 |
+
|
126 |
+
// Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
|
127 |
+
// other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
|
128 |
+
// even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under
|
129 |
+
// libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
|
130 |
+
// which works. If not under a known-good stl, provide our own name-based hash and equality
|
131 |
+
// functions that use the type name.
|
132 |
+
#if (PYBIND11_INTERNALS_VERSION <= 4 && defined(__GLIBCXX__)) \
|
133 |
+
|| (PYBIND11_INTERNALS_VERSION >= 5 && !defined(_LIBCPP_VERSION))
|
134 |
+
inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
|
135 |
+
using type_hash = std::hash<std::type_index>;
|
136 |
+
using type_equal_to = std::equal_to<std::type_index>;
|
137 |
+
#else
|
138 |
+
inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
|
139 |
+
return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
|
140 |
+
}
|
141 |
+
|
142 |
+
struct type_hash {
|
143 |
+
size_t operator()(const std::type_index &t) const {
|
144 |
+
size_t hash = 5381;
|
145 |
+
const char *ptr = t.name();
|
146 |
+
while (auto c = static_cast<unsigned char>(*ptr++)) {
|
147 |
+
hash = (hash * 33) ^ c;
|
148 |
+
}
|
149 |
+
return hash;
|
150 |
+
}
|
151 |
+
};
|
152 |
+
|
153 |
+
struct type_equal_to {
|
154 |
+
bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
|
155 |
+
return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
|
156 |
+
}
|
157 |
+
};
|
158 |
+
#endif
|
159 |
+
|
160 |
+
template <typename value_type>
|
161 |
+
using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
|
162 |
+
|
163 |
+
struct override_hash {
|
164 |
+
inline size_t operator()(const std::pair<const PyObject *, const char *> &v) const {
|
165 |
+
size_t value = std::hash<const void *>()(v.first);
|
166 |
+
value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);
|
167 |
+
return value;
|
168 |
+
}
|
169 |
+
};
|
170 |
+
|
171 |
+
/// Internal data structure used to track registered instances and types.
|
172 |
+
/// Whenever binary incompatible changes are made to this structure,
|
173 |
+
/// `PYBIND11_INTERNALS_VERSION` must be incremented.
|
174 |
+
struct internals {
|
175 |
+
// std::type_index -> pybind11's type information
|
176 |
+
type_map<type_info *> registered_types_cpp;
|
177 |
+
// PyTypeObject* -> base type_info(s)
|
178 |
+
std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
|
179 |
+
std::unordered_multimap<const void *, instance *> registered_instances; // void * -> instance*
|
180 |
+
std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
|
181 |
+
inactive_override_cache;
|
182 |
+
type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
|
183 |
+
std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
|
184 |
+
std::forward_list<ExceptionTranslator> registered_exception_translators;
|
185 |
+
std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
|
186 |
+
// extensions
|
187 |
+
#if PYBIND11_INTERNALS_VERSION == 4
|
188 |
+
std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
|
189 |
+
#endif
|
190 |
+
std::forward_list<std::string> static_strings; // Stores the std::strings backing
|
191 |
+
// detail::c_str()
|
192 |
+
PyTypeObject *static_property_type;
|
193 |
+
PyTypeObject *default_metaclass;
|
194 |
+
PyObject *instance_base;
|
195 |
+
#if defined(WITH_THREAD)
|
196 |
+
// Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
|
197 |
+
PYBIND11_TLS_KEY_INIT(tstate)
|
198 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
199 |
+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
|
200 |
+
# endif // PYBIND11_INTERNALS_VERSION > 4
|
201 |
+
// Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
|
202 |
+
PyInterpreterState *istate = nullptr;
|
203 |
+
|
204 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
205 |
+
// Note that we have to use a std::string to allocate memory to ensure a unique address
|
206 |
+
// We want unique addresses since we use pointer equality to compare function records
|
207 |
+
std::string function_record_capsule_name = internals_function_record_capsule_name;
|
208 |
+
# endif
|
209 |
+
|
210 |
+
internals() = default;
|
211 |
+
internals(const internals &other) = delete;
|
212 |
+
internals &operator=(const internals &other) = delete;
|
213 |
+
~internals() {
|
214 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
215 |
+
PYBIND11_TLS_FREE(loader_life_support_tls_key);
|
216 |
+
# endif // PYBIND11_INTERNALS_VERSION > 4
|
217 |
+
|
218 |
+
// This destructor is called *after* Py_Finalize() in finalize_interpreter().
|
219 |
+
// That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
|
220 |
+
// called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
|
221 |
+
// nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
|
222 |
+
// PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
|
223 |
+
// Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
|
224 |
+
// that the `tstate` be allocated with the CPython allocator.
|
225 |
+
PYBIND11_TLS_FREE(tstate);
|
226 |
+
}
|
227 |
+
#endif
|
228 |
+
};
|
229 |
+
|
230 |
+
/// Additional type information which does not fit into the PyTypeObject.
|
231 |
+
/// Changes to this struct also require bumping `PYBIND11_INTERNALS_VERSION`.
|
232 |
+
struct type_info {
|
233 |
+
PyTypeObject *type;
|
234 |
+
const std::type_info *cpptype;
|
235 |
+
size_t type_size, type_align, holder_size_in_ptrs;
|
236 |
+
void *(*operator_new)(size_t);
|
237 |
+
void (*init_instance)(instance *, const void *);
|
238 |
+
void (*dealloc)(value_and_holder &v_h);
|
239 |
+
std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
|
240 |
+
std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
|
241 |
+
std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
|
242 |
+
buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
|
243 |
+
void *get_buffer_data = nullptr;
|
244 |
+
void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
|
245 |
+
/* A simple type never occurs as a (direct or indirect) parent
|
246 |
+
* of a class that makes use of multiple inheritance.
|
247 |
+
* A type can be simple even if it has non-simple ancestors as long as it has no descendants.
|
248 |
+
*/
|
249 |
+
bool simple_type : 1;
|
250 |
+
/* True if there is no multiple inheritance in this type's inheritance tree */
|
251 |
+
bool simple_ancestors : 1;
|
252 |
+
/* for base vs derived holder_type checks */
|
253 |
+
bool default_holder : 1;
|
254 |
+
/* true if this is a type registered with py::module_local */
|
255 |
+
bool module_local : 1;
|
256 |
+
};
|
257 |
+
|
258 |
+
/// On MSVC, debug and release builds are not ABI-compatible!
|
259 |
+
#if defined(_MSC_VER) && defined(_DEBUG)
|
260 |
+
# define PYBIND11_BUILD_TYPE "_debug"
|
261 |
+
#else
|
262 |
+
# define PYBIND11_BUILD_TYPE ""
|
263 |
+
#endif
|
264 |
+
|
265 |
+
/// Let's assume that different compilers are ABI-incompatible.
|
266 |
+
/// A user can manually set this string if they know their
|
267 |
+
/// compiler is compatible.
|
268 |
+
#ifndef PYBIND11_COMPILER_TYPE
|
269 |
+
# if defined(_MSC_VER)
|
270 |
+
# define PYBIND11_COMPILER_TYPE "_msvc"
|
271 |
+
# elif defined(__INTEL_COMPILER)
|
272 |
+
# define PYBIND11_COMPILER_TYPE "_icc"
|
273 |
+
# elif defined(__clang__)
|
274 |
+
# define PYBIND11_COMPILER_TYPE "_clang"
|
275 |
+
# elif defined(__PGI)
|
276 |
+
# define PYBIND11_COMPILER_TYPE "_pgi"
|
277 |
+
# elif defined(__MINGW32__)
|
278 |
+
# define PYBIND11_COMPILER_TYPE "_mingw"
|
279 |
+
# elif defined(__CYGWIN__)
|
280 |
+
# define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
|
281 |
+
# elif defined(__GNUC__)
|
282 |
+
# define PYBIND11_COMPILER_TYPE "_gcc"
|
283 |
+
# else
|
284 |
+
# define PYBIND11_COMPILER_TYPE "_unknown"
|
285 |
+
# endif
|
286 |
+
#endif
|
287 |
+
|
288 |
+
/// Also standard libs
|
289 |
+
#ifndef PYBIND11_STDLIB
|
290 |
+
# if defined(_LIBCPP_VERSION)
|
291 |
+
# define PYBIND11_STDLIB "_libcpp"
|
292 |
+
# elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
|
293 |
+
# define PYBIND11_STDLIB "_libstdcpp"
|
294 |
+
# else
|
295 |
+
# define PYBIND11_STDLIB ""
|
296 |
+
# endif
|
297 |
+
#endif
|
298 |
+
|
299 |
+
/// On Linux/OSX, changes in __GXX_ABI_VERSION__ indicate ABI incompatibility.
|
300 |
+
/// On MSVC, changes in _MSC_VER may indicate ABI incompatibility (#2898).
|
301 |
+
#ifndef PYBIND11_BUILD_ABI
|
302 |
+
# if defined(__GXX_ABI_VERSION)
|
303 |
+
# define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
|
304 |
+
# elif defined(_MSC_VER)
|
305 |
+
# define PYBIND11_BUILD_ABI "_mscver" PYBIND11_TOSTRING(_MSC_VER)
|
306 |
+
# else
|
307 |
+
# define PYBIND11_BUILD_ABI ""
|
308 |
+
# endif
|
309 |
+
#endif
|
310 |
+
|
311 |
+
#ifndef PYBIND11_INTERNALS_KIND
|
312 |
+
# if defined(WITH_THREAD)
|
313 |
+
# define PYBIND11_INTERNALS_KIND ""
|
314 |
+
# else
|
315 |
+
# define PYBIND11_INTERNALS_KIND "_without_thread"
|
316 |
+
# endif
|
317 |
+
#endif
|
318 |
+
|
319 |
+
#define PYBIND11_INTERNALS_ID \
|
320 |
+
"__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
|
321 |
+
PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
|
322 |
+
PYBIND11_BUILD_TYPE "__"
|
323 |
+
|
324 |
+
#define PYBIND11_MODULE_LOCAL_ID \
|
325 |
+
"__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
|
326 |
+
PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
|
327 |
+
PYBIND11_BUILD_TYPE "__"
|
328 |
+
|
329 |
+
/// Each module locally stores a pointer to the `internals` data. The data
|
330 |
+
/// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.
|
331 |
+
inline internals **&get_internals_pp() {
|
332 |
+
static internals **internals_pp = nullptr;
|
333 |
+
return internals_pp;
|
334 |
+
}
|
335 |
+
|
336 |
+
// forward decl
|
337 |
+
inline void translate_exception(std::exception_ptr);
|
338 |
+
|
339 |
+
template <class T,
|
340 |
+
enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
|
341 |
+
bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
|
342 |
+
std::exception_ptr nested = exc.nested_ptr();
|
343 |
+
if (nested != nullptr && nested != p) {
|
344 |
+
translate_exception(nested);
|
345 |
+
return true;
|
346 |
+
}
|
347 |
+
return false;
|
348 |
+
}
|
349 |
+
|
350 |
+
template <class T,
|
351 |
+
enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
|
352 |
+
bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
|
353 |
+
if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
|
354 |
+
return handle_nested_exception(*nep, p);
|
355 |
+
}
|
356 |
+
return false;
|
357 |
+
}
|
358 |
+
|
359 |
+
inline bool raise_err(PyObject *exc_type, const char *msg) {
|
360 |
+
if (PyErr_Occurred()) {
|
361 |
+
raise_from(exc_type, msg);
|
362 |
+
return true;
|
363 |
+
}
|
364 |
+
set_error(exc_type, msg);
|
365 |
+
return false;
|
366 |
+
}
|
367 |
+
|
368 |
+
inline void translate_exception(std::exception_ptr p) {
|
369 |
+
if (!p) {
|
370 |
+
return;
|
371 |
+
}
|
372 |
+
try {
|
373 |
+
std::rethrow_exception(p);
|
374 |
+
} catch (error_already_set &e) {
|
375 |
+
handle_nested_exception(e, p);
|
376 |
+
e.restore();
|
377 |
+
return;
|
378 |
+
} catch (const builtin_exception &e) {
|
379 |
+
// Could not use template since it's an abstract class.
|
380 |
+
if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
|
381 |
+
handle_nested_exception(*nep, p);
|
382 |
+
}
|
383 |
+
e.set_error();
|
384 |
+
return;
|
385 |
+
} catch (const std::bad_alloc &e) {
|
386 |
+
handle_nested_exception(e, p);
|
387 |
+
raise_err(PyExc_MemoryError, e.what());
|
388 |
+
return;
|
389 |
+
} catch (const std::domain_error &e) {
|
390 |
+
handle_nested_exception(e, p);
|
391 |
+
raise_err(PyExc_ValueError, e.what());
|
392 |
+
return;
|
393 |
+
} catch (const std::invalid_argument &e) {
|
394 |
+
handle_nested_exception(e, p);
|
395 |
+
raise_err(PyExc_ValueError, e.what());
|
396 |
+
return;
|
397 |
+
} catch (const std::length_error &e) {
|
398 |
+
handle_nested_exception(e, p);
|
399 |
+
raise_err(PyExc_ValueError, e.what());
|
400 |
+
return;
|
401 |
+
} catch (const std::out_of_range &e) {
|
402 |
+
handle_nested_exception(e, p);
|
403 |
+
raise_err(PyExc_IndexError, e.what());
|
404 |
+
return;
|
405 |
+
} catch (const std::range_error &e) {
|
406 |
+
handle_nested_exception(e, p);
|
407 |
+
raise_err(PyExc_ValueError, e.what());
|
408 |
+
return;
|
409 |
+
} catch (const std::overflow_error &e) {
|
410 |
+
handle_nested_exception(e, p);
|
411 |
+
raise_err(PyExc_OverflowError, e.what());
|
412 |
+
return;
|
413 |
+
} catch (const std::exception &e) {
|
414 |
+
handle_nested_exception(e, p);
|
415 |
+
raise_err(PyExc_RuntimeError, e.what());
|
416 |
+
return;
|
417 |
+
} catch (const std::nested_exception &e) {
|
418 |
+
handle_nested_exception(e, p);
|
419 |
+
raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
|
420 |
+
return;
|
421 |
+
} catch (...) {
|
422 |
+
raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
|
423 |
+
return;
|
424 |
+
}
|
425 |
+
}
|
426 |
+
|
427 |
+
#if !defined(__GLIBCXX__)
|
428 |
+
inline void translate_local_exception(std::exception_ptr p) {
|
429 |
+
try {
|
430 |
+
if (p) {
|
431 |
+
std::rethrow_exception(p);
|
432 |
+
}
|
433 |
+
} catch (error_already_set &e) {
|
434 |
+
e.restore();
|
435 |
+
return;
|
436 |
+
} catch (const builtin_exception &e) {
|
437 |
+
e.set_error();
|
438 |
+
return;
|
439 |
+
}
|
440 |
+
}
|
441 |
+
#endif
|
442 |
+
|
443 |
+
inline object get_python_state_dict() {
|
444 |
+
object state_dict;
|
445 |
+
#if PYBIND11_INTERNALS_VERSION <= 4 || PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
|
446 |
+
state_dict = reinterpret_borrow<object>(PyEval_GetBuiltins());
|
447 |
+
#else
|
448 |
+
# if PY_VERSION_HEX < 0x03090000
|
449 |
+
PyInterpreterState *istate = _PyInterpreterState_Get();
|
450 |
+
# else
|
451 |
+
PyInterpreterState *istate = PyInterpreterState_Get();
|
452 |
+
# endif
|
453 |
+
if (istate) {
|
454 |
+
state_dict = reinterpret_borrow<object>(PyInterpreterState_GetDict(istate));
|
455 |
+
}
|
456 |
+
#endif
|
457 |
+
if (!state_dict) {
|
458 |
+
raise_from(PyExc_SystemError, "pybind11::detail::get_python_state_dict() FAILED");
|
459 |
+
throw error_already_set();
|
460 |
+
}
|
461 |
+
return state_dict;
|
462 |
+
}
|
463 |
+
|
464 |
+
inline object get_internals_obj_from_state_dict(handle state_dict) {
|
465 |
+
return reinterpret_borrow<object>(dict_getitemstring(state_dict.ptr(), PYBIND11_INTERNALS_ID));
|
466 |
+
}
|
467 |
+
|
468 |
+
inline internals **get_internals_pp_from_capsule(handle obj) {
|
469 |
+
void *raw_ptr = PyCapsule_GetPointer(obj.ptr(), /*name=*/nullptr);
|
470 |
+
if (raw_ptr == nullptr) {
|
471 |
+
raise_from(PyExc_SystemError, "pybind11::detail::get_internals_pp_from_capsule() FAILED");
|
472 |
+
throw error_already_set();
|
473 |
+
}
|
474 |
+
return static_cast<internals **>(raw_ptr);
|
475 |
+
}
|
476 |
+
|
477 |
+
/// Return a reference to the current `internals` data
|
478 |
+
PYBIND11_NOINLINE internals &get_internals() {
|
479 |
+
auto **&internals_pp = get_internals_pp();
|
480 |
+
if (internals_pp && *internals_pp) {
|
481 |
+
return **internals_pp;
|
482 |
+
}
|
483 |
+
|
484 |
+
#if defined(WITH_THREAD)
|
485 |
+
# if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
|
486 |
+
gil_scoped_acquire gil;
|
487 |
+
# else
|
488 |
+
// Ensure that the GIL is held since we will need to make Python calls.
|
489 |
+
// Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
|
490 |
+
struct gil_scoped_acquire_local {
|
491 |
+
gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
|
492 |
+
gil_scoped_acquire_local(const gil_scoped_acquire_local &) = delete;
|
493 |
+
gil_scoped_acquire_local &operator=(const gil_scoped_acquire_local &) = delete;
|
494 |
+
~gil_scoped_acquire_local() { PyGILState_Release(state); }
|
495 |
+
const PyGILState_STATE state;
|
496 |
+
} gil;
|
497 |
+
# endif
|
498 |
+
#endif
|
499 |
+
error_scope err_scope;
|
500 |
+
|
501 |
+
dict state_dict = get_python_state_dict();
|
502 |
+
if (object internals_obj = get_internals_obj_from_state_dict(state_dict)) {
|
503 |
+
internals_pp = get_internals_pp_from_capsule(internals_obj);
|
504 |
+
}
|
505 |
+
if (internals_pp && *internals_pp) {
|
506 |
+
// We loaded the internals through `state_dict`, which means that our `error_already_set`
|
507 |
+
// and `builtin_exception` may be different local classes than the ones set up in the
|
508 |
+
// initial exception translator, below, so add another for our local exception classes.
|
509 |
+
//
|
510 |
+
// libstdc++ doesn't require this (types there are identified only by name)
|
511 |
+
// libc++ with CPython doesn't require this (types are explicitly exported)
|
512 |
+
// libc++ with PyPy still need it, awaiting further investigation
|
513 |
+
#if !defined(__GLIBCXX__)
|
514 |
+
(*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
|
515 |
+
#endif
|
516 |
+
} else {
|
517 |
+
if (!internals_pp) {
|
518 |
+
internals_pp = new internals *();
|
519 |
+
}
|
520 |
+
auto *&internals_ptr = *internals_pp;
|
521 |
+
internals_ptr = new internals();
|
522 |
+
#if defined(WITH_THREAD)
|
523 |
+
|
524 |
+
PyThreadState *tstate = PyThreadState_Get();
|
525 |
+
// NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
|
526 |
+
if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
|
527 |
+
pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
|
528 |
+
}
|
529 |
+
PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
|
530 |
+
|
531 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
532 |
+
// NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
|
533 |
+
if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
|
534 |
+
pybind11_fail("get_internals: could not successfully initialize the "
|
535 |
+
"loader_life_support TSS key!");
|
536 |
+
}
|
537 |
+
# endif
|
538 |
+
internals_ptr->istate = tstate->interp;
|
539 |
+
#endif
|
540 |
+
state_dict[PYBIND11_INTERNALS_ID] = capsule(internals_pp);
|
541 |
+
internals_ptr->registered_exception_translators.push_front(&translate_exception);
|
542 |
+
internals_ptr->static_property_type = make_static_property_type();
|
543 |
+
internals_ptr->default_metaclass = make_default_metaclass();
|
544 |
+
internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
|
545 |
+
}
|
546 |
+
return **internals_pp;
|
547 |
+
}
|
548 |
+
|
549 |
+
// the internals struct (above) is shared between all the modules. local_internals are only
|
550 |
+
// for a single module. Any changes made to internals may require an update to
|
551 |
+
// PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
|
552 |
+
// restricted to a single module. Whether a module has local internals or not should not
|
553 |
+
// impact any other modules, because the only things accessing the local internals is the
|
554 |
+
// module that contains them.
|
555 |
+
struct local_internals {
|
556 |
+
type_map<type_info *> registered_types_cpp;
|
557 |
+
std::forward_list<ExceptionTranslator> registered_exception_translators;
|
558 |
+
#if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
|
559 |
+
|
560 |
+
// For ABI compatibility, we can't store the loader_life_support TLS key in
|
561 |
+
// the `internals` struct directly. Instead, we store it in `shared_data` and
|
562 |
+
// cache a copy in `local_internals`. If we allocated a separate TLS key for
|
563 |
+
// each instance of `local_internals`, we could end up allocating hundreds of
|
564 |
+
// TLS keys if hundreds of different pybind11 modules are loaded (which is a
|
565 |
+
// plausible number).
|
566 |
+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
|
567 |
+
|
568 |
+
// Holds the shared TLS key for the loader_life_support stack.
|
569 |
+
struct shared_loader_life_support_data {
|
570 |
+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
|
571 |
+
shared_loader_life_support_data() {
|
572 |
+
// NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
|
573 |
+
if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
|
574 |
+
pybind11_fail("local_internals: could not successfully initialize the "
|
575 |
+
"loader_life_support TLS key!");
|
576 |
+
}
|
577 |
+
}
|
578 |
+
// We can't help but leak the TLS key, because Python never unloads extension modules.
|
579 |
+
};
|
580 |
+
|
581 |
+
local_internals() {
|
582 |
+
auto &internals = get_internals();
|
583 |
+
// Get or create the `loader_life_support_stack_key`.
|
584 |
+
auto &ptr = internals.shared_data["_life_support"];
|
585 |
+
if (!ptr) {
|
586 |
+
ptr = new shared_loader_life_support_data;
|
587 |
+
}
|
588 |
+
loader_life_support_tls_key
|
589 |
+
= static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
|
590 |
+
}
|
591 |
+
#endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
|
592 |
+
};
|
593 |
+
|
594 |
+
/// Works like `get_internals`, but for things which are locally registered.
|
595 |
+
inline local_internals &get_local_internals() {
|
596 |
+
// Current static can be created in the interpreter finalization routine. If the later will be
|
597 |
+
// destroyed in another static variable destructor, creation of this static there will cause
|
598 |
+
// static deinitialization fiasco. In order to avoid it we avoid destruction of the
|
599 |
+
// local_internals static. One can read more about the problem and current solution here:
|
600 |
+
// https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
|
601 |
+
static auto *locals = new local_internals();
|
602 |
+
return *locals;
|
603 |
+
}
|
604 |
+
|
605 |
+
/// Constructs a std::string with the given arguments, stores it in `internals`, and returns its
|
606 |
+
/// `c_str()`. Such strings objects have a long storage duration -- the internal strings are only
|
607 |
+
/// cleared when the program exits or after interpreter shutdown (when embedding), and so are
|
608 |
+
/// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name).
|
609 |
+
template <typename... Args>
|
610 |
+
const char *c_str(Args &&...args) {
|
611 |
+
auto &strings = get_internals().static_strings;
|
612 |
+
strings.emplace_front(std::forward<Args>(args)...);
|
613 |
+
return strings.front().c_str();
|
614 |
+
}
|
615 |
+
|
616 |
+
inline const char *get_function_record_capsule_name() {
|
617 |
+
#if PYBIND11_INTERNALS_VERSION > 4
|
618 |
+
return get_internals().function_record_capsule_name.c_str();
|
619 |
+
#else
|
620 |
+
return nullptr;
|
621 |
+
#endif
|
622 |
+
}
|
623 |
+
|
624 |
+
// Determine whether or not the following capsule contains a pybind11 function record.
|
625 |
+
// Note that we use `internals` to make sure that only ABI compatible records are touched.
|
626 |
+
//
|
627 |
+
// This check is currently used in two places:
|
628 |
+
// - An important optimization in functional.h to avoid overhead in C++ -> Python -> C++
|
629 |
+
// - The sibling feature of cpp_function to allow overloads
|
630 |
+
inline bool is_function_record_capsule(const capsule &cap) {
|
631 |
+
// Pointer equality as we rely on internals() to ensure unique pointers
|
632 |
+
return cap.name() == get_function_record_capsule_name();
|
633 |
+
}
|
634 |
+
|
635 |
+
PYBIND11_NAMESPACE_END(detail)
|
636 |
+
|
637 |
+
/// Returns a named pointer that is shared among all extension modules (using the same
|
638 |
+
/// pybind11 version) running in the current interpreter. Names starting with underscores
|
639 |
+
/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
|
640 |
+
PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
|
641 |
+
auto &internals = detail::get_internals();
|
642 |
+
auto it = internals.shared_data.find(name);
|
643 |
+
return it != internals.shared_data.end() ? it->second : nullptr;
|
644 |
+
}
|
645 |
+
|
646 |
+
/// Set the shared data that can be later recovered by `get_shared_data()`.
|
647 |
+
PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
|
648 |
+
detail::get_internals().shared_data[name] = data;
|
649 |
+
return data;
|
650 |
+
}
|
651 |
+
|
652 |
+
/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
|
653 |
+
/// such entry exists. Otherwise, a new object of default-constructible type `T` is
|
654 |
+
/// added to the shared data under the given name and a reference to it is returned.
|
655 |
+
template <typename T>
|
656 |
+
T &get_or_create_shared_data(const std::string &name) {
|
657 |
+
auto &internals = detail::get_internals();
|
658 |
+
auto it = internals.shared_data.find(name);
|
659 |
+
T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
|
660 |
+
if (!ptr) {
|
661 |
+
ptr = new T();
|
662 |
+
internals.shared_data[name] = ptr;
|
663 |
+
}
|
664 |
+
return *ptr;
|
665 |
+
}
|
666 |
+
|
667 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/type_caster_base.h
ADDED
@@ -0,0 +1,1218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/detail/type_caster_base.h (originally first part of pybind11/cast.h)
|
3 |
+
|
4 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "../pytypes.h"
|
13 |
+
#include "common.h"
|
14 |
+
#include "descr.h"
|
15 |
+
#include "internals.h"
|
16 |
+
#include "typeid.h"
|
17 |
+
|
18 |
+
#include <cstdint>
|
19 |
+
#include <iterator>
|
20 |
+
#include <new>
|
21 |
+
#include <string>
|
22 |
+
#include <type_traits>
|
23 |
+
#include <typeindex>
|
24 |
+
#include <typeinfo>
|
25 |
+
#include <unordered_map>
|
26 |
+
#include <utility>
|
27 |
+
#include <vector>
|
28 |
+
|
29 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
30 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
31 |
+
|
32 |
+
/// A life support system for temporary objects created by `type_caster::load()`.
|
33 |
+
/// Adding a patient will keep it alive up until the enclosing function returns.
|
34 |
+
class loader_life_support {
|
35 |
+
private:
|
36 |
+
loader_life_support *parent = nullptr;
|
37 |
+
std::unordered_set<PyObject *> keep_alive;
|
38 |
+
|
39 |
+
#if defined(WITH_THREAD)
|
40 |
+
// Store stack pointer in thread-local storage.
|
41 |
+
static PYBIND11_TLS_KEY_REF get_stack_tls_key() {
|
42 |
+
# if PYBIND11_INTERNALS_VERSION == 4
|
43 |
+
return get_local_internals().loader_life_support_tls_key;
|
44 |
+
# else
|
45 |
+
return get_internals().loader_life_support_tls_key;
|
46 |
+
# endif
|
47 |
+
}
|
48 |
+
static loader_life_support *get_stack_top() {
|
49 |
+
return static_cast<loader_life_support *>(PYBIND11_TLS_GET_VALUE(get_stack_tls_key()));
|
50 |
+
}
|
51 |
+
static void set_stack_top(loader_life_support *value) {
|
52 |
+
PYBIND11_TLS_REPLACE_VALUE(get_stack_tls_key(), value);
|
53 |
+
}
|
54 |
+
#else
|
55 |
+
// Use single global variable for stack.
|
56 |
+
static loader_life_support **get_stack_pp() {
|
57 |
+
static loader_life_support *global_stack = nullptr;
|
58 |
+
return global_stack;
|
59 |
+
}
|
60 |
+
static loader_life_support *get_stack_top() { return *get_stack_pp(); }
|
61 |
+
static void set_stack_top(loader_life_support *value) { *get_stack_pp() = value; }
|
62 |
+
#endif
|
63 |
+
|
64 |
+
public:
|
65 |
+
/// A new patient frame is created when a function is entered
|
66 |
+
loader_life_support() : parent{get_stack_top()} { set_stack_top(this); }
|
67 |
+
|
68 |
+
/// ... and destroyed after it returns
|
69 |
+
~loader_life_support() {
|
70 |
+
if (get_stack_top() != this) {
|
71 |
+
pybind11_fail("loader_life_support: internal error");
|
72 |
+
}
|
73 |
+
set_stack_top(parent);
|
74 |
+
for (auto *item : keep_alive) {
|
75 |
+
Py_DECREF(item);
|
76 |
+
}
|
77 |
+
}
|
78 |
+
|
79 |
+
/// This can only be used inside a pybind11-bound function, either by `argument_loader`
|
80 |
+
/// at argument preparation time or by `py::cast()` at execution time.
|
81 |
+
PYBIND11_NOINLINE static void add_patient(handle h) {
|
82 |
+
loader_life_support *frame = get_stack_top();
|
83 |
+
if (!frame) {
|
84 |
+
// NOTE: It would be nice to include the stack frames here, as this indicates
|
85 |
+
// use of pybind11::cast<> outside the normal call framework, finding such
|
86 |
+
// a location is challenging. Developers could consider printing out
|
87 |
+
// stack frame addresses here using something like __builtin_frame_address(0)
|
88 |
+
throw cast_error("When called outside a bound function, py::cast() cannot "
|
89 |
+
"do Python -> C++ conversions which require the creation "
|
90 |
+
"of temporary values");
|
91 |
+
}
|
92 |
+
|
93 |
+
if (frame->keep_alive.insert(h.ptr()).second) {
|
94 |
+
Py_INCREF(h.ptr());
|
95 |
+
}
|
96 |
+
}
|
97 |
+
};
|
98 |
+
|
99 |
+
// Gets the cache entry for the given type, creating it if necessary. The return value is the pair
|
100 |
+
// returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
|
101 |
+
// just created.
|
102 |
+
inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
|
103 |
+
all_type_info_get_cache(PyTypeObject *type);
|
104 |
+
|
105 |
+
// Band-aid workaround to fix a subtle but serious bug in a minimalistic fashion. See PR #4762.
|
106 |
+
inline void all_type_info_add_base_most_derived_first(std::vector<type_info *> &bases,
|
107 |
+
type_info *addl_base) {
|
108 |
+
for (auto it = bases.begin(); it != bases.end(); it++) {
|
109 |
+
type_info *existing_base = *it;
|
110 |
+
if (PyType_IsSubtype(addl_base->type, existing_base->type) != 0) {
|
111 |
+
bases.insert(it, addl_base);
|
112 |
+
return;
|
113 |
+
}
|
114 |
+
}
|
115 |
+
bases.push_back(addl_base);
|
116 |
+
}
|
117 |
+
|
118 |
+
// Populates a just-created cache entry.
|
119 |
+
PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
|
120 |
+
assert(bases.empty());
|
121 |
+
std::vector<PyTypeObject *> check;
|
122 |
+
for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {
|
123 |
+
check.push_back((PyTypeObject *) parent.ptr());
|
124 |
+
}
|
125 |
+
|
126 |
+
auto const &type_dict = get_internals().registered_types_py;
|
127 |
+
for (size_t i = 0; i < check.size(); i++) {
|
128 |
+
auto *type = check[i];
|
129 |
+
// Ignore Python2 old-style class super type:
|
130 |
+
if (!PyType_Check((PyObject *) type)) {
|
131 |
+
continue;
|
132 |
+
}
|
133 |
+
|
134 |
+
// Check `type` in the current set of registered python types:
|
135 |
+
auto it = type_dict.find(type);
|
136 |
+
if (it != type_dict.end()) {
|
137 |
+
// We found a cache entry for it, so it's either pybind-registered or has pre-computed
|
138 |
+
// pybind bases, but we have to make sure we haven't already seen the type(s) before:
|
139 |
+
// we want to follow Python/virtual C++ rules that there should only be one instance of
|
140 |
+
// a common base.
|
141 |
+
for (auto *tinfo : it->second) {
|
142 |
+
// NB: Could use a second set here, rather than doing a linear search, but since
|
143 |
+
// having a large number of immediate pybind11-registered types seems fairly
|
144 |
+
// unlikely, that probably isn't worthwhile.
|
145 |
+
bool found = false;
|
146 |
+
for (auto *known : bases) {
|
147 |
+
if (known == tinfo) {
|
148 |
+
found = true;
|
149 |
+
break;
|
150 |
+
}
|
151 |
+
}
|
152 |
+
if (!found) {
|
153 |
+
all_type_info_add_base_most_derived_first(bases, tinfo);
|
154 |
+
}
|
155 |
+
}
|
156 |
+
} else if (type->tp_bases) {
|
157 |
+
// It's some python type, so keep follow its bases classes to look for one or more
|
158 |
+
// registered types
|
159 |
+
if (i + 1 == check.size()) {
|
160 |
+
// When we're at the end, we can pop off the current element to avoid growing
|
161 |
+
// `check` when adding just one base (which is typical--i.e. when there is no
|
162 |
+
// multiple inheritance)
|
163 |
+
check.pop_back();
|
164 |
+
i--;
|
165 |
+
}
|
166 |
+
for (handle parent : reinterpret_borrow<tuple>(type->tp_bases)) {
|
167 |
+
check.push_back((PyTypeObject *) parent.ptr());
|
168 |
+
}
|
169 |
+
}
|
170 |
+
}
|
171 |
+
}
|
172 |
+
|
173 |
+
/**
|
174 |
+
* Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
|
175 |
+
* be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
|
176 |
+
* derived class that uses single inheritance. Will contain as many types as required for a Python
|
177 |
+
* class that uses multiple inheritance to inherit (directly or indirectly) from multiple
|
178 |
+
* pybind-registered classes. Will be empty if neither the type nor any base classes are
|
179 |
+
* pybind-registered.
|
180 |
+
*
|
181 |
+
* The value is cached for the lifetime of the Python type.
|
182 |
+
*/
|
183 |
+
inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
|
184 |
+
auto ins = all_type_info_get_cache(type);
|
185 |
+
if (ins.second) {
|
186 |
+
// New cache entry: populate it
|
187 |
+
all_type_info_populate(type, ins.first->second);
|
188 |
+
}
|
189 |
+
|
190 |
+
return ins.first->second;
|
191 |
+
}
|
192 |
+
|
193 |
+
/**
|
194 |
+
* Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
|
195 |
+
* ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
|
196 |
+
* `all_type_info` instead if you want to support multiple bases.
|
197 |
+
*/
|
198 |
+
PYBIND11_NOINLINE detail::type_info *get_type_info(PyTypeObject *type) {
|
199 |
+
const auto &bases = all_type_info(type);
|
200 |
+
if (bases.empty()) {
|
201 |
+
return nullptr;
|
202 |
+
}
|
203 |
+
if (bases.size() > 1) {
|
204 |
+
pybind11_fail(
|
205 |
+
"pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
|
206 |
+
}
|
207 |
+
return bases.front();
|
208 |
+
}
|
209 |
+
|
210 |
+
inline detail::type_info *get_local_type_info(const std::type_index &tp) {
|
211 |
+
auto &locals = get_local_internals().registered_types_cpp;
|
212 |
+
auto it = locals.find(tp);
|
213 |
+
if (it != locals.end()) {
|
214 |
+
return it->second;
|
215 |
+
}
|
216 |
+
return nullptr;
|
217 |
+
}
|
218 |
+
|
219 |
+
inline detail::type_info *get_global_type_info(const std::type_index &tp) {
|
220 |
+
auto &types = get_internals().registered_types_cpp;
|
221 |
+
auto it = types.find(tp);
|
222 |
+
if (it != types.end()) {
|
223 |
+
return it->second;
|
224 |
+
}
|
225 |
+
return nullptr;
|
226 |
+
}
|
227 |
+
|
228 |
+
/// Return the type info for a given C++ type; on lookup failure can either throw or return
|
229 |
+
/// nullptr.
|
230 |
+
PYBIND11_NOINLINE detail::type_info *get_type_info(const std::type_index &tp,
|
231 |
+
bool throw_if_missing = false) {
|
232 |
+
if (auto *ltype = get_local_type_info(tp)) {
|
233 |
+
return ltype;
|
234 |
+
}
|
235 |
+
if (auto *gtype = get_global_type_info(tp)) {
|
236 |
+
return gtype;
|
237 |
+
}
|
238 |
+
|
239 |
+
if (throw_if_missing) {
|
240 |
+
std::string tname = tp.name();
|
241 |
+
detail::clean_type_id(tname);
|
242 |
+
pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \""
|
243 |
+
+ std::move(tname) + '"');
|
244 |
+
}
|
245 |
+
return nullptr;
|
246 |
+
}
|
247 |
+
|
248 |
+
PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
|
249 |
+
detail::type_info *type_info = get_type_info(tp, throw_if_missing);
|
250 |
+
return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
|
251 |
+
}
|
252 |
+
|
253 |
+
// Searches the inheritance graph for a registered Python instance, using all_type_info().
|
254 |
+
PYBIND11_NOINLINE handle find_registered_python_instance(void *src,
|
255 |
+
const detail::type_info *tinfo) {
|
256 |
+
auto it_instances = get_internals().registered_instances.equal_range(src);
|
257 |
+
for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
|
258 |
+
for (auto *instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
|
259 |
+
if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype)) {
|
260 |
+
return handle((PyObject *) it_i->second).inc_ref();
|
261 |
+
}
|
262 |
+
}
|
263 |
+
}
|
264 |
+
return handle();
|
265 |
+
}
|
266 |
+
|
267 |
+
struct value_and_holder {
|
268 |
+
instance *inst = nullptr;
|
269 |
+
size_t index = 0u;
|
270 |
+
const detail::type_info *type = nullptr;
|
271 |
+
void **vh = nullptr;
|
272 |
+
|
273 |
+
// Main constructor for a found value/holder:
|
274 |
+
value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
|
275 |
+
: inst{i}, index{index}, type{type},
|
276 |
+
vh{inst->simple_layout ? inst->simple_value_holder
|
277 |
+
: &inst->nonsimple.values_and_holders[vpos]} {}
|
278 |
+
|
279 |
+
// Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
|
280 |
+
value_and_holder() = default;
|
281 |
+
|
282 |
+
// Used for past-the-end iterator
|
283 |
+
explicit value_and_holder(size_t index) : index{index} {}
|
284 |
+
|
285 |
+
template <typename V = void>
|
286 |
+
V *&value_ptr() const {
|
287 |
+
return reinterpret_cast<V *&>(vh[0]);
|
288 |
+
}
|
289 |
+
// True if this `value_and_holder` has a non-null value pointer
|
290 |
+
explicit operator bool() const { return value_ptr() != nullptr; }
|
291 |
+
|
292 |
+
template <typename H>
|
293 |
+
H &holder() const {
|
294 |
+
return reinterpret_cast<H &>(vh[1]);
|
295 |
+
}
|
296 |
+
bool holder_constructed() const {
|
297 |
+
return inst->simple_layout
|
298 |
+
? inst->simple_holder_constructed
|
299 |
+
: (inst->nonsimple.status[index] & instance::status_holder_constructed) != 0u;
|
300 |
+
}
|
301 |
+
// NOLINTNEXTLINE(readability-make-member-function-const)
|
302 |
+
void set_holder_constructed(bool v = true) {
|
303 |
+
if (inst->simple_layout) {
|
304 |
+
inst->simple_holder_constructed = v;
|
305 |
+
} else if (v) {
|
306 |
+
inst->nonsimple.status[index] |= instance::status_holder_constructed;
|
307 |
+
} else {
|
308 |
+
inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_holder_constructed;
|
309 |
+
}
|
310 |
+
}
|
311 |
+
bool instance_registered() const {
|
312 |
+
return inst->simple_layout
|
313 |
+
? inst->simple_instance_registered
|
314 |
+
: ((inst->nonsimple.status[index] & instance::status_instance_registered) != 0);
|
315 |
+
}
|
316 |
+
// NOLINTNEXTLINE(readability-make-member-function-const)
|
317 |
+
void set_instance_registered(bool v = true) {
|
318 |
+
if (inst->simple_layout) {
|
319 |
+
inst->simple_instance_registered = v;
|
320 |
+
} else if (v) {
|
321 |
+
inst->nonsimple.status[index] |= instance::status_instance_registered;
|
322 |
+
} else {
|
323 |
+
inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_instance_registered;
|
324 |
+
}
|
325 |
+
}
|
326 |
+
};
|
327 |
+
|
328 |
+
// Container for accessing and iterating over an instance's values/holders
|
329 |
+
struct values_and_holders {
|
330 |
+
private:
|
331 |
+
instance *inst;
|
332 |
+
using type_vec = std::vector<detail::type_info *>;
|
333 |
+
const type_vec &tinfo;
|
334 |
+
|
335 |
+
public:
|
336 |
+
explicit values_and_holders(instance *inst)
|
337 |
+
: inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
|
338 |
+
|
339 |
+
explicit values_and_holders(PyObject *obj)
|
340 |
+
: inst{nullptr}, tinfo(all_type_info(Py_TYPE(obj))) {
|
341 |
+
if (!tinfo.empty()) {
|
342 |
+
inst = reinterpret_cast<instance *>(obj);
|
343 |
+
}
|
344 |
+
}
|
345 |
+
|
346 |
+
struct iterator {
|
347 |
+
private:
|
348 |
+
instance *inst = nullptr;
|
349 |
+
const type_vec *types = nullptr;
|
350 |
+
value_and_holder curr;
|
351 |
+
friend struct values_and_holders;
|
352 |
+
iterator(instance *inst, const type_vec *tinfo) : inst{inst}, types{tinfo} {
|
353 |
+
if (inst != nullptr) {
|
354 |
+
assert(!types->empty());
|
355 |
+
curr = value_and_holder(
|
356 |
+
inst /* instance */,
|
357 |
+
(*types)[0] /* type info */,
|
358 |
+
0, /* vpos: (non-simple types only): the first vptr comes first */
|
359 |
+
0 /* index */);
|
360 |
+
}
|
361 |
+
}
|
362 |
+
// Past-the-end iterator:
|
363 |
+
explicit iterator(size_t end) : curr(end) {}
|
364 |
+
|
365 |
+
public:
|
366 |
+
bool operator==(const iterator &other) const { return curr.index == other.curr.index; }
|
367 |
+
bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }
|
368 |
+
iterator &operator++() {
|
369 |
+
if (!inst->simple_layout) {
|
370 |
+
curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
|
371 |
+
}
|
372 |
+
++curr.index;
|
373 |
+
curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
|
374 |
+
return *this;
|
375 |
+
}
|
376 |
+
value_and_holder &operator*() { return curr; }
|
377 |
+
value_and_holder *operator->() { return &curr; }
|
378 |
+
};
|
379 |
+
|
380 |
+
iterator begin() { return iterator(inst, &tinfo); }
|
381 |
+
iterator end() { return iterator(tinfo.size()); }
|
382 |
+
|
383 |
+
iterator find(const type_info *find_type) {
|
384 |
+
auto it = begin(), endit = end();
|
385 |
+
while (it != endit && it->type != find_type) {
|
386 |
+
++it;
|
387 |
+
}
|
388 |
+
return it;
|
389 |
+
}
|
390 |
+
|
391 |
+
size_t size() { return tinfo.size(); }
|
392 |
+
|
393 |
+
// Band-aid workaround to fix a subtle but serious bug in a minimalistic fashion. See PR #4762.
|
394 |
+
bool is_redundant_value_and_holder(const value_and_holder &vh) {
|
395 |
+
for (size_t i = 0; i < vh.index; i++) {
|
396 |
+
if (PyType_IsSubtype(tinfo[i]->type, tinfo[vh.index]->type) != 0) {
|
397 |
+
return true;
|
398 |
+
}
|
399 |
+
}
|
400 |
+
return false;
|
401 |
+
}
|
402 |
+
};
|
403 |
+
|
404 |
+
/**
|
405 |
+
* Extracts C++ value and holder pointer references from an instance (which may contain multiple
|
406 |
+
* values/holders for python-side multiple inheritance) that match the given type. Throws an error
|
407 |
+
* if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
|
408 |
+
* `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
|
409 |
+
* regardless of type (and the resulting .type will be nullptr).
|
410 |
+
*
|
411 |
+
* The returned object should be short-lived: in particular, it must not outlive the called-upon
|
412 |
+
* instance.
|
413 |
+
*/
|
414 |
+
PYBIND11_NOINLINE value_and_holder
|
415 |
+
instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/,
|
416 |
+
bool throw_if_missing /*= true in common.h*/) {
|
417 |
+
// Optimize common case:
|
418 |
+
if (!find_type || Py_TYPE(this) == find_type->type) {
|
419 |
+
return value_and_holder(this, find_type, 0, 0);
|
420 |
+
}
|
421 |
+
|
422 |
+
detail::values_and_holders vhs(this);
|
423 |
+
auto it = vhs.find(find_type);
|
424 |
+
if (it != vhs.end()) {
|
425 |
+
return *it;
|
426 |
+
}
|
427 |
+
|
428 |
+
if (!throw_if_missing) {
|
429 |
+
return value_and_holder();
|
430 |
+
}
|
431 |
+
|
432 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
433 |
+
pybind11_fail("pybind11::detail::instance::get_value_and_holder: `"
|
434 |
+
+ get_fully_qualified_tp_name(find_type->type)
|
435 |
+
+ "' is not a pybind11 base of the given `"
|
436 |
+
+ get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
|
437 |
+
#else
|
438 |
+
pybind11_fail(
|
439 |
+
"pybind11::detail::instance::get_value_and_holder: "
|
440 |
+
"type is not a pybind11 base of the given instance "
|
441 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for type details)");
|
442 |
+
#endif
|
443 |
+
}
|
444 |
+
|
445 |
+
PYBIND11_NOINLINE void instance::allocate_layout() {
|
446 |
+
const auto &tinfo = all_type_info(Py_TYPE(this));
|
447 |
+
|
448 |
+
const size_t n_types = tinfo.size();
|
449 |
+
|
450 |
+
if (n_types == 0) {
|
451 |
+
pybind11_fail(
|
452 |
+
"instance allocation failed: new instance has no pybind11-registered base types");
|
453 |
+
}
|
454 |
+
|
455 |
+
simple_layout
|
456 |
+
= n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
|
457 |
+
|
458 |
+
// Simple path: no python-side multiple inheritance, and a small-enough holder
|
459 |
+
if (simple_layout) {
|
460 |
+
simple_value_holder[0] = nullptr;
|
461 |
+
simple_holder_constructed = false;
|
462 |
+
simple_instance_registered = false;
|
463 |
+
} else { // multiple base types or a too-large holder
|
464 |
+
// Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
|
465 |
+
// [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
|
466 |
+
// values that tracks whether each associated holder has been initialized. Each [block] is
|
467 |
+
// padded, if necessary, to an integer multiple of sizeof(void *).
|
468 |
+
size_t space = 0;
|
469 |
+
for (auto *t : tinfo) {
|
470 |
+
space += 1; // value pointer
|
471 |
+
space += t->holder_size_in_ptrs; // holder instance
|
472 |
+
}
|
473 |
+
size_t flags_at = space;
|
474 |
+
space += size_in_ptrs(n_types); // status bytes (holder_constructed and
|
475 |
+
// instance_registered)
|
476 |
+
|
477 |
+
// Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
|
478 |
+
// in particular, need to be 0). Use Python's memory allocation
|
479 |
+
// functions: Python is using pymalloc, which is designed to be
|
480 |
+
// efficient for small allocations like the one we're doing here;
|
481 |
+
// for larger allocations they are just wrappers around malloc.
|
482 |
+
// TODO: is this still true for pure Python 3.6?
|
483 |
+
nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
|
484 |
+
if (!nonsimple.values_and_holders) {
|
485 |
+
throw std::bad_alloc();
|
486 |
+
}
|
487 |
+
nonsimple.status
|
488 |
+
= reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);
|
489 |
+
}
|
490 |
+
owned = true;
|
491 |
+
}
|
492 |
+
|
493 |
+
// NOLINTNEXTLINE(readability-make-member-function-const)
|
494 |
+
PYBIND11_NOINLINE void instance::deallocate_layout() {
|
495 |
+
if (!simple_layout) {
|
496 |
+
PyMem_Free(nonsimple.values_and_holders);
|
497 |
+
}
|
498 |
+
}
|
499 |
+
|
500 |
+
PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp) {
|
501 |
+
handle type = detail::get_type_handle(tp, false);
|
502 |
+
if (!type) {
|
503 |
+
return false;
|
504 |
+
}
|
505 |
+
return isinstance(obj, type);
|
506 |
+
}
|
507 |
+
|
508 |
+
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type) {
|
509 |
+
auto &instances = get_internals().registered_instances;
|
510 |
+
auto range = instances.equal_range(ptr);
|
511 |
+
for (auto it = range.first; it != range.second; ++it) {
|
512 |
+
for (const auto &vh : values_and_holders(it->second)) {
|
513 |
+
if (vh.type == type) {
|
514 |
+
return handle((PyObject *) it->second);
|
515 |
+
}
|
516 |
+
}
|
517 |
+
}
|
518 |
+
return handle();
|
519 |
+
}
|
520 |
+
|
521 |
+
inline PyThreadState *get_thread_state_unchecked() {
|
522 |
+
#if defined(PYPY_VERSION)
|
523 |
+
return PyThreadState_GET();
|
524 |
+
#elif PY_VERSION_HEX < 0x030D0000
|
525 |
+
return _PyThreadState_UncheckedGet();
|
526 |
+
#else
|
527 |
+
return PyThreadState_GetUnchecked();
|
528 |
+
#endif
|
529 |
+
}
|
530 |
+
|
531 |
+
// Forward declarations
|
532 |
+
void keep_alive_impl(handle nurse, handle patient);
|
533 |
+
inline PyObject *make_new_instance(PyTypeObject *type);
|
534 |
+
|
535 |
+
class type_caster_generic {
|
536 |
+
public:
|
537 |
+
PYBIND11_NOINLINE explicit type_caster_generic(const std::type_info &type_info)
|
538 |
+
: typeinfo(get_type_info(type_info)), cpptype(&type_info) {}
|
539 |
+
|
540 |
+
explicit type_caster_generic(const type_info *typeinfo)
|
541 |
+
: typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}
|
542 |
+
|
543 |
+
bool load(handle src, bool convert) { return load_impl<type_caster_generic>(src, convert); }
|
544 |
+
|
545 |
+
PYBIND11_NOINLINE static handle cast(const void *_src,
|
546 |
+
return_value_policy policy,
|
547 |
+
handle parent,
|
548 |
+
const detail::type_info *tinfo,
|
549 |
+
void *(*copy_constructor)(const void *),
|
550 |
+
void *(*move_constructor)(const void *),
|
551 |
+
const void *existing_holder = nullptr) {
|
552 |
+
if (!tinfo) { // no type info: error will be set already
|
553 |
+
return handle();
|
554 |
+
}
|
555 |
+
|
556 |
+
void *src = const_cast<void *>(_src);
|
557 |
+
if (src == nullptr) {
|
558 |
+
return none().release();
|
559 |
+
}
|
560 |
+
|
561 |
+
if (handle registered_inst = find_registered_python_instance(src, tinfo)) {
|
562 |
+
return registered_inst;
|
563 |
+
}
|
564 |
+
|
565 |
+
auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
|
566 |
+
auto *wrapper = reinterpret_cast<instance *>(inst.ptr());
|
567 |
+
wrapper->owned = false;
|
568 |
+
void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
|
569 |
+
|
570 |
+
switch (policy) {
|
571 |
+
case return_value_policy::automatic:
|
572 |
+
case return_value_policy::take_ownership:
|
573 |
+
valueptr = src;
|
574 |
+
wrapper->owned = true;
|
575 |
+
break;
|
576 |
+
|
577 |
+
case return_value_policy::automatic_reference:
|
578 |
+
case return_value_policy::reference:
|
579 |
+
valueptr = src;
|
580 |
+
wrapper->owned = false;
|
581 |
+
break;
|
582 |
+
|
583 |
+
case return_value_policy::copy:
|
584 |
+
if (copy_constructor) {
|
585 |
+
valueptr = copy_constructor(src);
|
586 |
+
} else {
|
587 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
588 |
+
std::string type_name(tinfo->cpptype->name());
|
589 |
+
detail::clean_type_id(type_name);
|
590 |
+
throw cast_error("return_value_policy = copy, but type " + type_name
|
591 |
+
+ " is non-copyable!");
|
592 |
+
#else
|
593 |
+
throw cast_error("return_value_policy = copy, but type is "
|
594 |
+
"non-copyable! (#define PYBIND11_DETAILED_ERROR_MESSAGES or "
|
595 |
+
"compile in debug mode for details)");
|
596 |
+
#endif
|
597 |
+
}
|
598 |
+
wrapper->owned = true;
|
599 |
+
break;
|
600 |
+
|
601 |
+
case return_value_policy::move:
|
602 |
+
if (move_constructor) {
|
603 |
+
valueptr = move_constructor(src);
|
604 |
+
} else if (copy_constructor) {
|
605 |
+
valueptr = copy_constructor(src);
|
606 |
+
} else {
|
607 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
608 |
+
std::string type_name(tinfo->cpptype->name());
|
609 |
+
detail::clean_type_id(type_name);
|
610 |
+
throw cast_error("return_value_policy = move, but type " + type_name
|
611 |
+
+ " is neither movable nor copyable!");
|
612 |
+
#else
|
613 |
+
throw cast_error("return_value_policy = move, but type is neither "
|
614 |
+
"movable nor copyable! "
|
615 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in "
|
616 |
+
"debug mode for details)");
|
617 |
+
#endif
|
618 |
+
}
|
619 |
+
wrapper->owned = true;
|
620 |
+
break;
|
621 |
+
|
622 |
+
case return_value_policy::reference_internal:
|
623 |
+
valueptr = src;
|
624 |
+
wrapper->owned = false;
|
625 |
+
keep_alive_impl(inst, parent);
|
626 |
+
break;
|
627 |
+
|
628 |
+
default:
|
629 |
+
throw cast_error("unhandled return_value_policy: should not happen!");
|
630 |
+
}
|
631 |
+
|
632 |
+
tinfo->init_instance(wrapper, existing_holder);
|
633 |
+
|
634 |
+
return inst.release();
|
635 |
+
}
|
636 |
+
|
637 |
+
// Base methods for generic caster; there are overridden in copyable_holder_caster
|
638 |
+
void load_value(value_and_holder &&v_h) {
|
639 |
+
auto *&vptr = v_h.value_ptr();
|
640 |
+
// Lazy allocation for unallocated values:
|
641 |
+
if (vptr == nullptr) {
|
642 |
+
const auto *type = v_h.type ? v_h.type : typeinfo;
|
643 |
+
if (type->operator_new) {
|
644 |
+
vptr = type->operator_new(type->type_size);
|
645 |
+
} else {
|
646 |
+
#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
|
647 |
+
if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
|
648 |
+
vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));
|
649 |
+
} else {
|
650 |
+
vptr = ::operator new(type->type_size);
|
651 |
+
}
|
652 |
+
#else
|
653 |
+
vptr = ::operator new(type->type_size);
|
654 |
+
#endif
|
655 |
+
}
|
656 |
+
}
|
657 |
+
value = vptr;
|
658 |
+
}
|
659 |
+
bool try_implicit_casts(handle src, bool convert) {
|
660 |
+
for (const auto &cast : typeinfo->implicit_casts) {
|
661 |
+
type_caster_generic sub_caster(*cast.first);
|
662 |
+
if (sub_caster.load(src, convert)) {
|
663 |
+
value = cast.second(sub_caster.value);
|
664 |
+
return true;
|
665 |
+
}
|
666 |
+
}
|
667 |
+
return false;
|
668 |
+
}
|
669 |
+
bool try_direct_conversions(handle src) {
|
670 |
+
for (auto &converter : *typeinfo->direct_conversions) {
|
671 |
+
if (converter(src.ptr(), value)) {
|
672 |
+
return true;
|
673 |
+
}
|
674 |
+
}
|
675 |
+
return false;
|
676 |
+
}
|
677 |
+
void check_holder_compat() {}
|
678 |
+
|
679 |
+
PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
|
680 |
+
auto caster = type_caster_generic(ti);
|
681 |
+
if (caster.load(src, false)) {
|
682 |
+
return caster.value;
|
683 |
+
}
|
684 |
+
return nullptr;
|
685 |
+
}
|
686 |
+
|
687 |
+
/// Try to load with foreign typeinfo, if available. Used when there is no
|
688 |
+
/// native typeinfo, or when the native one wasn't able to produce a value.
|
689 |
+
PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
|
690 |
+
constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
|
691 |
+
const auto pytype = type::handle_of(src);
|
692 |
+
if (!hasattr(pytype, local_key)) {
|
693 |
+
return false;
|
694 |
+
}
|
695 |
+
|
696 |
+
type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
|
697 |
+
// Only consider this foreign loader if actually foreign and is a loader of the correct cpp
|
698 |
+
// type
|
699 |
+
if (foreign_typeinfo->module_local_load == &local_load
|
700 |
+
|| (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {
|
701 |
+
return false;
|
702 |
+
}
|
703 |
+
|
704 |
+
if (auto *result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
|
705 |
+
value = result;
|
706 |
+
return true;
|
707 |
+
}
|
708 |
+
return false;
|
709 |
+
}
|
710 |
+
|
711 |
+
// Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
|
712 |
+
// bits of code between here and copyable_holder_caster where the two classes need different
|
713 |
+
// logic (without having to resort to virtual inheritance).
|
714 |
+
template <typename ThisT>
|
715 |
+
PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
|
716 |
+
if (!src) {
|
717 |
+
return false;
|
718 |
+
}
|
719 |
+
if (!typeinfo) {
|
720 |
+
return try_load_foreign_module_local(src);
|
721 |
+
}
|
722 |
+
|
723 |
+
auto &this_ = static_cast<ThisT &>(*this);
|
724 |
+
this_.check_holder_compat();
|
725 |
+
|
726 |
+
PyTypeObject *srctype = Py_TYPE(src.ptr());
|
727 |
+
|
728 |
+
// Case 1: If src is an exact type match for the target type then we can reinterpret_cast
|
729 |
+
// the instance's value pointer to the target type:
|
730 |
+
if (srctype == typeinfo->type) {
|
731 |
+
this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
|
732 |
+
return true;
|
733 |
+
}
|
734 |
+
// Case 2: We have a derived class
|
735 |
+
if (PyType_IsSubtype(srctype, typeinfo->type)) {
|
736 |
+
const auto &bases = all_type_info(srctype);
|
737 |
+
bool no_cpp_mi = typeinfo->simple_type;
|
738 |
+
|
739 |
+
// Case 2a: the python type is a Python-inherited derived class that inherits from just
|
740 |
+
// one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
|
741 |
+
// the right type and we can use reinterpret_cast.
|
742 |
+
// (This is essentially the same as case 2b, but because not using multiple inheritance
|
743 |
+
// is extremely common, we handle it specially to avoid the loop iterator and type
|
744 |
+
// pointer lookup overhead)
|
745 |
+
if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
|
746 |
+
this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
|
747 |
+
return true;
|
748 |
+
}
|
749 |
+
// Case 2b: the python type inherits from multiple C++ bases. Check the bases to see
|
750 |
+
// if we can find an exact match (or, for a simple C++ type, an inherited match); if
|
751 |
+
// so, we can safely reinterpret_cast to the relevant pointer.
|
752 |
+
if (bases.size() > 1) {
|
753 |
+
for (auto *base : bases) {
|
754 |
+
if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)
|
755 |
+
: base->type == typeinfo->type) {
|
756 |
+
this_.load_value(
|
757 |
+
reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
|
758 |
+
return true;
|
759 |
+
}
|
760 |
+
}
|
761 |
+
}
|
762 |
+
|
763 |
+
// Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
|
764 |
+
// match in the registered bases, above, so try implicit casting (needed for proper C++
|
765 |
+
// casting when MI is involved).
|
766 |
+
if (this_.try_implicit_casts(src, convert)) {
|
767 |
+
return true;
|
768 |
+
}
|
769 |
+
}
|
770 |
+
|
771 |
+
// Perform an implicit conversion
|
772 |
+
if (convert) {
|
773 |
+
for (const auto &converter : typeinfo->implicit_conversions) {
|
774 |
+
auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
|
775 |
+
if (load_impl<ThisT>(temp, false)) {
|
776 |
+
loader_life_support::add_patient(temp);
|
777 |
+
return true;
|
778 |
+
}
|
779 |
+
}
|
780 |
+
if (this_.try_direct_conversions(src)) {
|
781 |
+
return true;
|
782 |
+
}
|
783 |
+
}
|
784 |
+
|
785 |
+
// Failed to match local typeinfo. Try again with global.
|
786 |
+
if (typeinfo->module_local) {
|
787 |
+
if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
|
788 |
+
typeinfo = gtype;
|
789 |
+
return load(src, false);
|
790 |
+
}
|
791 |
+
}
|
792 |
+
|
793 |
+
// Global typeinfo has precedence over foreign module_local
|
794 |
+
if (try_load_foreign_module_local(src)) {
|
795 |
+
return true;
|
796 |
+
}
|
797 |
+
|
798 |
+
// Custom converters didn't take None, now we convert None to nullptr.
|
799 |
+
if (src.is_none()) {
|
800 |
+
// Defer accepting None to other overloads (if we aren't in convert mode):
|
801 |
+
if (!convert) {
|
802 |
+
return false;
|
803 |
+
}
|
804 |
+
value = nullptr;
|
805 |
+
return true;
|
806 |
+
}
|
807 |
+
|
808 |
+
return false;
|
809 |
+
}
|
810 |
+
|
811 |
+
// Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
|
812 |
+
// isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
|
813 |
+
// with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
|
814 |
+
PYBIND11_NOINLINE static std::pair<const void *, const type_info *>
|
815 |
+
src_and_type(const void *src,
|
816 |
+
const std::type_info &cast_type,
|
817 |
+
const std::type_info *rtti_type = nullptr) {
|
818 |
+
if (auto *tpi = get_type_info(cast_type)) {
|
819 |
+
return {src, const_cast<const type_info *>(tpi)};
|
820 |
+
}
|
821 |
+
|
822 |
+
// Not found, set error:
|
823 |
+
std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
|
824 |
+
detail::clean_type_id(tname);
|
825 |
+
std::string msg = "Unregistered type : " + tname;
|
826 |
+
set_error(PyExc_TypeError, msg.c_str());
|
827 |
+
return {nullptr, nullptr};
|
828 |
+
}
|
829 |
+
|
830 |
+
const type_info *typeinfo = nullptr;
|
831 |
+
const std::type_info *cpptype = nullptr;
|
832 |
+
void *value = nullptr;
|
833 |
+
};
|
834 |
+
|
835 |
+
/**
|
836 |
+
* Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
|
837 |
+
* needs to provide `operator T*()` and `operator T&()` operators.
|
838 |
+
*
|
839 |
+
* If the type supports moving the value away via an `operator T&&() &&` method, it should use
|
840 |
+
* `movable_cast_op_type` instead.
|
841 |
+
*/
|
842 |
+
template <typename T>
|
843 |
+
using cast_op_type = conditional_t<std::is_pointer<remove_reference_t<T>>::value,
|
844 |
+
typename std::add_pointer<intrinsic_t<T>>::type,
|
845 |
+
typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
|
846 |
+
|
847 |
+
/**
|
848 |
+
* Determine suitable casting operator for a type caster with a movable value. Such a type caster
|
849 |
+
* needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
|
850 |
+
* called in appropriate contexts where the value can be moved rather than copied.
|
851 |
+
*
|
852 |
+
* These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
|
853 |
+
*/
|
854 |
+
template <typename T>
|
855 |
+
using movable_cast_op_type
|
856 |
+
= conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
|
857 |
+
typename std::add_pointer<intrinsic_t<T>>::type,
|
858 |
+
conditional_t<std::is_rvalue_reference<T>::value,
|
859 |
+
typename std::add_rvalue_reference<intrinsic_t<T>>::type,
|
860 |
+
typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
|
861 |
+
|
862 |
+
// Does the container have a mapped type and is it recursive?
|
863 |
+
// Implemented by specializations below.
|
864 |
+
template <typename Container, typename SFINAE = void>
|
865 |
+
struct container_mapped_type_traits {
|
866 |
+
static constexpr bool has_mapped_type = false;
|
867 |
+
static constexpr bool has_recursive_mapped_type = false;
|
868 |
+
};
|
869 |
+
|
870 |
+
template <typename Container>
|
871 |
+
struct container_mapped_type_traits<
|
872 |
+
Container,
|
873 |
+
typename std::enable_if<
|
874 |
+
std::is_same<typename Container::mapped_type, Container>::value>::type> {
|
875 |
+
static constexpr bool has_mapped_type = true;
|
876 |
+
static constexpr bool has_recursive_mapped_type = true;
|
877 |
+
};
|
878 |
+
|
879 |
+
template <typename Container>
|
880 |
+
struct container_mapped_type_traits<
|
881 |
+
Container,
|
882 |
+
typename std::enable_if<
|
883 |
+
negation<std::is_same<typename Container::mapped_type, Container>>::value>::type> {
|
884 |
+
static constexpr bool has_mapped_type = true;
|
885 |
+
static constexpr bool has_recursive_mapped_type = false;
|
886 |
+
};
|
887 |
+
|
888 |
+
// Does the container have a value type and is it recursive?
|
889 |
+
// Implemented by specializations below.
|
890 |
+
template <typename Container, typename SFINAE = void>
|
891 |
+
struct container_value_type_traits : std::false_type {
|
892 |
+
static constexpr bool has_value_type = false;
|
893 |
+
static constexpr bool has_recursive_value_type = false;
|
894 |
+
};
|
895 |
+
|
896 |
+
template <typename Container>
|
897 |
+
struct container_value_type_traits<
|
898 |
+
Container,
|
899 |
+
typename std::enable_if<
|
900 |
+
std::is_same<typename Container::value_type, Container>::value>::type> {
|
901 |
+
static constexpr bool has_value_type = true;
|
902 |
+
static constexpr bool has_recursive_value_type = true;
|
903 |
+
};
|
904 |
+
|
905 |
+
template <typename Container>
|
906 |
+
struct container_value_type_traits<
|
907 |
+
Container,
|
908 |
+
typename std::enable_if<
|
909 |
+
negation<std::is_same<typename Container::value_type, Container>>::value>::type> {
|
910 |
+
static constexpr bool has_value_type = true;
|
911 |
+
static constexpr bool has_recursive_value_type = false;
|
912 |
+
};
|
913 |
+
|
914 |
+
/*
|
915 |
+
* Tag to be used for representing the bottom of recursively defined types.
|
916 |
+
* Define this tag so we don't have to use void.
|
917 |
+
*/
|
918 |
+
struct recursive_bottom {};
|
919 |
+
|
920 |
+
/*
|
921 |
+
* Implementation detail of `recursive_container_traits` below.
|
922 |
+
* `T` is the `value_type` of the container, which might need to be modified to
|
923 |
+
* avoid recursive types and const types.
|
924 |
+
*/
|
925 |
+
template <typename T, bool is_this_a_map>
|
926 |
+
struct impl_type_to_check_recursively {
|
927 |
+
/*
|
928 |
+
* If the container is recursive, then no further recursion should be done.
|
929 |
+
*/
|
930 |
+
using if_recursive = recursive_bottom;
|
931 |
+
/*
|
932 |
+
* Otherwise yield `T` unchanged.
|
933 |
+
*/
|
934 |
+
using if_not_recursive = T;
|
935 |
+
};
|
936 |
+
|
937 |
+
/*
|
938 |
+
* For pairs - only as value type of a map -, the first type should remove the `const`.
|
939 |
+
* Also, if the map is recursive, then the recursive checking should consider
|
940 |
+
* the first type only.
|
941 |
+
*/
|
942 |
+
template <typename A, typename B>
|
943 |
+
struct impl_type_to_check_recursively<std::pair<A, B>, /* is_this_a_map = */ true> {
|
944 |
+
using if_recursive = typename std::remove_const<A>::type;
|
945 |
+
using if_not_recursive = std::pair<typename std::remove_const<A>::type, B>;
|
946 |
+
};
|
947 |
+
|
948 |
+
/*
|
949 |
+
* Implementation of `recursive_container_traits` below.
|
950 |
+
*/
|
951 |
+
template <typename Container, typename SFINAE = void>
|
952 |
+
struct impl_recursive_container_traits {
|
953 |
+
using type_to_check_recursively = recursive_bottom;
|
954 |
+
};
|
955 |
+
|
956 |
+
template <typename Container>
|
957 |
+
struct impl_recursive_container_traits<
|
958 |
+
Container,
|
959 |
+
typename std::enable_if<container_value_type_traits<Container>::has_value_type>::type> {
|
960 |
+
static constexpr bool is_recursive
|
961 |
+
= container_mapped_type_traits<Container>::has_recursive_mapped_type
|
962 |
+
|| container_value_type_traits<Container>::has_recursive_value_type;
|
963 |
+
/*
|
964 |
+
* This member dictates which type Pybind11 should check recursively in traits
|
965 |
+
* such as `is_move_constructible`, `is_copy_constructible`, `is_move_assignable`, ...
|
966 |
+
* Direct access to `value_type` should be avoided:
|
967 |
+
* 1. `value_type` might recursively contain the type again
|
968 |
+
* 2. `value_type` of STL map types is `std::pair<A const, B>`, the `const`
|
969 |
+
* should be removed.
|
970 |
+
*
|
971 |
+
*/
|
972 |
+
using type_to_check_recursively = typename std::conditional<
|
973 |
+
is_recursive,
|
974 |
+
typename impl_type_to_check_recursively<
|
975 |
+
typename Container::value_type,
|
976 |
+
container_mapped_type_traits<Container>::has_mapped_type>::if_recursive,
|
977 |
+
typename impl_type_to_check_recursively<
|
978 |
+
typename Container::value_type,
|
979 |
+
container_mapped_type_traits<Container>::has_mapped_type>::if_not_recursive>::type;
|
980 |
+
};
|
981 |
+
|
982 |
+
/*
|
983 |
+
* This trait defines the `type_to_check_recursively` which is needed to properly
|
984 |
+
* handle recursively defined traits such as `is_move_constructible` without going
|
985 |
+
* into an infinite recursion.
|
986 |
+
* Should be used instead of directly accessing the `value_type`.
|
987 |
+
* It cancels the recursion by returning the `recursive_bottom` tag.
|
988 |
+
*
|
989 |
+
* The default definition of `type_to_check_recursively` is as follows:
|
990 |
+
*
|
991 |
+
* 1. By default, it is `recursive_bottom`, so that the recursion is canceled.
|
992 |
+
* 2. If the type is non-recursive and defines a `value_type`, then the `value_type` is used.
|
993 |
+
* If the `value_type` is a pair and a `mapped_type` is defined,
|
994 |
+
* then the `const` is removed from the first type.
|
995 |
+
* 3. If the type is recursive and `value_type` is not a pair, then `recursive_bottom` is returned.
|
996 |
+
* 4. If the type is recursive and `value_type` is a pair and a `mapped_type` is defined,
|
997 |
+
* then `const` is removed from the first type and the first type is returned.
|
998 |
+
*
|
999 |
+
* This behavior can be extended by the user as seen in test_stl_binders.cpp.
|
1000 |
+
*
|
1001 |
+
* This struct is exactly the same as impl_recursive_container_traits.
|
1002 |
+
* The duplication achieves that user-defined specializations don't compete
|
1003 |
+
* with internal specializations, but take precedence.
|
1004 |
+
*/
|
1005 |
+
template <typename Container, typename SFINAE = void>
|
1006 |
+
struct recursive_container_traits : impl_recursive_container_traits<Container> {};
|
1007 |
+
|
1008 |
+
template <typename T>
|
1009 |
+
struct is_move_constructible
|
1010 |
+
: all_of<std::is_move_constructible<T>,
|
1011 |
+
is_move_constructible<
|
1012 |
+
typename recursive_container_traits<T>::type_to_check_recursively>> {};
|
1013 |
+
|
1014 |
+
template <>
|
1015 |
+
struct is_move_constructible<recursive_bottom> : std::true_type {};
|
1016 |
+
|
1017 |
+
// Likewise for std::pair
|
1018 |
+
// (after C++17 it is mandatory that the move constructor not exist when the two types aren't
|
1019 |
+
// themselves move constructible, but this can not be relied upon when T1 or T2 are themselves
|
1020 |
+
// containers).
|
1021 |
+
template <typename T1, typename T2>
|
1022 |
+
struct is_move_constructible<std::pair<T1, T2>>
|
1023 |
+
: all_of<is_move_constructible<T1>, is_move_constructible<T2>> {};
|
1024 |
+
|
1025 |
+
// std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
|
1026 |
+
// T is non-copyable, but code containing such a copy constructor fails to actually compile.
|
1027 |
+
template <typename T>
|
1028 |
+
struct is_copy_constructible
|
1029 |
+
: all_of<std::is_copy_constructible<T>,
|
1030 |
+
is_copy_constructible<
|
1031 |
+
typename recursive_container_traits<T>::type_to_check_recursively>> {};
|
1032 |
+
|
1033 |
+
template <>
|
1034 |
+
struct is_copy_constructible<recursive_bottom> : std::true_type {};
|
1035 |
+
|
1036 |
+
// Likewise for std::pair
|
1037 |
+
// (after C++17 it is mandatory that the copy constructor not exist when the two types aren't
|
1038 |
+
// themselves copy constructible, but this can not be relied upon when T1 or T2 are themselves
|
1039 |
+
// containers).
|
1040 |
+
template <typename T1, typename T2>
|
1041 |
+
struct is_copy_constructible<std::pair<T1, T2>>
|
1042 |
+
: all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
|
1043 |
+
|
1044 |
+
// The same problems arise with std::is_copy_assignable, so we use the same workaround.
|
1045 |
+
template <typename T>
|
1046 |
+
struct is_copy_assignable
|
1047 |
+
: all_of<
|
1048 |
+
std::is_copy_assignable<T>,
|
1049 |
+
is_copy_assignable<typename recursive_container_traits<T>::type_to_check_recursively>> {
|
1050 |
+
};
|
1051 |
+
|
1052 |
+
template <>
|
1053 |
+
struct is_copy_assignable<recursive_bottom> : std::true_type {};
|
1054 |
+
|
1055 |
+
template <typename T1, typename T2>
|
1056 |
+
struct is_copy_assignable<std::pair<T1, T2>>
|
1057 |
+
: all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
|
1058 |
+
|
1059 |
+
PYBIND11_NAMESPACE_END(detail)
|
1060 |
+
|
1061 |
+
// polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
|
1062 |
+
// to by `src` actually is an instance of some class derived from `itype`.
|
1063 |
+
// If so, it sets `tinfo` to point to the std::type_info representing that derived
|
1064 |
+
// type, and returns a pointer to the start of the most-derived object of that type
|
1065 |
+
// (in which `src` is a subobject; this will be the same address as `src` in most
|
1066 |
+
// single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
|
1067 |
+
// and leaves `tinfo` at its default value of nullptr.
|
1068 |
+
//
|
1069 |
+
// The default polymorphic_type_hook just returns src. A specialization for polymorphic
|
1070 |
+
// types determines the runtime type of the passed object and adjusts the this-pointer
|
1071 |
+
// appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
|
1072 |
+
// to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
|
1073 |
+
// registered with pybind11, and this Animal is in fact a Dog).
|
1074 |
+
//
|
1075 |
+
// You may specialize polymorphic_type_hook yourself for types that want to appear
|
1076 |
+
// polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
|
1077 |
+
// in performance-sensitive applications, used most notably in LLVM.)
|
1078 |
+
//
|
1079 |
+
// polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
|
1080 |
+
// std::enable_if. User provided specializations will always have higher priority than
|
1081 |
+
// the default implementation and specialization provided in polymorphic_type_hook_base.
|
1082 |
+
template <typename itype, typename SFINAE = void>
|
1083 |
+
struct polymorphic_type_hook_base {
|
1084 |
+
static const void *get(const itype *src, const std::type_info *&) { return src; }
|
1085 |
+
};
|
1086 |
+
template <typename itype>
|
1087 |
+
struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>> {
|
1088 |
+
static const void *get(const itype *src, const std::type_info *&type) {
|
1089 |
+
type = src ? &typeid(*src) : nullptr;
|
1090 |
+
return dynamic_cast<const void *>(src);
|
1091 |
+
}
|
1092 |
+
};
|
1093 |
+
template <typename itype, typename SFINAE = void>
|
1094 |
+
struct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};
|
1095 |
+
|
1096 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
1097 |
+
|
1098 |
+
/// Generic type caster for objects stored on the heap
|
1099 |
+
template <typename type>
|
1100 |
+
class type_caster_base : public type_caster_generic {
|
1101 |
+
using itype = intrinsic_t<type>;
|
1102 |
+
|
1103 |
+
public:
|
1104 |
+
static constexpr auto name = const_name<type>();
|
1105 |
+
|
1106 |
+
type_caster_base() : type_caster_base(typeid(type)) {}
|
1107 |
+
explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) {}
|
1108 |
+
|
1109 |
+
static handle cast(const itype &src, return_value_policy policy, handle parent) {
|
1110 |
+
if (policy == return_value_policy::automatic
|
1111 |
+
|| policy == return_value_policy::automatic_reference) {
|
1112 |
+
policy = return_value_policy::copy;
|
1113 |
+
}
|
1114 |
+
return cast(&src, policy, parent);
|
1115 |
+
}
|
1116 |
+
|
1117 |
+
static handle cast(itype &&src, return_value_policy, handle parent) {
|
1118 |
+
return cast(&src, return_value_policy::move, parent);
|
1119 |
+
}
|
1120 |
+
|
1121 |
+
// Returns a (pointer, type_info) pair taking care of necessary type lookup for a
|
1122 |
+
// polymorphic type (using RTTI by default, but can be overridden by specializing
|
1123 |
+
// polymorphic_type_hook). If the instance isn't derived, returns the base version.
|
1124 |
+
static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
|
1125 |
+
const auto &cast_type = typeid(itype);
|
1126 |
+
const std::type_info *instance_type = nullptr;
|
1127 |
+
const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
|
1128 |
+
if (instance_type && !same_type(cast_type, *instance_type)) {
|
1129 |
+
// This is a base pointer to a derived type. If the derived type is registered
|
1130 |
+
// with pybind11, we want to make the full derived object available.
|
1131 |
+
// In the typical case where itype is polymorphic, we get the correct
|
1132 |
+
// derived pointer (which may be != base pointer) by a dynamic_cast to
|
1133 |
+
// most derived type. If itype is not polymorphic, we won't get here
|
1134 |
+
// except via a user-provided specialization of polymorphic_type_hook,
|
1135 |
+
// and the user has promised that no this-pointer adjustment is
|
1136 |
+
// required in that case, so it's OK to use static_cast.
|
1137 |
+
if (const auto *tpi = get_type_info(*instance_type)) {
|
1138 |
+
return {vsrc, tpi};
|
1139 |
+
}
|
1140 |
+
}
|
1141 |
+
// Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer,
|
1142 |
+
// so don't do a cast
|
1143 |
+
return type_caster_generic::src_and_type(src, cast_type, instance_type);
|
1144 |
+
}
|
1145 |
+
|
1146 |
+
static handle cast(const itype *src, return_value_policy policy, handle parent) {
|
1147 |
+
auto st = src_and_type(src);
|
1148 |
+
return type_caster_generic::cast(st.first,
|
1149 |
+
policy,
|
1150 |
+
parent,
|
1151 |
+
st.second,
|
1152 |
+
make_copy_constructor(src),
|
1153 |
+
make_move_constructor(src));
|
1154 |
+
}
|
1155 |
+
|
1156 |
+
static handle cast_holder(const itype *src, const void *holder) {
|
1157 |
+
auto st = src_and_type(src);
|
1158 |
+
return type_caster_generic::cast(st.first,
|
1159 |
+
return_value_policy::take_ownership,
|
1160 |
+
{},
|
1161 |
+
st.second,
|
1162 |
+
nullptr,
|
1163 |
+
nullptr,
|
1164 |
+
holder);
|
1165 |
+
}
|
1166 |
+
|
1167 |
+
template <typename T>
|
1168 |
+
using cast_op_type = detail::cast_op_type<T>;
|
1169 |
+
|
1170 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
1171 |
+
operator itype *() { return (type *) value; }
|
1172 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
1173 |
+
operator itype &() {
|
1174 |
+
if (!value) {
|
1175 |
+
throw reference_cast_error();
|
1176 |
+
}
|
1177 |
+
return *((itype *) value);
|
1178 |
+
}
|
1179 |
+
|
1180 |
+
protected:
|
1181 |
+
using Constructor = void *(*) (const void *);
|
1182 |
+
|
1183 |
+
/* Only enabled when the types are {copy,move}-constructible *and* when the type
|
1184 |
+
does not have a private operator new implementation. A comma operator is used in the
|
1185 |
+
decltype argument to apply SFINAE to the public copy/move constructors.*/
|
1186 |
+
template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
|
1187 |
+
static auto make_copy_constructor(const T *)
|
1188 |
+
-> decltype(new T(std::declval<const T>()), Constructor{}) {
|
1189 |
+
return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };
|
1190 |
+
}
|
1191 |
+
|
1192 |
+
template <typename T, typename = enable_if_t<is_move_constructible<T>::value>>
|
1193 |
+
static auto make_move_constructor(const T *)
|
1194 |
+
-> decltype(new T(std::declval<T &&>()), Constructor{}) {
|
1195 |
+
return [](const void *arg) -> void * {
|
1196 |
+
return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
|
1197 |
+
};
|
1198 |
+
}
|
1199 |
+
|
1200 |
+
static Constructor make_copy_constructor(...) { return nullptr; }
|
1201 |
+
static Constructor make_move_constructor(...) { return nullptr; }
|
1202 |
+
};
|
1203 |
+
|
1204 |
+
inline std::string quote_cpp_type_name(const std::string &cpp_type_name) {
|
1205 |
+
return cpp_type_name; // No-op for now. See PR #4888
|
1206 |
+
}
|
1207 |
+
|
1208 |
+
PYBIND11_NOINLINE std::string type_info_description(const std::type_info &ti) {
|
1209 |
+
if (auto *type_data = get_type_info(ti)) {
|
1210 |
+
handle th((PyObject *) type_data->type);
|
1211 |
+
return th.attr("__module__").cast<std::string>() + '.'
|
1212 |
+
+ th.attr("__qualname__").cast<std::string>();
|
1213 |
+
}
|
1214 |
+
return quote_cpp_type_name(clean_type_id(ti.name()));
|
1215 |
+
}
|
1216 |
+
|
1217 |
+
PYBIND11_NAMESPACE_END(detail)
|
1218 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/detail/typeid.h
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/detail/typeid.h: Compiler-independent access to type identifiers
|
3 |
+
|
4 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include <cstdio>
|
13 |
+
#include <cstdlib>
|
14 |
+
|
15 |
+
#if defined(__GNUG__)
|
16 |
+
# include <cxxabi.h>
|
17 |
+
#endif
|
18 |
+
|
19 |
+
#include "common.h"
|
20 |
+
|
21 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
22 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
23 |
+
|
24 |
+
/// Erase all occurrences of a substring
|
25 |
+
inline void erase_all(std::string &string, const std::string &search) {
|
26 |
+
for (size_t pos = 0;;) {
|
27 |
+
pos = string.find(search, pos);
|
28 |
+
if (pos == std::string::npos) {
|
29 |
+
break;
|
30 |
+
}
|
31 |
+
string.erase(pos, search.length());
|
32 |
+
}
|
33 |
+
}
|
34 |
+
|
35 |
+
PYBIND11_NOINLINE void clean_type_id(std::string &name) {
|
36 |
+
#if defined(__GNUG__)
|
37 |
+
int status = 0;
|
38 |
+
std::unique_ptr<char, void (*)(void *)> res{
|
39 |
+
abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free};
|
40 |
+
if (status == 0) {
|
41 |
+
name = res.get();
|
42 |
+
}
|
43 |
+
#else
|
44 |
+
detail::erase_all(name, "class ");
|
45 |
+
detail::erase_all(name, "struct ");
|
46 |
+
detail::erase_all(name, "enum ");
|
47 |
+
#endif
|
48 |
+
detail::erase_all(name, "pybind11::");
|
49 |
+
}
|
50 |
+
|
51 |
+
inline std::string clean_type_id(const char *typeid_name) {
|
52 |
+
std::string name(typeid_name);
|
53 |
+
detail::clean_type_id(name);
|
54 |
+
return name;
|
55 |
+
}
|
56 |
+
|
57 |
+
PYBIND11_NAMESPACE_END(detail)
|
58 |
+
|
59 |
+
/// Return a string representation of a C++ type
|
60 |
+
template <typename T>
|
61 |
+
static std::string type_id() {
|
62 |
+
return detail::clean_type_id(typeid(T).name());
|
63 |
+
}
|
64 |
+
|
65 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen.h
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices
|
3 |
+
|
4 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "eigen/matrix.h"
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/common.h
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright (c) 2023 The pybind Community.
|
2 |
+
|
3 |
+
#pragma once
|
4 |
+
|
5 |
+
// Common message for `static_assert()`s, which are useful to easily
|
6 |
+
// preempt much less obvious errors.
|
7 |
+
#define PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED \
|
8 |
+
"Pointer types (in particular `PyObject *`) are not supported as scalar types for Eigen " \
|
9 |
+
"types."
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/matrix.h
ADDED
@@ -0,0 +1,714 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/eigen/matrix.h: Transparent conversion for dense and sparse Eigen matrices
|
3 |
+
|
4 |
+
Copyright (c) 2016 Wenzel Jakob <[email protected]>
|
5 |
+
|
6 |
+
All rights reserved. Use of this source code is governed by a
|
7 |
+
BSD-style license that can be found in the LICENSE file.
|
8 |
+
*/
|
9 |
+
|
10 |
+
#pragma once
|
11 |
+
|
12 |
+
#include "../numpy.h"
|
13 |
+
#include "common.h"
|
14 |
+
|
15 |
+
/* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
|
16 |
+
See also:
|
17 |
+
https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
|
18 |
+
https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
|
19 |
+
*/
|
20 |
+
PYBIND11_WARNING_PUSH
|
21 |
+
PYBIND11_WARNING_DISABLE_MSVC(5054) // https://github.com/pybind/pybind11/pull/3741
|
22 |
+
// C5054: operator '&': deprecated between enumerations of different types
|
23 |
+
#if defined(__MINGW32__)
|
24 |
+
PYBIND11_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
|
25 |
+
#endif
|
26 |
+
|
27 |
+
#include <Eigen/Core>
|
28 |
+
#include <Eigen/SparseCore>
|
29 |
+
|
30 |
+
PYBIND11_WARNING_POP
|
31 |
+
|
32 |
+
// Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
|
33 |
+
// move constructors that break things. We could detect this an explicitly copy, but an extra copy
|
34 |
+
// of matrices seems highly undesirable.
|
35 |
+
static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
|
36 |
+
"Eigen matrix support in pybind11 requires Eigen >= 3.2.7");
|
37 |
+
|
38 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
39 |
+
|
40 |
+
PYBIND11_WARNING_DISABLE_MSVC(4127)
|
41 |
+
|
42 |
+
// Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
|
43 |
+
using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
|
44 |
+
template <typename MatrixType>
|
45 |
+
using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
|
46 |
+
template <typename MatrixType>
|
47 |
+
using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
|
48 |
+
|
49 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
50 |
+
|
51 |
+
#if EIGEN_VERSION_AT_LEAST(3, 3, 0)
|
52 |
+
using EigenIndex = Eigen::Index;
|
53 |
+
template <typename Scalar, int Flags, typename StorageIndex>
|
54 |
+
using EigenMapSparseMatrix = Eigen::Map<Eigen::SparseMatrix<Scalar, Flags, StorageIndex>>;
|
55 |
+
#else
|
56 |
+
using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
|
57 |
+
template <typename Scalar, int Flags, typename StorageIndex>
|
58 |
+
using EigenMapSparseMatrix = Eigen::MappedSparseMatrix<Scalar, Flags, StorageIndex>;
|
59 |
+
#endif
|
60 |
+
|
61 |
+
// Matches Eigen::Map, Eigen::Ref, blocks, etc:
|
62 |
+
template <typename T>
|
63 |
+
using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,
|
64 |
+
std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
|
65 |
+
template <typename T>
|
66 |
+
using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
|
67 |
+
template <typename T>
|
68 |
+
using is_eigen_dense_plain
|
69 |
+
= all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
|
70 |
+
template <typename T>
|
71 |
+
using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
|
72 |
+
// Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
|
73 |
+
// basically covers anything that can be assigned to a dense matrix but that don't have a typical
|
74 |
+
// matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
|
75 |
+
// SelfAdjointView fall into this category.
|
76 |
+
template <typename T>
|
77 |
+
using is_eigen_other
|
78 |
+
= all_of<is_template_base_of<Eigen::EigenBase, T>,
|
79 |
+
negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;
|
80 |
+
|
81 |
+
// Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
|
82 |
+
template <bool EigenRowMajor>
|
83 |
+
struct EigenConformable {
|
84 |
+
bool conformable = false;
|
85 |
+
EigenIndex rows = 0, cols = 0;
|
86 |
+
EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
|
87 |
+
bool negativestrides = false; // If true, do not use stride!
|
88 |
+
|
89 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
90 |
+
EigenConformable(bool fits = false) : conformable{fits} {}
|
91 |
+
// Matrix type:
|
92 |
+
EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
|
93 |
+
: conformable{true}, rows{r}, cols{c},
|
94 |
+
// TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
|
95 |
+
// http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
|
96 |
+
stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
|
97 |
+
: (cstride > 0 ? cstride : 0) /* outer stride */,
|
98 |
+
EigenRowMajor ? (cstride > 0 ? cstride : 0)
|
99 |
+
: (rstride > 0 ? rstride : 0) /* inner stride */},
|
100 |
+
negativestrides{rstride < 0 || cstride < 0} {}
|
101 |
+
// Vector type:
|
102 |
+
EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
|
103 |
+
: EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
|
104 |
+
|
105 |
+
template <typename props>
|
106 |
+
bool stride_compatible() const {
|
107 |
+
// To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
|
108 |
+
// matching strides, or a dimension size of 1 (in which case the stride value is
|
109 |
+
// irrelevant). Alternatively, if any dimension size is 0, the strides are not relevant
|
110 |
+
// (and numpy ≥ 1.23 sets the strides to 0 in that case, so we need to check explicitly).
|
111 |
+
if (negativestrides) {
|
112 |
+
return false;
|
113 |
+
}
|
114 |
+
if (rows == 0 || cols == 0) {
|
115 |
+
return true;
|
116 |
+
}
|
117 |
+
return (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
|
118 |
+
|| (EigenRowMajor ? cols : rows) == 1)
|
119 |
+
&& (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
|
120 |
+
|| (EigenRowMajor ? rows : cols) == 1);
|
121 |
+
}
|
122 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
123 |
+
operator bool() const { return conformable; }
|
124 |
+
};
|
125 |
+
|
126 |
+
template <typename Type>
|
127 |
+
struct eigen_extract_stride {
|
128 |
+
using type = Type;
|
129 |
+
};
|
130 |
+
template <typename PlainObjectType, int MapOptions, typename StrideType>
|
131 |
+
struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
|
132 |
+
using type = StrideType;
|
133 |
+
};
|
134 |
+
template <typename PlainObjectType, int Options, typename StrideType>
|
135 |
+
struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
|
136 |
+
using type = StrideType;
|
137 |
+
};
|
138 |
+
|
139 |
+
// Helper struct for extracting information from an Eigen type
|
140 |
+
template <typename Type_>
|
141 |
+
struct EigenProps {
|
142 |
+
using Type = Type_;
|
143 |
+
using Scalar = typename Type::Scalar;
|
144 |
+
using StrideType = typename eigen_extract_stride<Type>::type;
|
145 |
+
static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
|
146 |
+
size = Type::SizeAtCompileTime;
|
147 |
+
static constexpr bool row_major = Type::IsRowMajor,
|
148 |
+
vector
|
149 |
+
= Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
|
150 |
+
fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
|
151 |
+
fixed = size != Eigen::Dynamic, // Fully-fixed size
|
152 |
+
dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
|
153 |
+
|
154 |
+
template <EigenIndex i, EigenIndex ifzero>
|
155 |
+
using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
|
156 |
+
static constexpr EigenIndex inner_stride
|
157 |
+
= if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
|
158 |
+
outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
|
159 |
+
vector ? size
|
160 |
+
: row_major ? cols
|
161 |
+
: rows > ::value;
|
162 |
+
static constexpr bool dynamic_stride
|
163 |
+
= inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
|
164 |
+
static constexpr bool requires_row_major
|
165 |
+
= !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
|
166 |
+
static constexpr bool requires_col_major
|
167 |
+
= !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
|
168 |
+
|
169 |
+
// Takes an input array and determines whether we can make it fit into the Eigen type. If
|
170 |
+
// the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
|
171 |
+
// (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
|
172 |
+
static EigenConformable<row_major> conformable(const array &a) {
|
173 |
+
const auto dims = a.ndim();
|
174 |
+
if (dims < 1 || dims > 2) {
|
175 |
+
return false;
|
176 |
+
}
|
177 |
+
|
178 |
+
if (dims == 2) { // Matrix type: require exact match (or dynamic)
|
179 |
+
|
180 |
+
EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
|
181 |
+
np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
|
182 |
+
np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
|
183 |
+
if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols)) {
|
184 |
+
return false;
|
185 |
+
}
|
186 |
+
|
187 |
+
return {np_rows, np_cols, np_rstride, np_cstride};
|
188 |
+
}
|
189 |
+
|
190 |
+
// Otherwise we're storing an n-vector. Only one of the strides will be used, but
|
191 |
+
// whichever is used, we want the (single) numpy stride value.
|
192 |
+
const EigenIndex n = a.shape(0),
|
193 |
+
stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
|
194 |
+
|
195 |
+
if (vector) { // Eigen type is a compile-time vector
|
196 |
+
if (fixed && size != n) {
|
197 |
+
return false; // Vector size mismatch
|
198 |
+
}
|
199 |
+
return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
|
200 |
+
}
|
201 |
+
if (fixed) {
|
202 |
+
// The type has a fixed size, but is not a vector: abort
|
203 |
+
return false;
|
204 |
+
}
|
205 |
+
if (fixed_cols) {
|
206 |
+
// Since this isn't a vector, cols must be != 1. We allow this only if it exactly
|
207 |
+
// equals the number of elements (rows is Dynamic, and so 1 row is allowed).
|
208 |
+
if (cols != n) {
|
209 |
+
return false;
|
210 |
+
}
|
211 |
+
return {1, n, stride};
|
212 |
+
} // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
|
213 |
+
if (fixed_rows && rows != n) {
|
214 |
+
return false;
|
215 |
+
}
|
216 |
+
return {n, 1, stride};
|
217 |
+
}
|
218 |
+
|
219 |
+
static constexpr bool show_writeable
|
220 |
+
= is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
|
221 |
+
static constexpr bool show_order = is_eigen_dense_map<Type>::value;
|
222 |
+
static constexpr bool show_c_contiguous = show_order && requires_row_major;
|
223 |
+
static constexpr bool show_f_contiguous
|
224 |
+
= !show_c_contiguous && show_order && requires_col_major;
|
225 |
+
|
226 |
+
static constexpr auto descriptor
|
227 |
+
= const_name("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + const_name("[")
|
228 |
+
+ const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
|
229 |
+
+ const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
|
230 |
+
+
|
231 |
+
// For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
|
232 |
+
// be satisfied: writeable=True (for a mutable reference), and, depending on the map's
|
233 |
+
// stride options, possibly f_contiguous or c_contiguous. We include them in the
|
234 |
+
// descriptor output to provide some hint as to why a TypeError is occurring (otherwise
|
235 |
+
// it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
|
236 |
+
// an error message that you *gave* a numpy.ndarray of the right type and dimensions.
|
237 |
+
const_name<show_writeable>(", flags.writeable", "")
|
238 |
+
+ const_name<show_c_contiguous>(", flags.c_contiguous", "")
|
239 |
+
+ const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
|
240 |
+
};
|
241 |
+
|
242 |
+
// Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
|
243 |
+
// otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
|
244 |
+
template <typename props>
|
245 |
+
handle
|
246 |
+
eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
|
247 |
+
constexpr ssize_t elem_size = sizeof(typename props::Scalar);
|
248 |
+
array a;
|
249 |
+
if (props::vector) {
|
250 |
+
a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
|
251 |
+
} else {
|
252 |
+
a = array({src.rows(), src.cols()},
|
253 |
+
{elem_size * src.rowStride(), elem_size * src.colStride()},
|
254 |
+
src.data(),
|
255 |
+
base);
|
256 |
+
}
|
257 |
+
|
258 |
+
if (!writeable) {
|
259 |
+
array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
|
260 |
+
}
|
261 |
+
|
262 |
+
return a.release();
|
263 |
+
}
|
264 |
+
|
265 |
+
// Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
|
266 |
+
// reference the Eigen object's data with `base` as the python-registered base class (if omitted,
|
267 |
+
// the base will be set to None, and lifetime management is up to the caller). The numpy array is
|
268 |
+
// non-writeable if the given type is const.
|
269 |
+
template <typename props, typename Type>
|
270 |
+
handle eigen_ref_array(Type &src, handle parent = none()) {
|
271 |
+
// none here is to get past array's should-we-copy detection, which currently always
|
272 |
+
// copies when there is no base. Setting the base to None should be harmless.
|
273 |
+
return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
|
274 |
+
}
|
275 |
+
|
276 |
+
// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
|
277 |
+
// numpy array that references the encapsulated data with a python-side reference to the capsule to
|
278 |
+
// tie its destruction to that of any dependent python objects. Const-ness is determined by
|
279 |
+
// whether or not the Type of the pointer given is const.
|
280 |
+
template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
|
281 |
+
handle eigen_encapsulate(Type *src) {
|
282 |
+
capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
|
283 |
+
return eigen_ref_array<props>(*src, base);
|
284 |
+
}
|
285 |
+
|
286 |
+
// Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
|
287 |
+
// types.
|
288 |
+
template <typename Type>
|
289 |
+
struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
|
290 |
+
using Scalar = typename Type::Scalar;
|
291 |
+
static_assert(!std::is_pointer<Scalar>::value,
|
292 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
293 |
+
using props = EigenProps<Type>;
|
294 |
+
|
295 |
+
bool load(handle src, bool convert) {
|
296 |
+
// If we're in no-convert mode, only load if given an array of the correct type
|
297 |
+
if (!convert && !isinstance<array_t<Scalar>>(src)) {
|
298 |
+
return false;
|
299 |
+
}
|
300 |
+
|
301 |
+
// Coerce into an array, but don't do type conversion yet; the copy below handles it.
|
302 |
+
auto buf = array::ensure(src);
|
303 |
+
|
304 |
+
if (!buf) {
|
305 |
+
return false;
|
306 |
+
}
|
307 |
+
|
308 |
+
auto dims = buf.ndim();
|
309 |
+
if (dims < 1 || dims > 2) {
|
310 |
+
return false;
|
311 |
+
}
|
312 |
+
|
313 |
+
auto fits = props::conformable(buf);
|
314 |
+
if (!fits) {
|
315 |
+
return false;
|
316 |
+
}
|
317 |
+
|
318 |
+
// Allocate the new type, then build a numpy reference into it
|
319 |
+
value = Type(fits.rows, fits.cols);
|
320 |
+
auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
|
321 |
+
if (dims == 1) {
|
322 |
+
ref = ref.squeeze();
|
323 |
+
} else if (ref.ndim() == 1) {
|
324 |
+
buf = buf.squeeze();
|
325 |
+
}
|
326 |
+
|
327 |
+
int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
|
328 |
+
|
329 |
+
if (result < 0) { // Copy failed!
|
330 |
+
PyErr_Clear();
|
331 |
+
return false;
|
332 |
+
}
|
333 |
+
|
334 |
+
return true;
|
335 |
+
}
|
336 |
+
|
337 |
+
private:
|
338 |
+
// Cast implementation
|
339 |
+
template <typename CType>
|
340 |
+
static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
|
341 |
+
switch (policy) {
|
342 |
+
case return_value_policy::take_ownership:
|
343 |
+
case return_value_policy::automatic:
|
344 |
+
return eigen_encapsulate<props>(src);
|
345 |
+
case return_value_policy::move:
|
346 |
+
return eigen_encapsulate<props>(new CType(std::move(*src)));
|
347 |
+
case return_value_policy::copy:
|
348 |
+
return eigen_array_cast<props>(*src);
|
349 |
+
case return_value_policy::reference:
|
350 |
+
case return_value_policy::automatic_reference:
|
351 |
+
return eigen_ref_array<props>(*src);
|
352 |
+
case return_value_policy::reference_internal:
|
353 |
+
return eigen_ref_array<props>(*src, parent);
|
354 |
+
default:
|
355 |
+
throw cast_error("unhandled return_value_policy: should not happen!");
|
356 |
+
};
|
357 |
+
}
|
358 |
+
|
359 |
+
public:
|
360 |
+
// Normal returned non-reference, non-const value:
|
361 |
+
static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
|
362 |
+
return cast_impl(&src, return_value_policy::move, parent);
|
363 |
+
}
|
364 |
+
// If you return a non-reference const, we mark the numpy array readonly:
|
365 |
+
static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
|
366 |
+
return cast_impl(&src, return_value_policy::move, parent);
|
367 |
+
}
|
368 |
+
// lvalue reference return; default (automatic) becomes copy
|
369 |
+
static handle cast(Type &src, return_value_policy policy, handle parent) {
|
370 |
+
if (policy == return_value_policy::automatic
|
371 |
+
|| policy == return_value_policy::automatic_reference) {
|
372 |
+
policy = return_value_policy::copy;
|
373 |
+
}
|
374 |
+
return cast_impl(&src, policy, parent);
|
375 |
+
}
|
376 |
+
// const lvalue reference return; default (automatic) becomes copy
|
377 |
+
static handle cast(const Type &src, return_value_policy policy, handle parent) {
|
378 |
+
if (policy == return_value_policy::automatic
|
379 |
+
|| policy == return_value_policy::automatic_reference) {
|
380 |
+
policy = return_value_policy::copy;
|
381 |
+
}
|
382 |
+
return cast(&src, policy, parent);
|
383 |
+
}
|
384 |
+
// non-const pointer return
|
385 |
+
static handle cast(Type *src, return_value_policy policy, handle parent) {
|
386 |
+
return cast_impl(src, policy, parent);
|
387 |
+
}
|
388 |
+
// const pointer return
|
389 |
+
static handle cast(const Type *src, return_value_policy policy, handle parent) {
|
390 |
+
return cast_impl(src, policy, parent);
|
391 |
+
}
|
392 |
+
|
393 |
+
static constexpr auto name = props::descriptor;
|
394 |
+
|
395 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
396 |
+
operator Type *() { return &value; }
|
397 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
398 |
+
operator Type &() { return value; }
|
399 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
400 |
+
operator Type &&() && { return std::move(value); }
|
401 |
+
template <typename T>
|
402 |
+
using cast_op_type = movable_cast_op_type<T>;
|
403 |
+
|
404 |
+
private:
|
405 |
+
Type value;
|
406 |
+
};
|
407 |
+
|
408 |
+
// Base class for casting reference/map/block/etc. objects back to python.
|
409 |
+
template <typename MapType>
|
410 |
+
struct eigen_map_caster {
|
411 |
+
static_assert(!std::is_pointer<typename MapType::Scalar>::value,
|
412 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
413 |
+
|
414 |
+
private:
|
415 |
+
using props = EigenProps<MapType>;
|
416 |
+
|
417 |
+
public:
|
418 |
+
// Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
|
419 |
+
// to stay around), but we'll allow it under the assumption that you know what you're doing
|
420 |
+
// (and have an appropriate keep_alive in place). We return a numpy array pointing directly at
|
421 |
+
// the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
|
422 |
+
// Note that this means you need to ensure you don't destroy the object in some other way (e.g.
|
423 |
+
// with an appropriate keep_alive, or with a reference to a statically allocated matrix).
|
424 |
+
static handle cast(const MapType &src, return_value_policy policy, handle parent) {
|
425 |
+
switch (policy) {
|
426 |
+
case return_value_policy::copy:
|
427 |
+
return eigen_array_cast<props>(src);
|
428 |
+
case return_value_policy::reference_internal:
|
429 |
+
return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
|
430 |
+
case return_value_policy::reference:
|
431 |
+
case return_value_policy::automatic:
|
432 |
+
case return_value_policy::automatic_reference:
|
433 |
+
return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
|
434 |
+
default:
|
435 |
+
// move, take_ownership don't make any sense for a ref/map:
|
436 |
+
pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
|
437 |
+
}
|
438 |
+
}
|
439 |
+
|
440 |
+
static constexpr auto name = props::descriptor;
|
441 |
+
|
442 |
+
// Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
|
443 |
+
// types but not bound arguments). We still provide them (with an explicitly delete) so that
|
444 |
+
// you end up here if you try anyway.
|
445 |
+
bool load(handle, bool) = delete;
|
446 |
+
operator MapType() = delete;
|
447 |
+
template <typename>
|
448 |
+
using cast_op_type = MapType;
|
449 |
+
};
|
450 |
+
|
451 |
+
// We can return any map-like object (but can only load Refs, specialized next):
|
452 |
+
template <typename Type>
|
453 |
+
struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};
|
454 |
+
|
455 |
+
// Loader for Ref<...> arguments. See the documentation for info on how to make this work without
|
456 |
+
// copying (it requires some extra effort in many cases).
|
457 |
+
template <typename PlainObjectType, typename StrideType>
|
458 |
+
struct type_caster<
|
459 |
+
Eigen::Ref<PlainObjectType, 0, StrideType>,
|
460 |
+
enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>
|
461 |
+
: public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
|
462 |
+
private:
|
463 |
+
using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
|
464 |
+
using props = EigenProps<Type>;
|
465 |
+
using Scalar = typename props::Scalar;
|
466 |
+
static_assert(!std::is_pointer<Scalar>::value,
|
467 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
468 |
+
using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
|
469 |
+
using Array
|
470 |
+
= array_t<Scalar,
|
471 |
+
array::forcecast
|
472 |
+
| ((props::row_major ? props::inner_stride : props::outer_stride) == 1
|
473 |
+
? array::c_style
|
474 |
+
: (props::row_major ? props::outer_stride : props::inner_stride) == 1
|
475 |
+
? array::f_style
|
476 |
+
: 0)>;
|
477 |
+
static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
|
478 |
+
// Delay construction (these have no default constructor)
|
479 |
+
std::unique_ptr<MapType> map;
|
480 |
+
std::unique_ptr<Type> ref;
|
481 |
+
// Our array. When possible, this is just a numpy array pointing to the source data, but
|
482 |
+
// sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
|
483 |
+
// incompatible layout, or is an array of a type that needs to be converted). Using a numpy
|
484 |
+
// temporary (rather than an Eigen temporary) saves an extra copy when we need both type
|
485 |
+
// conversion and storage order conversion. (Note that we refuse to use this temporary copy
|
486 |
+
// when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
|
487 |
+
Array copy_or_ref;
|
488 |
+
|
489 |
+
public:
|
490 |
+
bool load(handle src, bool convert) {
|
491 |
+
// First check whether what we have is already an array of the right type. If not, we
|
492 |
+
// can't avoid a copy (because the copy is also going to do type conversion).
|
493 |
+
bool need_copy = !isinstance<Array>(src);
|
494 |
+
|
495 |
+
EigenConformable<props::row_major> fits;
|
496 |
+
if (!need_copy) {
|
497 |
+
// We don't need a converting copy, but we also need to check whether the strides are
|
498 |
+
// compatible with the Ref's stride requirements
|
499 |
+
auto aref = reinterpret_borrow<Array>(src);
|
500 |
+
|
501 |
+
if (aref && (!need_writeable || aref.writeable())) {
|
502 |
+
fits = props::conformable(aref);
|
503 |
+
if (!fits) {
|
504 |
+
return false; // Incompatible dimensions
|
505 |
+
}
|
506 |
+
if (!fits.template stride_compatible<props>()) {
|
507 |
+
need_copy = true;
|
508 |
+
} else {
|
509 |
+
copy_or_ref = std::move(aref);
|
510 |
+
}
|
511 |
+
} else {
|
512 |
+
need_copy = true;
|
513 |
+
}
|
514 |
+
}
|
515 |
+
|
516 |
+
if (need_copy) {
|
517 |
+
// We need to copy: If we need a mutable reference, or we're not supposed to convert
|
518 |
+
// (either because we're in the no-convert overload pass, or because we're explicitly
|
519 |
+
// instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
|
520 |
+
if (!convert || need_writeable) {
|
521 |
+
return false;
|
522 |
+
}
|
523 |
+
|
524 |
+
Array copy = Array::ensure(src);
|
525 |
+
if (!copy) {
|
526 |
+
return false;
|
527 |
+
}
|
528 |
+
fits = props::conformable(copy);
|
529 |
+
if (!fits || !fits.template stride_compatible<props>()) {
|
530 |
+
return false;
|
531 |
+
}
|
532 |
+
copy_or_ref = std::move(copy);
|
533 |
+
loader_life_support::add_patient(copy_or_ref);
|
534 |
+
}
|
535 |
+
|
536 |
+
ref.reset();
|
537 |
+
map.reset(new MapType(data(copy_or_ref),
|
538 |
+
fits.rows,
|
539 |
+
fits.cols,
|
540 |
+
make_stride(fits.stride.outer(), fits.stride.inner())));
|
541 |
+
ref.reset(new Type(*map));
|
542 |
+
|
543 |
+
return true;
|
544 |
+
}
|
545 |
+
|
546 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
547 |
+
operator Type *() { return ref.get(); }
|
548 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
549 |
+
operator Type &() { return *ref; }
|
550 |
+
template <typename _T>
|
551 |
+
using cast_op_type = pybind11::detail::cast_op_type<_T>;
|
552 |
+
|
553 |
+
private:
|
554 |
+
template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
|
555 |
+
Scalar *data(Array &a) {
|
556 |
+
return a.mutable_data();
|
557 |
+
}
|
558 |
+
|
559 |
+
template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
|
560 |
+
const Scalar *data(Array &a) {
|
561 |
+
return a.data();
|
562 |
+
}
|
563 |
+
|
564 |
+
// Attempt to figure out a constructor of `Stride` that will work.
|
565 |
+
// If both strides are fixed, use a default constructor:
|
566 |
+
template <typename S>
|
567 |
+
using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
|
568 |
+
&& S::OuterStrideAtCompileTime != Eigen::Dynamic
|
569 |
+
&& std::is_default_constructible<S>::value>;
|
570 |
+
// Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
|
571 |
+
// Eigen::Stride, and use it:
|
572 |
+
template <typename S>
|
573 |
+
using stride_ctor_dual
|
574 |
+
= bool_constant<!stride_ctor_default<S>::value
|
575 |
+
&& std::is_constructible<S, EigenIndex, EigenIndex>::value>;
|
576 |
+
// Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
|
577 |
+
// it (passing whichever stride is dynamic).
|
578 |
+
template <typename S>
|
579 |
+
using stride_ctor_outer
|
580 |
+
= bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
|
581 |
+
&& S::OuterStrideAtCompileTime == Eigen::Dynamic
|
582 |
+
&& S::InnerStrideAtCompileTime != Eigen::Dynamic
|
583 |
+
&& std::is_constructible<S, EigenIndex>::value>;
|
584 |
+
template <typename S>
|
585 |
+
using stride_ctor_inner
|
586 |
+
= bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
|
587 |
+
&& S::InnerStrideAtCompileTime == Eigen::Dynamic
|
588 |
+
&& S::OuterStrideAtCompileTime != Eigen::Dynamic
|
589 |
+
&& std::is_constructible<S, EigenIndex>::value>;
|
590 |
+
|
591 |
+
template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
|
592 |
+
static S make_stride(EigenIndex, EigenIndex) {
|
593 |
+
return S();
|
594 |
+
}
|
595 |
+
template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
|
596 |
+
static S make_stride(EigenIndex outer, EigenIndex inner) {
|
597 |
+
return S(outer, inner);
|
598 |
+
}
|
599 |
+
template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
|
600 |
+
static S make_stride(EigenIndex outer, EigenIndex) {
|
601 |
+
return S(outer);
|
602 |
+
}
|
603 |
+
template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
|
604 |
+
static S make_stride(EigenIndex, EigenIndex inner) {
|
605 |
+
return S(inner);
|
606 |
+
}
|
607 |
+
};
|
608 |
+
|
609 |
+
// type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
|
610 |
+
// EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
|
611 |
+
// load() is not supported, but we can cast them into the python domain by first copying to a
|
612 |
+
// regular Eigen::Matrix, then casting that.
|
613 |
+
template <typename Type>
|
614 |
+
struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
|
615 |
+
static_assert(!std::is_pointer<typename Type::Scalar>::value,
|
616 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
617 |
+
|
618 |
+
protected:
|
619 |
+
using Matrix
|
620 |
+
= Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
|
621 |
+
using props = EigenProps<Matrix>;
|
622 |
+
|
623 |
+
public:
|
624 |
+
static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
|
625 |
+
handle h = eigen_encapsulate<props>(new Matrix(src));
|
626 |
+
return h;
|
627 |
+
}
|
628 |
+
static handle cast(const Type *src, return_value_policy policy, handle parent) {
|
629 |
+
return cast(*src, policy, parent);
|
630 |
+
}
|
631 |
+
|
632 |
+
static constexpr auto name = props::descriptor;
|
633 |
+
|
634 |
+
// Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
|
635 |
+
// types but not bound arguments). We still provide them (with an explicitly delete) so that
|
636 |
+
// you end up here if you try anyway.
|
637 |
+
bool load(handle, bool) = delete;
|
638 |
+
operator Type() = delete;
|
639 |
+
template <typename>
|
640 |
+
using cast_op_type = Type;
|
641 |
+
};
|
642 |
+
|
643 |
+
template <typename Type>
|
644 |
+
struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
|
645 |
+
using Scalar = typename Type::Scalar;
|
646 |
+
static_assert(!std::is_pointer<Scalar>::value,
|
647 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
648 |
+
using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;
|
649 |
+
using Index = typename Type::Index;
|
650 |
+
static constexpr bool rowMajor = Type::IsRowMajor;
|
651 |
+
|
652 |
+
bool load(handle src, bool) {
|
653 |
+
if (!src) {
|
654 |
+
return false;
|
655 |
+
}
|
656 |
+
|
657 |
+
auto obj = reinterpret_borrow<object>(src);
|
658 |
+
object sparse_module = module_::import("scipy.sparse");
|
659 |
+
object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
|
660 |
+
|
661 |
+
if (!type::handle_of(obj).is(matrix_type)) {
|
662 |
+
try {
|
663 |
+
obj = matrix_type(obj);
|
664 |
+
} catch (const error_already_set &) {
|
665 |
+
return false;
|
666 |
+
}
|
667 |
+
}
|
668 |
+
|
669 |
+
auto values = array_t<Scalar>((object) obj.attr("data"));
|
670 |
+
auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
|
671 |
+
auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
|
672 |
+
auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
|
673 |
+
auto nnz = obj.attr("nnz").cast<Index>();
|
674 |
+
|
675 |
+
if (!values || !innerIndices || !outerIndices) {
|
676 |
+
return false;
|
677 |
+
}
|
678 |
+
|
679 |
+
value = EigenMapSparseMatrix<Scalar,
|
680 |
+
Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
|
681 |
+
StorageIndex>(shape[0].cast<Index>(),
|
682 |
+
shape[1].cast<Index>(),
|
683 |
+
std::move(nnz),
|
684 |
+
outerIndices.mutable_data(),
|
685 |
+
innerIndices.mutable_data(),
|
686 |
+
values.mutable_data());
|
687 |
+
|
688 |
+
return true;
|
689 |
+
}
|
690 |
+
|
691 |
+
static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
|
692 |
+
const_cast<Type &>(src).makeCompressed();
|
693 |
+
|
694 |
+
object matrix_type
|
695 |
+
= module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
|
696 |
+
|
697 |
+
array data(src.nonZeros(), src.valuePtr());
|
698 |
+
array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
|
699 |
+
array innerIndices(src.nonZeros(), src.innerIndexPtr());
|
700 |
+
|
701 |
+
return matrix_type(pybind11::make_tuple(
|
702 |
+
std::move(data), std::move(innerIndices), std::move(outerIndices)),
|
703 |
+
pybind11::make_tuple(src.rows(), src.cols()))
|
704 |
+
.release();
|
705 |
+
}
|
706 |
+
|
707 |
+
PYBIND11_TYPE_CASTER(Type,
|
708 |
+
const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
|
709 |
+
"scipy.sparse.csc_matrix[")
|
710 |
+
+ npy_format_descriptor<Scalar>::name + const_name("]"));
|
711 |
+
};
|
712 |
+
|
713 |
+
PYBIND11_NAMESPACE_END(detail)
|
714 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
env-llmeval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/tensor.h
ADDED
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
pybind11/eigen/tensor.h: Transparent conversion for Eigen tensors
|
3 |
+
|
4 |
+
All rights reserved. Use of this source code is governed by a
|
5 |
+
BSD-style license that can be found in the LICENSE file.
|
6 |
+
*/
|
7 |
+
|
8 |
+
#pragma once
|
9 |
+
|
10 |
+
#include "../numpy.h"
|
11 |
+
#include "common.h"
|
12 |
+
|
13 |
+
#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
|
14 |
+
static_assert(__GNUC__ > 5, "Eigen Tensor support in pybind11 requires GCC > 5.0");
|
15 |
+
#endif
|
16 |
+
|
17 |
+
// Disable warnings for Eigen
|
18 |
+
PYBIND11_WARNING_PUSH
|
19 |
+
PYBIND11_WARNING_DISABLE_MSVC(4554)
|
20 |
+
PYBIND11_WARNING_DISABLE_MSVC(4127)
|
21 |
+
#if defined(__MINGW32__)
|
22 |
+
PYBIND11_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
|
23 |
+
#endif
|
24 |
+
|
25 |
+
#include <unsupported/Eigen/CXX11/Tensor>
|
26 |
+
|
27 |
+
PYBIND11_WARNING_POP
|
28 |
+
|
29 |
+
static_assert(EIGEN_VERSION_AT_LEAST(3, 3, 0),
|
30 |
+
"Eigen Tensor support in pybind11 requires Eigen >= 3.3.0");
|
31 |
+
|
32 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
33 |
+
|
34 |
+
PYBIND11_WARNING_DISABLE_MSVC(4127)
|
35 |
+
|
36 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
37 |
+
|
38 |
+
inline bool is_tensor_aligned(const void *data) {
|
39 |
+
return (reinterpret_cast<std::size_t>(data) % EIGEN_DEFAULT_ALIGN_BYTES) == 0;
|
40 |
+
}
|
41 |
+
|
42 |
+
template <typename T>
|
43 |
+
constexpr int compute_array_flag_from_tensor() {
|
44 |
+
static_assert((static_cast<int>(T::Layout) == static_cast<int>(Eigen::RowMajor))
|
45 |
+
|| (static_cast<int>(T::Layout) == static_cast<int>(Eigen::ColMajor)),
|
46 |
+
"Layout must be row or column major");
|
47 |
+
return (static_cast<int>(T::Layout) == static_cast<int>(Eigen::RowMajor)) ? array::c_style
|
48 |
+
: array::f_style;
|
49 |
+
}
|
50 |
+
|
51 |
+
template <typename T>
|
52 |
+
struct eigen_tensor_helper {};
|
53 |
+
|
54 |
+
template <typename Scalar_, int NumIndices_, int Options_, typename IndexType>
|
55 |
+
struct eigen_tensor_helper<Eigen::Tensor<Scalar_, NumIndices_, Options_, IndexType>> {
|
56 |
+
using Type = Eigen::Tensor<Scalar_, NumIndices_, Options_, IndexType>;
|
57 |
+
using ValidType = void;
|
58 |
+
|
59 |
+
static Eigen::DSizes<typename Type::Index, Type::NumIndices> get_shape(const Type &f) {
|
60 |
+
return f.dimensions();
|
61 |
+
}
|
62 |
+
|
63 |
+
static constexpr bool
|
64 |
+
is_correct_shape(const Eigen::DSizes<typename Type::Index, Type::NumIndices> & /*shape*/) {
|
65 |
+
return true;
|
66 |
+
}
|
67 |
+
|
68 |
+
template <typename T>
|
69 |
+
struct helper {};
|
70 |
+
|
71 |
+
template <size_t... Is>
|
72 |
+
struct helper<index_sequence<Is...>> {
|
73 |
+
static constexpr auto value = ::pybind11::detail::concat(const_name(((void) Is, "?"))...);
|
74 |
+
};
|
75 |
+
|
76 |
+
static constexpr auto dimensions_descriptor
|
77 |
+
= helper<decltype(make_index_sequence<Type::NumIndices>())>::value;
|
78 |
+
|
79 |
+
template <typename... Args>
|
80 |
+
static Type *alloc(Args &&...args) {
|
81 |
+
return new Type(std::forward<Args>(args)...);
|
82 |
+
}
|
83 |
+
|
84 |
+
static void free(Type *tensor) { delete tensor; }
|
85 |
+
};
|
86 |
+
|
87 |
+
template <typename Scalar_, typename std::ptrdiff_t... Indices, int Options_, typename IndexType>
|
88 |
+
struct eigen_tensor_helper<
|
89 |
+
Eigen::TensorFixedSize<Scalar_, Eigen::Sizes<Indices...>, Options_, IndexType>> {
|
90 |
+
using Type = Eigen::TensorFixedSize<Scalar_, Eigen::Sizes<Indices...>, Options_, IndexType>;
|
91 |
+
using ValidType = void;
|
92 |
+
|
93 |
+
static constexpr Eigen::DSizes<typename Type::Index, Type::NumIndices>
|
94 |
+
get_shape(const Type & /*f*/) {
|
95 |
+
return get_shape();
|
96 |
+
}
|
97 |
+
|
98 |
+
static constexpr Eigen::DSizes<typename Type::Index, Type::NumIndices> get_shape() {
|
99 |
+
return Eigen::DSizes<typename Type::Index, Type::NumIndices>(Indices...);
|
100 |
+
}
|
101 |
+
|
102 |
+
static bool
|
103 |
+
is_correct_shape(const Eigen::DSizes<typename Type::Index, Type::NumIndices> &shape) {
|
104 |
+
return get_shape() == shape;
|
105 |
+
}
|
106 |
+
|
107 |
+
static constexpr auto dimensions_descriptor
|
108 |
+
= ::pybind11::detail::concat(const_name<Indices>()...);
|
109 |
+
|
110 |
+
template <typename... Args>
|
111 |
+
static Type *alloc(Args &&...args) {
|
112 |
+
Eigen::aligned_allocator<Type> allocator;
|
113 |
+
return ::new (allocator.allocate(1)) Type(std::forward<Args>(args)...);
|
114 |
+
}
|
115 |
+
|
116 |
+
static void free(Type *tensor) {
|
117 |
+
Eigen::aligned_allocator<Type> allocator;
|
118 |
+
tensor->~Type();
|
119 |
+
allocator.deallocate(tensor, 1);
|
120 |
+
}
|
121 |
+
};
|
122 |
+
|
123 |
+
template <typename Type, bool ShowDetails, bool NeedsWriteable = false>
|
124 |
+
struct get_tensor_descriptor {
|
125 |
+
static constexpr auto details
|
126 |
+
= const_name<NeedsWriteable>(", flags.writeable", "")
|
127 |
+
+ const_name<static_cast<int>(Type::Layout) == static_cast<int>(Eigen::RowMajor)>(
|
128 |
+
", flags.c_contiguous", ", flags.f_contiguous");
|
129 |
+
static constexpr auto value
|
130 |
+
= const_name("numpy.ndarray[") + npy_format_descriptor<typename Type::Scalar>::name
|
131 |
+
+ const_name("[") + eigen_tensor_helper<remove_cv_t<Type>>::dimensions_descriptor
|
132 |
+
+ const_name("]") + const_name<ShowDetails>(details, const_name("")) + const_name("]");
|
133 |
+
};
|
134 |
+
|
135 |
+
// When EIGEN_AVOID_STL_ARRAY is defined, Eigen::DSizes<T, 0> does not have the begin() member
|
136 |
+
// function. Falling back to a simple loop works around this issue.
|
137 |
+
//
|
138 |
+
// We need to disable the type-limits warning for the inner loop when size = 0.
|
139 |
+
|
140 |
+
PYBIND11_WARNING_PUSH
|
141 |
+
PYBIND11_WARNING_DISABLE_GCC("-Wtype-limits")
|
142 |
+
|
143 |
+
template <typename T, int size>
|
144 |
+
std::vector<T> convert_dsizes_to_vector(const Eigen::DSizes<T, size> &arr) {
|
145 |
+
std::vector<T> result(size);
|
146 |
+
|
147 |
+
for (size_t i = 0; i < size; i++) {
|
148 |
+
result[i] = arr[i];
|
149 |
+
}
|
150 |
+
|
151 |
+
return result;
|
152 |
+
}
|
153 |
+
|
154 |
+
template <typename T, int size>
|
155 |
+
Eigen::DSizes<T, size> get_shape_for_array(const array &arr) {
|
156 |
+
Eigen::DSizes<T, size> result;
|
157 |
+
const T *shape = arr.shape();
|
158 |
+
for (size_t i = 0; i < size; i++) {
|
159 |
+
result[i] = shape[i];
|
160 |
+
}
|
161 |
+
|
162 |
+
return result;
|
163 |
+
}
|
164 |
+
|
165 |
+
PYBIND11_WARNING_POP
|
166 |
+
|
167 |
+
template <typename Type>
|
168 |
+
struct type_caster<Type, typename eigen_tensor_helper<Type>::ValidType> {
|
169 |
+
static_assert(!std::is_pointer<typename Type::Scalar>::value,
|
170 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
171 |
+
using Helper = eigen_tensor_helper<Type>;
|
172 |
+
static constexpr auto temp_name = get_tensor_descriptor<Type, false>::value;
|
173 |
+
PYBIND11_TYPE_CASTER(Type, temp_name);
|
174 |
+
|
175 |
+
bool load(handle src, bool convert) {
|
176 |
+
if (!convert) {
|
177 |
+
if (!isinstance<array>(src)) {
|
178 |
+
return false;
|
179 |
+
}
|
180 |
+
array temp = array::ensure(src);
|
181 |
+
if (!temp) {
|
182 |
+
return false;
|
183 |
+
}
|
184 |
+
|
185 |
+
if (!temp.dtype().is(dtype::of<typename Type::Scalar>())) {
|
186 |
+
return false;
|
187 |
+
}
|
188 |
+
}
|
189 |
+
|
190 |
+
array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()> arr(
|
191 |
+
reinterpret_borrow<object>(src));
|
192 |
+
|
193 |
+
if (arr.ndim() != Type::NumIndices) {
|
194 |
+
return false;
|
195 |
+
}
|
196 |
+
auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);
|
197 |
+
|
198 |
+
if (!Helper::is_correct_shape(shape)) {
|
199 |
+
return false;
|
200 |
+
}
|
201 |
+
|
202 |
+
#if EIGEN_VERSION_AT_LEAST(3, 4, 0)
|
203 |
+
auto data_pointer = arr.data();
|
204 |
+
#else
|
205 |
+
// Handle Eigen bug
|
206 |
+
auto data_pointer = const_cast<typename Type::Scalar *>(arr.data());
|
207 |
+
#endif
|
208 |
+
|
209 |
+
if (is_tensor_aligned(arr.data())) {
|
210 |
+
value = Eigen::TensorMap<const Type, Eigen::Aligned>(data_pointer, shape);
|
211 |
+
} else {
|
212 |
+
value = Eigen::TensorMap<const Type>(data_pointer, shape);
|
213 |
+
}
|
214 |
+
|
215 |
+
return true;
|
216 |
+
}
|
217 |
+
|
218 |
+
static handle cast(Type &&src, return_value_policy policy, handle parent) {
|
219 |
+
if (policy == return_value_policy::reference
|
220 |
+
|| policy == return_value_policy::reference_internal) {
|
221 |
+
pybind11_fail("Cannot use a reference return value policy for an rvalue");
|
222 |
+
}
|
223 |
+
return cast_impl(&src, return_value_policy::move, parent);
|
224 |
+
}
|
225 |
+
|
226 |
+
static handle cast(const Type &&src, return_value_policy policy, handle parent) {
|
227 |
+
if (policy == return_value_policy::reference
|
228 |
+
|| policy == return_value_policy::reference_internal) {
|
229 |
+
pybind11_fail("Cannot use a reference return value policy for an rvalue");
|
230 |
+
}
|
231 |
+
return cast_impl(&src, return_value_policy::move, parent);
|
232 |
+
}
|
233 |
+
|
234 |
+
static handle cast(Type &src, return_value_policy policy, handle parent) {
|
235 |
+
if (policy == return_value_policy::automatic
|
236 |
+
|| policy == return_value_policy::automatic_reference) {
|
237 |
+
policy = return_value_policy::copy;
|
238 |
+
}
|
239 |
+
return cast_impl(&src, policy, parent);
|
240 |
+
}
|
241 |
+
|
242 |
+
static handle cast(const Type &src, return_value_policy policy, handle parent) {
|
243 |
+
if (policy == return_value_policy::automatic
|
244 |
+
|| policy == return_value_policy::automatic_reference) {
|
245 |
+
policy = return_value_policy::copy;
|
246 |
+
}
|
247 |
+
return cast(&src, policy, parent);
|
248 |
+
}
|
249 |
+
|
250 |
+
static handle cast(Type *src, return_value_policy policy, handle parent) {
|
251 |
+
if (policy == return_value_policy::automatic) {
|
252 |
+
policy = return_value_policy::take_ownership;
|
253 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
254 |
+
policy = return_value_policy::reference;
|
255 |
+
}
|
256 |
+
return cast_impl(src, policy, parent);
|
257 |
+
}
|
258 |
+
|
259 |
+
static handle cast(const Type *src, return_value_policy policy, handle parent) {
|
260 |
+
if (policy == return_value_policy::automatic) {
|
261 |
+
policy = return_value_policy::take_ownership;
|
262 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
263 |
+
policy = return_value_policy::reference;
|
264 |
+
}
|
265 |
+
return cast_impl(src, policy, parent);
|
266 |
+
}
|
267 |
+
|
268 |
+
template <typename C>
|
269 |
+
static handle cast_impl(C *src, return_value_policy policy, handle parent) {
|
270 |
+
object parent_object;
|
271 |
+
bool writeable = false;
|
272 |
+
switch (policy) {
|
273 |
+
case return_value_policy::move:
|
274 |
+
if (std::is_const<C>::value) {
|
275 |
+
pybind11_fail("Cannot move from a constant reference");
|
276 |
+
}
|
277 |
+
|
278 |
+
src = Helper::alloc(std::move(*src));
|
279 |
+
|
280 |
+
parent_object
|
281 |
+
= capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });
|
282 |
+
writeable = true;
|
283 |
+
break;
|
284 |
+
|
285 |
+
case return_value_policy::take_ownership:
|
286 |
+
if (std::is_const<C>::value) {
|
287 |
+
// This cast is ugly, and might be UB in some cases, but we don't have an
|
288 |
+
// alternative here as we must free that memory
|
289 |
+
Helper::free(const_cast<Type *>(src));
|
290 |
+
pybind11_fail("Cannot take ownership of a const reference");
|
291 |
+
}
|
292 |
+
|
293 |
+
parent_object
|
294 |
+
= capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });
|
295 |
+
writeable = true;
|
296 |
+
break;
|
297 |
+
|
298 |
+
case return_value_policy::copy:
|
299 |
+
writeable = true;
|
300 |
+
break;
|
301 |
+
|
302 |
+
case return_value_policy::reference:
|
303 |
+
parent_object = none();
|
304 |
+
writeable = !std::is_const<C>::value;
|
305 |
+
break;
|
306 |
+
|
307 |
+
case return_value_policy::reference_internal:
|
308 |
+
// Default should do the right thing
|
309 |
+
if (!parent) {
|
310 |
+
pybind11_fail("Cannot use reference internal when there is no parent");
|
311 |
+
}
|
312 |
+
parent_object = reinterpret_borrow<object>(parent);
|
313 |
+
writeable = !std::is_const<C>::value;
|
314 |
+
break;
|
315 |
+
|
316 |
+
default:
|
317 |
+
pybind11_fail("pybind11 bug in eigen.h, please file a bug report");
|
318 |
+
}
|
319 |
+
|
320 |
+
auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(
|
321 |
+
convert_dsizes_to_vector(Helper::get_shape(*src)), src->data(), parent_object);
|
322 |
+
|
323 |
+
if (!writeable) {
|
324 |
+
array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
|
325 |
+
}
|
326 |
+
|
327 |
+
return result.release();
|
328 |
+
}
|
329 |
+
};
|
330 |
+
|
331 |
+
template <typename StoragePointerType,
|
332 |
+
bool needs_writeable,
|
333 |
+
enable_if_t<!needs_writeable, bool> = true>
|
334 |
+
StoragePointerType get_array_data_for_type(array &arr) {
|
335 |
+
#if EIGEN_VERSION_AT_LEAST(3, 4, 0)
|
336 |
+
return reinterpret_cast<StoragePointerType>(arr.data());
|
337 |
+
#else
|
338 |
+
// Handle Eigen bug
|
339 |
+
return reinterpret_cast<StoragePointerType>(const_cast<void *>(arr.data()));
|
340 |
+
#endif
|
341 |
+
}
|
342 |
+
|
343 |
+
template <typename StoragePointerType,
|
344 |
+
bool needs_writeable,
|
345 |
+
enable_if_t<needs_writeable, bool> = true>
|
346 |
+
StoragePointerType get_array_data_for_type(array &arr) {
|
347 |
+
return reinterpret_cast<StoragePointerType>(arr.mutable_data());
|
348 |
+
}
|
349 |
+
|
350 |
+
template <typename T, typename = void>
|
351 |
+
struct get_storage_pointer_type;
|
352 |
+
|
353 |
+
template <typename MapType>
|
354 |
+
struct get_storage_pointer_type<MapType, void_t<typename MapType::StoragePointerType>> {
|
355 |
+
using SPT = typename MapType::StoragePointerType;
|
356 |
+
};
|
357 |
+
|
358 |
+
template <typename MapType>
|
359 |
+
struct get_storage_pointer_type<MapType, void_t<typename MapType::PointerArgType>> {
|
360 |
+
using SPT = typename MapType::PointerArgType;
|
361 |
+
};
|
362 |
+
|
363 |
+
template <typename Type, int Options>
|
364 |
+
struct type_caster<Eigen::TensorMap<Type, Options>,
|
365 |
+
typename eigen_tensor_helper<remove_cv_t<Type>>::ValidType> {
|
366 |
+
static_assert(!std::is_pointer<typename Type::Scalar>::value,
|
367 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
368 |
+
using MapType = Eigen::TensorMap<Type, Options>;
|
369 |
+
using Helper = eigen_tensor_helper<remove_cv_t<Type>>;
|
370 |
+
|
371 |
+
bool load(handle src, bool /*convert*/) {
|
372 |
+
// Note that we have a lot more checks here as we want to make sure to avoid copies
|
373 |
+
if (!isinstance<array>(src)) {
|
374 |
+
return false;
|
375 |
+
}
|
376 |
+
auto arr = reinterpret_borrow<array>(src);
|
377 |
+
if ((arr.flags() & compute_array_flag_from_tensor<Type>()) == 0) {
|
378 |
+
return false;
|
379 |
+
}
|
380 |
+
|
381 |
+
if (!arr.dtype().is(dtype::of<typename Type::Scalar>())) {
|
382 |
+
return false;
|
383 |
+
}
|
384 |
+
|
385 |
+
if (arr.ndim() != Type::NumIndices) {
|
386 |
+
return false;
|
387 |
+
}
|
388 |
+
|
389 |
+
constexpr bool is_aligned = (Options & Eigen::Aligned) != 0;
|
390 |
+
|
391 |
+
if (is_aligned && !is_tensor_aligned(arr.data())) {
|
392 |
+
return false;
|
393 |
+
}
|
394 |
+
|
395 |
+
auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);
|
396 |
+
|
397 |
+
if (!Helper::is_correct_shape(shape)) {
|
398 |
+
return false;
|
399 |
+
}
|
400 |
+
|
401 |
+
if (needs_writeable && !arr.writeable()) {
|
402 |
+
return false;
|
403 |
+
}
|
404 |
+
|
405 |
+
auto result = get_array_data_for_type<typename get_storage_pointer_type<MapType>::SPT,
|
406 |
+
needs_writeable>(arr);
|
407 |
+
|
408 |
+
value.reset(new MapType(std::move(result), std::move(shape)));
|
409 |
+
|
410 |
+
return true;
|
411 |
+
}
|
412 |
+
|
413 |
+
static handle cast(MapType &&src, return_value_policy policy, handle parent) {
|
414 |
+
return cast_impl(&src, policy, parent);
|
415 |
+
}
|
416 |
+
|
417 |
+
static handle cast(const MapType &&src, return_value_policy policy, handle parent) {
|
418 |
+
return cast_impl(&src, policy, parent);
|
419 |
+
}
|
420 |
+
|
421 |
+
static handle cast(MapType &src, return_value_policy policy, handle parent) {
|
422 |
+
if (policy == return_value_policy::automatic
|
423 |
+
|| policy == return_value_policy::automatic_reference) {
|
424 |
+
policy = return_value_policy::copy;
|
425 |
+
}
|
426 |
+
return cast_impl(&src, policy, parent);
|
427 |
+
}
|
428 |
+
|
429 |
+
static handle cast(const MapType &src, return_value_policy policy, handle parent) {
|
430 |
+
if (policy == return_value_policy::automatic
|
431 |
+
|| policy == return_value_policy::automatic_reference) {
|
432 |
+
policy = return_value_policy::copy;
|
433 |
+
}
|
434 |
+
return cast(&src, policy, parent);
|
435 |
+
}
|
436 |
+
|
437 |
+
static handle cast(MapType *src, return_value_policy policy, handle parent) {
|
438 |
+
if (policy == return_value_policy::automatic) {
|
439 |
+
policy = return_value_policy::take_ownership;
|
440 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
441 |
+
policy = return_value_policy::reference;
|
442 |
+
}
|
443 |
+
return cast_impl(src, policy, parent);
|
444 |
+
}
|
445 |
+
|
446 |
+
static handle cast(const MapType *src, return_value_policy policy, handle parent) {
|
447 |
+
if (policy == return_value_policy::automatic) {
|
448 |
+
policy = return_value_policy::take_ownership;
|
449 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
450 |
+
policy = return_value_policy::reference;
|
451 |
+
}
|
452 |
+
return cast_impl(src, policy, parent);
|
453 |
+
}
|
454 |
+
|
455 |
+
template <typename C>
|
456 |
+
static handle cast_impl(C *src, return_value_policy policy, handle parent) {
|
457 |
+
object parent_object;
|
458 |
+
constexpr bool writeable = !std::is_const<C>::value;
|
459 |
+
switch (policy) {
|
460 |
+
case return_value_policy::reference:
|
461 |
+
parent_object = none();
|
462 |
+
break;
|
463 |
+
|
464 |
+
case return_value_policy::reference_internal:
|
465 |
+
// Default should do the right thing
|
466 |
+
if (!parent) {
|
467 |
+
pybind11_fail("Cannot use reference internal when there is no parent");
|
468 |
+
}
|
469 |
+
parent_object = reinterpret_borrow<object>(parent);
|
470 |
+
break;
|
471 |
+
|
472 |
+
case return_value_policy::take_ownership:
|
473 |
+
delete src;
|
474 |
+
// fallthrough
|
475 |
+
default:
|
476 |
+
// move, take_ownership don't make any sense for a ref/map:
|
477 |
+
pybind11_fail("Invalid return_value_policy for Eigen Map type, must be either "
|
478 |
+
"reference or reference_internal");
|
479 |
+
}
|
480 |
+
|
481 |
+
auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(
|
482 |
+
convert_dsizes_to_vector(Helper::get_shape(*src)),
|
483 |
+
src->data(),
|
484 |
+
std::move(parent_object));
|
485 |
+
|
486 |
+
if (!writeable) {
|
487 |
+
array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
|
488 |
+
}
|
489 |
+
|
490 |
+
return result.release();
|
491 |
+
}
|
492 |
+
|
493 |
+
#if EIGEN_VERSION_AT_LEAST(3, 4, 0)
|
494 |
+
|
495 |
+
static constexpr bool needs_writeable = !std::is_const<typename std::remove_pointer<
|
496 |
+
typename get_storage_pointer_type<MapType>::SPT>::type>::value;
|
497 |
+
#else
|
498 |
+
// Handle Eigen bug
|
499 |
+
static constexpr bool needs_writeable = !std::is_const<Type>::value;
|
500 |
+
#endif
|
501 |
+
|
502 |
+
protected:
|
503 |
+
// TODO: Move to std::optional once std::optional has more support
|
504 |
+
std::unique_ptr<MapType> value;
|
505 |
+
|
506 |
+
public:
|
507 |
+
static constexpr auto name = get_tensor_descriptor<Type, true, needs_writeable>::value;
|
508 |
+
explicit operator MapType *() { return value.get(); }
|
509 |
+
explicit operator MapType &() { return *value; }
|
510 |
+
explicit operator MapType &&() && { return std::move(*value); }
|
511 |
+
|
512 |
+
template <typename T_>
|
513 |
+
using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>;
|
514 |
+
};
|
515 |
+
|
516 |
+
PYBIND11_NAMESPACE_END(detail)
|
517 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|