assassinlike commited on
Commit
38bf482
·
verified ·
1 Parent(s): c08bf44

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmes-0.1.0.dist-info/licenses/LICENSE +201 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji-2.15.0.dist-info/licenses/LICENSE.txt +28 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/mbstrdecoder-1.1.5.dist-info/licenses/LICENSE +21 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pluggy-1.6.0.dist-info/licenses/LICENSE +21 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1-0.6.3.dist-info/licenses/LICENSE.rst +24 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc +0 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc +0 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc +0 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h +730 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h +209 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h +2446 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h +227 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/common.h +2 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/complex.h +93 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/critical_section.h +56 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen.h +12 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/tensor.h +520 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/embed.h +320 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/eval.h +161 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/functional.h +147 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/gil.h +203 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/gil_safe_call_once.h +273 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/gil_simple.h +37 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/iostream.h +301 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/native_enum.h +76 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/numpy.h +2412 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/operators.h +202 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/options.h +92 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/pybind11.h +0 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/pytypes.h +0 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/stl.h +666 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/stl/filesystem.h +114 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/stl_bind.h +858 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/subinterpreter.h +291 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/trampoline_self_life_support.h +65 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/type_caster_pyobject_ptr.h +61 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/typing.h +295 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/warnings.h +75 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/share/__init__.py +0 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/__init__.cpython-310.pyc +0 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_gpu_trace.cpython-310.pyc +0 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_memory_viz.cpython-310.pyc +0 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_pin_memory_utils.cpython-310.pyc +0 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_sanitizer.cpython-310.pyc +0 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_utils.cpython-310.pyc +0 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/comm.cpython-310.pyc +0 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/error.cpython-310.pyc +0 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/gds.cpython-310.pyc +0 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/ai2_olmes-0.1.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ https://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/emoji-2.15.0.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ New BSD License
2
+
3
+ Copyright (c) 2014-2025, Taehoon Kim, Kevin Wurster
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * The names of its contributors may not be used to endorse or promote products
17
+ derived from this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/mbstrdecoder-1.1.5.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2016 Tsuyoshi Hombashi
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.
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pluggy-1.6.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 holger krekel (rather uses bitbucket/hpk42)
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.
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pyasn1-0.6.3.dist-info/licenses/LICENSE.rst ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice,
8
+ this list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
18
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24
+ POSSIBILITY OF SUCH DAMAGE.
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (602 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (2.53 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc ADDED
Binary file (639 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/attr.h: Infrastructure for processing custom
3
+ type and function attributes
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ #include "trampoline_self_life_support.h"
16
+
17
+ #include <functional>
18
+
19
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
20
+
21
+ /// \addtogroup annotations
22
+ /// @{
23
+
24
+ /// Annotation for methods
25
+ struct is_method {
26
+ handle class_;
27
+ explicit is_method(const handle &c) : class_(c) {}
28
+ };
29
+
30
+ /// Annotation for setters
31
+ struct is_setter {};
32
+
33
+ /// Annotation for operators
34
+ struct is_operator {};
35
+
36
+ /// Annotation for classes that cannot be subclassed
37
+ struct is_final {};
38
+
39
+ /// Annotation for parent scope
40
+ struct scope {
41
+ handle value;
42
+ explicit scope(const handle &s) : value(s) {}
43
+ };
44
+
45
+ /// Annotation for documentation
46
+ struct doc {
47
+ const char *value;
48
+ explicit doc(const char *value) : value(value) {}
49
+ };
50
+
51
+ /// Annotation for function names
52
+ struct name {
53
+ const char *value;
54
+ explicit name(const char *value) : value(value) {}
55
+ };
56
+
57
+ /// Annotation indicating that a function is an overload associated with a given "sibling"
58
+ struct sibling {
59
+ handle value;
60
+ explicit sibling(const handle &value) : value(value.ptr()) {}
61
+ };
62
+
63
+ /// Annotation indicating that a class derives from another given type
64
+ template <typename T>
65
+ struct base {
66
+
67
+ PYBIND11_DEPRECATED(
68
+ "base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
69
+ base() = default;
70
+ };
71
+
72
+ /// Keep patient alive while nurse lives
73
+ template <size_t Nurse, size_t Patient>
74
+ struct keep_alive {};
75
+
76
+ /// Annotation indicating that a class is involved in a multiple inheritance relationship
77
+ struct multiple_inheritance {};
78
+
79
+ /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
80
+ struct dynamic_attr {};
81
+
82
+ /// Annotation which enables the buffer protocol for a type
83
+ struct buffer_protocol {};
84
+
85
+ /// Annotation which enables releasing the GIL before calling the C++ destructor of wrapped
86
+ /// instances (pybind/pybind11#1446).
87
+ struct release_gil_before_calling_cpp_dtor {};
88
+
89
+ /// Annotation which requests that a special metaclass is created for a type
90
+ struct metaclass {
91
+ handle value;
92
+
93
+ PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
94
+ metaclass() = default;
95
+
96
+ /// Override pybind11's default metaclass
97
+ explicit metaclass(handle value) : value(value) {}
98
+ };
99
+
100
+ /// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that
101
+ /// may be used to customize the Python type.
102
+ ///
103
+ /// The callback is invoked immediately before `PyType_Ready`.
104
+ ///
105
+ /// Note: This is an advanced interface, and uses of it may require changes to
106
+ /// work with later versions of pybind11. You may wish to consult the
107
+ /// implementation of `make_new_python_type` in `detail/classes.h` to understand
108
+ /// the context in which the callback will be run.
109
+ struct custom_type_setup {
110
+ using callback = std::function<void(PyHeapTypeObject *heap_type)>;
111
+
112
+ explicit custom_type_setup(callback value) : value(std::move(value)) {}
113
+
114
+ callback value;
115
+ };
116
+
117
+ /// Annotation that marks a class as local to the module:
118
+ struct module_local {
119
+ const bool value;
120
+ constexpr explicit module_local(bool v = true) : value(v) {}
121
+ };
122
+
123
+ /// Annotation to mark enums as an arithmetic type
124
+ struct arithmetic {};
125
+
126
+ /// Mark a function for addition at the beginning of the existing overload chain instead of the end
127
+ struct prepend {};
128
+
129
+ /** \rst
130
+ A call policy which places one or more guard variables (``Ts...``) around the function call.
131
+
132
+ For example, this definition:
133
+
134
+ .. code-block:: cpp
135
+
136
+ m.def("foo", foo, py::call_guard<T>());
137
+
138
+ is equivalent to the following pseudocode:
139
+
140
+ .. code-block:: cpp
141
+
142
+ m.def("foo", [](args...) {
143
+ T scope_guard;
144
+ return foo(args...); // forwarded arguments
145
+ });
146
+ \endrst */
147
+ template <typename... Ts>
148
+ struct call_guard;
149
+
150
+ template <>
151
+ struct call_guard<> {
152
+ using type = detail::void_type;
153
+ };
154
+
155
+ template <typename T>
156
+ struct call_guard<T> {
157
+ static_assert(std::is_default_constructible<T>::value,
158
+ "The guard type must be default constructible");
159
+
160
+ using type = T;
161
+ };
162
+
163
+ template <typename T, typename... Ts>
164
+ struct call_guard<T, Ts...> {
165
+ struct type {
166
+ T guard{}; // Compose multiple guard types with left-to-right default-constructor order
167
+ typename call_guard<Ts...>::type next{};
168
+ };
169
+ };
170
+
171
+ /// @} annotations
172
+
173
+ PYBIND11_NAMESPACE_BEGIN(detail)
174
+ /* Forward declarations */
175
+ enum op_id : int;
176
+ enum op_type : int;
177
+ struct undefined_t;
178
+ template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>
179
+ struct op_;
180
+ void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
181
+
182
+ /// Internal data structure which holds metadata about a keyword argument
183
+ struct argument_record {
184
+ const char *name; ///< Argument name
185
+ const char *descr; ///< Human-readable version of the argument value
186
+ handle value; ///< Associated Python object
187
+ bool convert : 1; ///< True if the argument is allowed to convert when loading
188
+ bool none : 1; ///< True if None is allowed when loading
189
+
190
+ argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
191
+ : name(name), descr(descr), value(value), convert(convert), none(none) {}
192
+ };
193
+
194
+ /// Internal data structure which holds metadata about a bound function (signature, overloads,
195
+ /// etc.)
196
+ #define PYBIND11_DETAIL_FUNCTION_RECORD_ABI_ID "v1" // PLEASE UPDATE if the struct is changed.
197
+ struct function_record {
198
+ function_record()
199
+ : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
200
+ is_operator(false), is_method(false), is_setter(false), has_args(false),
201
+ has_kwargs(false), prepend(false) {}
202
+
203
+ /// Function name
204
+ char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
205
+
206
+ // User-specified documentation string
207
+ char *doc = nullptr;
208
+
209
+ /// Human-readable version of the function signature
210
+ char *signature = nullptr;
211
+
212
+ /// List of registered keyword arguments
213
+ std::vector<argument_record> args;
214
+
215
+ /// Pointer to lambda function which converts arguments and performs the actual call
216
+ handle (*impl)(function_call &) = nullptr;
217
+
218
+ /// Storage for the wrapped function pointer and captured data, if any
219
+ void *data[3] = {};
220
+
221
+ /// Pointer to custom destructor for 'data' (if needed)
222
+ void (*free_data)(function_record *ptr) = nullptr;
223
+
224
+ /// Return value policy associated with this function
225
+ return_value_policy policy = return_value_policy::automatic;
226
+
227
+ /// True if name == '__init__'
228
+ bool is_constructor : 1;
229
+
230
+ /// True if this is a new-style `__init__` defined in `detail/init.h`
231
+ bool is_new_style_constructor : 1;
232
+
233
+ /// True if this is a stateless function pointer
234
+ bool is_stateless : 1;
235
+
236
+ /// True if this is an operator (__add__), etc.
237
+ bool is_operator : 1;
238
+
239
+ /// True if this is a method
240
+ bool is_method : 1;
241
+
242
+ /// True if this is a setter
243
+ bool is_setter : 1;
244
+
245
+ /// True if the function has a '*args' argument
246
+ bool has_args : 1;
247
+
248
+ /// True if the function has a '**kwargs' argument
249
+ bool has_kwargs : 1;
250
+
251
+ /// True if this function is to be inserted at the beginning of the overload resolution chain
252
+ bool prepend : 1;
253
+
254
+ /// Number of arguments (including py::args and/or py::kwargs, if present)
255
+ std::uint16_t nargs;
256
+
257
+ /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs
258
+ /// argument or by a py::kw_only annotation.
259
+ std::uint16_t nargs_pos = 0;
260
+
261
+ /// Number of leading arguments (counted in `nargs`) that are positional-only
262
+ std::uint16_t nargs_pos_only = 0;
263
+
264
+ /// Python method object
265
+ PyMethodDef *def = nullptr;
266
+
267
+ /// Python handle to the parent scope (a class or a module)
268
+ handle scope;
269
+
270
+ /// Python handle to the sibling function representing an overload chain
271
+ handle sibling;
272
+
273
+ /// Pointer to next overload
274
+ function_record *next = nullptr;
275
+ };
276
+ // The main purpose of this macro is to make it easy to pin-point the critically related code
277
+ // sections.
278
+ #define PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(...) \
279
+ static_assert( \
280
+ __VA_ARGS__, \
281
+ "Violation of precondition for pybind11/functional.h performance optimizations!")
282
+
283
+ /// Special data structure which (temporarily) holds metadata about a bound class
284
+ struct type_record {
285
+ PYBIND11_NOINLINE type_record()
286
+ : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
287
+ module_local(false), is_final(false), release_gil_before_calling_cpp_dtor(false) {}
288
+
289
+ /// Handle to the parent scope
290
+ handle scope;
291
+
292
+ /// Name of the class
293
+ const char *name = nullptr;
294
+
295
+ // Pointer to RTTI type_info data structure
296
+ const std::type_info *type = nullptr;
297
+
298
+ /// How large is the underlying C++ type?
299
+ size_t type_size = 0;
300
+
301
+ /// What is the alignment of the underlying C++ type?
302
+ size_t type_align = 0;
303
+
304
+ /// How large is the type's holder?
305
+ size_t holder_size = 0;
306
+
307
+ /// The global operator new can be overridden with a class-specific variant
308
+ void *(*operator_new)(size_t) = nullptr;
309
+
310
+ /// Function pointer to class_<..>::init_instance
311
+ void (*init_instance)(instance *, const void *) = nullptr;
312
+
313
+ /// Function pointer to class_<..>::dealloc
314
+ void (*dealloc)(detail::value_and_holder &) = nullptr;
315
+
316
+ /// Function pointer for casting alias class (aka trampoline) pointer to
317
+ /// trampoline_self_life_support pointer. Sidesteps cross-DSO RTTI issues
318
+ /// on platforms like macOS (see PR #5728 for details).
319
+ get_trampoline_self_life_support_fn get_trampoline_self_life_support
320
+ = [](void *) -> trampoline_self_life_support * { return nullptr; };
321
+
322
+ /// List of base classes of the newly created type
323
+ list bases;
324
+
325
+ /// Optional docstring
326
+ const char *doc = nullptr;
327
+
328
+ /// Custom metaclass (optional)
329
+ handle metaclass;
330
+
331
+ /// Custom type setup.
332
+ custom_type_setup::callback custom_type_setup_callback;
333
+
334
+ /// Multiple inheritance marker
335
+ bool multiple_inheritance : 1;
336
+
337
+ /// Does the class manage a __dict__?
338
+ bool dynamic_attr : 1;
339
+
340
+ /// Does the class implement the buffer protocol?
341
+ bool buffer_protocol : 1;
342
+
343
+ /// Is the class definition local to the module shared object?
344
+ bool module_local : 1;
345
+
346
+ /// Is the class inheritable from python classes?
347
+ bool is_final : 1;
348
+
349
+ /// Solves pybind/pybind11#1446
350
+ bool release_gil_before_calling_cpp_dtor : 1;
351
+
352
+ holder_enum_t holder_enum_v = holder_enum_t::undefined;
353
+
354
+ PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {
355
+ auto *base_info = detail::get_type_info(base, false);
356
+ if (!base_info) {
357
+ std::string tname(base.name());
358
+ detail::clean_type_id(tname);
359
+ pybind11_fail("generic_type: type \"" + std::string(name)
360
+ + "\" referenced unknown base type \"" + tname + "\"");
361
+ }
362
+
363
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
364
+ bool this_has_unique_ptr_holder = (holder_enum_v == holder_enum_t::std_unique_ptr);
365
+ bool base_has_unique_ptr_holder
366
+ = (base_info->holder_enum_v == holder_enum_t::std_unique_ptr);
367
+ if (this_has_unique_ptr_holder != base_has_unique_ptr_holder) {
368
+ std::string tname(base.name());
369
+ detail::clean_type_id(tname);
370
+ pybind11_fail("generic_type: type \"" + std::string(name) + "\" "
371
+ + (this_has_unique_ptr_holder ? "does not have" : "has")
372
+ + " a non-default holder type while its base \"" + tname + "\" "
373
+ + (base_has_unique_ptr_holder ? "does not" : "does"));
374
+ }
375
+
376
+ bases.append(reinterpret_cast<PyObject *>(base_info->type));
377
+
378
+ #ifdef PYBIND11_BACKWARD_COMPATIBILITY_TP_DICTOFFSET
379
+ dynamic_attr |= base_info->type->tp_dictoffset != 0;
380
+ #else
381
+ dynamic_attr |= (PyType_GetFlags(base_info->type) & Py_TPFLAGS_MANAGED_DICT) != 0;
382
+ #endif
383
+
384
+ if (caster) {
385
+ base_info->implicit_casts.emplace_back(type, caster);
386
+ }
387
+ }
388
+ };
389
+
390
+ inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {
391
+ args.reserve(f.nargs);
392
+ args_convert.reserve(f.nargs);
393
+ }
394
+
395
+ /// Tag for a new-style `__init__` defined in `detail/init.h`
396
+ struct is_new_style_constructor {};
397
+
398
+ /**
399
+ * Partial template specializations to process custom attributes provided to
400
+ * cpp_function_ and class_. These are either used to initialize the respective
401
+ * fields in the type_record and function_record data structures or executed at
402
+ * runtime to deal with custom call policies (e.g. keep_alive).
403
+ */
404
+ template <typename T, typename SFINAE = void>
405
+ struct process_attribute;
406
+
407
+ template <typename T>
408
+ struct process_attribute_default {
409
+ /// Default implementation: do nothing
410
+ static void init(const T &, function_record *) {}
411
+ static void init(const T &, type_record *) {}
412
+ static void precall(function_call &) {}
413
+ static void postcall(function_call &, handle) {}
414
+ };
415
+
416
+ /// Process an attribute specifying the function's name
417
+ template <>
418
+ struct process_attribute<name> : process_attribute_default<name> {
419
+ static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
420
+ };
421
+
422
+ /// Process an attribute specifying the function's docstring
423
+ template <>
424
+ struct process_attribute<doc> : process_attribute_default<doc> {
425
+ static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
426
+ };
427
+
428
+ /// Process an attribute specifying the function's docstring (provided as a C-style string)
429
+ template <>
430
+ struct process_attribute<const char *> : process_attribute_default<const char *> {
431
+ static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
432
+ static void init(const char *d, type_record *r) { r->doc = d; }
433
+ };
434
+ template <>
435
+ struct process_attribute<char *> : process_attribute<const char *> {};
436
+
437
+ /// Process an attribute indicating the function's return value policy
438
+ template <>
439
+ struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
440
+ static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
441
+ };
442
+
443
+ /// Process an attribute which indicates that this is an overloaded function associated with a
444
+ /// given sibling
445
+ template <>
446
+ struct process_attribute<sibling> : process_attribute_default<sibling> {
447
+ static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
448
+ };
449
+
450
+ /// Process an attribute which indicates that this function is a method
451
+ template <>
452
+ struct process_attribute<is_method> : process_attribute_default<is_method> {
453
+ static void init(const is_method &s, function_record *r) {
454
+ r->is_method = true;
455
+ r->scope = s.class_;
456
+ }
457
+ };
458
+
459
+ /// Process an attribute which indicates that this function is a setter
460
+ template <>
461
+ struct process_attribute<is_setter> : process_attribute_default<is_setter> {
462
+ static void init(const is_setter &, function_record *r) { r->is_setter = true; }
463
+ };
464
+
465
+ /// Process an attribute which indicates the parent scope of a method
466
+ template <>
467
+ struct process_attribute<scope> : process_attribute_default<scope> {
468
+ static void init(const scope &s, function_record *r) { r->scope = s.value; }
469
+ };
470
+
471
+ /// Process an attribute which indicates that this function is an operator
472
+ template <>
473
+ struct process_attribute<is_operator> : process_attribute_default<is_operator> {
474
+ static void init(const is_operator &, function_record *r) { r->is_operator = true; }
475
+ };
476
+
477
+ template <>
478
+ struct process_attribute<is_new_style_constructor>
479
+ : process_attribute_default<is_new_style_constructor> {
480
+ static void init(const is_new_style_constructor &, function_record *r) {
481
+ r->is_new_style_constructor = true;
482
+ }
483
+ };
484
+
485
+ inline void check_kw_only_arg(const arg &a, function_record *r) {
486
+ if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) {
487
+ pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or "
488
+ "args() argument");
489
+ }
490
+ }
491
+
492
+ inline void append_self_arg_if_needed(function_record *r) {
493
+ if (r->is_method && r->args.empty()) {
494
+ r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false);
495
+ }
496
+ }
497
+
498
+ /// Process a keyword argument attribute (*without* a default value)
499
+ template <>
500
+ struct process_attribute<arg> : process_attribute_default<arg> {
501
+ static void init(const arg &a, function_record *r) {
502
+ append_self_arg_if_needed(r);
503
+ r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
504
+
505
+ check_kw_only_arg(a, r);
506
+ }
507
+ };
508
+
509
+ /// Process a keyword argument attribute (*with* a default value)
510
+ template <>
511
+ struct process_attribute<arg_v> : process_attribute_default<arg_v> {
512
+ static void init(const arg_v &a, function_record *r) {
513
+ if (r->is_method && r->args.empty()) {
514
+ r->args.emplace_back(
515
+ "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);
516
+ }
517
+
518
+ if (!a.value) {
519
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
520
+ std::string descr("'");
521
+ if (a.name) {
522
+ descr += std::string(a.name) + ": ";
523
+ }
524
+ descr += a.type + "'";
525
+ if (r->is_method) {
526
+ if (r->name) {
527
+ descr += " in method '" + (std::string) str(r->scope) + "."
528
+ + (std::string) r->name + "'";
529
+ } else {
530
+ descr += " in method of '" + (std::string) str(r->scope) + "'";
531
+ }
532
+ } else if (r->name) {
533
+ descr += " in function '" + (std::string) r->name + "'";
534
+ }
535
+ pybind11_fail("arg(): could not convert default argument " + descr
536
+ + " into a Python object (type not registered yet?)");
537
+ #else
538
+ pybind11_fail("arg(): could not convert default argument "
539
+ "into a Python object (type not registered yet?). "
540
+ "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
541
+ "more information.");
542
+ #endif
543
+ }
544
+ r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
545
+
546
+ check_kw_only_arg(a, r);
547
+ }
548
+ };
549
+
550
+ /// Process a keyword-only-arguments-follow pseudo argument
551
+ template <>
552
+ struct process_attribute<kw_only> : process_attribute_default<kw_only> {
553
+ static void init(const kw_only &, function_record *r) {
554
+ append_self_arg_if_needed(r);
555
+ if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
556
+ pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
557
+ "argument location (or omit kw_only() entirely)");
558
+ }
559
+ r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
560
+ }
561
+ };
562
+
563
+ /// Process a positional-only-argument maker
564
+ template <>
565
+ struct process_attribute<pos_only> : process_attribute_default<pos_only> {
566
+ static void init(const pos_only &, function_record *r) {
567
+ append_self_arg_if_needed(r);
568
+ r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
569
+ if (r->nargs_pos_only > r->nargs_pos) {
570
+ pybind11_fail("pos_only(): cannot follow a py::args() argument");
571
+ }
572
+ // It also can't follow a kw_only, but a static_assert in pybind11.h checks that
573
+ }
574
+ };
575
+
576
+ /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
577
+ /// that)
578
+ template <typename T>
579
+ struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
580
+ : process_attribute_default<handle> {
581
+ static void init(const handle &h, type_record *r) { r->bases.append(h); }
582
+ };
583
+
584
+ /// Process a parent class attribute (deprecated, does not support multiple inheritance)
585
+ template <typename T>
586
+ struct process_attribute<base<T>> : process_attribute_default<base<T>> {
587
+ static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
588
+ };
589
+
590
+ /// Process a multiple inheritance attribute
591
+ template <>
592
+ struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
593
+ static void init(const multiple_inheritance &, type_record *r) {
594
+ r->multiple_inheritance = true;
595
+ }
596
+ };
597
+
598
+ template <>
599
+ struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
600
+ static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
601
+ };
602
+
603
+ template <>
604
+ struct process_attribute<custom_type_setup> {
605
+ static void init(const custom_type_setup &value, type_record *r) {
606
+ r->custom_type_setup_callback = value.value;
607
+ }
608
+ };
609
+
610
+ template <>
611
+ struct process_attribute<is_final> : process_attribute_default<is_final> {
612
+ static void init(const is_final &, type_record *r) { r->is_final = true; }
613
+ };
614
+
615
+ template <>
616
+ struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
617
+ static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
618
+ };
619
+
620
+ template <>
621
+ struct process_attribute<metaclass> : process_attribute_default<metaclass> {
622
+ static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
623
+ };
624
+
625
+ template <>
626
+ struct process_attribute<module_local> : process_attribute_default<module_local> {
627
+ static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
628
+ };
629
+
630
+ template <>
631
+ struct process_attribute<release_gil_before_calling_cpp_dtor>
632
+ : process_attribute_default<release_gil_before_calling_cpp_dtor> {
633
+ static void init(const release_gil_before_calling_cpp_dtor &, type_record *r) {
634
+ r->release_gil_before_calling_cpp_dtor = true;
635
+ }
636
+ };
637
+
638
+ /// Process a 'prepend' attribute, putting this at the beginning of the overload chain
639
+ template <>
640
+ struct process_attribute<prepend> : process_attribute_default<prepend> {
641
+ static void init(const prepend &, function_record *r) { r->prepend = true; }
642
+ };
643
+
644
+ /// Process an 'arithmetic' attribute for enums (does nothing here)
645
+ template <>
646
+ struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
647
+
648
+ template <typename... Ts>
649
+ struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
650
+
651
+ /**
652
+ * Process a keep_alive call policy -- invokes keep_alive_impl during the
653
+ * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
654
+ * otherwise
655
+ */
656
+ template <size_t Nurse, size_t Patient>
657
+ struct process_attribute<keep_alive<Nurse, Patient>>
658
+ : public process_attribute_default<keep_alive<Nurse, Patient>> {
659
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
660
+ static void precall(function_call &call) {
661
+ keep_alive_impl(Nurse, Patient, call, handle());
662
+ }
663
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
664
+ static void postcall(function_call &, handle) {}
665
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
666
+ static void precall(function_call &) {}
667
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
668
+ static void postcall(function_call &call, handle ret) {
669
+ keep_alive_impl(Nurse, Patient, call, ret);
670
+ }
671
+ };
672
+
673
+ /// Recursively iterate over variadic template arguments
674
+ template <typename... Args>
675
+ struct process_attributes {
676
+ static void init(const Args &...args, function_record *r) {
677
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
678
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
679
+ using expander = int[];
680
+ (void) expander{
681
+ 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
682
+ }
683
+ static void init(const Args &...args, type_record *r) {
684
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
685
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
686
+ using expander = int[];
687
+ (void) expander{0,
688
+ (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
689
+ }
690
+ static void precall(function_call &call) {
691
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
692
+ using expander = int[];
693
+ (void) expander{0,
694
+ (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
695
+ }
696
+ static void postcall(function_call &call, handle fn_ret) {
697
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
698
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
699
+ using expander = int[];
700
+ (void) expander{
701
+ 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
702
+ }
703
+ };
704
+
705
+ template <typename T>
706
+ struct is_keep_alive : std::false_type {};
707
+
708
+ template <size_t Nurse, size_t Patient>
709
+ struct is_keep_alive<keep_alive<Nurse, Patient>> : std::true_type {};
710
+
711
+ template <typename T>
712
+ using is_call_guard = is_instantiation<call_guard, T>;
713
+
714
+ /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
715
+ template <typename... Extra>
716
+ using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
717
+
718
+ /// Check the number of named arguments at compile time
719
+ template <typename... Extra,
720
+ size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
721
+ size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
722
+ constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
723
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
724
+ return named == 0
725
+ || (self + named + static_cast<size_t>(has_args) + static_cast<size_t>(has_kwargs))
726
+ == nargs;
727
+ }
728
+
729
+ PYBIND11_NAMESPACE_END(detail)
730
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/buffer_info.h: Python buffer object interface
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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 != static_cast<ssize_t>(shape.size())
70
+ || ndim != static_cast<ssize_t>(strides.size())) {
71
+ pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length");
72
+ }
73
+ for (size_t i = 0; i < static_cast<size_t>(ndim); ++i) {
74
+ size *= shape[i];
75
+ }
76
+ }
77
+
78
+ template <typename T>
79
+ buffer_info(T *ptr,
80
+ detail::any_container<ssize_t> shape_in,
81
+ detail::any_container<ssize_t> strides_in,
82
+ bool readonly = false)
83
+ : buffer_info(private_ctr_tag(),
84
+ ptr,
85
+ sizeof(T),
86
+ format_descriptor<T>::format(),
87
+ static_cast<ssize_t>(shape_in->size()),
88
+ std::move(shape_in),
89
+ std::move(strides_in),
90
+ readonly) {}
91
+
92
+ buffer_info(void *ptr,
93
+ ssize_t itemsize,
94
+ const std::string &format,
95
+ ssize_t size,
96
+ bool readonly = false)
97
+ : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {}
98
+
99
+ template <typename T>
100
+ buffer_info(T *ptr, ssize_t size, bool readonly = false)
101
+ : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) {}
102
+
103
+ template <typename T>
104
+ buffer_info(const T *ptr, ssize_t size, bool readonly = true)
105
+ : buffer_info(
106
+ const_cast<T *>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) {}
107
+
108
+ explicit buffer_info(Py_buffer *view, bool ownview = true)
109
+ : buffer_info(
110
+ view->buf,
111
+ view->itemsize,
112
+ view->format,
113
+ view->ndim,
114
+ {view->shape, view->shape + view->ndim},
115
+ /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects
116
+ * ignore this flag and return a view with NULL strides.
117
+ * When strides are NULL, build them manually. */
118
+ view->strides
119
+ ? std::vector<ssize_t>(view->strides, view->strides + view->ndim)
120
+ : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize),
121
+ (view->readonly != 0)) {
122
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
123
+ this->m_view = view;
124
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
125
+ this->ownview = ownview;
126
+ }
127
+
128
+ buffer_info(const buffer_info &) = delete;
129
+ buffer_info &operator=(const buffer_info &) = delete;
130
+
131
+ buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); }
132
+
133
+ buffer_info &operator=(buffer_info &&rhs) noexcept {
134
+ ptr = rhs.ptr;
135
+ itemsize = rhs.itemsize;
136
+ size = rhs.size;
137
+ format = std::move(rhs.format);
138
+ ndim = rhs.ndim;
139
+ shape = std::move(rhs.shape);
140
+ strides = std::move(rhs.strides);
141
+ std::swap(m_view, rhs.m_view);
142
+ std::swap(ownview, rhs.ownview);
143
+ readonly = rhs.readonly;
144
+ return *this;
145
+ }
146
+
147
+ ~buffer_info() {
148
+ if (m_view && ownview) {
149
+ PyBuffer_Release(m_view);
150
+ delete m_view;
151
+ }
152
+ }
153
+
154
+ Py_buffer *view() const { return m_view; }
155
+ Py_buffer *&view() { return m_view; }
156
+
157
+ /* True if the buffer item type is equivalent to `T`. */
158
+ // To define "equivalent" by example:
159
+ // `buffer_info::item_type_is_equivalent_to<int>(b)` and
160
+ // `buffer_info::item_type_is_equivalent_to<long>(b)` may both be true
161
+ // on some platforms, but `int` and `unsigned` will never be equivalent.
162
+ // For the ground truth, please inspect `detail::compare_buffer_info<>`.
163
+ template <typename T>
164
+ bool item_type_is_equivalent_to() const {
165
+ return detail::compare_buffer_info<T>::compare(*this);
166
+ }
167
+
168
+ private:
169
+ struct private_ctr_tag {};
170
+
171
+ buffer_info(private_ctr_tag,
172
+ void *ptr,
173
+ ssize_t itemsize,
174
+ const std::string &format,
175
+ ssize_t ndim,
176
+ detail::any_container<ssize_t> &&shape_in,
177
+ detail::any_container<ssize_t> &&strides_in,
178
+ bool readonly)
179
+ : buffer_info(
180
+ ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {}
181
+
182
+ Py_buffer *m_view = nullptr;
183
+ bool ownview = false;
184
+ };
185
+
186
+ PYBIND11_NAMESPACE_BEGIN(detail)
187
+
188
+ template <typename T, typename SFINAE>
189
+ struct compare_buffer_info {
190
+ static bool compare(const buffer_info &b) {
191
+ // NOLINTNEXTLINE(bugprone-sizeof-expression) Needed for `PyObject *`
192
+ return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T);
193
+ }
194
+ };
195
+
196
+ template <typename T>
197
+ struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
198
+ static bool compare(const buffer_info &b) {
199
+ return static_cast<size_t>(b.itemsize) == sizeof(T)
200
+ && (b.format == format_descriptor<T>::value
201
+ || ((sizeof(T) == sizeof(long))
202
+ && b.format == (std::is_unsigned<T>::value ? "L" : "l"))
203
+ || ((sizeof(T) == sizeof(size_t))
204
+ && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
205
+ }
206
+ };
207
+
208
+ PYBIND11_NAMESPACE_END(detail)
209
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h ADDED
@@ -0,0 +1,2446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/cast.h: Partial template specializations to cast between
3
+ C++ and Python types
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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/argument_vector.h"
14
+ #include "detail/common.h"
15
+ #include "detail/descr.h"
16
+ #include "detail/holder_caster_foreign_helpers.h"
17
+ #include "detail/native_enum_data.h"
18
+ #include "detail/type_caster_base.h"
19
+ #include "detail/typeid.h"
20
+ #include "pytypes.h"
21
+
22
+ #include <array>
23
+ #include <cstring>
24
+ #include <functional>
25
+ #include <iosfwd>
26
+ #include <iterator>
27
+ #include <memory>
28
+ #include <string>
29
+ #include <tuple>
30
+ #include <type_traits>
31
+ #include <utility>
32
+ #include <vector>
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
35
+
36
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
37
+
38
+ PYBIND11_NAMESPACE_BEGIN(detail)
39
+
40
+ template <typename type, typename SFINAE = void>
41
+ class type_caster : public type_caster_base<type> {};
42
+ template <typename type>
43
+ using make_caster = type_caster<intrinsic_t<type>>;
44
+
45
+ // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
46
+ template <typename T>
47
+ typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
48
+ using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893
49
+ return caster.operator result_t();
50
+ }
51
+ template <typename T>
52
+ typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
53
+ cast_op(make_caster<T> &&caster) {
54
+ using result_t = typename make_caster<T>::template cast_op_type<
55
+ typename std::add_rvalue_reference<T>::type>; // See PR #4893
56
+ return std::move(caster).operator result_t();
57
+ }
58
+
59
+ template <typename EnumType>
60
+ class type_caster_enum_type {
61
+ private:
62
+ using Underlying = typename std::underlying_type<EnumType>::type;
63
+
64
+ public:
65
+ static constexpr auto name = const_name<EnumType>();
66
+
67
+ template <typename SrcType>
68
+ static handle cast(SrcType &&src, return_value_policy, handle parent) {
69
+ handle native_enum
70
+ = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));
71
+ if (native_enum) {
72
+ return native_enum(static_cast<Underlying>(src)).release();
73
+ }
74
+ return type_caster_base<EnumType>::cast(
75
+ std::forward<SrcType>(src),
76
+ // Fixes https://github.com/pybind/pybind11/pull/3643#issuecomment-1022987818:
77
+ return_value_policy::copy,
78
+ parent);
79
+ }
80
+
81
+ template <typename SrcType>
82
+ static handle cast(SrcType *src, return_value_policy policy, handle parent) {
83
+ return cast(*src, policy, parent);
84
+ }
85
+
86
+ bool load(handle src, bool convert) {
87
+ handle native_enum
88
+ = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));
89
+ if (native_enum) {
90
+ if (!isinstance(src, native_enum)) {
91
+ return false;
92
+ }
93
+ type_caster<Underlying> underlying_caster;
94
+ if (!underlying_caster.load(src.attr("value"), convert)) {
95
+ pybind11_fail("native_enum internal consistency failure.");
96
+ }
97
+ native_value = static_cast<EnumType>(static_cast<Underlying>(underlying_caster));
98
+ native_loaded = true;
99
+ return true;
100
+ }
101
+
102
+ type_caster_base<EnumType> legacy_caster;
103
+ if (legacy_caster.load(src, convert)) {
104
+ legacy_ptr = static_cast<EnumType *>(legacy_caster);
105
+ return true;
106
+ }
107
+ return false;
108
+ }
109
+
110
+ template <typename T>
111
+ using cast_op_type = detail::cast_op_type<T>;
112
+
113
+ // NOLINTNEXTLINE(google-explicit-constructor)
114
+ operator EnumType *() { return native_loaded ? &native_value : legacy_ptr; }
115
+
116
+ // NOLINTNEXTLINE(google-explicit-constructor)
117
+ operator EnumType &() {
118
+ if (!native_loaded && !legacy_ptr) {
119
+ throw reference_cast_error();
120
+ }
121
+ return native_loaded ? native_value : *legacy_ptr;
122
+ }
123
+
124
+ private:
125
+ EnumType native_value; // if loading a py::native_enum
126
+ bool native_loaded = false;
127
+ EnumType *legacy_ptr = nullptr; // if loading a py::enum_
128
+ };
129
+
130
+ template <typename EnumType, typename SFINAE = void>
131
+ struct type_caster_enum_type_enabled : std::true_type {};
132
+
133
+ template <typename T>
134
+ struct type_uses_type_caster_enum_type {
135
+ static constexpr bool value
136
+ = std::is_enum<T>::value && type_caster_enum_type_enabled<T>::value;
137
+ };
138
+
139
+ template <typename EnumType>
140
+ class type_caster<EnumType, detail::enable_if_t<type_uses_type_caster_enum_type<EnumType>::value>>
141
+ : public type_caster_enum_type<EnumType> {};
142
+
143
+ template <typename T, detail::enable_if_t<std::is_enum<T>::value, int> = 0>
144
+ bool isinstance_native_enum_impl(handle obj, const std::type_info &tp) {
145
+ handle native_enum = global_internals_native_enum_type_map_get_item(tp);
146
+ if (!native_enum) {
147
+ return false;
148
+ }
149
+ return isinstance(obj, native_enum);
150
+ }
151
+
152
+ template <typename T, detail::enable_if_t<!std::is_enum<T>::value, int> = 0>
153
+ bool isinstance_native_enum_impl(handle, const std::type_info &) {
154
+ return false;
155
+ }
156
+
157
+ template <typename T>
158
+ bool isinstance_native_enum(handle obj, const std::type_info &tp) {
159
+ return isinstance_native_enum_impl<intrinsic_t<T>>(obj, tp);
160
+ }
161
+
162
+ template <typename type>
163
+ class type_caster<std::reference_wrapper<type>> {
164
+ private:
165
+ using caster_t = make_caster<type>;
166
+ caster_t subcaster;
167
+ using reference_t = type &;
168
+ using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
169
+
170
+ static_assert(
171
+ std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
172
+ || std::is_same<reference_t, subcaster_cast_op_type>::value,
173
+ "std::reference_wrapper<T> caster requires T to have a caster with an "
174
+ "`operator T &()` or `operator const T &()`");
175
+
176
+ public:
177
+ bool load(handle src, bool convert) { return subcaster.load(src, convert); }
178
+ static constexpr auto name = caster_t::name;
179
+ static handle
180
+ cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
181
+ // It is definitely wrong to take ownership of this pointer, so mask that rvp
182
+ if (policy == return_value_policy::take_ownership
183
+ || policy == return_value_policy::automatic) {
184
+ policy = return_value_policy::automatic_reference;
185
+ }
186
+ return caster_t::cast(&src.get(), policy, parent);
187
+ }
188
+ template <typename T>
189
+ using cast_op_type = std::reference_wrapper<type>;
190
+ explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
191
+ };
192
+
193
+ #define PYBIND11_TYPE_CASTER(type, py_name) \
194
+ protected: \
195
+ type value; \
196
+ \
197
+ public: \
198
+ static constexpr auto name = py_name; \
199
+ template <typename T_, \
200
+ ::pybind11::detail::enable_if_t< \
201
+ std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
202
+ int> = 0> \
203
+ static ::pybind11::handle cast( \
204
+ T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
205
+ if (!src) \
206
+ return ::pybind11::none().release(); \
207
+ if (policy == ::pybind11::return_value_policy::take_ownership) { \
208
+ auto h = cast(std::move(*src), policy, parent); \
209
+ delete src; \
210
+ return h; \
211
+ } \
212
+ return cast(*src, policy, parent); \
213
+ } \
214
+ operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
215
+ operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
216
+ operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
217
+ template <typename T_> \
218
+ using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
219
+
220
+ template <typename CharT>
221
+ using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
222
+ #if defined(PYBIND11_HAS_U8STRING)
223
+ std::is_same<CharT, char8_t>, /* std::u8string */
224
+ #endif
225
+ std::is_same<CharT, char16_t>, /* std::u16string */
226
+ std::is_same<CharT, char32_t>, /* std::u32string */
227
+ std::is_same<CharT, wchar_t> /* std::wstring */
228
+ >;
229
+
230
+ template <typename T>
231
+ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
232
+ using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
233
+ using _py_type_1 = conditional_t<std::is_signed<T>::value,
234
+ _py_type_0,
235
+ typename std::make_unsigned<_py_type_0>::type>;
236
+ using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
237
+
238
+ public:
239
+ bool load(handle src, bool convert) {
240
+ py_type py_value;
241
+
242
+ if (!src) {
243
+ return false;
244
+ }
245
+
246
+ #if !defined(PYPY_VERSION)
247
+ auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
248
+ #else
249
+ // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
250
+ // while CPython only considers the existence of `nb_index`/`__index__`.
251
+ auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
252
+ #endif
253
+
254
+ if (std::is_floating_point<T>::value) {
255
+ if (convert || PyFloat_Check(src.ptr())) {
256
+ py_value = (py_type) PyFloat_AsDouble(src.ptr());
257
+ } else {
258
+ return false;
259
+ }
260
+ } else if (PyFloat_Check(src.ptr())
261
+ || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
262
+ return false;
263
+ } else {
264
+ handle src_or_index = src;
265
+ // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
266
+ #if defined(PYPY_VERSION)
267
+ object index;
268
+ if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
269
+ index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
270
+ if (!index) {
271
+ PyErr_Clear();
272
+ if (!convert)
273
+ return false;
274
+ } else {
275
+ src_or_index = index;
276
+ }
277
+ }
278
+ #endif
279
+ if (std::is_unsigned<py_type>::value) {
280
+ py_value = as_unsigned<py_type>(src_or_index.ptr());
281
+ } else { // signed integer:
282
+ py_value = sizeof(T) <= sizeof(long)
283
+ ? (py_type) PyLong_AsLong(src_or_index.ptr())
284
+ : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
285
+ }
286
+ }
287
+
288
+ // Python API reported an error
289
+ bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
290
+
291
+ // Check to see if the conversion is valid (integers should match exactly)
292
+ // Signed/unsigned checks happen elsewhere
293
+ if (py_err
294
+ || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
295
+ && py_value != (py_type) (T) py_value)) {
296
+ PyErr_Clear();
297
+ if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
298
+ auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
299
+ ? PyNumber_Float(src.ptr())
300
+ : PyNumber_Long(src.ptr()));
301
+ PyErr_Clear();
302
+ return load(tmp, false);
303
+ }
304
+ return false;
305
+ }
306
+
307
+ value = (T) py_value;
308
+ return true;
309
+ }
310
+
311
+ template <typename U = T>
312
+ static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
313
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
314
+ return PyFloat_FromDouble((double) src);
315
+ }
316
+
317
+ template <typename U = T>
318
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
319
+ && (sizeof(U) <= sizeof(long)),
320
+ handle>::type
321
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
322
+ return PYBIND11_LONG_FROM_SIGNED((long) src);
323
+ }
324
+
325
+ template <typename U = T>
326
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
327
+ && (sizeof(U) <= sizeof(unsigned long)),
328
+ handle>::type
329
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
330
+ return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
331
+ }
332
+
333
+ template <typename U = T>
334
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
335
+ && (sizeof(U) > sizeof(long)),
336
+ handle>::type
337
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
338
+ return PyLong_FromLongLong((long long) src);
339
+ }
340
+
341
+ template <typename U = T>
342
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
343
+ && (sizeof(U) > sizeof(unsigned long)),
344
+ handle>::type
345
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
346
+ return PyLong_FromUnsignedLongLong((unsigned long long) src);
347
+ }
348
+
349
+ PYBIND11_TYPE_CASTER(
350
+ T,
351
+ io_name<std::is_integral<T>::value>("typing.SupportsInt | typing.SupportsIndex",
352
+ "int",
353
+ "typing.SupportsFloat | typing.SupportsIndex",
354
+ "float"));
355
+ };
356
+
357
+ template <typename T>
358
+ struct void_caster {
359
+ public:
360
+ bool load(handle src, bool) {
361
+ if (src && src.is_none()) {
362
+ return true;
363
+ }
364
+ return false;
365
+ }
366
+ static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
367
+ return none().release();
368
+ }
369
+ PYBIND11_TYPE_CASTER(T, const_name("None"));
370
+ };
371
+
372
+ template <>
373
+ class type_caster<void_type> : public void_caster<void_type> {};
374
+
375
+ template <>
376
+ class type_caster<void> : public type_caster<void_type> {
377
+ public:
378
+ using type_caster<void_type>::cast;
379
+
380
+ bool load(handle h, bool) {
381
+ if (!h) {
382
+ return false;
383
+ }
384
+ if (h.is_none()) {
385
+ value = nullptr;
386
+ return true;
387
+ }
388
+
389
+ /* Check if this is a capsule */
390
+ if (isinstance<capsule>(h)) {
391
+ value = reinterpret_borrow<capsule>(h);
392
+ return true;
393
+ }
394
+
395
+ /* Check if this is a C++ type */
396
+ const auto &bases
397
+ = all_type_info(reinterpret_cast<PyTypeObject *>(type::handle_of(h).ptr()));
398
+ if (bases.size() == 1) { // Only allowing loading from a single-value type
399
+ value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
400
+ return true;
401
+ }
402
+
403
+ /* Fail */
404
+ return false;
405
+ }
406
+
407
+ static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
408
+ if (ptr) {
409
+ return capsule(ptr).release();
410
+ }
411
+ return none().release();
412
+ }
413
+
414
+ template <typename T>
415
+ using cast_op_type = void *&;
416
+ explicit operator void *&() { return value; }
417
+ static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);
418
+
419
+ private:
420
+ void *value = nullptr;
421
+ };
422
+
423
+ template <>
424
+ class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
425
+
426
+ template <>
427
+ class type_caster<bool> {
428
+ public:
429
+ bool load(handle src, bool convert) {
430
+ if (!src) {
431
+ return false;
432
+ }
433
+ if (src.ptr() == Py_True) {
434
+ value = true;
435
+ return true;
436
+ }
437
+ if (src.ptr() == Py_False) {
438
+ value = false;
439
+ return true;
440
+ }
441
+ if (convert || is_numpy_bool(src)) {
442
+ // (allow non-implicit conversion for numpy booleans), use strncmp
443
+ // since NumPy 1.x had an additional trailing underscore.
444
+
445
+ Py_ssize_t res = -1;
446
+ if (src.is_none()) {
447
+ res = 0; // None is implicitly converted to False
448
+ }
449
+ #if defined(PYPY_VERSION)
450
+ // On PyPy, check that "__bool__" attr exists
451
+ else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
452
+ res = PyObject_IsTrue(src.ptr());
453
+ }
454
+ #else
455
+ // Alternate approach for CPython: this does the same as the above, but optimized
456
+ // using the CPython API so as to avoid an unneeded attribute lookup.
457
+ else if (auto *tp_as_number = Py_TYPE(src.ptr())->tp_as_number) {
458
+ if (PYBIND11_NB_BOOL(tp_as_number)) {
459
+ res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
460
+ }
461
+ }
462
+ #endif
463
+ if (res == 0 || res == 1) {
464
+ value = (res != 0);
465
+ return true;
466
+ }
467
+ PyErr_Clear();
468
+ }
469
+ return false;
470
+ }
471
+ static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
472
+ return handle(src ? Py_True : Py_False).inc_ref();
473
+ }
474
+ PYBIND11_TYPE_CASTER(bool, const_name("bool"));
475
+
476
+ private:
477
+ // Test if an object is a NumPy boolean (without fetching the type).
478
+ static bool is_numpy_bool(handle object) {
479
+ const char *type_name = Py_TYPE(object.ptr())->tp_name;
480
+ // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support
481
+ return std::strcmp("numpy.bool", type_name) == 0
482
+ || std::strcmp("numpy.bool_", type_name) == 0;
483
+ }
484
+ };
485
+
486
+ // Helper class for UTF-{8,16,32} C++ stl strings:
487
+ template <typename StringType, bool IsView = false>
488
+ struct string_caster {
489
+ using CharT = typename StringType::value_type;
490
+
491
+ // Simplify life by being able to assume standard char sizes (the standard only guarantees
492
+ // minimums, but Python requires exact sizes)
493
+ static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
494
+ "Unsupported char size != 1");
495
+ #if defined(PYBIND11_HAS_U8STRING)
496
+ static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
497
+ "Unsupported char8_t size != 1");
498
+ #endif
499
+ static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
500
+ "Unsupported char16_t size != 2");
501
+ static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
502
+ "Unsupported char32_t size != 4");
503
+ // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
504
+ static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
505
+ "Unsupported wchar_t size != 2/4");
506
+ static constexpr size_t UTF_N = 8 * sizeof(CharT);
507
+
508
+ bool load(handle src, bool) {
509
+ handle load_src = src;
510
+ if (!src) {
511
+ return false;
512
+ }
513
+ if (!PyUnicode_Check(load_src.ptr())) {
514
+ return load_raw(load_src);
515
+ }
516
+
517
+ // For UTF-8 we avoid the need for a temporary `bytes` object by using
518
+ // `PyUnicode_AsUTF8AndSize`.
519
+ if (UTF_N == 8) {
520
+ Py_ssize_t size = -1;
521
+ const auto *buffer
522
+ = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
523
+ if (!buffer) {
524
+ PyErr_Clear();
525
+ return false;
526
+ }
527
+ value = StringType(buffer, static_cast<size_t>(size));
528
+ return true;
529
+ }
530
+
531
+ auto utfNbytes
532
+ = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
533
+ UTF_N == 8 ? "utf-8"
534
+ : UTF_N == 16 ? "utf-16"
535
+ : "utf-32",
536
+ nullptr));
537
+ if (!utfNbytes) {
538
+ PyErr_Clear();
539
+ return false;
540
+ }
541
+
542
+ const auto *buffer
543
+ = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
544
+ size_t length = static_cast<size_t>(PYBIND11_BYTES_SIZE(utfNbytes.ptr())) / sizeof(CharT);
545
+ // Skip BOM for UTF-16/32
546
+ if (UTF_N > 8) {
547
+ buffer++;
548
+ length--;
549
+ }
550
+ value = StringType(buffer, length);
551
+
552
+ // If we're loading a string_view we need to keep the encoded Python object alive:
553
+ if (IsView) {
554
+ loader_life_support::add_patient(utfNbytes);
555
+ }
556
+
557
+ return true;
558
+ }
559
+
560
+ static handle
561
+ cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
562
+ const char *buffer = reinterpret_cast<const char *>(src.data());
563
+ auto nbytes = ssize_t(src.size() * sizeof(CharT));
564
+ handle s = decode_utfN(buffer, nbytes);
565
+ if (!s) {
566
+ throw error_already_set();
567
+ }
568
+ return s;
569
+ }
570
+
571
+ PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
572
+
573
+ private:
574
+ static handle decode_utfN(const char *buffer, ssize_t nbytes) {
575
+ #if !defined(PYPY_VERSION)
576
+ return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
577
+ : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
578
+ : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
579
+ #else
580
+ // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
581
+ // well), so bypass the whole thing by just passing the encoding as a string value, which
582
+ // works properly:
583
+ return PyUnicode_Decode(buffer,
584
+ nbytes,
585
+ UTF_N == 8 ? "utf-8"
586
+ : UTF_N == 16 ? "utf-16"
587
+ : "utf-32",
588
+ nullptr);
589
+ #endif
590
+ }
591
+
592
+ // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
593
+ // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
594
+ // which supports loading a unicode from a str, doesn't take this path.
595
+ template <typename C = CharT>
596
+ bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
597
+ if (PYBIND11_BYTES_CHECK(src.ptr())) {
598
+ // We were passed raw bytes; accept it into a std::string or char*
599
+ // without any encoding attempt.
600
+ const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
601
+ if (!bytes) {
602
+ pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
603
+ }
604
+ value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
605
+ return true;
606
+ }
607
+ if (PyByteArray_Check(src.ptr())) {
608
+ // We were passed a bytearray; accept it into a std::string or char*
609
+ // without any encoding attempt.
610
+ const char *bytearray = PyByteArray_AsString(src.ptr());
611
+ if (!bytearray) {
612
+ pybind11_fail("Unexpected PyByteArray_AsString() failure.");
613
+ }
614
+ value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
615
+ return true;
616
+ }
617
+
618
+ return false;
619
+ }
620
+
621
+ template <typename C = CharT>
622
+ bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
623
+ return false;
624
+ }
625
+ };
626
+
627
+ template <typename CharT, class Traits, class Allocator>
628
+ struct type_caster<std::basic_string<CharT, Traits, Allocator>,
629
+ enable_if_t<is_std_char_type<CharT>::value>>
630
+ : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
631
+
632
+ #ifdef PYBIND11_HAS_STRING_VIEW
633
+ template <typename CharT, class Traits>
634
+ struct type_caster<std::basic_string_view<CharT, Traits>,
635
+ enable_if_t<is_std_char_type<CharT>::value>>
636
+ : string_caster<std::basic_string_view<CharT, Traits>, true> {};
637
+ #endif
638
+
639
+ // Type caster for C-style strings. We basically use a std::string type caster, but also add the
640
+ // ability to use None as a nullptr char* (which the string caster doesn't allow).
641
+ template <typename CharT>
642
+ struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
643
+ using StringType = std::basic_string<CharT>;
644
+ using StringCaster = make_caster<StringType>;
645
+ StringCaster str_caster;
646
+ bool none = false;
647
+ CharT one_char = 0;
648
+
649
+ public:
650
+ bool load(handle src, bool convert) {
651
+ if (!src) {
652
+ return false;
653
+ }
654
+ if (src.is_none()) {
655
+ // Defer accepting None to other overloads (if we aren't in convert mode):
656
+ if (!convert) {
657
+ return false;
658
+ }
659
+ none = true;
660
+ return true;
661
+ }
662
+ return str_caster.load(src, convert);
663
+ }
664
+
665
+ static handle cast(const CharT *src, return_value_policy policy, handle parent) {
666
+ if (src == nullptr) {
667
+ return pybind11::none().release();
668
+ }
669
+ return StringCaster::cast(StringType(src), policy, parent);
670
+ }
671
+
672
+ static handle cast(CharT src, return_value_policy policy, handle parent) {
673
+ if (std::is_same<char, CharT>::value) {
674
+ handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
675
+ if (!s) {
676
+ throw error_already_set();
677
+ }
678
+ return s;
679
+ }
680
+ return StringCaster::cast(StringType(1, src), policy, parent);
681
+ }
682
+
683
+ explicit operator CharT *() {
684
+ return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
685
+ }
686
+ explicit operator CharT &() {
687
+ if (none) {
688
+ throw value_error("Cannot convert None to a character");
689
+ }
690
+
691
+ auto &value = static_cast<StringType &>(str_caster);
692
+ size_t str_len = value.size();
693
+ if (str_len == 0) {
694
+ throw value_error("Cannot convert empty string to a character");
695
+ }
696
+
697
+ // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
698
+ // is too high, and one for multiple unicode characters (caught later), so we need to
699
+ // figure out how long the first encoded character is in bytes to distinguish between these
700
+ // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
701
+ // those can fit into a single char value.
702
+ if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
703
+ auto v0 = static_cast<unsigned char>(value[0]);
704
+ // low bits only: 0-127
705
+ // 0b110xxxxx - start of 2-byte sequence
706
+ // 0b1110xxxx - start of 3-byte sequence
707
+ // 0b11110xxx - start of 4-byte sequence
708
+ size_t char0_bytes = (v0 & 0x80) == 0 ? 1
709
+ : (v0 & 0xE0) == 0xC0 ? 2
710
+ : (v0 & 0xF0) == 0xE0 ? 3
711
+ : 4;
712
+
713
+ if (char0_bytes == str_len) {
714
+ // If we have a 128-255 value, we can decode it into a single char:
715
+ if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
716
+ one_char = static_cast<CharT>(((v0 & 3) << 6)
717
+ + (static_cast<unsigned char>(value[1]) & 0x3F));
718
+ return one_char;
719
+ }
720
+ // Otherwise we have a single character, but it's > U+00FF
721
+ throw value_error("Character code point not in range(0x100)");
722
+ }
723
+ }
724
+
725
+ // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
726
+ // surrogate pair with total length 2 instantly indicates a range error (but not a "your
727
+ // string was too long" error).
728
+ else if (StringCaster::UTF_N == 16 && str_len == 2) {
729
+ one_char = static_cast<CharT>(value[0]);
730
+ if (one_char >= 0xD800 && one_char < 0xE000) {
731
+ throw value_error("Character code point not in range(0x10000)");
732
+ }
733
+ }
734
+
735
+ if (str_len != 1) {
736
+ throw value_error("Expected a character, but multi-character string found");
737
+ }
738
+
739
+ one_char = value[0];
740
+ return one_char;
741
+ }
742
+
743
+ static constexpr auto name = const_name(PYBIND11_STRING_NAME);
744
+ template <typename _T>
745
+ using cast_op_type = pybind11::detail::cast_op_type<_T>;
746
+ };
747
+
748
+ // Base implementation for std::tuple and std::pair
749
+ template <template <typename...> class Tuple, typename... Ts>
750
+ class tuple_caster {
751
+ using type = Tuple<Ts...>;
752
+ static constexpr auto size = sizeof...(Ts);
753
+ using indices = make_index_sequence<size>;
754
+
755
+ public:
756
+ bool load(handle src, bool convert) {
757
+ if (!isinstance<sequence>(src)) {
758
+ return false;
759
+ }
760
+ const auto seq = reinterpret_borrow<sequence>(src);
761
+ if (seq.size() != size) {
762
+ return false;
763
+ }
764
+ return load_impl(seq, convert, indices{});
765
+ }
766
+
767
+ template <typename T>
768
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
769
+ return cast_impl(std::forward<T>(src), policy, parent, indices{});
770
+ }
771
+
772
+ // copied from the PYBIND11_TYPE_CASTER macro
773
+ template <typename T>
774
+ static handle cast(T *src, return_value_policy policy, handle parent) {
775
+ if (!src) {
776
+ return none().release();
777
+ }
778
+ if (policy == return_value_policy::take_ownership) {
779
+ auto h = cast(std::move(*src), policy, parent);
780
+ delete src;
781
+ return h;
782
+ }
783
+ return cast(*src, policy, parent);
784
+ }
785
+
786
+ static constexpr auto name = const_name("tuple[")
787
+ + ::pybind11::detail::concat(make_caster<Ts>::name...)
788
+ + const_name("]");
789
+
790
+ template <typename T>
791
+ using cast_op_type = type;
792
+
793
+ explicit operator type() & { return implicit_cast(indices{}); }
794
+ explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
795
+
796
+ protected:
797
+ template <size_t... Is>
798
+ type implicit_cast(index_sequence<Is...>) & {
799
+ return type(cast_op<Ts>(std::get<Is>(subcasters))...);
800
+ }
801
+ template <size_t... Is>
802
+ type implicit_cast(index_sequence<Is...>) && {
803
+ return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
804
+ }
805
+
806
+ static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
807
+
808
+ template <size_t... Is>
809
+ bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
810
+ #ifdef __cpp_fold_expressions
811
+ if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
812
+ return false;
813
+ }
814
+ #else
815
+ for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
816
+ if (!r) {
817
+ return false;
818
+ }
819
+ }
820
+ #endif
821
+ return true;
822
+ }
823
+
824
+ /* Implementation: Convert a C++ tuple into a Python tuple */
825
+ template <typename T, size_t... Is>
826
+ static handle
827
+ cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
828
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
829
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
830
+
831
+ std::array<object, size> entries{{reinterpret_steal<object>(
832
+ // NOLINTNEXTLINE(bugprone-use-after-move)
833
+ make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
834
+ for (const auto &entry : entries) {
835
+ if (!entry) {
836
+ return handle();
837
+ }
838
+ }
839
+ tuple result(size);
840
+ int counter = 0;
841
+ for (auto &entry : entries) {
842
+ PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
843
+ }
844
+ return result.release();
845
+ }
846
+
847
+ Tuple<make_caster<Ts>...> subcasters;
848
+ };
849
+
850
+ template <typename T1, typename T2>
851
+ class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
852
+
853
+ template <typename... Ts>
854
+ class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
855
+
856
+ template <>
857
+ class type_caster<std::tuple<>> : public tuple_caster<std::tuple> {
858
+ public:
859
+ // PEP 484 specifies this syntax for an empty tuple
860
+ static constexpr auto name = const_name("tuple[()]");
861
+ };
862
+
863
+ /// Helper class which abstracts away certain actions. Users can provide specializations for
864
+ /// custom holders, but it's only necessary if the type has a non-standard interface.
865
+ template <typename T>
866
+ struct holder_helper {
867
+ static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
868
+ };
869
+
870
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to shared_ptr specialization.
871
+ /// Type caster for holder types like std::shared_ptr, etc.
872
+ /// The SFINAE hook is provided to help work around the current lack of support
873
+ /// for smart-pointer interoperability. Please consider it an implementation
874
+ /// detail that may change in the future, as formal support for smart-pointer
875
+ /// interoperability is added into pybind11.
876
+ template <typename type, typename holder_type, typename SFINAE = void>
877
+ struct copyable_holder_caster : public type_caster_base<type> {
878
+ public:
879
+ using base = type_caster_base<type>;
880
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
881
+ "Holder classes are only supported for custom types");
882
+ using base::base;
883
+ using base::cast;
884
+ using base::typeinfo;
885
+ using base::value;
886
+
887
+ bool load(handle src, bool convert) {
888
+ return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
889
+ }
890
+
891
+ explicit operator type *() { return this->value; }
892
+ // static_cast works around compiler error with MSVC 17 and CUDA 10.2
893
+ // see issue #2180
894
+ explicit operator type &() { return *(static_cast<type *>(this->value)); }
895
+ explicit operator holder_type *() { return std::addressof(holder); }
896
+ explicit operator holder_type &() { return holder; }
897
+
898
+ static handle cast(const holder_type &src, return_value_policy, handle) {
899
+ const auto *ptr = holder_helper<holder_type>::get(src);
900
+ return type_caster_base<type>::cast_holder(ptr, &src);
901
+ }
902
+
903
+ protected:
904
+ friend class type_caster_generic;
905
+ void check_holder_compat() {
906
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
907
+ bool inst_has_unique_ptr_holder
908
+ = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);
909
+ if (inst_has_unique_ptr_holder) {
910
+ throw cast_error("Unable to load a custom holder type from a default-holder instance");
911
+ }
912
+ }
913
+
914
+ bool set_foreign_holder(handle src) {
915
+ return holder_caster_foreign_helpers::set_foreign_holder(src, (type *) value, &holder);
916
+ }
917
+
918
+ void load_value(value_and_holder &&v_h) {
919
+ if (v_h.holder_constructed()) {
920
+ value = v_h.value_ptr();
921
+ holder = v_h.template holder<holder_type>();
922
+ return;
923
+ }
924
+ throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
925
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
926
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
927
+ "type information)");
928
+ #else
929
+ "of type '"
930
+ + type_id<holder_type>() + "''");
931
+ #endif
932
+ }
933
+
934
+ template <typename T = holder_type,
935
+ detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
936
+ bool try_implicit_casts(handle, bool) {
937
+ return false;
938
+ }
939
+
940
+ template <typename T = holder_type,
941
+ detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
942
+ bool try_implicit_casts(handle src, bool convert) {
943
+ for (auto &cast : typeinfo->implicit_casts) {
944
+ copyable_holder_caster sub_caster(*cast.first);
945
+ if (sub_caster.load(src, convert)) {
946
+ value = cast.second(sub_caster.value);
947
+ holder = holder_type(sub_caster.holder, (type *) value);
948
+ return true;
949
+ }
950
+ }
951
+ return false;
952
+ }
953
+
954
+ static bool try_direct_conversions(handle) { return false; }
955
+
956
+ holder_type holder;
957
+ };
958
+
959
+ template <typename, typename SFINAE = void>
960
+ struct copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled : std::true_type {};
961
+
962
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor copyable_holder_caster to reduce code duplication.
963
+ template <typename type>
964
+ struct copyable_holder_caster<
965
+ type,
966
+ std::shared_ptr<type>,
967
+ enable_if_t<copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled<type>::value>>
968
+ : public type_caster_base<type> {
969
+ public:
970
+ using base = type_caster_base<type>;
971
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
972
+ "Holder classes are only supported for custom types");
973
+ using base::base;
974
+ using base::cast;
975
+ using base::typeinfo;
976
+ using base::value;
977
+
978
+ bool load(handle src, bool convert) {
979
+ if (base::template load_impl<copyable_holder_caster<type, std::shared_ptr<type>>>(
980
+ src, convert)) {
981
+ sh_load_helper.maybe_set_python_instance_is_alias(src);
982
+ return true;
983
+ }
984
+ return false;
985
+ }
986
+
987
+ explicit operator std::shared_ptr<type> *() {
988
+ if (sh_load_helper.was_populated) {
989
+ pybind11_fail("Passing `std::shared_ptr<T> *` from Python to C++ is not supported "
990
+ "(inherently unsafe).");
991
+ }
992
+ return std::addressof(shared_ptr_storage);
993
+ }
994
+
995
+ explicit operator std::shared_ptr<type> &() {
996
+ if (sh_load_helper.was_populated) {
997
+ shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);
998
+ }
999
+ return shared_ptr_storage;
1000
+ }
1001
+
1002
+ std::weak_ptr<type> potentially_slicing_weak_ptr() {
1003
+ if (sh_load_helper.was_populated) {
1004
+ // Reusing shared_ptr code to minimize code complexity.
1005
+ shared_ptr_storage
1006
+ = sh_load_helper.load_as_shared_ptr(typeinfo,
1007
+ value,
1008
+ /*responsible_parent=*/nullptr,
1009
+ /*force_potentially_slicing_shared_ptr=*/true);
1010
+ }
1011
+ return shared_ptr_storage;
1012
+ }
1013
+
1014
+ static handle
1015
+ cast(const std::shared_ptr<type> &src, return_value_policy policy, handle parent) {
1016
+ const auto *ptr = src.get();
1017
+ typename type_caster_base<type>::cast_sources srcs{ptr};
1018
+ if (srcs.creates_smart_holder()) {
1019
+ return smart_holder_type_caster_support::smart_holder_from_shared_ptr(
1020
+ src, policy, parent, srcs.result);
1021
+ }
1022
+
1023
+ auto *tinfo = srcs.result.tinfo;
1024
+ if (tinfo != nullptr && tinfo->holder_enum_v == holder_enum_t::std_shared_ptr) {
1025
+ return type_caster_base<type>::cast_holder(srcs, &src);
1026
+ }
1027
+
1028
+ if (parent) {
1029
+ return type_caster_generic::cast_non_owning(
1030
+ srcs, return_value_policy::reference_internal, parent);
1031
+ }
1032
+
1033
+ throw cast_error("Unable to convert std::shared_ptr<T> to Python when the bound type "
1034
+ "does not use std::shared_ptr or py::smart_holder as its holder type");
1035
+ }
1036
+
1037
+ // This function will succeed even if the `responsible_parent` does not own the
1038
+ // wrapped C++ object directly.
1039
+ // It is the responsibility of the caller to ensure that the `responsible_parent`
1040
+ // has a `keep_alive` relationship with the owner of the wrapped C++ object, or
1041
+ // that the wrapped C++ object lives for the duration of the process.
1042
+ static std::shared_ptr<type> shared_ptr_with_responsible_parent(handle responsible_parent) {
1043
+ copyable_holder_caster loader;
1044
+ loader.load(responsible_parent, /*convert=*/false);
1045
+ assert(loader.typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder);
1046
+ return loader.sh_load_helper.load_as_shared_ptr(
1047
+ loader.typeinfo, loader.value, responsible_parent);
1048
+ }
1049
+
1050
+ protected:
1051
+ friend class type_caster_generic;
1052
+ void check_holder_compat() {
1053
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
1054
+ bool inst_has_unique_ptr_holder
1055
+ = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);
1056
+ if (inst_has_unique_ptr_holder) {
1057
+ throw cast_error("Unable to load a custom holder type from a default-holder instance");
1058
+ }
1059
+ }
1060
+
1061
+ bool set_foreign_holder(handle src) {
1062
+ return holder_caster_foreign_helpers::set_foreign_holder(
1063
+ src, (type *) value, &shared_ptr_storage);
1064
+ }
1065
+
1066
+ void load_value(value_and_holder &&v_h) {
1067
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1068
+ sh_load_helper.loaded_v_h = v_h;
1069
+ sh_load_helper.was_populated = true;
1070
+ value = sh_load_helper.get_void_ptr_or_nullptr();
1071
+ return;
1072
+ }
1073
+ if (v_h.holder_constructed()) {
1074
+ value = v_h.value_ptr();
1075
+ shared_ptr_storage = v_h.template holder<std::shared_ptr<type>>();
1076
+ return;
1077
+ }
1078
+ throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
1079
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1080
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
1081
+ "type information)");
1082
+ #else
1083
+ "of type '"
1084
+ + type_id<std::shared_ptr<type>>() + "''");
1085
+ #endif
1086
+ }
1087
+
1088
+ template <typename T = std::shared_ptr<type>,
1089
+ detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
1090
+ bool try_implicit_casts(handle, bool) {
1091
+ return false;
1092
+ }
1093
+
1094
+ template <typename T = std::shared_ptr<type>,
1095
+ detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
1096
+ bool try_implicit_casts(handle src, bool convert) {
1097
+ for (auto &cast : typeinfo->implicit_casts) {
1098
+ copyable_holder_caster sub_caster(*cast.first);
1099
+ if (sub_caster.load(src, convert)) {
1100
+ value = cast.second(sub_caster.value);
1101
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1102
+ sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;
1103
+ sh_load_helper.was_populated = true;
1104
+ } else {
1105
+ shared_ptr_storage
1106
+ = std::shared_ptr<type>(sub_caster.shared_ptr_storage, (type *) value);
1107
+ }
1108
+ return true;
1109
+ }
1110
+ }
1111
+ return false;
1112
+ }
1113
+
1114
+ static bool try_direct_conversions(handle) { return false; }
1115
+
1116
+ smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl
1117
+ std::shared_ptr<type> shared_ptr_storage;
1118
+ };
1119
+
1120
+ /// Specialize for the common std::shared_ptr, so users don't need to
1121
+ template <typename T>
1122
+ class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
1123
+
1124
+ PYBIND11_NAMESPACE_END(detail)
1125
+
1126
+ /// Return a std::shared_ptr with the SAME CONTROL BLOCK as the std::shared_ptr owned by the
1127
+ /// class_ holder. For class_-wrapped types with trampolines, the returned std::shared_ptr
1128
+ /// does NOT keep any derived Python objects alive (see issue #1333).
1129
+ ///
1130
+ /// For class_-wrapped types using std::shared_ptr as the holder, the following expressions
1131
+ /// produce equivalent results (see tests/test_potentially_slicing_weak_ptr.cpp,py):
1132
+ ///
1133
+ /// - obj.cast<std::shared_ptr<T>>()
1134
+ /// - py::potentially_slicing_weak_ptr<T>(obj).lock()
1135
+ ///
1136
+ /// For class_-wrapped types with trampolines and using py::smart_holder, obj.cast<>()
1137
+ /// produces a std::shared_ptr that keeps any derived Python objects alive for its own lifetime,
1138
+ /// but this is achieved by introducing a std::shared_ptr control block that is independent of
1139
+ /// the one owned by the py::smart_holder. This can lead to surprising std::weak_ptr behavior
1140
+ /// (see issue #5623). An easy solution is to use py::potentially_slicing_weak_ptr<>(obj),
1141
+ /// as exercised in tests/test_potentially_slicing_weak_ptr.cpp,py (look for
1142
+ /// "set_wp_potentially_slicing"). Note, however, that this reintroduces the inheritance
1143
+ /// slicing issue (see issue #1333). The ideal — but usually more involved — solution is to use
1144
+ /// a Python weakref to the derived Python object, instead of a C++ base-class std::weak_ptr.
1145
+ ///
1146
+ /// It is not possible (at least no known approach exists at the time of this writing) to
1147
+ /// simultaneously achieve both desirable properties:
1148
+ ///
1149
+ /// - the same std::shared_ptr control block as the class_ holder
1150
+ /// - automatic lifetime extension of any derived Python objects
1151
+ ///
1152
+ /// The reason is that this would introduce a reference cycle that cannot be garbage collected:
1153
+ ///
1154
+ /// - the derived Python object owns the class_ holder
1155
+ /// - the class_ holder owns the std::shared_ptr
1156
+ /// - the std::shared_ptr would own a reference to the derived Python object,
1157
+ /// completing the cycle
1158
+ template <typename T>
1159
+ std::weak_ptr<T> potentially_slicing_weak_ptr(handle obj) {
1160
+ detail::make_caster<std::shared_ptr<T>> caster;
1161
+ if (caster.load(obj, /*convert=*/true)) {
1162
+ return caster.potentially_slicing_weak_ptr();
1163
+ }
1164
+ const char *obj_type_name = detail::obj_class_name(obj.ptr());
1165
+ throw type_error("\"" + std::string(obj_type_name)
1166
+ + "\" object is not convertible to std::weak_ptr<T> (with T = " + type_id<T>()
1167
+ + ")");
1168
+ }
1169
+
1170
+ PYBIND11_NAMESPACE_BEGIN(detail)
1171
+
1172
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to unique_ptr specialization.
1173
+ /// Type caster for holder types like std::unique_ptr.
1174
+ /// Please consider the SFINAE hook an implementation detail, as explained
1175
+ /// in the comment for the copyable_holder_caster.
1176
+ template <typename type, typename holder_type, typename SFINAE = void>
1177
+ struct move_only_holder_caster {
1178
+ static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
1179
+ "Holder classes are only supported for custom types");
1180
+
1181
+ static handle cast(holder_type &&src, return_value_policy, handle) {
1182
+ auto *ptr = holder_helper<holder_type>::get(src);
1183
+ return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
1184
+ }
1185
+ static constexpr auto name = type_caster_base<type>::name;
1186
+ };
1187
+
1188
+ template <typename, typename SFINAE = void>
1189
+ struct move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled : std::true_type {};
1190
+
1191
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor move_only_holder_caster to reduce code duplication.
1192
+ template <typename type, typename deleter>
1193
+ struct move_only_holder_caster<
1194
+ type,
1195
+ std::unique_ptr<type, deleter>,
1196
+ enable_if_t<move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled<type>::value>>
1197
+ : public type_caster_base<type> {
1198
+ public:
1199
+ using base = type_caster_base<type>;
1200
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
1201
+ "Holder classes are only supported for custom types");
1202
+ using base::base;
1203
+ using base::cast;
1204
+ using base::typeinfo;
1205
+ using base::value;
1206
+
1207
+ static handle
1208
+ cast(std::unique_ptr<type, deleter> &&src, return_value_policy policy, handle parent) {
1209
+ auto *ptr = src.get();
1210
+ typename type_caster_base<type>::cast_sources srcs{ptr};
1211
+ if (srcs.creates_smart_holder()) {
1212
+ return smart_holder_type_caster_support::smart_holder_from_unique_ptr(
1213
+ std::move(src), policy, parent, srcs.result);
1214
+ }
1215
+ return type_caster_base<type>::cast_holder(srcs, &src);
1216
+ }
1217
+
1218
+ static handle
1219
+ cast(const std::unique_ptr<type, deleter> &src, return_value_policy policy, handle parent) {
1220
+ if (!src) {
1221
+ return none().release();
1222
+ }
1223
+ if (policy == return_value_policy::automatic) {
1224
+ policy = return_value_policy::reference_internal;
1225
+ }
1226
+ if (policy != return_value_policy::reference_internal) {
1227
+ throw cast_error("Invalid return_value_policy for const unique_ptr&");
1228
+ }
1229
+ return type_caster_base<type>::cast(src.get(), policy, parent);
1230
+ }
1231
+
1232
+ bool load(handle src, bool convert) {
1233
+ if (base::template load_impl<
1234
+ move_only_holder_caster<type, std::unique_ptr<type, deleter>>>(src, convert)) {
1235
+ sh_load_helper.maybe_set_python_instance_is_alias(src);
1236
+ return true;
1237
+ }
1238
+ return false;
1239
+ }
1240
+
1241
+ bool set_foreign_holder(handle) {
1242
+ throw cast_error("Foreign instance cannot be converted to std::unique_ptr "
1243
+ "because we don't know how to make it relinquish "
1244
+ "ownership");
1245
+ }
1246
+
1247
+ void load_value(value_and_holder &&v_h) {
1248
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1249
+ sh_load_helper.loaded_v_h = v_h;
1250
+ sh_load_helper.loaded_v_h.type = typeinfo;
1251
+ sh_load_helper.was_populated = true;
1252
+ value = sh_load_helper.get_void_ptr_or_nullptr();
1253
+ return;
1254
+ }
1255
+ pybind11_fail("Passing `std::unique_ptr<T>` from Python to C++ requires `py::class_<T, "
1256
+ "py::smart_holder>` (with T = "
1257
+ + clean_type_id(typeinfo->cpptype->name()) + ")");
1258
+ }
1259
+
1260
+ template <typename T_>
1261
+ using cast_op_type
1262
+ = conditional_t<std::is_same<typename std::remove_volatile<T_>::type,
1263
+ const std::unique_ptr<type, deleter> &>::value
1264
+ || std::is_same<typename std::remove_volatile<T_>::type,
1265
+ const std::unique_ptr<const type, deleter> &>::value,
1266
+ const std::unique_ptr<type, deleter> &,
1267
+ std::unique_ptr<type, deleter>>;
1268
+
1269
+ explicit operator std::unique_ptr<type, deleter>() {
1270
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1271
+ return sh_load_helper.template load_as_unique_ptr<deleter>(typeinfo, value);
1272
+ }
1273
+ pybind11_fail("Expected to be UNREACHABLE: " __FILE__ ":" PYBIND11_TOSTRING(__LINE__));
1274
+ }
1275
+
1276
+ explicit operator const std::unique_ptr<type, deleter> &() {
1277
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1278
+ // Get shared_ptr to ensure that the Python object is not disowned elsewhere.
1279
+ shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);
1280
+ // Build a temporary unique_ptr that is meant to never expire.
1281
+ unique_ptr_storage = std::shared_ptr<std::unique_ptr<type, deleter>>(
1282
+ new std::unique_ptr<type, deleter>{
1283
+ sh_load_helper.template load_as_const_unique_ptr<deleter>(
1284
+ typeinfo, shared_ptr_storage.get())},
1285
+ [](std::unique_ptr<type, deleter> *ptr) {
1286
+ if (!ptr) {
1287
+ pybind11_fail("FATAL: `const std::unique_ptr<T, D> &` was disowned "
1288
+ "(EXPECT UNDEFINED BEHAVIOR).");
1289
+ }
1290
+ (void) ptr->release();
1291
+ delete ptr;
1292
+ });
1293
+ return *unique_ptr_storage;
1294
+ }
1295
+ pybind11_fail("Expected to be UNREACHABLE: " __FILE__ ":" PYBIND11_TOSTRING(__LINE__));
1296
+ }
1297
+
1298
+ bool try_implicit_casts(handle src, bool convert) {
1299
+ for (auto &cast : typeinfo->implicit_casts) {
1300
+ move_only_holder_caster sub_caster(*cast.first);
1301
+ if (sub_caster.load(src, convert)) {
1302
+ value = cast.second(sub_caster.value);
1303
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1304
+ sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;
1305
+ sh_load_helper.was_populated = true;
1306
+ } else {
1307
+ pybind11_fail("Expected to be UNREACHABLE: " __FILE__
1308
+ ":" PYBIND11_TOSTRING(__LINE__));
1309
+ }
1310
+ return true;
1311
+ }
1312
+ }
1313
+ return false;
1314
+ }
1315
+
1316
+ static bool try_direct_conversions(handle) { return false; }
1317
+
1318
+ smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl
1319
+ std::shared_ptr<type> shared_ptr_storage; // Serves as a pseudo lock.
1320
+ std::shared_ptr<std::unique_ptr<type, deleter>> unique_ptr_storage;
1321
+ };
1322
+
1323
+ template <typename type, typename deleter>
1324
+ class type_caster<std::unique_ptr<type, deleter>>
1325
+ : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
1326
+
1327
+ template <typename type, typename holder_type>
1328
+ using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
1329
+ copyable_holder_caster<type, holder_type>,
1330
+ move_only_holder_caster<type, holder_type>>;
1331
+
1332
+ template <bool Value = false>
1333
+ struct always_construct_holder_value {
1334
+ static constexpr bool value = Value;
1335
+ };
1336
+
1337
+ template <typename T, bool Value = false>
1338
+ struct always_construct_holder : always_construct_holder_value<Value> {};
1339
+
1340
+ /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
1341
+ #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
1342
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
1343
+ namespace detail { \
1344
+ template <typename type> \
1345
+ struct always_construct_holder<holder_type> : always_construct_holder_value<__VA_ARGS__> {}; \
1346
+ template <typename type> \
1347
+ class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
1348
+ : public type_caster_holder<type, holder_type> {}; \
1349
+ } \
1350
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1351
+
1352
+ // PYBIND11_DECLARE_HOLDER_TYPE holder types:
1353
+ template <typename base, typename holder>
1354
+ struct is_holder_type
1355
+ : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
1356
+
1357
+ // Specializations for always-supported holders:
1358
+ template <typename base, typename deleter>
1359
+ struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
1360
+
1361
+ template <typename base>
1362
+ struct is_holder_type<base, smart_holder> : std::true_type {};
1363
+
1364
+ #ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
1365
+
1366
+ // This leads to compilation errors if a specialization is missing.
1367
+ template <typename T>
1368
+ struct handle_type_name;
1369
+
1370
+ #else
1371
+
1372
+ template <typename T>
1373
+ struct handle_type_name {
1374
+ static constexpr auto name = const_name<T>();
1375
+ };
1376
+
1377
+ #endif
1378
+
1379
+ template <>
1380
+ struct handle_type_name<object> {
1381
+ static constexpr auto name = const_name("object");
1382
+ };
1383
+ template <>
1384
+ struct handle_type_name<list> {
1385
+ static constexpr auto name = const_name("list");
1386
+ };
1387
+ template <>
1388
+ struct handle_type_name<dict> {
1389
+ static constexpr auto name = const_name("dict");
1390
+ };
1391
+ template <>
1392
+ struct handle_type_name<anyset> {
1393
+ static constexpr auto name = const_name("set | frozenset");
1394
+ };
1395
+ template <>
1396
+ struct handle_type_name<set> {
1397
+ static constexpr auto name = const_name("set");
1398
+ };
1399
+ template <>
1400
+ struct handle_type_name<frozenset> {
1401
+ static constexpr auto name = const_name("frozenset");
1402
+ };
1403
+ template <>
1404
+ struct handle_type_name<str> {
1405
+ static constexpr auto name = const_name("str");
1406
+ };
1407
+ template <>
1408
+ struct handle_type_name<tuple> {
1409
+ static constexpr auto name = const_name("tuple");
1410
+ };
1411
+ template <>
1412
+ struct handle_type_name<bool_> {
1413
+ static constexpr auto name = const_name("bool");
1414
+ };
1415
+ template <>
1416
+ struct handle_type_name<bytes> {
1417
+ static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
1418
+ };
1419
+ template <>
1420
+ struct handle_type_name<buffer> {
1421
+ static constexpr auto name = const_name(PYBIND11_BUFFER_TYPE_HINT);
1422
+ };
1423
+ template <>
1424
+ struct handle_type_name<int_> {
1425
+ static constexpr auto name = const_name("int");
1426
+ };
1427
+ template <>
1428
+ struct handle_type_name<iterable> {
1429
+ static constexpr auto name = const_name("collections.abc.Iterable");
1430
+ };
1431
+ template <>
1432
+ struct handle_type_name<iterator> {
1433
+ static constexpr auto name = const_name("collections.abc.Iterator");
1434
+ };
1435
+ template <>
1436
+ struct handle_type_name<float_> {
1437
+ static constexpr auto name = const_name("float");
1438
+ };
1439
+ template <>
1440
+ struct handle_type_name<function> {
1441
+ static constexpr auto name = const_name("collections.abc.Callable");
1442
+ };
1443
+ template <>
1444
+ struct handle_type_name<handle> {
1445
+ static constexpr auto name = handle_type_name<object>::name;
1446
+ };
1447
+ template <>
1448
+ struct handle_type_name<none> {
1449
+ static constexpr auto name = const_name("None");
1450
+ };
1451
+ template <>
1452
+ struct handle_type_name<sequence> {
1453
+ static constexpr auto name = const_name("collections.abc.Sequence");
1454
+ };
1455
+ template <>
1456
+ struct handle_type_name<bytearray> {
1457
+ static constexpr auto name = const_name("bytearray");
1458
+ };
1459
+ template <>
1460
+ struct handle_type_name<memoryview> {
1461
+ static constexpr auto name = const_name("memoryview");
1462
+ };
1463
+ template <>
1464
+ struct handle_type_name<slice> {
1465
+ static constexpr auto name = const_name("slice");
1466
+ };
1467
+ template <>
1468
+ struct handle_type_name<type> {
1469
+ static constexpr auto name = const_name("type");
1470
+ };
1471
+ template <>
1472
+ struct handle_type_name<capsule> {
1473
+ static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);
1474
+ };
1475
+ template <>
1476
+ struct handle_type_name<ellipsis> {
1477
+ static constexpr auto name = const_name("ellipsis");
1478
+ };
1479
+ template <>
1480
+ struct handle_type_name<weakref> {
1481
+ static constexpr auto name = const_name("weakref.ReferenceType");
1482
+ };
1483
+ // args/Args/kwargs/KWArgs have name as well as typehint included
1484
+ template <>
1485
+ struct handle_type_name<args> {
1486
+ static constexpr auto name = io_name("*args", "tuple");
1487
+ };
1488
+ template <typename T>
1489
+ struct handle_type_name<Args<T>> {
1490
+ static constexpr auto name
1491
+ = io_name("*args: ", "tuple[") + make_caster<T>::name + io_name("", ", ...]");
1492
+ };
1493
+ template <>
1494
+ struct handle_type_name<kwargs> {
1495
+ static constexpr auto name = io_name("**kwargs", "dict[str, typing.Any]");
1496
+ };
1497
+ template <typename T>
1498
+ struct handle_type_name<KWArgs<T>> {
1499
+ static constexpr auto name
1500
+ = io_name("**kwargs: ", "dict[str, ") + make_caster<T>::name + io_name("", "]");
1501
+ };
1502
+ template <>
1503
+ struct handle_type_name<obj_attr_accessor> {
1504
+ static constexpr auto name = const_name<obj_attr_accessor>();
1505
+ };
1506
+ template <>
1507
+ struct handle_type_name<str_attr_accessor> {
1508
+ static constexpr auto name = const_name<str_attr_accessor>();
1509
+ };
1510
+ template <>
1511
+ struct handle_type_name<item_accessor> {
1512
+ static constexpr auto name = const_name<item_accessor>();
1513
+ };
1514
+ template <>
1515
+ struct handle_type_name<sequence_accessor> {
1516
+ static constexpr auto name = const_name<sequence_accessor>();
1517
+ };
1518
+ template <>
1519
+ struct handle_type_name<list_accessor> {
1520
+ static constexpr auto name = const_name<list_accessor>();
1521
+ };
1522
+ template <>
1523
+ struct handle_type_name<tuple_accessor> {
1524
+ static constexpr auto name = const_name<tuple_accessor>();
1525
+ };
1526
+
1527
+ template <typename type>
1528
+ struct pyobject_caster {
1529
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1530
+ pyobject_caster() : value() {}
1531
+
1532
+ // `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
1533
+ // to a nil handle is safe since it will only be accessed if `load` succeeds.
1534
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1535
+ pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
1536
+
1537
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1538
+ bool load(handle src, bool /* convert */) {
1539
+ value = src;
1540
+ return static_cast<bool>(value);
1541
+ }
1542
+
1543
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1544
+ bool load(handle src, bool /* convert */) {
1545
+ if (!isinstance<type>(src)) {
1546
+ return false;
1547
+ }
1548
+ value = reinterpret_borrow<type>(src);
1549
+ return true;
1550
+ }
1551
+
1552
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1553
+ return src.inc_ref();
1554
+ }
1555
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1556
+ };
1557
+
1558
+ template <typename T>
1559
+ class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
1560
+
1561
+ template <>
1562
+ class type_caster<float_> : public pyobject_caster<float_> {
1563
+ public:
1564
+ bool load(handle src, bool /* convert */) {
1565
+ if (isinstance<float_>(src)) {
1566
+ value = reinterpret_borrow<float_>(src);
1567
+ } else if (isinstance<int_>(src)) {
1568
+ value = float_(reinterpret_borrow<int_>(src));
1569
+ } else {
1570
+ return false;
1571
+ }
1572
+ return true;
1573
+ }
1574
+ };
1575
+
1576
+ // Our conditions for enabling moving are quite restrictive:
1577
+ // At compile time:
1578
+ // - T needs to be a non-const, non-pointer, non-reference type
1579
+ // - type_caster<T>::operator T&() must exist
1580
+ // - the type must be move constructible (obviously)
1581
+ // At run-time:
1582
+ // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
1583
+ // must have ref_count() == 1)h
1584
+ // If any of the above are not satisfied, we fall back to copying.
1585
+ template <typename T>
1586
+ using move_is_plain_type
1587
+ = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
1588
+ template <typename T, typename SFINAE = void>
1589
+ struct move_always : std::false_type {};
1590
+ template <typename T>
1591
+ struct move_always<
1592
+ T,
1593
+ enable_if_t<
1594
+ all_of<move_is_plain_type<T>,
1595
+ negation<is_copy_constructible<T>>,
1596
+ is_move_constructible<T>,
1597
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1598
+ : std::true_type {};
1599
+ template <typename T, typename SFINAE = void>
1600
+ struct move_if_unreferenced : std::false_type {};
1601
+ template <typename T>
1602
+ struct move_if_unreferenced<
1603
+ T,
1604
+ enable_if_t<
1605
+ all_of<move_is_plain_type<T>,
1606
+ negation<move_always<T>>,
1607
+ is_move_constructible<T>,
1608
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1609
+ : std::true_type {};
1610
+ template <typename T>
1611
+ using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
1612
+
1613
+ // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
1614
+ // reference or pointer to a local variable of the type_caster. Basically, only
1615
+ // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
1616
+ // everything else returns a reference/pointer to a local variable.
1617
+ template <typename type>
1618
+ using cast_is_temporary_value_reference
1619
+ = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
1620
+ && !std::is_base_of<type_caster_generic, make_caster<type>>::value
1621
+ && !std::is_same<intrinsic_t<type>, void>::value>;
1622
+
1623
+ // When a value returned from a C++ function is being cast back to Python, we almost always want to
1624
+ // force `policy = move`, regardless of the return value policy the function/method was declared
1625
+ // with.
1626
+ template <typename Return, typename SFINAE = void>
1627
+ struct return_value_policy_override {
1628
+ static return_value_policy policy(return_value_policy p) { return p; }
1629
+ };
1630
+
1631
+ template <typename Return>
1632
+ struct return_value_policy_override<
1633
+ Return,
1634
+ detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1635
+ static return_value_policy policy(return_value_policy p) {
1636
+ return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1637
+ ? return_value_policy::move
1638
+ : p;
1639
+ }
1640
+ };
1641
+
1642
+ // Basic python -> C++ casting; throws if casting fails
1643
+ template <typename T, typename SFINAE>
1644
+ type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1645
+ static_assert(!detail::is_pyobject<T>::value,
1646
+ "Internal error: type_caster should only be used for C++ types");
1647
+ if (!conv.load(handle, true)) {
1648
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1649
+ throw cast_error(
1650
+ "Unable to cast Python instance of type "
1651
+ + str(type::handle_of(handle)).cast<std::string>()
1652
+ + " to C++ type '?' (#define "
1653
+ "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1654
+ #else
1655
+ throw cast_error("Unable to cast Python instance of type "
1656
+ + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
1657
+ + type_id<T>() + "'");
1658
+ #endif
1659
+ }
1660
+ return conv;
1661
+ }
1662
+ // Wrapper around the above that also constructs and returns a type_caster
1663
+ template <typename T>
1664
+ make_caster<T> load_type(const handle &handle) {
1665
+ make_caster<T> conv;
1666
+ load_type(conv, handle);
1667
+ return conv;
1668
+ }
1669
+
1670
+ PYBIND11_NAMESPACE_END(detail)
1671
+
1672
+ // pytype -> C++ type
1673
+ template <typename T,
1674
+ detail::enable_if_t<!detail::is_pyobject<T>::value
1675
+ && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1676
+ int> = 0>
1677
+ T cast(const handle &handle) {
1678
+ using namespace detail;
1679
+ constexpr bool is_enum_cast = type_uses_type_caster_enum_type<intrinsic_t<T>>::value;
1680
+ static_assert(!cast_is_temporary_value_reference<T>::value || is_enum_cast,
1681
+ "Unable to cast type to reference: value is local to type caster");
1682
+ #ifndef NDEBUG
1683
+ if (is_enum_cast && cast_is_temporary_value_reference<T>::value) {
1684
+ if (detail::global_internals_native_enum_type_map_contains(
1685
+ std::type_index(typeid(intrinsic_t<T>)))) {
1686
+ pybind11_fail("Unable to cast native enum type to reference");
1687
+ }
1688
+ }
1689
+ #endif
1690
+ return cast_op<T>(load_type<T>(handle));
1691
+ }
1692
+
1693
+ // pytype -> pytype (calls converting constructor)
1694
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1695
+ T cast(const handle &handle) {
1696
+ return T(reinterpret_borrow<object>(handle));
1697
+ }
1698
+
1699
+ // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
1700
+ // This is necessary for the case that `obj` is a temporary, and could
1701
+ // not possibly be different, given
1702
+ // 1. the established convention that the passed `handle` is borrowed, and
1703
+ // 2. we don't want to force all generic code using `cast<T>()` to special-case
1704
+ // handling of `T` = `PyObject *` (to increment the reference count there).
1705
+ // It is the responsibility of the caller to ensure that the reference count
1706
+ // is decremented.
1707
+ template <typename T,
1708
+ typename Handle,
1709
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1710
+ && detail::is_same_ignoring_cvref<Handle, handle>::value,
1711
+ int> = 0>
1712
+ T cast(Handle &&handle) {
1713
+ return handle.inc_ref().ptr();
1714
+ }
1715
+ // To optimize way an inc_ref/dec_ref cycle:
1716
+ template <typename T,
1717
+ typename Object,
1718
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1719
+ && detail::is_same_ignoring_cvref<Object, object>::value,
1720
+ int> = 0>
1721
+ T cast(Object &&obj) {
1722
+ return obj.release().ptr();
1723
+ }
1724
+
1725
+ // C++ type -> py::object
1726
+ template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1727
+ object cast(T &&value,
1728
+ return_value_policy policy = return_value_policy::automatic_reference,
1729
+ handle parent = handle()) {
1730
+ using no_ref_T = typename std::remove_reference<T>::type;
1731
+ if (policy == return_value_policy::automatic) {
1732
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
1733
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1734
+ : return_value_policy::move;
1735
+ } else if (policy == return_value_policy::automatic_reference) {
1736
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
1737
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1738
+ : return_value_policy::move;
1739
+ }
1740
+ return reinterpret_steal<object>(
1741
+ detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1742
+ }
1743
+
1744
+ template <typename T>
1745
+ T handle::cast() const {
1746
+ return pybind11::cast<T>(*this);
1747
+ }
1748
+ template <>
1749
+ inline void handle::cast() const {
1750
+ return;
1751
+ }
1752
+
1753
+ template <typename T>
1754
+ detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1755
+ if (obj.ref_count() > 1) {
1756
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1757
+ throw cast_error(
1758
+ "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
1759
+ + " instance to C++ rvalue: instance has multiple references"
1760
+ " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1761
+ #else
1762
+ throw cast_error("Unable to move from Python "
1763
+ + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
1764
+ + type_id<T>() + " instance: instance has multiple references");
1765
+ #endif
1766
+ }
1767
+
1768
+ // Move into a temporary and return that, because the reference may be a local value of `conv`
1769
+ T ret = std::move(detail::load_type<T>(obj).operator T &());
1770
+ return ret;
1771
+ }
1772
+
1773
+ // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1774
+ // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
1775
+ // object has multiple references, but trying to copy will fail to compile.
1776
+ // - If both movable and copyable, check ref count: if 1, move; otherwise copy
1777
+ // - Otherwise (not movable), copy.
1778
+ template <typename T>
1779
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
1780
+ cast(object &&object) {
1781
+ return move<T>(std::move(object));
1782
+ }
1783
+ template <typename T>
1784
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
1785
+ cast(object &&object) {
1786
+ if (object.ref_count() > 1) {
1787
+ return cast<T>(object);
1788
+ }
1789
+ return move<T>(std::move(object));
1790
+ }
1791
+ template <typename T>
1792
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
1793
+ cast(object &&object) {
1794
+ return cast<T>(object);
1795
+ }
1796
+
1797
+ // pytype rvalue -> pytype (calls converting constructor)
1798
+ template <typename T>
1799
+ detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
1800
+ return T(std::move(object));
1801
+ }
1802
+
1803
+ template <typename T>
1804
+ T object::cast() const & {
1805
+ return pybind11::cast<T>(*this);
1806
+ }
1807
+ template <typename T>
1808
+ T object::cast() && {
1809
+ return pybind11::cast<T>(std::move(*this));
1810
+ }
1811
+ template <>
1812
+ inline void object::cast() const & {
1813
+ return;
1814
+ }
1815
+ template <>
1816
+ inline void object::cast() && {
1817
+ return;
1818
+ }
1819
+
1820
+ PYBIND11_NAMESPACE_BEGIN(detail)
1821
+
1822
+ // forward declaration (definition in pybind11.h)
1823
+ template <typename T>
1824
+ std::string generate_type_signature();
1825
+
1826
+ // Declared in pytypes.h:
1827
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1828
+ object object_or_cast(T &&o) {
1829
+ return pybind11::cast(std::forward<T>(o));
1830
+ }
1831
+
1832
+ // Declared in pytypes.h:
1833
+ // Implemented here so that make_caster<T> can be used.
1834
+ template <typename D>
1835
+ template <typename T>
1836
+ str_attr_accessor object_api<D>::attr_with_type_hint(const char *key) const {
1837
+ #if !defined(__cpp_inline_variables)
1838
+ static_assert(always_false<T>::value,
1839
+ "C++17 feature __cpp_inline_variables not available: "
1840
+ "https://en.cppreference.com/w/cpp/language/static#Static_data_members");
1841
+ #endif
1842
+ object ann = annotations();
1843
+ if (ann.contains(key)) {
1844
+ throw std::runtime_error("__annotations__[\"" + std::string(key) + "\"] was set already.");
1845
+ }
1846
+
1847
+ ann[key] = generate_type_signature<T>();
1848
+ return {derived(), key};
1849
+ }
1850
+
1851
+ template <typename D>
1852
+ template <typename T>
1853
+ obj_attr_accessor object_api<D>::attr_with_type_hint(handle key) const {
1854
+ (void) attr_with_type_hint<T>(key.cast<std::string>().c_str());
1855
+ return {derived(), reinterpret_borrow<object>(key)};
1856
+ }
1857
+
1858
+ // Placeholder type for the unneeded (and dead code) static variable in the
1859
+ // PYBIND11_OVERRIDE_OVERRIDE macro
1860
+ struct override_unused {};
1861
+ template <typename ret_type>
1862
+ using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
1863
+ make_caster<ret_type>,
1864
+ override_unused>;
1865
+
1866
+ // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1867
+ // store the result in the given variable. For other types, this is a no-op.
1868
+ template <typename T>
1869
+ enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
1870
+ make_caster<T> &caster) {
1871
+ return cast_op<T>(load_type(caster, o));
1872
+ }
1873
+ template <typename T>
1874
+ enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
1875
+ override_unused &) {
1876
+ pybind11_fail("Internal error: cast_ref fallback invoked");
1877
+ }
1878
+
1879
+ // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
1880
+ // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
1881
+ // that only does anything in cases where pybind11::cast is valid.
1882
+ template <typename T>
1883
+ enable_if_t<cast_is_temporary_value_reference<T>::value
1884
+ && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1885
+ T>
1886
+ cast_safe(object &&) {
1887
+ pybind11_fail("Internal error: cast_safe fallback invoked");
1888
+ }
1889
+ template <typename T>
1890
+ enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
1891
+ template <typename T>
1892
+ enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>
1893
+ cast_safe(object &&o) {
1894
+ return o.release().ptr();
1895
+ }
1896
+ template <typename T>
1897
+ enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
1898
+ detail::is_same_ignoring_cvref<T, PyObject *>,
1899
+ std::is_void<T>>::value,
1900
+ T>
1901
+ cast_safe(object &&o) {
1902
+ return pybind11::cast<T>(std::move(o));
1903
+ }
1904
+
1905
+ PYBIND11_NAMESPACE_END(detail)
1906
+
1907
+ // The overloads could coexist, i.e. the #if is not strictly speaking needed,
1908
+ // but it is an easy minor optimization.
1909
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1910
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
1911
+ return cast_error("Unable to convert call argument '" + name
1912
+ + "' to Python object (#define "
1913
+ "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1914
+ }
1915
+ #else
1916
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1917
+ const std::string &type) {
1918
+ return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1919
+ + "' to Python object");
1920
+ }
1921
+ #endif
1922
+
1923
+ namespace typing {
1924
+ template <typename... Types>
1925
+ class Tuple : public tuple {
1926
+ using tuple::tuple;
1927
+ };
1928
+ } // namespace typing
1929
+
1930
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1931
+ typing::Tuple<> make_tuple() {
1932
+ return tuple(0);
1933
+ }
1934
+
1935
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1936
+ typing::Tuple<Args...> make_tuple(Args &&...args_) {
1937
+ constexpr size_t size = sizeof...(Args);
1938
+ std::array<object, size> args{{reinterpret_steal<object>(
1939
+ detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1940
+ for (size_t i = 0; i < args.size(); i++) {
1941
+ if (!args[i]) {
1942
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1943
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i));
1944
+ #else
1945
+ std::array<std::string, size> argtypes{{type_id<Args>()...}};
1946
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1947
+ #endif
1948
+ }
1949
+ }
1950
+ tuple result(size);
1951
+ int counter = 0;
1952
+ for (auto &arg_value : args) {
1953
+ PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1954
+ }
1955
+ PYBIND11_WARNING_PUSH
1956
+ #ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
1957
+ PYBIND11_WARNING_DISABLE_CLANG("-Wreturn-std-move")
1958
+ #endif
1959
+ return result;
1960
+ PYBIND11_WARNING_POP
1961
+ }
1962
+
1963
+ /// \ingroup annotations
1964
+ /// Annotation for arguments
1965
+ struct arg {
1966
+ /// Constructs an argument with the name of the argument; if null or omitted, this is a
1967
+ /// positional argument.
1968
+ constexpr explicit arg(const char *name = nullptr)
1969
+ : name(name), flag_noconvert(false), flag_none(true) {}
1970
+ /// Assign a value to this argument
1971
+ template <typename T>
1972
+ arg_v operator=(T &&value) const;
1973
+ /// Indicate that the type should not be converted in the type caster
1974
+ arg &noconvert(bool flag = true) {
1975
+ flag_noconvert = flag;
1976
+ return *this;
1977
+ }
1978
+ /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1979
+ arg &none(bool flag = true) {
1980
+ flag_none = flag;
1981
+ return *this;
1982
+ }
1983
+
1984
+ const char *name; ///< If non-null, this is a named kwargs argument
1985
+ bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
1986
+ ///< caster!)
1987
+ bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
1988
+ };
1989
+
1990
+ /// \ingroup annotations
1991
+ /// Annotation for arguments with values
1992
+ struct arg_v : arg {
1993
+ private:
1994
+ template <typename T>
1995
+ arg_v(arg &&base, T &&x, const char *descr = nullptr)
1996
+ : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
1997
+ std::forward<T>(x), return_value_policy::automatic, {}))),
1998
+ descr(descr)
1999
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2000
+ ,
2001
+ type(type_id<T>())
2002
+ #endif
2003
+ {
2004
+ // Workaround! See:
2005
+ // https://github.com/pybind/pybind11/issues/2336
2006
+ // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
2007
+ if (PyErr_Occurred()) {
2008
+ PyErr_Clear();
2009
+ }
2010
+ }
2011
+
2012
+ public:
2013
+ /// Direct construction with name, default, and description
2014
+ template <typename T>
2015
+ arg_v(const char *name, T &&x, const char *descr = nullptr)
2016
+ : arg_v(arg(name), std::forward<T>(x), descr) {}
2017
+
2018
+ /// Called internally when invoking `py::arg("a") = value`
2019
+ template <typename T>
2020
+ arg_v(const arg &base, T &&x, const char *descr = nullptr)
2021
+ : arg_v(arg(base), std::forward<T>(x), descr) {}
2022
+
2023
+ /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
2024
+ arg_v &noconvert(bool flag = true) {
2025
+ arg::noconvert(flag);
2026
+ return *this;
2027
+ }
2028
+
2029
+ /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
2030
+ arg_v &none(bool flag = true) {
2031
+ arg::none(flag);
2032
+ return *this;
2033
+ }
2034
+
2035
+ /// The default value
2036
+ object value;
2037
+ /// The (optional) description of the default value
2038
+ const char *descr;
2039
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2040
+ /// The C++ type name of the default value (only available when compiled in debug mode)
2041
+ std::string type;
2042
+ #endif
2043
+ };
2044
+
2045
+ /// \ingroup annotations
2046
+ /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
2047
+ /// an unnamed '*' argument
2048
+ struct kw_only {};
2049
+
2050
+ /// \ingroup annotations
2051
+ /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
2052
+ /// an unnamed '/' argument
2053
+ struct pos_only {};
2054
+
2055
+ template <typename T>
2056
+ arg_v arg::operator=(T &&value) const {
2057
+ return {*this, std::forward<T>(value)};
2058
+ }
2059
+
2060
+ /// Alias for backward compatibility -- to be removed in version 2.0
2061
+ template <typename /*unused*/>
2062
+ using arg_t = arg_v;
2063
+
2064
+ inline namespace literals {
2065
+ /** \rst
2066
+ String literal version of `arg`
2067
+ \endrst */
2068
+ constexpr arg
2069
+ #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
2070
+ operator"" _a // gcc 4.8.5 insists on having a space (hard error).
2071
+ #else
2072
+ operator""_a // clang 17 generates a deprecation warning if there is a space.
2073
+ #endif
2074
+ (const char *name, size_t) {
2075
+ return arg(name);
2076
+ }
2077
+ } // namespace literals
2078
+
2079
+ PYBIND11_NAMESPACE_BEGIN(detail)
2080
+
2081
+ template <typename T>
2082
+ using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
2083
+ template <typename T>
2084
+ using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
2085
+
2086
+ // forward declaration (definition in attr.h)
2087
+ struct function_record;
2088
+
2089
+ /// Inline size chosen mostly arbitrarily.
2090
+ constexpr std::size_t arg_vector_small_size = 6;
2091
+
2092
+ /// Internal data associated with a single function call
2093
+ struct function_call {
2094
+ function_call(const function_record &f, handle p); // Implementation in attr.h
2095
+
2096
+ /// The function data:
2097
+ const function_record &func;
2098
+
2099
+ /// Arguments passed to the function:
2100
+ argument_vector<arg_vector_small_size> args;
2101
+
2102
+ /// The `convert` value the arguments should be loaded with
2103
+ args_convert_vector<arg_vector_small_size> args_convert;
2104
+
2105
+ /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
2106
+ /// present, are also in `args` but without a reference).
2107
+ object args_ref, kwargs_ref;
2108
+
2109
+ /// The parent, if any
2110
+ handle parent;
2111
+
2112
+ /// If this is a call to an initializer, this argument contains `self`
2113
+ handle init_self;
2114
+ };
2115
+
2116
+ // See PR #5396 for the discussion that led to this
2117
+ template <typename Base, typename Derived, typename = void>
2118
+ struct is_same_or_base_of : std::is_same<Base, Derived> {};
2119
+
2120
+ // Only evaluate is_base_of if Derived is complete.
2121
+ // is_base_of raises a compiler error if Derived is incomplete.
2122
+ template <typename Base, typename Derived>
2123
+ struct is_same_or_base_of<Base, Derived, decltype(void(sizeof(Derived)))>
2124
+ : any_of<std::is_same<Base, Derived>, std::is_base_of<Base, Derived>> {};
2125
+
2126
+ /// Helper class which loads arguments for C++ functions called from Python
2127
+ template <typename... Args>
2128
+ class argument_loader {
2129
+ using indices = make_index_sequence<sizeof...(Args)>;
2130
+ template <typename Arg>
2131
+ using argument_is_args = is_same_or_base_of<args, intrinsic_t<Arg>>;
2132
+ template <typename Arg>
2133
+ using argument_is_kwargs = is_same_or_base_of<kwargs, intrinsic_t<Arg>>;
2134
+ // Get kwargs argument position, or -1 if not present:
2135
+ static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
2136
+
2137
+ static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
2138
+ "py::kwargs is only permitted as the last argument of a function");
2139
+
2140
+ public:
2141
+ static constexpr bool has_kwargs = kwargs_pos != -1;
2142
+
2143
+ // py::args argument position; -1 if not present.
2144
+ static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
2145
+
2146
+ static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
2147
+ "py::args cannot be specified more than once");
2148
+
2149
+ static constexpr auto arg_names
2150
+ = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
2151
+
2152
+ bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
2153
+
2154
+ template <typename Return, typename Guard, typename Func>
2155
+ // NOLINTNEXTLINE(readability-const-return-type)
2156
+ enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
2157
+ return std::move(*this).template call_impl<remove_cv_t<Return>>(
2158
+ std::forward<Func>(f), indices{}, Guard{});
2159
+ }
2160
+
2161
+ template <typename Return, typename Guard, typename Func>
2162
+ enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
2163
+ std::move(*this).template call_impl<remove_cv_t<Return>>(
2164
+ std::forward<Func>(f), indices{}, Guard{});
2165
+ return void_type();
2166
+ }
2167
+
2168
+ private:
2169
+ static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
2170
+
2171
+ template <size_t... Is>
2172
+ bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
2173
+ PYBIND11_WARNING_PUSH
2174
+ #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 13
2175
+ // Work around a GCC -Warray-bounds false positive in argument_vector usage.
2176
+ PYBIND11_WARNING_DISABLE_GCC("-Warray-bounds")
2177
+ #endif
2178
+ #ifdef __cpp_fold_expressions
2179
+ if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
2180
+ return false;
2181
+ }
2182
+ #else
2183
+ for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
2184
+ if (!r) {
2185
+ return false;
2186
+ }
2187
+ }
2188
+ #endif
2189
+ PYBIND11_WARNING_POP
2190
+ return true;
2191
+ }
2192
+
2193
+ template <typename Return, typename Func, size_t... Is, typename Guard>
2194
+ Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
2195
+ return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
2196
+ }
2197
+
2198
+ std::tuple<make_caster<Args>...> argcasters;
2199
+ };
2200
+
2201
+ // [workaround(intel)] Separate function required here
2202
+ // We need to put this into a separate function because the Intel compiler
2203
+ // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
2204
+ // (tested with ICC 2021.1 Beta 20200827).
2205
+ template <typename... Args>
2206
+ constexpr bool args_has_keyword_or_ds() {
2207
+ return any_of<is_keyword_or_ds<Args>...>::value;
2208
+ }
2209
+
2210
+ /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
2211
+ template <return_value_policy policy>
2212
+ class unpacking_collector {
2213
+ public:
2214
+ template <typename... Ts>
2215
+ explicit unpacking_collector(Ts &&...values)
2216
+ : m_names(reinterpret_steal<tuple>(
2217
+ handle())) // initialize to null to avoid useless allocation of 0-length tuple
2218
+ {
2219
+ /*
2220
+ Python can sometimes utilize an extra space before the arguments to prepend `self`.
2221
+ This is important enough that there is a special flag for it:
2222
+ PY_VECTORCALL_ARGUMENTS_OFFSET.
2223
+ All we have to do is allocate an extra space at the beginning of this array, and set the
2224
+ flag. Note that the extra space is not passed directly in to vectorcall.
2225
+ */
2226
+ m_args.reserve(sizeof...(values) + 1);
2227
+ m_args.push_back_null();
2228
+
2229
+ if (args_has_keyword_or_ds<Ts...>()) {
2230
+ list names_list;
2231
+
2232
+ // collect_arguments guarantees this can't be constructed with kwargs before the last
2233
+ // positional so we don't need to worry about Ts... being in anything but normal python
2234
+ // order.
2235
+ using expander = int[];
2236
+ (void) expander{0, (process(names_list, std::forward<Ts>(values)), 0)...};
2237
+
2238
+ m_names = reinterpret_steal<tuple>(PyList_AsTuple(names_list.ptr()));
2239
+ } else {
2240
+ auto not_used
2241
+ = reinterpret_steal<list>(handle()); // initialize as null (to avoid an allocation)
2242
+
2243
+ using expander = int[];
2244
+ (void) expander{0, (process(not_used, std::forward<Ts>(values)), 0)...};
2245
+ }
2246
+ }
2247
+
2248
+ /// Call a Python function and pass the collected arguments
2249
+ object call(PyObject *ptr) const {
2250
+ size_t nargs = m_args.size() - 1; // -1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)
2251
+ if (m_names) {
2252
+ nargs -= m_names.size();
2253
+ }
2254
+ PyObject *result =
2255
+ #if PY_VERSION_HEX >= 0x03090000
2256
+ PyObject_Vectorcall(
2257
+ #else
2258
+ _PyObject_Vectorcall(
2259
+ #endif
2260
+ ptr, m_args.data() + 1, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, m_names.ptr());
2261
+ if (!result) {
2262
+ throw error_already_set();
2263
+ }
2264
+ return reinterpret_steal<object>(result);
2265
+ }
2266
+
2267
+ tuple args() const {
2268
+ size_t nargs = m_args.size() - 1; // -1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)
2269
+ if (m_names) {
2270
+ nargs -= m_names.size();
2271
+ }
2272
+ tuple val(nargs);
2273
+ for (size_t i = 0; i < nargs; ++i) {
2274
+ // +1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)
2275
+ val[i] = reinterpret_borrow<object>(m_args[i + 1]);
2276
+ }
2277
+ return val;
2278
+ }
2279
+
2280
+ dict kwargs() const {
2281
+ dict val;
2282
+ if (m_names) {
2283
+ size_t offset = m_args.size() - m_names.size();
2284
+ for (size_t i = 0; i < m_names.size(); ++i, ++offset) {
2285
+ val[m_names[i]] = reinterpret_borrow<object>(m_args[offset]);
2286
+ }
2287
+ }
2288
+ return val;
2289
+ }
2290
+
2291
+ private:
2292
+ // normal argument, possibly needing conversion
2293
+ template <typename T>
2294
+ void process(list & /*names_list*/, T &&x) {
2295
+ handle h = detail::make_caster<T>::cast(std::forward<T>(x), policy, {});
2296
+ if (!h) {
2297
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2298
+ throw cast_error_unable_to_convert_call_arg(std::to_string(m_args.size() - 1));
2299
+ #else
2300
+ throw cast_error_unable_to_convert_call_arg(std::to_string(m_args.size() - 1),
2301
+ type_id<T>());
2302
+ #endif
2303
+ }
2304
+ m_args.push_back_steal(h.ptr()); // cast returns a new reference
2305
+ }
2306
+
2307
+ // * unpacking
2308
+ void process(list & /*names_list*/, detail::args_proxy ap) {
2309
+ if (!ap) {
2310
+ return;
2311
+ }
2312
+ for (auto a : ap) {
2313
+ m_args.push_back_borrow(a.ptr());
2314
+ }
2315
+ }
2316
+
2317
+ // named argument
2318
+ // NOLINTNEXTLINE(performance-unnecessary-value-param)
2319
+ void process(list &names_list, arg_v a) {
2320
+ assert(names_list);
2321
+ if (!a.name) {
2322
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2323
+ nameless_argument_error();
2324
+ #else
2325
+ nameless_argument_error(a.type);
2326
+ #endif
2327
+ }
2328
+ auto name = str(a.name);
2329
+ if (names_list.contains(name)) {
2330
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2331
+ multiple_values_error();
2332
+ #else
2333
+ multiple_values_error(a.name);
2334
+ #endif
2335
+ }
2336
+ if (!a.value) {
2337
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2338
+ throw cast_error_unable_to_convert_call_arg(a.name);
2339
+ #else
2340
+ throw cast_error_unable_to_convert_call_arg(a.name, a.type);
2341
+ #endif
2342
+ }
2343
+ names_list.append(std::move(name));
2344
+ m_args.push_back_borrow(a.value.ptr());
2345
+ }
2346
+
2347
+ // ** unpacking
2348
+ void process(list &names_list, detail::kwargs_proxy kp) {
2349
+ if (!kp) {
2350
+ return;
2351
+ }
2352
+ assert(names_list);
2353
+ for (auto &&k : reinterpret_borrow<dict>(kp)) {
2354
+ auto name = str(k.first);
2355
+ if (names_list.contains(name)) {
2356
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2357
+ multiple_values_error();
2358
+ #else
2359
+ multiple_values_error(name);
2360
+ #endif
2361
+ }
2362
+ names_list.append(std::move(name));
2363
+ m_args.push_back_borrow(k.second.ptr());
2364
+ }
2365
+ }
2366
+
2367
+ [[noreturn]] static void nameless_argument_error() {
2368
+ throw type_error(
2369
+ "Got kwargs without a name; only named arguments "
2370
+ "may be passed via py::arg() to a python function call. "
2371
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
2372
+ }
2373
+ [[noreturn]] static void nameless_argument_error(const std::string &type) {
2374
+ throw type_error("Got kwargs without a name of type '" + type
2375
+ + "'; only named "
2376
+ "arguments may be passed via py::arg() to a python function call. ");
2377
+ }
2378
+ [[noreturn]] static void multiple_values_error() {
2379
+ throw type_error(
2380
+ "Got multiple values for keyword argument "
2381
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
2382
+ }
2383
+
2384
+ [[noreturn]] static void multiple_values_error(const std::string &name) {
2385
+ throw type_error("Got multiple values for keyword argument '" + name + "'");
2386
+ }
2387
+
2388
+ private:
2389
+ ref_small_vector<arg_vector_small_size> m_args;
2390
+ tuple m_names;
2391
+ };
2392
+
2393
+ /// Collect all arguments, including keywords and unpacking
2394
+ template <return_value_policy policy, typename... Args>
2395
+ unpacking_collector<policy> collect_arguments(Args &&...args) {
2396
+ // Following argument order rules for generalized unpacking according to PEP 448
2397
+ static_assert(
2398
+ constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>(),
2399
+ "Invalid function call: positional args must precede keywords and */** unpacking;");
2400
+ static_assert(constexpr_last<is_s_unpacking, Args...>()
2401
+ < constexpr_first<is_ds_unpacking, Args...>(),
2402
+ "Invalid function call: * unpacking must precede ** unpacking");
2403
+ return unpacking_collector<policy>(std::forward<Args>(args)...);
2404
+ }
2405
+
2406
+ template <typename Derived>
2407
+ template <return_value_policy policy, typename... Args>
2408
+ object object_api<Derived>::operator()(Args &&...args) const {
2409
+ #ifndef NDEBUG
2410
+ if (!PyGILState_Check()) {
2411
+ pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
2412
+ }
2413
+ #endif
2414
+ return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
2415
+ }
2416
+
2417
+ template <typename Derived>
2418
+ template <return_value_policy policy, typename... Args>
2419
+ object object_api<Derived>::call(Args &&...args) const {
2420
+ return operator()<policy>(std::forward<Args>(args)...);
2421
+ }
2422
+
2423
+ PYBIND11_NAMESPACE_END(detail)
2424
+
2425
+ template <typename T>
2426
+ handle type::handle_of() {
2427
+ static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
2428
+ "py::type::of<T> only supports the case where T is a registered C++ types.");
2429
+
2430
+ return detail::get_type_handle(typeid(T), true);
2431
+ }
2432
+
2433
+ #define PYBIND11_MAKE_OPAQUE(...) \
2434
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
2435
+ namespace detail { \
2436
+ template <> \
2437
+ class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
2438
+ } \
2439
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
2440
+
2441
+ /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
2442
+ /// typedef, e.g.:
2443
+ /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
2444
+ #define PYBIND11_TYPE(...) __VA_ARGS__
2445
+
2446
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime
3
+
4
+ Copyright (c) 2016 Trent Houliston <trent@houliston.me> and
5
+ Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ static const std::chrono::duration<rep, period> &
67
+ get_duration(const std::chrono::duration<rep, period> &&) = delete;
68
+
69
+ // If this is a time_point get the time_since_epoch
70
+ template <typename Clock>
71
+ static std::chrono::duration<rep, period>
72
+ get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
73
+ return src.time_since_epoch();
74
+ }
75
+
76
+ static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
77
+ using namespace std::chrono;
78
+
79
+ // Use overloaded function to get our duration from our source
80
+ // Works out if it is a duration or time_point and get the duration
81
+ auto d = get_duration(src);
82
+
83
+ // Lazy initialise the PyDateTime import
84
+ if (!PyDateTimeAPI) {
85
+ PyDateTime_IMPORT;
86
+ }
87
+
88
+ // Declare these special duration types so the conversions happen with the correct
89
+ // primitive types (int)
90
+ using dd_t = duration<int, std::ratio<86400>>;
91
+ using ss_t = duration<int, std::ratio<1>>;
92
+ using us_t = duration<int, std::micro>;
93
+
94
+ auto dd = duration_cast<dd_t>(d);
95
+ auto subd = d - dd;
96
+ auto ss = duration_cast<ss_t>(subd);
97
+ auto us = duration_cast<us_t>(subd - ss);
98
+ return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
99
+ }
100
+
101
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
102
+ };
103
+
104
+ inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
105
+ #if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
106
+ if (localtime_s(buf, time))
107
+ return nullptr;
108
+ return buf;
109
+ #else
110
+ static std::mutex mtx;
111
+ std::lock_guard<std::mutex> lock(mtx);
112
+ std::tm *tm_ptr = std::localtime(time);
113
+ if (tm_ptr != nullptr) {
114
+ *buf = *tm_ptr;
115
+ }
116
+ return tm_ptr;
117
+ #endif
118
+ }
119
+
120
+ // This is for casting times on the system clock into datetime.datetime instances
121
+ template <typename Duration>
122
+ class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
123
+ public:
124
+ using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
125
+ bool load(handle src, bool) {
126
+ using namespace std::chrono;
127
+
128
+ // Lazy initialise the PyDateTime import
129
+ if (!PyDateTimeAPI) {
130
+ PyDateTime_IMPORT;
131
+ }
132
+
133
+ if (!src) {
134
+ return false;
135
+ }
136
+
137
+ std::tm cal;
138
+ microseconds msecs;
139
+
140
+ if (PyDateTime_Check(src.ptr())) {
141
+ cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
142
+ cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
143
+ cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
144
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
145
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
146
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
147
+ cal.tm_isdst = -1;
148
+ msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
149
+ } else if (PyDate_Check(src.ptr())) {
150
+ cal.tm_sec = 0;
151
+ cal.tm_min = 0;
152
+ cal.tm_hour = 0;
153
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
154
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
155
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
156
+ cal.tm_isdst = -1;
157
+ msecs = microseconds(0);
158
+ } else if (PyTime_Check(src.ptr())) {
159
+ cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
160
+ cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
161
+ cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
162
+ cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
163
+ cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
164
+ cal.tm_year = 70; // earliest available date for Python's datetime
165
+ cal.tm_isdst = -1;
166
+ msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
167
+ } else {
168
+ return false;
169
+ }
170
+
171
+ value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
172
+ return true;
173
+ }
174
+
175
+ static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
176
+ return_value_policy /* policy */,
177
+ handle /* parent */) {
178
+ using namespace std::chrono;
179
+
180
+ // Lazy initialise the PyDateTime import
181
+ if (!PyDateTimeAPI) {
182
+ PyDateTime_IMPORT;
183
+ }
184
+
185
+ // Get out microseconds, and make sure they are positive, to avoid bug in eastern
186
+ // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
187
+ using us_t = duration<int, std::micro>;
188
+ auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
189
+ if (us.count() < 0) {
190
+ us += duration_cast<us_t>(seconds(1));
191
+ }
192
+
193
+ // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
194
+ // > If std::time_t has lower precision, it is implementation-defined whether the value is
195
+ // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
196
+ std::time_t tt
197
+ = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
198
+
199
+ std::tm localtime;
200
+ std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
201
+ if (!localtime_ptr) {
202
+ throw cast_error("Unable to represent system_clock in local time");
203
+ }
204
+ return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
205
+ localtime.tm_mon + 1,
206
+ localtime.tm_mday,
207
+ localtime.tm_hour,
208
+ localtime.tm_min,
209
+ localtime.tm_sec,
210
+ us.count());
211
+ }
212
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
213
+ };
214
+
215
+ // Other clocks that are not the system clock are not measured as datetime.datetime objects
216
+ // since they are not measured on calendar time. So instead we just make them timedeltas
217
+ // Or if they have passed us a time as a float we convert that
218
+ template <typename Clock, typename Duration>
219
+ class type_caster<std::chrono::time_point<Clock, Duration>>
220
+ : public duration_caster<std::chrono::time_point<Clock, Duration>> {};
221
+
222
+ template <typename Rep, typename Period>
223
+ class type_caster<std::chrono::duration<Rep, Period>>
224
+ : public duration_caster<std::chrono::duration<Rep, Period>> {};
225
+
226
+ PYBIND11_NAMESPACE_END(detail)
227
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/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'."
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/complex.h ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/complex.h: Complex number support
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ handle src_or_index = src;
58
+ // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
59
+ // The same logic is used in numeric_caster for ints and floats
60
+ #if defined(PYPY_VERSION)
61
+ object index;
62
+ if (PYBIND11_INDEX_CHECK(src.ptr())) {
63
+ index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
64
+ if (!index) {
65
+ PyErr_Clear();
66
+ if (!convert)
67
+ return false;
68
+ } else {
69
+ src_or_index = index;
70
+ }
71
+ }
72
+ #endif
73
+ Py_complex result = PyComplex_AsCComplex(src_or_index.ptr());
74
+ if (result.real == -1.0 && PyErr_Occurred()) {
75
+ PyErr_Clear();
76
+ return false;
77
+ }
78
+ value = std::complex<T>((T) result.real, (T) result.imag);
79
+ return true;
80
+ }
81
+
82
+ static handle
83
+ cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
84
+ return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
85
+ }
86
+
87
+ PYBIND11_TYPE_CASTER(
88
+ std::complex<T>,
89
+ io_name("typing.SupportsComplex | typing.SupportsFloat | typing.SupportsIndex",
90
+ "complex"));
91
+ };
92
+ PYBIND11_NAMESPACE_END(detail)
93
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/critical_section.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2016-2025 The Pybind Development Team.
2
+ // All rights reserved. Use of this source code is governed by a
3
+ // BSD-style license that can be found in the LICENSE file.
4
+
5
+ #pragma once
6
+
7
+ #include "pytypes.h"
8
+
9
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
10
+
11
+ /// This does not do anything if there's a GIL. On free-threaded Python,
12
+ /// it locks an object. This uses the CPython API, which has limits
13
+ class scoped_critical_section {
14
+ public:
15
+ #ifdef Py_GIL_DISABLED
16
+ explicit scoped_critical_section(handle obj1, handle obj2 = handle{}) {
17
+ if (obj1) {
18
+ if (obj2) {
19
+ PyCriticalSection2_Begin(&section2, obj1.ptr(), obj2.ptr());
20
+ rank = 2;
21
+ } else {
22
+ PyCriticalSection_Begin(&section, obj1.ptr());
23
+ rank = 1;
24
+ }
25
+ } else if (obj2) {
26
+ PyCriticalSection_Begin(&section, obj2.ptr());
27
+ rank = 1;
28
+ }
29
+ }
30
+
31
+ ~scoped_critical_section() {
32
+ if (rank == 1) {
33
+ PyCriticalSection_End(&section);
34
+ } else if (rank == 2) {
35
+ PyCriticalSection2_End(&section2);
36
+ }
37
+ }
38
+ #else
39
+ explicit scoped_critical_section(handle, handle = handle{}) {};
40
+ ~scoped_critical_section() = default;
41
+ #endif
42
+
43
+ scoped_critical_section(const scoped_critical_section &) = delete;
44
+ scoped_critical_section &operator=(const scoped_critical_section &) = delete;
45
+
46
+ private:
47
+ #ifdef Py_GIL_DISABLED
48
+ int rank{0};
49
+ union {
50
+ PyCriticalSection section;
51
+ PyCriticalSection2 section2;
52
+ };
53
+ #endif
54
+ };
55
+
56
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/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 <wenzel.jakob@epfl.ch>
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"
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/tensor.h ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <pybind11/numpy.h>
11
+
12
+ #include "common.h"
13
+
14
+ #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
15
+ static_assert(__GNUC__ > 5, "Eigen Tensor support in pybind11 requires GCC > 5.0");
16
+ #endif
17
+
18
+ // Disable warnings for Eigen
19
+ PYBIND11_WARNING_PUSH
20
+ PYBIND11_WARNING_DISABLE_MSVC(4554)
21
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
22
+ #if defined(__MINGW32__)
23
+ PYBIND11_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
24
+ #endif
25
+
26
+ #include <unsupported/Eigen/CXX11/Tensor>
27
+
28
+ PYBIND11_WARNING_POP
29
+
30
+ static_assert(EIGEN_VERSION_AT_LEAST(3, 3, 0),
31
+ "Eigen Tensor support in pybind11 requires Eigen >= 3.3.0");
32
+
33
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
34
+
35
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
36
+
37
+ PYBIND11_NAMESPACE_BEGIN(detail)
38
+
39
+ inline bool is_tensor_aligned(const void *data) {
40
+ return (reinterpret_cast<std::size_t>(data) % EIGEN_DEFAULT_ALIGN_BYTES) == 0;
41
+ }
42
+
43
+ template <typename T>
44
+ constexpr int compute_array_flag_from_tensor() {
45
+ static_assert((static_cast<int>(T::Layout) == static_cast<int>(Eigen::RowMajor))
46
+ || (static_cast<int>(T::Layout) == static_cast<int>(Eigen::ColMajor)),
47
+ "Layout must be row or column major");
48
+ return (static_cast<int>(T::Layout) == static_cast<int>(Eigen::RowMajor)) ? array::c_style
49
+ : array::f_style;
50
+ }
51
+
52
+ template <typename T>
53
+ struct eigen_tensor_helper {};
54
+
55
+ template <typename Scalar_, int NumIndices_, int Options_, typename IndexType>
56
+ struct eigen_tensor_helper<Eigen::Tensor<Scalar_, NumIndices_, Options_, IndexType>> {
57
+ using Type = Eigen::Tensor<Scalar_, NumIndices_, Options_, IndexType>;
58
+ using ValidType = void;
59
+
60
+ static Eigen::DSizes<typename Type::Index, Type::NumIndices> get_shape(const Type &f) {
61
+ return f.dimensions();
62
+ }
63
+
64
+ static constexpr bool
65
+ is_correct_shape(const Eigen::DSizes<typename Type::Index, Type::NumIndices> & /*shape*/) {
66
+ return true;
67
+ }
68
+
69
+ template <typename T>
70
+ struct helper {};
71
+
72
+ template <size_t... Is>
73
+ struct helper<index_sequence<Is...>> {
74
+ static constexpr auto value = ::pybind11::detail::concat(const_name(((void) Is, "?"))...);
75
+ };
76
+
77
+ static constexpr auto dimensions_descriptor
78
+ = helper<decltype(make_index_sequence<Type::NumIndices>())>::value;
79
+
80
+ template <typename... Args>
81
+ static Type *alloc(Args &&...args) {
82
+ return new Type(std::forward<Args>(args)...);
83
+ }
84
+
85
+ static void free(Type *tensor) { delete tensor; }
86
+ };
87
+
88
+ template <typename Scalar_, typename std::ptrdiff_t... Indices, int Options_, typename IndexType>
89
+ struct eigen_tensor_helper<
90
+ Eigen::TensorFixedSize<Scalar_, Eigen::Sizes<Indices...>, Options_, IndexType>> {
91
+ using Type = Eigen::TensorFixedSize<Scalar_, Eigen::Sizes<Indices...>, Options_, IndexType>;
92
+ using ValidType = void;
93
+
94
+ static constexpr Eigen::DSizes<typename Type::Index, Type::NumIndices>
95
+ get_shape(const Type & /*f*/) {
96
+ return get_shape();
97
+ }
98
+
99
+ static constexpr Eigen::DSizes<typename Type::Index, Type::NumIndices> get_shape() {
100
+ return Eigen::DSizes<typename Type::Index, Type::NumIndices>(Indices...);
101
+ }
102
+
103
+ static bool
104
+ is_correct_shape(const Eigen::DSizes<typename Type::Index, Type::NumIndices> &shape) {
105
+ return get_shape() == shape;
106
+ }
107
+
108
+ static constexpr auto dimensions_descriptor
109
+ = ::pybind11::detail::concat(const_name<Indices>()...);
110
+
111
+ template <typename... Args>
112
+ static Type *alloc(Args &&...args) {
113
+ Eigen::aligned_allocator<Type> allocator;
114
+ return ::new (allocator.allocate(1)) Type(std::forward<Args>(args)...);
115
+ }
116
+
117
+ static void free(Type *tensor) {
118
+ Eigen::aligned_allocator<Type> allocator;
119
+ tensor->~Type();
120
+ allocator.deallocate(tensor, 1);
121
+ }
122
+ };
123
+
124
+ template <typename Type, bool ShowDetails, bool NeedsWriteable = false>
125
+ struct get_tensor_descriptor {
126
+ static constexpr auto details
127
+ = const_name<NeedsWriteable>(", \"flags.writeable\"", "")
128
+ + const_name<static_cast<int>(Type::Layout) == static_cast<int>(Eigen::RowMajor)>(
129
+ ", \"flags.c_contiguous\"", ", \"flags.f_contiguous\"");
130
+ static constexpr auto value
131
+ = const_name("typing.Annotated[")
132
+ + io_name("numpy.typing.ArrayLike, ", "numpy.typing.NDArray[")
133
+ + npy_format_descriptor<typename Type::Scalar>::name + io_name("", "]")
134
+ + const_name(", \"[") + eigen_tensor_helper<remove_cv_t<Type>>::dimensions_descriptor
135
+ + const_name("]\"") + const_name<ShowDetails>(details, const_name("")) + const_name("]");
136
+ };
137
+
138
+ // When EIGEN_AVOID_STL_ARRAY is defined, Eigen::DSizes<T, 0> does not have the begin() member
139
+ // function. Falling back to a simple loop works around this issue.
140
+ //
141
+ // We need to disable the type-limits warning for the inner loop when size = 0.
142
+
143
+ PYBIND11_WARNING_PUSH
144
+ PYBIND11_WARNING_DISABLE_GCC("-Wtype-limits")
145
+
146
+ template <typename T, int size>
147
+ std::vector<T> convert_dsizes_to_vector(const Eigen::DSizes<T, size> &arr) {
148
+ std::vector<T> result(size);
149
+
150
+ for (size_t i = 0; i < size; i++) {
151
+ result[i] = arr[i];
152
+ }
153
+
154
+ return result;
155
+ }
156
+
157
+ template <typename T, int size>
158
+ Eigen::DSizes<T, size> get_shape_for_array(const array &arr) {
159
+ Eigen::DSizes<T, size> result;
160
+ const T *shape = arr.shape();
161
+ for (size_t i = 0; i < size; i++) {
162
+ result[i] = shape[i];
163
+ }
164
+
165
+ return result;
166
+ }
167
+
168
+ PYBIND11_WARNING_POP
169
+
170
+ template <typename Type>
171
+ struct type_caster<Type, typename eigen_tensor_helper<Type>::ValidType> {
172
+ static_assert(!std::is_pointer<typename Type::Scalar>::value,
173
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
174
+ using Helper = eigen_tensor_helper<Type>;
175
+ static constexpr auto temp_name = get_tensor_descriptor<Type, false>::value;
176
+ PYBIND11_TYPE_CASTER(Type, temp_name);
177
+
178
+ bool load(handle src, bool convert) {
179
+ if (!convert) {
180
+ if (!isinstance<array>(src)) {
181
+ return false;
182
+ }
183
+ array temp = array::ensure(src);
184
+ if (!temp) {
185
+ return false;
186
+ }
187
+
188
+ if (!temp.dtype().is(dtype::of<typename Type::Scalar>())) {
189
+ return false;
190
+ }
191
+ }
192
+
193
+ array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()> arr(
194
+ reinterpret_borrow<object>(src));
195
+
196
+ if (arr.ndim() != Type::NumIndices) {
197
+ return false;
198
+ }
199
+ auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);
200
+
201
+ if (!Helper::is_correct_shape(shape)) {
202
+ return false;
203
+ }
204
+
205
+ #if EIGEN_VERSION_AT_LEAST(3, 4, 0)
206
+ auto data_pointer = arr.data();
207
+ #else
208
+ // Handle Eigen bug
209
+ auto data_pointer = const_cast<typename Type::Scalar *>(arr.data());
210
+ #endif
211
+
212
+ if (is_tensor_aligned(arr.data())) {
213
+ value = Eigen::TensorMap<const Type, Eigen::Aligned>(data_pointer, shape);
214
+ } else {
215
+ value = Eigen::TensorMap<const Type>(data_pointer, shape);
216
+ }
217
+
218
+ return true;
219
+ }
220
+
221
+ static handle cast(Type &&src, return_value_policy policy, handle parent) {
222
+ if (policy == return_value_policy::reference
223
+ || policy == return_value_policy::reference_internal) {
224
+ pybind11_fail("Cannot use a reference return value policy for an rvalue");
225
+ }
226
+ return cast_impl(&src, return_value_policy::move, parent);
227
+ }
228
+
229
+ static handle cast(const Type &&src, return_value_policy policy, handle parent) {
230
+ if (policy == return_value_policy::reference
231
+ || policy == return_value_policy::reference_internal) {
232
+ pybind11_fail("Cannot use a reference return value policy for an rvalue");
233
+ }
234
+ return cast_impl(&src, return_value_policy::move, parent);
235
+ }
236
+
237
+ static handle cast(Type &src, return_value_policy policy, handle parent) {
238
+ if (policy == return_value_policy::automatic
239
+ || policy == return_value_policy::automatic_reference) {
240
+ policy = return_value_policy::copy;
241
+ }
242
+ return cast_impl(&src, policy, parent);
243
+ }
244
+
245
+ static handle cast(const Type &src, return_value_policy policy, handle parent) {
246
+ if (policy == return_value_policy::automatic
247
+ || policy == return_value_policy::automatic_reference) {
248
+ policy = return_value_policy::copy;
249
+ }
250
+ return cast(&src, policy, parent);
251
+ }
252
+
253
+ static handle cast(Type *src, return_value_policy policy, handle parent) {
254
+ if (policy == return_value_policy::automatic) {
255
+ policy = return_value_policy::take_ownership;
256
+ } else if (policy == return_value_policy::automatic_reference) {
257
+ policy = return_value_policy::reference;
258
+ }
259
+ return cast_impl(src, policy, parent);
260
+ }
261
+
262
+ static handle cast(const Type *src, return_value_policy policy, handle parent) {
263
+ if (policy == return_value_policy::automatic) {
264
+ policy = return_value_policy::take_ownership;
265
+ } else if (policy == return_value_policy::automatic_reference) {
266
+ policy = return_value_policy::reference;
267
+ }
268
+ return cast_impl(src, policy, parent);
269
+ }
270
+
271
+ template <typename C>
272
+ static handle cast_impl(C *src, return_value_policy policy, handle parent) {
273
+ object parent_object;
274
+ bool writeable = false;
275
+ switch (policy) {
276
+ case return_value_policy::move:
277
+ if (std::is_const<C>::value) {
278
+ pybind11_fail("Cannot move from a constant reference");
279
+ }
280
+
281
+ src = Helper::alloc(std::move(*src));
282
+
283
+ parent_object
284
+ = capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });
285
+ writeable = true;
286
+ break;
287
+
288
+ case return_value_policy::take_ownership:
289
+ if (std::is_const<C>::value) {
290
+ // This cast is ugly, and might be UB in some cases, but we don't have an
291
+ // alternative here as we must free that memory
292
+ Helper::free(const_cast<Type *>(src));
293
+ pybind11_fail("Cannot take ownership of a const reference");
294
+ }
295
+
296
+ parent_object
297
+ = capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });
298
+ writeable = true;
299
+ break;
300
+
301
+ case return_value_policy::copy:
302
+ writeable = true;
303
+ break;
304
+
305
+ case return_value_policy::reference:
306
+ parent_object = none();
307
+ writeable = !std::is_const<C>::value;
308
+ break;
309
+
310
+ case return_value_policy::reference_internal:
311
+ // Default should do the right thing
312
+ if (!parent) {
313
+ pybind11_fail("Cannot use reference internal when there is no parent");
314
+ }
315
+ parent_object = reinterpret_borrow<object>(parent);
316
+ writeable = !std::is_const<C>::value;
317
+ break;
318
+
319
+ default:
320
+ pybind11_fail("pybind11 bug in eigen.h, please file a bug report");
321
+ }
322
+
323
+ auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(
324
+ convert_dsizes_to_vector(Helper::get_shape(*src)), src->data(), parent_object);
325
+
326
+ if (!writeable) {
327
+ array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
328
+ }
329
+
330
+ return result.release();
331
+ }
332
+ };
333
+
334
+ template <typename StoragePointerType,
335
+ bool needs_writeable,
336
+ enable_if_t<!needs_writeable, bool> = true>
337
+ StoragePointerType get_array_data_for_type(array &arr) {
338
+ #if EIGEN_VERSION_AT_LEAST(3, 4, 0)
339
+ return reinterpret_cast<StoragePointerType>(arr.data());
340
+ #else
341
+ // Handle Eigen bug
342
+ return reinterpret_cast<StoragePointerType>(const_cast<void *>(arr.data()));
343
+ #endif
344
+ }
345
+
346
+ template <typename StoragePointerType,
347
+ bool needs_writeable,
348
+ enable_if_t<needs_writeable, bool> = true>
349
+ StoragePointerType get_array_data_for_type(array &arr) {
350
+ return reinterpret_cast<StoragePointerType>(arr.mutable_data());
351
+ }
352
+
353
+ template <typename T, typename = void>
354
+ struct get_storage_pointer_type;
355
+
356
+ template <typename MapType>
357
+ struct get_storage_pointer_type<MapType, void_t<typename MapType::StoragePointerType>> {
358
+ using SPT = typename MapType::StoragePointerType;
359
+ };
360
+
361
+ template <typename MapType>
362
+ struct get_storage_pointer_type<MapType, void_t<typename MapType::PointerArgType>> {
363
+ using SPT = typename MapType::PointerArgType;
364
+ };
365
+
366
+ template <typename Type, int Options>
367
+ struct type_caster<Eigen::TensorMap<Type, Options>,
368
+ typename eigen_tensor_helper<remove_cv_t<Type>>::ValidType> {
369
+ static_assert(!std::is_pointer<typename Type::Scalar>::value,
370
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
371
+ using MapType = Eigen::TensorMap<Type, Options>;
372
+ using Helper = eigen_tensor_helper<remove_cv_t<Type>>;
373
+
374
+ bool load(handle src, bool /*convert*/) {
375
+ // Note that we have a lot more checks here as we want to make sure to avoid copies
376
+ if (!isinstance<array>(src)) {
377
+ return false;
378
+ }
379
+ auto arr = reinterpret_borrow<array>(src);
380
+ if ((arr.flags() & compute_array_flag_from_tensor<Type>()) == 0) {
381
+ return false;
382
+ }
383
+
384
+ if (!arr.dtype().is(dtype::of<typename Type::Scalar>())) {
385
+ return false;
386
+ }
387
+
388
+ if (arr.ndim() != Type::NumIndices) {
389
+ return false;
390
+ }
391
+
392
+ constexpr bool is_aligned = (Options & Eigen::Aligned) != 0;
393
+
394
+ if (is_aligned && !is_tensor_aligned(arr.data())) {
395
+ return false;
396
+ }
397
+
398
+ auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);
399
+
400
+ if (!Helper::is_correct_shape(shape)) {
401
+ return false;
402
+ }
403
+
404
+ if (needs_writeable && !arr.writeable()) {
405
+ return false;
406
+ }
407
+
408
+ auto result = get_array_data_for_type<typename get_storage_pointer_type<MapType>::SPT,
409
+ needs_writeable>(arr);
410
+
411
+ value.reset(new MapType(std::move(result), std::move(shape)));
412
+
413
+ return true;
414
+ }
415
+
416
+ static handle cast(MapType &&src, return_value_policy policy, handle parent) {
417
+ return cast_impl(&src, policy, parent);
418
+ }
419
+
420
+ static handle cast(const MapType &&src, return_value_policy policy, handle parent) {
421
+ return cast_impl(&src, policy, parent);
422
+ }
423
+
424
+ static handle cast(MapType &src, return_value_policy policy, handle parent) {
425
+ if (policy == return_value_policy::automatic
426
+ || policy == return_value_policy::automatic_reference) {
427
+ policy = return_value_policy::copy;
428
+ }
429
+ return cast_impl(&src, policy, parent);
430
+ }
431
+
432
+ static handle cast(const MapType &src, return_value_policy policy, handle parent) {
433
+ if (policy == return_value_policy::automatic
434
+ || policy == return_value_policy::automatic_reference) {
435
+ policy = return_value_policy::copy;
436
+ }
437
+ return cast(&src, policy, parent);
438
+ }
439
+
440
+ static handle cast(MapType *src, return_value_policy policy, handle parent) {
441
+ if (policy == return_value_policy::automatic) {
442
+ policy = return_value_policy::take_ownership;
443
+ } else if (policy == return_value_policy::automatic_reference) {
444
+ policy = return_value_policy::reference;
445
+ }
446
+ return cast_impl(src, policy, parent);
447
+ }
448
+
449
+ static handle cast(const MapType *src, return_value_policy policy, handle parent) {
450
+ if (policy == return_value_policy::automatic) {
451
+ policy = return_value_policy::take_ownership;
452
+ } else if (policy == return_value_policy::automatic_reference) {
453
+ policy = return_value_policy::reference;
454
+ }
455
+ return cast_impl(src, policy, parent);
456
+ }
457
+
458
+ template <typename C>
459
+ static handle cast_impl(C *src, return_value_policy policy, handle parent) {
460
+ object parent_object;
461
+ constexpr bool writeable = !std::is_const<C>::value;
462
+ switch (policy) {
463
+ case return_value_policy::reference:
464
+ parent_object = none();
465
+ break;
466
+
467
+ case return_value_policy::reference_internal:
468
+ // Default should do the right thing
469
+ if (!parent) {
470
+ pybind11_fail("Cannot use reference internal when there is no parent");
471
+ }
472
+ parent_object = reinterpret_borrow<object>(parent);
473
+ break;
474
+
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
+ // return_descr forces the use of NDArray instead of ArrayLike since refs can only reference
508
+ // arrays
509
+ static constexpr auto name
510
+ = return_descr(get_tensor_descriptor<Type, true, needs_writeable>::value);
511
+ explicit operator MapType *() { return value.get(); }
512
+ explicit operator MapType &() { return *value; }
513
+ explicit operator MapType &&() && { return std::move(*value); }
514
+
515
+ template <typename T_>
516
+ using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>;
517
+ };
518
+
519
+ PYBIND11_NAMESPACE_END(detail)
520
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/embed.h ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/embed.h: Support for embedding the interpreter
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ #include "eval.h"
14
+
15
+ #include <memory>
16
+ #include <vector>
17
+
18
+ #if defined(PYPY_VERSION)
19
+ # error Embedding the interpreter is not supported with PyPy
20
+ #endif
21
+
22
+ #define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
23
+ extern "C" PyObject *pybind11_init_impl_##name(); \
24
+ extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }
25
+
26
+ /** \rst
27
+ Add a new module to the table of builtins for the interpreter. Must be
28
+ defined in global scope. The first macro parameter is the name of the
29
+ module (without quotes). The second parameter is the variable which will
30
+ be used as the interface to add functions and classes to the module.
31
+
32
+ .. code-block:: cpp
33
+
34
+ PYBIND11_EMBEDDED_MODULE(example, m) {
35
+ // ... initialize functions and classes here
36
+ m.def("foo", []() {
37
+ return "Hello, World!";
38
+ });
39
+ }
40
+
41
+ The third and subsequent macro arguments are optional, and can be used to
42
+ mark the module as supporting various Python features.
43
+
44
+ - ``mod_gil_not_used()``
45
+ - ``multiple_interpreters::per_interpreter_gil()``
46
+ - ``multiple_interpreters::shared_gil()``
47
+ - ``multiple_interpreters::not_supported()``
48
+
49
+ .. code-block:: cpp
50
+
51
+ PYBIND11_EMBEDDED_MODULE(example, m, py::mod_gil_not_used()) {
52
+ m.def("foo", []() {
53
+ return "Hello, Free-threaded World!";
54
+ });
55
+ }
56
+
57
+ \endrst */
58
+ PYBIND11_WARNING_PUSH
59
+ PYBIND11_WARNING_DISABLE_CLANG("-Wgnu-zero-variadic-macro-arguments")
60
+ #define PYBIND11_EMBEDDED_MODULE(name, variable, ...) \
61
+ PYBIND11_MODULE_PYINIT(name, ##__VA_ARGS__) \
62
+ ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \
63
+ PYBIND11_TOSTRING(name), PYBIND11_CONCAT(PyInit_, name)); \
64
+ PYBIND11_MODULE_EXEC(name, variable)
65
+ PYBIND11_WARNING_POP
66
+
67
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
68
+ PYBIND11_NAMESPACE_BEGIN(detail)
69
+
70
+ /// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.
71
+ struct embedded_module {
72
+ using init_t = PyObject *(*) ();
73
+ embedded_module(const char *name, init_t init) {
74
+ if (Py_IsInitialized() != 0) {
75
+ pybind11_fail("Can't add new modules after the interpreter has been initialized");
76
+ }
77
+
78
+ auto result = PyImport_AppendInittab(name, init);
79
+ if (result == -1) {
80
+ pybind11_fail("Insufficient memory to add a new module");
81
+ }
82
+ }
83
+ };
84
+
85
+ struct wide_char_arg_deleter {
86
+ void operator()(wchar_t *ptr) const {
87
+ // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale
88
+ PyMem_RawFree(ptr);
89
+ }
90
+ };
91
+
92
+ inline wchar_t *widen_chars(const char *safe_arg) {
93
+ wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);
94
+ return widened_arg;
95
+ }
96
+
97
+ inline void precheck_interpreter() {
98
+ if (Py_IsInitialized() != 0) {
99
+ pybind11_fail("The interpreter is already running");
100
+ }
101
+ }
102
+
103
+ #if !defined(PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX)
104
+ # define PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX (0x03080000)
105
+ #endif
106
+
107
+ #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
108
+ inline void initialize_interpreter_pre_pyconfig(bool init_signal_handlers,
109
+ int argc,
110
+ const char *const *argv,
111
+ bool add_program_dir_to_path) {
112
+ detail::precheck_interpreter();
113
+ Py_InitializeEx(init_signal_handlers ? 1 : 0);
114
+
115
+ auto argv_size = static_cast<size_t>(argc);
116
+ // SetArgv* on python 3 takes wchar_t, so we have to convert.
117
+ std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
118
+ std::vector<std::unique_ptr<wchar_t[], detail::wide_char_arg_deleter>> widened_argv_entries;
119
+ widened_argv_entries.reserve(argv_size);
120
+ for (size_t ii = 0; ii < argv_size; ++ii) {
121
+ widened_argv_entries.emplace_back(detail::widen_chars(argv[ii]));
122
+ if (!widened_argv_entries.back()) {
123
+ // A null here indicates a character-encoding failure or the python
124
+ // interpreter out of memory. Give up.
125
+ return;
126
+ }
127
+ widened_argv[ii] = widened_argv_entries.back().get();
128
+ }
129
+
130
+ auto *pysys_argv = widened_argv.get();
131
+
132
+ PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
133
+ }
134
+ #endif
135
+
136
+ PYBIND11_NAMESPACE_END(detail)
137
+
138
+ #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
139
+ inline void initialize_interpreter(PyConfig *config,
140
+ int argc = 0,
141
+ const char *const *argv = nullptr,
142
+ bool add_program_dir_to_path = true) {
143
+ detail::precheck_interpreter();
144
+ PyStatus status = PyConfig_SetBytesArgv(config, argc, const_cast<char *const *>(argv));
145
+ if (PyStatus_Exception(status) != 0) {
146
+ // A failure here indicates a character-encoding failure or the python
147
+ // interpreter out of memory. Give up.
148
+ PyConfig_Clear(config);
149
+ throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
150
+ : "Failed to prepare CPython");
151
+ }
152
+ status = Py_InitializeFromConfig(config);
153
+ if (PyStatus_Exception(status) != 0) {
154
+ PyConfig_Clear(config);
155
+ throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
156
+ : "Failed to init CPython");
157
+ }
158
+ if (add_program_dir_to_path) {
159
+ PyRun_SimpleString("import sys, os.path; "
160
+ "sys.path.insert(0, "
161
+ "os.path.abspath(os.path.dirname(sys.argv[0])) "
162
+ "if sys.argv and os.path.exists(sys.argv[0]) else '')");
163
+ }
164
+ PyConfig_Clear(config);
165
+ }
166
+ #endif
167
+
168
+ /** \rst
169
+ Initialize the Python interpreter. No other pybind11 or CPython API functions can be
170
+ called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The
171
+ optional `init_signal_handlers` parameter can be used to skip the registration of
172
+ signal handlers (see the `Python documentation`_ for details). Calling this function
173
+ again after the interpreter has already been initialized is a fatal error.
174
+
175
+ If initializing the Python interpreter fails, then the program is terminated. (This
176
+ is controlled by the CPython runtime and is an exception to pybind11's normal behavior
177
+ of throwing exceptions on errors.)
178
+
179
+ The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are
180
+ used to populate ``sys.argv`` and ``sys.path``.
181
+ See the |PySys_SetArgvEx documentation|_ for details.
182
+
183
+ .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
184
+ .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation
185
+ .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx
186
+ \endrst */
187
+ inline void initialize_interpreter(bool init_signal_handlers = true,
188
+ int argc = 0,
189
+ const char *const *argv = nullptr,
190
+ bool add_program_dir_to_path = true) {
191
+ #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
192
+ detail::initialize_interpreter_pre_pyconfig(
193
+ init_signal_handlers, argc, argv, add_program_dir_to_path);
194
+ #else
195
+ PyConfig config;
196
+ PyConfig_InitPythonConfig(&config);
197
+ // See PR #4473 for background
198
+ config.parse_argv = 0;
199
+
200
+ config.install_signal_handlers = init_signal_handlers ? 1 : 0;
201
+ initialize_interpreter(&config, argc, argv, add_program_dir_to_path);
202
+ #endif
203
+
204
+ // There is exactly one interpreter alive currently.
205
+ detail::has_seen_non_main_interpreter() = false;
206
+ }
207
+
208
+ /** \rst
209
+ Shut down the Python interpreter. No pybind11 or CPython API functions can be called
210
+ after this. In addition, pybind11 objects must not outlive the interpreter:
211
+
212
+ .. code-block:: cpp
213
+
214
+ { // BAD
215
+ py::initialize_interpreter();
216
+ auto hello = py::str("Hello, World!");
217
+ py::finalize_interpreter();
218
+ } // <-- BOOM, hello's destructor is called after interpreter shutdown
219
+
220
+ { // GOOD
221
+ py::initialize_interpreter();
222
+ { // scoped
223
+ auto hello = py::str("Hello, World!");
224
+ } // <-- OK, hello is cleaned up properly
225
+ py::finalize_interpreter();
226
+ }
227
+
228
+ { // BETTER
229
+ py::scoped_interpreter guard{};
230
+ auto hello = py::str("Hello, World!");
231
+ }
232
+
233
+ .. warning::
234
+
235
+ The interpreter can be restarted by calling `initialize_interpreter` again.
236
+ Modules created using pybind11 can be safely re-initialized. However, Python
237
+ itself cannot completely unload binary extension modules and there are several
238
+ caveats with regard to interpreter restarting. All the details can be found
239
+ in the CPython documentation. In short, not all interpreter memory may be
240
+ freed, either due to reference cycles or user-created global data.
241
+
242
+ \endrst */
243
+ inline void finalize_interpreter() {
244
+ // get rid of any thread-local interpreter cache that currently exists
245
+ if (detail::has_seen_non_main_interpreter()) {
246
+ detail::get_internals_pp_manager().unref();
247
+ detail::get_local_internals_pp_manager().unref();
248
+
249
+ // We know there can be no other interpreter alive now
250
+ detail::has_seen_non_main_interpreter() = false;
251
+ }
252
+
253
+ // Re-fetch the internals pointer-to-pointer (but not the internals itself, which might not
254
+ // exist). It's possible for the internals to be created during Py_Finalize() (e.g. if a
255
+ // py::capsule calls `get_internals()` during destruction), so we get the pointer-pointer here
256
+ // and check it after Py_Finalize().
257
+ detail::get_internals_pp_manager().get_pp();
258
+ detail::get_local_internals_pp_manager().get_pp();
259
+
260
+ Py_Finalize();
261
+
262
+ detail::get_internals_pp_manager().destroy();
263
+
264
+ // Local internals contains data managed by the current interpreter, so we must clear them to
265
+ // avoid undefined behaviors when initializing another interpreter
266
+ detail::get_local_internals_pp_manager().destroy();
267
+
268
+ // We know there is no interpreter alive now, so we can reset the multi-flag
269
+ detail::has_seen_non_main_interpreter() = false;
270
+ }
271
+
272
+ /** \rst
273
+ Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
274
+ This a move-only guard and only a single instance can exist.
275
+
276
+ See `initialize_interpreter` for a discussion of its constructor arguments.
277
+
278
+ .. code-block:: cpp
279
+
280
+ #include <pybind11/embed.h>
281
+
282
+ int main() {
283
+ py::scoped_interpreter guard{};
284
+ py::print(Hello, World!);
285
+ } // <-- interpreter shutdown
286
+ \endrst */
287
+ class scoped_interpreter {
288
+ public:
289
+ explicit scoped_interpreter(bool init_signal_handlers = true,
290
+ int argc = 0,
291
+ const char *const *argv = nullptr,
292
+ bool add_program_dir_to_path = true) {
293
+ initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
294
+ }
295
+
296
+ #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
297
+ explicit scoped_interpreter(PyConfig *config,
298
+ int argc = 0,
299
+ const char *const *argv = nullptr,
300
+ bool add_program_dir_to_path = true) {
301
+ initialize_interpreter(config, argc, argv, add_program_dir_to_path);
302
+ }
303
+ #endif
304
+
305
+ scoped_interpreter(const scoped_interpreter &) = delete;
306
+ scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
307
+ scoped_interpreter &operator=(const scoped_interpreter &) = delete;
308
+ scoped_interpreter &operator=(scoped_interpreter &&) = delete;
309
+
310
+ ~scoped_interpreter() {
311
+ if (is_valid) {
312
+ finalize_interpreter();
313
+ }
314
+ }
315
+
316
+ private:
317
+ bool is_valid = true;
318
+ };
319
+
320
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/eval.h ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eval.h: Support for evaluating Python expressions and statements
3
+ from strings and files
4
+
5
+ Copyright (c) 2016 Klemens Morgenstern <klemens.morgenstern@ed-chemnitz.de> and
6
+ Wenzel Jakob <wenzel.jakob@epfl.ch>
7
+
8
+ All rights reserved. Use of this source code is governed by a
9
+ BSD-style license that can be found in the LICENSE file.
10
+ */
11
+
12
+ #pragma once
13
+
14
+ #include "pybind11.h"
15
+
16
+ #include <utility>
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19
+ PYBIND11_NAMESPACE_BEGIN(detail)
20
+
21
+ inline void ensure_builtins_in_globals(object &global) {
22
+ #if defined(PYPY_VERSION)
23
+ // Running exec and eval adds `builtins` module under `__builtins__` key to
24
+ // globals if not yet present. Python 3.8 made PyRun_String behave
25
+ // similarly. Let's also do that for older versions, for consistency. This
26
+ // was missing from PyPy3.8 7.3.7.
27
+ if (!global.contains("__builtins__"))
28
+ global["__builtins__"] = module_::import(PYBIND11_BUILTINS_MODULE);
29
+ #else
30
+ (void) global;
31
+ #endif
32
+ }
33
+
34
+ PYBIND11_NAMESPACE_END(detail)
35
+
36
+ enum eval_mode {
37
+ /// Evaluate a string containing an isolated expression
38
+ eval_expr,
39
+
40
+ /// Evaluate a string containing a single statement. Returns \c none
41
+ eval_single_statement,
42
+
43
+ /// Evaluate a string containing a sequence of statement. Returns \c none
44
+ eval_statements
45
+ };
46
+
47
+ template <eval_mode mode = eval_expr>
48
+ object eval(const str &expr, object global = globals(), object local = object()) {
49
+ if (!local) {
50
+ local = global;
51
+ }
52
+
53
+ detail::ensure_builtins_in_globals(global);
54
+
55
+ /* PyRun_String does not accept a PyObject / encoding specifier,
56
+ this seems to be the only alternative */
57
+ std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr;
58
+
59
+ int start = 0;
60
+ switch (mode) {
61
+ case eval_expr:
62
+ start = Py_eval_input;
63
+ break;
64
+ case eval_single_statement:
65
+ start = Py_single_input;
66
+ break;
67
+ case eval_statements:
68
+ start = Py_file_input;
69
+ break;
70
+ default:
71
+ pybind11_fail("invalid evaluation mode");
72
+ }
73
+
74
+ PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr());
75
+ if (!result) {
76
+ throw error_already_set();
77
+ }
78
+ return reinterpret_steal<object>(result);
79
+ }
80
+
81
+ template <eval_mode mode = eval_expr, size_t N>
82
+ object eval(const char (&s)[N], object global = globals(), object local = object()) {
83
+ /* Support raw string literals by removing common leading whitespace */
84
+ auto expr = (s[0] == '\n') ? str(module_::import("textwrap").attr("dedent")(s)) : str(s);
85
+ return eval<mode>(expr, std::move(global), std::move(local));
86
+ }
87
+
88
+ inline void exec(const str &expr, object global = globals(), object local = object()) {
89
+ eval<eval_statements>(expr, std::move(global), std::move(local));
90
+ }
91
+
92
+ template <size_t N>
93
+ void exec(const char (&s)[N], object global = globals(), object local = object()) {
94
+ eval<eval_statements>(s, std::move(global), std::move(local));
95
+ }
96
+
97
+ #if defined(PYPY_VERSION) || defined(GRAALVM_PYTHON)
98
+ template <eval_mode mode = eval_statements>
99
+ object eval_file(str, object, object) {
100
+ pybind11_fail("eval_file not supported in this interpreter. Use eval");
101
+ }
102
+ template <eval_mode mode = eval_statements>
103
+ object eval_file(str, object) {
104
+ pybind11_fail("eval_file not supported in this interpreter. Use eval");
105
+ }
106
+ template <eval_mode mode = eval_statements>
107
+ object eval_file(str) {
108
+ pybind11_fail("eval_file not supported in this interpreter. Use eval");
109
+ }
110
+ #else
111
+ template <eval_mode mode = eval_statements>
112
+ object eval_file(str fname, object global = globals(), object local = object()) {
113
+ if (!local) {
114
+ local = global;
115
+ }
116
+
117
+ detail::ensure_builtins_in_globals(global);
118
+
119
+ int start = 0;
120
+ switch (mode) {
121
+ case eval_expr:
122
+ start = Py_eval_input;
123
+ break;
124
+ case eval_single_statement:
125
+ start = Py_single_input;
126
+ break;
127
+ case eval_statements:
128
+ start = Py_file_input;
129
+ break;
130
+ default:
131
+ pybind11_fail("invalid evaluation mode");
132
+ }
133
+
134
+ int closeFile = 1;
135
+ std::string fname_str = (std::string) fname;
136
+ FILE *f =
137
+ # if PY_VERSION_HEX >= 0x030E0000
138
+ Py_fopen(fname.ptr(), "r");
139
+ # else
140
+ _Py_fopen_obj(fname.ptr(), "r");
141
+ # endif
142
+ if (!f) {
143
+ PyErr_Clear();
144
+ pybind11_fail("File \"" + fname_str + "\" could not be opened!");
145
+ }
146
+
147
+ if (!global.contains("__file__")) {
148
+ global["__file__"] = std::move(fname);
149
+ }
150
+
151
+ PyObject *result
152
+ = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile);
153
+
154
+ if (!result) {
155
+ throw error_already_set();
156
+ }
157
+ return reinterpret_steal<object>(result);
158
+ }
159
+ #endif
160
+
161
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/functional.h ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/functional.h: std::function<> support
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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 <functional>
15
+
16
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
17
+ PYBIND11_NAMESPACE_BEGIN(detail)
18
+ PYBIND11_NAMESPACE_BEGIN(type_caster_std_function_specializations)
19
+
20
+ // ensure GIL is held during functor destruction
21
+ struct func_handle {
22
+ function f;
23
+ #if !(defined(_MSC_VER) && _MSC_VER == 1916 && defined(PYBIND11_CPP17))
24
+ // This triggers a syntax error under very special conditions (very weird indeed).
25
+ explicit
26
+ #endif
27
+ func_handle(function &&f_) noexcept
28
+ : f(std::move(f_)) {
29
+ }
30
+ func_handle(const func_handle &f_) { operator=(f_); }
31
+ func_handle &operator=(const func_handle &f_) {
32
+ gil_scoped_acquire acq;
33
+ f = f_.f;
34
+ return *this;
35
+ }
36
+ ~func_handle() {
37
+ gil_scoped_acquire acq;
38
+ function kill_f(std::move(f));
39
+ }
40
+ };
41
+
42
+ // to emulate 'move initialization capture' in C++11
43
+ struct func_wrapper_base {
44
+ func_handle hfunc;
45
+ explicit func_wrapper_base(func_handle &&hf) noexcept : hfunc(hf) {}
46
+ };
47
+
48
+ template <typename Return, typename... Args>
49
+ struct func_wrapper : func_wrapper_base {
50
+ using func_wrapper_base::func_wrapper_base;
51
+ Return operator()(Args... args) const { // NOLINT(performance-unnecessary-value-param)
52
+ gil_scoped_acquire acq;
53
+ // casts the returned object as a rvalue to the return type
54
+ return hfunc.f(std::forward<Args>(args)...).template cast<Return>();
55
+ }
56
+ };
57
+
58
+ PYBIND11_NAMESPACE_END(type_caster_std_function_specializations)
59
+
60
+ template <typename Return, typename... Args>
61
+ struct type_caster<std::function<Return(Args...)>> {
62
+ using type = std::function<Return(Args...)>;
63
+ using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
64
+ using function_type = Return (*)(Args...);
65
+
66
+ public:
67
+ bool load(handle src, bool convert) {
68
+ if (src.is_none()) {
69
+ // Defer accepting None to other overloads (if we aren't in convert mode):
70
+ if (!convert) {
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+
76
+ if (!isinstance<function>(src)) {
77
+ return false;
78
+ }
79
+
80
+ auto func = reinterpret_borrow<function>(src);
81
+
82
+ /*
83
+ When passing a C++ function as an argument to another C++
84
+ function via Python, every function call would normally involve
85
+ a full C++ -> Python -> C++ roundtrip, which can be prohibitive.
86
+ Here, we try to at least detect the case where the function is
87
+ stateless (i.e. function pointer or lambda function without
88
+ captured variables), in which case the roundtrip can be avoided.
89
+ */
90
+ if (auto cfunc = func.cpp_function()) {
91
+ auto *cfunc_self = PyCFunction_GET_SELF(cfunc.ptr());
92
+ if (cfunc_self == nullptr) {
93
+ PyErr_Clear();
94
+ } else {
95
+ function_record *rec = function_record_ptr_from_PyObject(cfunc_self);
96
+ while (rec != nullptr) {
97
+ if (rec->is_stateless
98
+ && same_type(typeid(function_type),
99
+ *reinterpret_cast<const std::type_info *>(rec->data[1]))) {
100
+ struct capture {
101
+ function_type f;
102
+
103
+ static capture *from_data(void **data) {
104
+ return PYBIND11_STD_LAUNDER(reinterpret_cast<capture *>(data));
105
+ }
106
+ };
107
+ PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(
108
+ std::is_standard_layout<capture>::value);
109
+ value = capture::from_data(rec->data)->f;
110
+ return true;
111
+ }
112
+ rec = rec->next;
113
+ }
114
+ }
115
+ // PYPY segfaults here when passing builtin function like sum.
116
+ // Raising an fail exception here works to prevent the segfault, but only on gcc.
117
+ // See PR #1413 for full details
118
+ }
119
+
120
+ value = type_caster_std_function_specializations::func_wrapper<Return, Args...>(
121
+ type_caster_std_function_specializations::func_handle(std::move(func)));
122
+ return true;
123
+ }
124
+
125
+ template <typename Func>
126
+ static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {
127
+ if (!f_) {
128
+ return none().release();
129
+ }
130
+
131
+ auto result = f_.template target<function_type>();
132
+ if (result) {
133
+ return cpp_function(*result, policy).release();
134
+ }
135
+ return cpp_function(std::forward<Func>(f_), policy).release();
136
+ }
137
+
138
+ PYBIND11_TYPE_CASTER(
139
+ type,
140
+ const_name("collections.abc.Callable[[")
141
+ + ::pybind11::detail::concat(::pybind11::detail::arg_descr(make_caster<Args>::name)...)
142
+ + const_name("], ") + ::pybind11::detail::return_descr(make_caster<retval_type>::name)
143
+ + const_name("]"));
144
+ };
145
+
146
+ PYBIND11_NAMESPACE_END(detail)
147
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/gil.h ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/gil.h: RAII helpers for managing the GIL
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ #if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
13
+
14
+ # include "detail/common.h"
15
+ # include "gil_simple.h"
16
+
17
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
18
+
19
+ using gil_scoped_acquire = gil_scoped_acquire_simple;
20
+ using gil_scoped_release = gil_scoped_release_simple;
21
+
22
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
23
+
24
+ #else
25
+
26
+ # include "detail/common.h"
27
+ # include "detail/internals.h"
28
+
29
+ # include <cassert>
30
+
31
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
32
+
33
+ PYBIND11_NAMESPACE_BEGIN(detail)
34
+
35
+ PYBIND11_WARNING_PUSH
36
+ PYBIND11_WARNING_DISABLE_GCC("-Wredundant-decls")
37
+
38
+ // forward declarations
39
+ PyThreadState *get_thread_state_unchecked();
40
+
41
+ PYBIND11_WARNING_POP
42
+
43
+ PYBIND11_NAMESPACE_END(detail)
44
+
45
+ /* The functions below essentially reproduce the PyGILState_* API using a RAII
46
+ * pattern, but there are a few important differences:
47
+ *
48
+ * 1. When acquiring the GIL from an non-main thread during the finalization
49
+ * phase, the GILState API blindly terminates the calling thread, which
50
+ * is often not what is wanted. This API does not do this.
51
+ *
52
+ * 2. The gil_scoped_release function can optionally cut the relationship
53
+ * of a PyThreadState and its associated thread, which allows moving it to
54
+ * another thread (this is a fairly rare/advanced use case).
55
+ *
56
+ * 3. The reference count of an acquired thread state can be controlled. This
57
+ * can be handy to prevent cases where callbacks issued from an external
58
+ * thread would otherwise constantly construct and destroy thread state data
59
+ * structures.
60
+ *
61
+ * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
62
+ * example which uses features 2 and 3 to migrate the Python thread of
63
+ * execution to another thread (to run the event loop on the original thread,
64
+ * in this case).
65
+ */
66
+
67
+ class gil_scoped_acquire {
68
+ public:
69
+ PYBIND11_NOINLINE gil_scoped_acquire() {
70
+ auto &internals = detail::get_internals();
71
+ tstate = internals.tstate.get();
72
+
73
+ if (!tstate) {
74
+ /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
75
+ calling from a Python thread). Since we use a different key, this ensures
76
+ we don't create a new thread state and deadlock in PyEval_AcquireThread
77
+ below. Note we don't save this state with internals.tstate, since we don't
78
+ create it we would fail to clear it (its reference count should be > 0). */
79
+ tstate = PyGILState_GetThisThreadState();
80
+ }
81
+
82
+ if (!tstate) {
83
+ tstate = PyThreadState_New(internals.istate);
84
+ # if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
85
+ if (!tstate) {
86
+ pybind11_fail("scoped_acquire: could not create thread state!");
87
+ }
88
+ # endif
89
+ tstate->gilstate_counter = 0;
90
+ internals.tstate = tstate;
91
+ } else {
92
+ release = detail::get_thread_state_unchecked() != tstate;
93
+ }
94
+
95
+ if (release) {
96
+ PyEval_AcquireThread(tstate);
97
+ }
98
+
99
+ inc_ref();
100
+ }
101
+
102
+ gil_scoped_acquire(const gil_scoped_acquire &) = delete;
103
+ gil_scoped_acquire &operator=(const gil_scoped_acquire &) = delete;
104
+
105
+ void inc_ref() { ++tstate->gilstate_counter; }
106
+
107
+ PYBIND11_NOINLINE void dec_ref() {
108
+ --tstate->gilstate_counter;
109
+ # if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
110
+ if (detail::get_thread_state_unchecked() != tstate) {
111
+ pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
112
+ }
113
+ if (tstate->gilstate_counter < 0) {
114
+ pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
115
+ }
116
+ # endif
117
+ if (tstate->gilstate_counter == 0) {
118
+ # if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
119
+ if (!release) {
120
+ pybind11_fail("scoped_acquire::dec_ref(): internal error!");
121
+ }
122
+ # endif
123
+ // Make sure that PyThreadState_Clear is not recursively called by finalizers.
124
+ // See issue #5827
125
+ ++tstate->gilstate_counter;
126
+ PyThreadState_Clear(tstate);
127
+ --tstate->gilstate_counter;
128
+ if (active) {
129
+ PyThreadState_DeleteCurrent();
130
+ }
131
+ detail::get_internals().tstate.reset();
132
+ release = false;
133
+ }
134
+ }
135
+
136
+ /// This method will disable the PyThreadState_DeleteCurrent call and the
137
+ /// GIL won't be released. This method should be used if the interpreter
138
+ /// could be shutting down when this is called, as thread deletion is not
139
+ /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
140
+ /// protect subsequent code.
141
+ PYBIND11_NOINLINE void disarm() { active = false; }
142
+
143
+ PYBIND11_NOINLINE ~gil_scoped_acquire() {
144
+ dec_ref();
145
+ if (release) {
146
+ PyEval_SaveThread();
147
+ }
148
+ }
149
+
150
+ private:
151
+ PyThreadState *tstate = nullptr;
152
+ bool release = true;
153
+ bool active = true;
154
+ };
155
+
156
+ class gil_scoped_release {
157
+ public:
158
+ // PRECONDITION: The GIL must be held when this constructor is called.
159
+ explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
160
+ assert(PyGILState_Check());
161
+ // `get_internals()` must be called here unconditionally in order to initialize
162
+ // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
163
+ // initialization race could occur as multiple threads try `gil_scoped_acquire`.
164
+ auto &internals = detail::get_internals();
165
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
166
+ tstate = PyEval_SaveThread();
167
+ if (disassoc) {
168
+ internals.tstate.reset();
169
+ }
170
+ }
171
+
172
+ gil_scoped_release(const gil_scoped_release &) = delete;
173
+ gil_scoped_release &operator=(const gil_scoped_release &) = delete;
174
+
175
+ /// This method will disable the PyThreadState_DeleteCurrent call and the
176
+ /// GIL won't be acquired. This method should be used if the interpreter
177
+ /// could be shutting down when this is called, as thread deletion is not
178
+ /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
179
+ /// protect subsequent code.
180
+ PYBIND11_NOINLINE void disarm() { active = false; }
181
+
182
+ ~gil_scoped_release() {
183
+ if (!tstate) {
184
+ return;
185
+ }
186
+ // `PyEval_RestoreThread()` should not be called if runtime is finalizing
187
+ if (active) {
188
+ PyEval_RestoreThread(tstate);
189
+ }
190
+ if (disassoc) {
191
+ detail::get_internals().tstate = tstate;
192
+ }
193
+ }
194
+
195
+ private:
196
+ PyThreadState *tstate;
197
+ bool disassoc;
198
+ bool active = true;
199
+ };
200
+
201
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
202
+
203
+ #endif // !PYBIND11_SIMPLE_GIL_MANAGEMENT
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/gil_safe_call_once.h ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2023 The pybind Community.
2
+
3
+ #pragma once
4
+
5
+ #include "detail/common.h"
6
+ #include "detail/internals.h"
7
+ #include "gil.h"
8
+
9
+ #include <cassert>
10
+ #include <mutex>
11
+
12
+ #if defined(Py_GIL_DISABLED) || defined(PYBIND11_HAS_SUBINTERPRETER_SUPPORT)
13
+ # include <atomic>
14
+ #endif
15
+ #ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
16
+ # include <cstdint>
17
+ # include <memory>
18
+ # include <string>
19
+ #endif
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+
23
+ PYBIND11_NAMESPACE_BEGIN(detail)
24
+ #if defined(Py_GIL_DISABLED) || defined(PYBIND11_HAS_SUBINTERPRETER_SUPPORT)
25
+ using atomic_bool = std::atomic_bool;
26
+ #else
27
+ using atomic_bool = bool;
28
+ #endif
29
+ PYBIND11_NAMESPACE_END(detail)
30
+
31
+ // Use the `gil_safe_call_once_and_store` class below instead of the naive
32
+ //
33
+ // static auto imported_obj = py::module_::import("module_name"); // BAD, DO NOT USE!
34
+ //
35
+ // which has two serious issues:
36
+ //
37
+ // 1. Py_DECREF() calls potentially after the Python interpreter was finalized already, and
38
+ // 2. deadlocks in multi-threaded processes (because of missing lock ordering).
39
+ //
40
+ // The following alternative avoids both problems:
41
+ //
42
+ // PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> storage;
43
+ // auto &imported_obj = storage // Do NOT make this `static`!
44
+ // .call_once_and_store_result([]() {
45
+ // return py::module_::import("module_name");
46
+ // })
47
+ // .get_stored();
48
+ //
49
+ // The parameter of `call_once_and_store_result()` must be callable. It can make
50
+ // CPython API calls, and in particular, it can temporarily release the GIL.
51
+ //
52
+ // `T` can be any C++ type, it does not have to involve CPython API types.
53
+ //
54
+ // The behavior with regard to signals, e.g. `SIGINT` (`KeyboardInterrupt`),
55
+ // is not ideal. If the main thread is the one to actually run the `Callable`,
56
+ // then a `KeyboardInterrupt` will interrupt it if it is running normal Python
57
+ // code. The situation is different if a non-main thread runs the
58
+ // `Callable`, and then the main thread starts waiting for it to complete:
59
+ // a `KeyboardInterrupt` will not interrupt the non-main thread, but it will
60
+ // get processed only when it is the main thread's turn again and it is running
61
+ // normal Python code. However, this will be unnoticeable for quick call-once
62
+ // functions, which is usually the case.
63
+ //
64
+ // For in-depth background, see docs/advanced/deadlock.md
65
+ #ifndef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
66
+ // Subinterpreter support is disabled.
67
+ // In this case, we can store the result globally, because there is only a single interpreter.
68
+ //
69
+ // The life span of the stored result is the entire process lifetime. It is leaked on process
70
+ // termination to avoid destructor calls after the Python interpreter was finalized.
71
+ template <typename T>
72
+ class gil_safe_call_once_and_store {
73
+ public:
74
+ // PRECONDITION: The GIL must be held when `call_once_and_store_result()` is called.
75
+ //
76
+ // NOTE: The second parameter (finalize callback) is intentionally unused when subinterpreter
77
+ // support is disabled. In that case, storage is process-global and intentionally leaked to
78
+ // avoid calling destructors after the Python interpreter has been finalized.
79
+ template <typename Callable>
80
+ gil_safe_call_once_and_store &call_once_and_store_result(Callable &&fn,
81
+ void (*)(T &) /*unused*/ = nullptr) {
82
+ if (!is_initialized_) { // This read is guarded by the GIL.
83
+ // Multiple threads may enter here, because the GIL is released in the next line and
84
+ // CPython API calls in the `fn()` call below may release and reacquire the GIL.
85
+ gil_scoped_release gil_rel; // Needed to establish lock ordering.
86
+ std::call_once(once_flag_, [&] {
87
+ // Only one thread will ever enter here.
88
+ gil_scoped_acquire gil_acq;
89
+ ::new (storage_) T(fn()); // fn may release, but will reacquire, the GIL.
90
+ is_initialized_ = true; // This write is guarded by the GIL.
91
+ });
92
+ // All threads will observe `is_initialized_` as true here.
93
+ }
94
+ // Intentionally not returning `T &` to ensure the calling code is self-documenting.
95
+ return *this;
96
+ }
97
+
98
+ // This must only be called after `call_once_and_store_result()` was called.
99
+ T &get_stored() {
100
+ assert(is_initialized_);
101
+ PYBIND11_WARNING_PUSH
102
+ # if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
103
+ // Needed for gcc 4.8.5
104
+ PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing")
105
+ # endif
106
+ return *reinterpret_cast<T *>(storage_);
107
+ PYBIND11_WARNING_POP
108
+ }
109
+
110
+ constexpr gil_safe_call_once_and_store() = default;
111
+ // The instance is a global static, so its destructor runs when the process
112
+ // is terminating. Therefore, do nothing here because the Python interpreter
113
+ // may have been finalized already.
114
+ PYBIND11_DTOR_CONSTEXPR ~gil_safe_call_once_and_store() = default;
115
+
116
+ // Disable copy and move operations.
117
+ gil_safe_call_once_and_store(const gil_safe_call_once_and_store &) = delete;
118
+ gil_safe_call_once_and_store(gil_safe_call_once_and_store &&) = delete;
119
+ gil_safe_call_once_and_store &operator=(const gil_safe_call_once_and_store &) = delete;
120
+ gil_safe_call_once_and_store &operator=(gil_safe_call_once_and_store &&) = delete;
121
+
122
+ private:
123
+ // The global static storage (per-process) when subinterpreter support is disabled.
124
+ alignas(T) char storage_[sizeof(T)] = {};
125
+ std::once_flag once_flag_;
126
+
127
+ // The `is_initialized_`-`storage_` pair is very similar to `std::optional`,
128
+ // but the latter does not have the triviality properties of former,
129
+ // therefore `std::optional` is not a viable alternative here.
130
+ detail::atomic_bool is_initialized_{false};
131
+ };
132
+ #else
133
+ // Subinterpreter support is enabled.
134
+ // In this case, we should store the result per-interpreter instead of globally, because each
135
+ // subinterpreter has its own separate state. The cached result may not shareable across
136
+ // interpreters (e.g., imported modules and their members).
137
+
138
+ PYBIND11_NAMESPACE_BEGIN(detail)
139
+
140
+ template <typename T>
141
+ struct call_once_storage {
142
+ alignas(T) char storage[sizeof(T)] = {};
143
+ std::once_flag once_flag;
144
+ void (*finalize)(T &) = nullptr;
145
+ std::atomic_bool is_initialized{false};
146
+
147
+ call_once_storage() = default;
148
+ ~call_once_storage() {
149
+ if (is_initialized) {
150
+ if (finalize != nullptr) {
151
+ finalize(*reinterpret_cast<T *>(storage));
152
+ } else {
153
+ reinterpret_cast<T *>(storage)->~T();
154
+ }
155
+ }
156
+ }
157
+ call_once_storage(const call_once_storage &) = delete;
158
+ call_once_storage(call_once_storage &&) = delete;
159
+ call_once_storage &operator=(const call_once_storage &) = delete;
160
+ call_once_storage &operator=(call_once_storage &&) = delete;
161
+ };
162
+
163
+ PYBIND11_NAMESPACE_END(detail)
164
+
165
+ // Prefix for storage keys in the interpreter state dict.
166
+ # define PYBIND11_CALL_ONCE_STORAGE_KEY_PREFIX PYBIND11_INTERNALS_ID "_call_once_storage__"
167
+
168
+ // The life span of the stored result is the entire interpreter lifetime. An additional
169
+ // `finalize_fn` can be provided to clean up the stored result when the interpreter is destroyed.
170
+ template <typename T>
171
+ class gil_safe_call_once_and_store {
172
+ public:
173
+ // PRECONDITION: The GIL must be held when `call_once_and_store_result()` is called.
174
+ template <typename Callable>
175
+ gil_safe_call_once_and_store &call_once_and_store_result(Callable &&fn,
176
+ void (*finalize_fn)(T &) = nullptr) {
177
+ if (!is_last_storage_valid()) {
178
+ // Multiple threads may enter here, because the GIL is released in the next line and
179
+ // CPython API calls in the `fn()` call below may release and reacquire the GIL.
180
+ gil_scoped_release gil_rel; // Needed to establish lock ordering.
181
+ // There can be multiple threads going through here.
182
+ storage_type *value = nullptr;
183
+ {
184
+ gil_scoped_acquire gil_acq; // Restore lock ordering.
185
+ // This function is thread-safe under free-threading.
186
+ value = get_or_create_storage_in_state_dict();
187
+ }
188
+ assert(value != nullptr);
189
+ std::call_once(value->once_flag, [&] {
190
+ // Only one thread will ever enter here.
191
+ gil_scoped_acquire gil_acq;
192
+ // fn may release, but will reacquire, the GIL.
193
+ ::new (value->storage) T(fn());
194
+ value->finalize = finalize_fn;
195
+ value->is_initialized = true;
196
+ last_storage_ptr_ = reinterpret_cast<T *>(value->storage);
197
+ is_initialized_by_at_least_one_interpreter_ = true;
198
+ });
199
+ // All threads will observe `is_initialized_by_at_least_one_interpreter_` as true here.
200
+ }
201
+ // Intentionally not returning `T &` to ensure the calling code is self-documenting.
202
+ return *this;
203
+ }
204
+
205
+ // This must only be called after `call_once_and_store_result()` was called.
206
+ T &get_stored() {
207
+ T *result = last_storage_ptr_;
208
+ if (!is_last_storage_valid()) {
209
+ gil_scoped_acquire gil_acq;
210
+ auto *value = get_or_create_storage_in_state_dict();
211
+ result = last_storage_ptr_ = reinterpret_cast<T *>(value->storage);
212
+ }
213
+ assert(result != nullptr);
214
+ return *result;
215
+ }
216
+
217
+ constexpr gil_safe_call_once_and_store() = default;
218
+ // The instance is a global static, so its destructor runs when the process
219
+ // is terminating. Therefore, do nothing here because the Python interpreter
220
+ // may have been finalized already.
221
+ PYBIND11_DTOR_CONSTEXPR ~gil_safe_call_once_and_store() = default;
222
+
223
+ // Disable copy and move operations because the memory address is used as key.
224
+ gil_safe_call_once_and_store(const gil_safe_call_once_and_store &) = delete;
225
+ gil_safe_call_once_and_store(gil_safe_call_once_and_store &&) = delete;
226
+ gil_safe_call_once_and_store &operator=(const gil_safe_call_once_and_store &) = delete;
227
+ gil_safe_call_once_and_store &operator=(gil_safe_call_once_and_store &&) = delete;
228
+
229
+ private:
230
+ using storage_type = detail::call_once_storage<T>;
231
+
232
+ // Indicator of fast path for single-interpreter case.
233
+ bool is_last_storage_valid() const {
234
+ return is_initialized_by_at_least_one_interpreter_
235
+ && !detail::has_seen_non_main_interpreter();
236
+ }
237
+
238
+ // Get the unique key for this storage instance in the interpreter's state dict.
239
+ // The return type should not be `py::str` because PyObject is interpreter-dependent.
240
+ std::string get_storage_key() const {
241
+ // The instance is expected to be global static, so using its address as unique identifier.
242
+ // The typical usage is like:
243
+ //
244
+ // PYBIND11_CONSTINIT static gil_safe_call_once_and_store<T> storage;
245
+ //
246
+ return PYBIND11_CALL_ONCE_STORAGE_KEY_PREFIX
247
+ + std::to_string(reinterpret_cast<std::uintptr_t>(this));
248
+ }
249
+
250
+ // Get or create per-storage capsule in the current interpreter's state dict.
251
+ // The storage is interpreter-dependent and will not be shared across interpreters.
252
+ storage_type *get_or_create_storage_in_state_dict() {
253
+ return detail::atomic_get_or_create_in_state_dict<storage_type>(get_storage_key().c_str())
254
+ .first;
255
+ }
256
+
257
+ // No storage needed when subinterpreter support is enabled.
258
+ // The actual storage is stored in the per-interpreter state dict via
259
+ // `get_or_create_storage_in_state_dict()`.
260
+
261
+ // Fast local cache to avoid repeated lookups when there are no multiple interpreters.
262
+ // This is only valid if there is a single interpreter. Otherwise, it is not used.
263
+ // WARNING: We cannot use thread local cache similar to `internals_pp_manager::internals_p_tls`
264
+ // because the thread local storage cannot be explicitly invalidated when interpreters
265
+ // are destroyed (unlike `internals_pp_manager` which has explicit hooks for that).
266
+ T *last_storage_ptr_ = nullptr;
267
+ // This flag is true if the value has been initialized by any interpreter (may not be the
268
+ // current one).
269
+ detail::atomic_bool is_initialized_by_at_least_one_interpreter_{false};
270
+ };
271
+ #endif
272
+
273
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/gil_simple.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2016-2025 The Pybind Development Team.
2
+ // All rights reserved. Use of this source code is governed by a
3
+ // BSD-style license that can be found in the LICENSE file.
4
+
5
+ #pragma once
6
+
7
+ #include "detail/common.h"
8
+
9
+ #include <cassert>
10
+
11
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
12
+
13
+ class gil_scoped_acquire_simple {
14
+ PyGILState_STATE state;
15
+
16
+ public:
17
+ gil_scoped_acquire_simple() : state{PyGILState_Ensure()} {}
18
+ gil_scoped_acquire_simple(const gil_scoped_acquire_simple &) = delete;
19
+ gil_scoped_acquire_simple &operator=(const gil_scoped_acquire_simple &) = delete;
20
+ ~gil_scoped_acquire_simple() { PyGILState_Release(state); }
21
+ };
22
+
23
+ class gil_scoped_release_simple {
24
+ PyThreadState *state;
25
+
26
+ public:
27
+ // PRECONDITION: The GIL must be held when this constructor is called.
28
+ gil_scoped_release_simple() {
29
+ assert(PyGILState_Check());
30
+ state = PyEval_SaveThread();
31
+ }
32
+ gil_scoped_release_simple(const gil_scoped_release_simple &) = delete;
33
+ gil_scoped_release_simple &operator=(const gil_scoped_release_simple &) = delete;
34
+ ~gil_scoped_release_simple() { PyEval_RestoreThread(state); }
35
+ };
36
+
37
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/iostream.h ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
3
+
4
+ Copyright (c) 2017 Henry F. Schreiner
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
+ WARNING: The implementation in this file is NOT thread safe. Multiple
10
+ threads writing to a redirected ostream concurrently cause data races
11
+ and potentially buffer overflows. Therefore it is currently a requirement
12
+ that all (possibly) concurrent redirected ostream writes are protected by
13
+ a mutex.
14
+ #HelpAppreciated: Work on iostream.h thread safety.
15
+ For more background see the discussions under
16
+ https://github.com/pybind/pybind11/pull/2982 and
17
+ https://github.com/pybind/pybind11/pull/2995.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include "pybind11.h"
23
+
24
+ #include <algorithm>
25
+ #include <cstring>
26
+ #include <iostream>
27
+ #include <iterator>
28
+ #include <memory>
29
+ #include <ostream>
30
+ #include <streambuf>
31
+ #include <string>
32
+ #include <utility>
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
35
+ PYBIND11_NAMESPACE_BEGIN(detail)
36
+
37
+ // Buffer that writes to Python instead of C++
38
+ class pythonbuf : public std::streambuf {
39
+ private:
40
+ using traits_type = std::streambuf::traits_type;
41
+
42
+ const size_t buf_size;
43
+ std::unique_ptr<char[]> d_buffer;
44
+ object pywrite;
45
+ object pyflush;
46
+
47
+ int overflow(int c) override {
48
+ if (!traits_type::eq_int_type(c, traits_type::eof())) {
49
+ *pptr() = traits_type::to_char_type(c);
50
+ pbump(1);
51
+ }
52
+ return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
53
+ }
54
+
55
+ // Computes how many bytes at the end of the buffer are part of an
56
+ // incomplete sequence of UTF-8 bytes.
57
+ // Precondition: pbase() < pptr()
58
+ size_t utf8_remainder() const {
59
+ const auto rbase = std::reverse_iterator<char *>(pbase());
60
+ const auto rpptr = std::reverse_iterator<char *>(pptr());
61
+ auto is_ascii = [](char c) { return (static_cast<unsigned char>(c) & 0x80) == 0x00; };
62
+ auto is_leading = [](char c) { return (static_cast<unsigned char>(c) & 0xC0) == 0xC0; };
63
+ auto is_leading_2b = [](char c) { return static_cast<unsigned char>(c) <= 0xDF; };
64
+ auto is_leading_3b = [](char c) { return static_cast<unsigned char>(c) <= 0xEF; };
65
+ // If the last character is ASCII, there are no incomplete code points
66
+ if (is_ascii(*rpptr)) {
67
+ return 0;
68
+ }
69
+ // Otherwise, work back from the end of the buffer and find the first
70
+ // UTF-8 leading byte
71
+ const auto rpend = rbase - rpptr >= 3 ? rpptr + 3 : rbase;
72
+ const auto leading = std::find_if(rpptr, rpend, is_leading);
73
+ if (leading == rbase) {
74
+ return 0;
75
+ }
76
+ const auto dist = static_cast<size_t>(leading - rpptr);
77
+ size_t remainder = 0;
78
+
79
+ if (dist == 0) {
80
+ remainder = 1; // 1-byte code point is impossible
81
+ } else if (dist == 1) {
82
+ remainder = is_leading_2b(*leading) ? 0 : dist + 1;
83
+ } else if (dist == 2) {
84
+ remainder = is_leading_3b(*leading) ? 0 : dist + 1;
85
+ }
86
+ // else if (dist >= 3), at least 4 bytes before encountering an UTF-8
87
+ // leading byte, either no remainder or invalid UTF-8.
88
+ // Invalid UTF-8 will cause an exception later when converting
89
+ // to a Python string, so that's not handled here.
90
+ return remainder;
91
+ }
92
+
93
+ // This function must be non-virtual to be called in a destructor.
94
+ int _sync() {
95
+ if (pbase() != pptr()) { // If buffer is not empty
96
+ gil_scoped_acquire tmp;
97
+ // This subtraction cannot be negative, so dropping the sign.
98
+ auto size = static_cast<size_t>(pptr() - pbase());
99
+ size_t remainder = utf8_remainder();
100
+
101
+ if (size > remainder) {
102
+ str line(pbase(), size - remainder);
103
+ pywrite(std::move(line));
104
+ pyflush();
105
+ }
106
+
107
+ // Copy the remainder at the end of the buffer to the beginning:
108
+ if (remainder > 0) {
109
+ std::memmove(pbase(), pptr() - remainder, remainder);
110
+ }
111
+ setp(pbase(), epptr());
112
+ pbump(static_cast<int>(remainder));
113
+ }
114
+ return 0;
115
+ }
116
+
117
+ int sync() override { return _sync(); }
118
+
119
+ public:
120
+ // Minimum buffer size must accommodate the largest incomplete UTF-8 sequence
121
+ // (3 bytes) plus one position reserved for overflow(), i.e. 4 bytes total.
122
+ static constexpr size_t minimum_buffer_size = 4;
123
+
124
+ explicit pythonbuf(const object &pyostream, size_t buffer_size = 1024)
125
+ : buf_size(buffer_size < minimum_buffer_size // ternary avoids C++14 std::max ODR-use of
126
+ // static constexpr
127
+ ? minimum_buffer_size
128
+ : buffer_size),
129
+ d_buffer(new char[buf_size]), pywrite(pyostream.attr("write")),
130
+ pyflush(pyostream.attr("flush")) {
131
+ setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
132
+ }
133
+
134
+ pythonbuf(pythonbuf &&other) noexcept
135
+ : buf_size(other.buf_size), d_buffer(std::move(other.d_buffer)),
136
+ pywrite(std::move(other.pywrite)), pyflush(std::move(other.pyflush)) {
137
+ const auto pending = (other.pbase() != nullptr && other.pptr() != nullptr)
138
+ ? static_cast<int>(other.pptr() - other.pbase())
139
+ : 0;
140
+ if (d_buffer != nullptr) {
141
+ // Rebuild the put area from the transferred storage.
142
+ setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
143
+ pbump(pending);
144
+ } else {
145
+ setp(nullptr, nullptr);
146
+ }
147
+ // Prevent the moved-from destructor from flushing through moved-out handles.
148
+ other.setp(nullptr, nullptr);
149
+ }
150
+
151
+ /// Sync before destroy
152
+ ~pythonbuf() override { _sync(); }
153
+ };
154
+
155
+ PYBIND11_NAMESPACE_END(detail)
156
+
157
+ /** \rst
158
+ This a move-only guard that redirects output.
159
+
160
+ .. code-block:: cpp
161
+
162
+ #include <pybind11/iostream.h>
163
+
164
+ ...
165
+
166
+ {
167
+ py::scoped_ostream_redirect output;
168
+ std::cout << "Hello, World!"; // Python stdout
169
+ } // <-- return std::cout to normal
170
+
171
+ You can explicitly pass the c++ stream and the python object,
172
+ for example to guard stderr instead.
173
+
174
+ .. code-block:: cpp
175
+
176
+ {
177
+ py::scoped_ostream_redirect output{
178
+ std::cerr, py::module::import("sys").attr("stderr")};
179
+ std::cout << "Hello, World!";
180
+ }
181
+ \endrst */
182
+ class scoped_ostream_redirect {
183
+ protected:
184
+ std::streambuf *old;
185
+ std::ostream &costream;
186
+ detail::pythonbuf buffer;
187
+ bool active = true;
188
+
189
+ public:
190
+ explicit scoped_ostream_redirect(std::ostream &costream = std::cout,
191
+ const object &pyostream
192
+ = module_::import("sys").attr("stdout"))
193
+ : costream(costream), buffer(pyostream) {
194
+ old = costream.rdbuf(&buffer);
195
+ }
196
+
197
+ ~scoped_ostream_redirect() {
198
+ if (active) {
199
+ costream.rdbuf(old);
200
+ }
201
+ }
202
+
203
+ scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
204
+ // NOLINTNEXTLINE(performance-noexcept-move-constructor)
205
+ scoped_ostream_redirect(scoped_ostream_redirect &&other)
206
+ : old(other.old), costream(other.costream), buffer(std::move(other.buffer)),
207
+ active(other.active) {
208
+ if (active) {
209
+ costream.rdbuf(&buffer); // Re-point stream to our buffer
210
+ other.active = false;
211
+ }
212
+ }
213
+ scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
214
+ scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
215
+ };
216
+
217
+ /** \rst
218
+ Like `scoped_ostream_redirect`, but redirects cerr by default. This class
219
+ is provided primary to make ``py::call_guard`` easier to make.
220
+
221
+ .. code-block:: cpp
222
+
223
+ m.def("noisy_func", &noisy_func,
224
+ py::call_guard<scoped_ostream_redirect,
225
+ scoped_estream_redirect>());
226
+
227
+ \endrst */
228
+ class scoped_estream_redirect : public scoped_ostream_redirect {
229
+ public:
230
+ explicit scoped_estream_redirect(std::ostream &costream = std::cerr,
231
+ const object &pyostream
232
+ = module_::import("sys").attr("stderr"))
233
+ : scoped_ostream_redirect(costream, pyostream) {}
234
+ };
235
+
236
+ PYBIND11_NAMESPACE_BEGIN(detail)
237
+
238
+ // Class to redirect output as a context manager. C++ backend.
239
+ class OstreamRedirect {
240
+ bool do_stdout_;
241
+ bool do_stderr_;
242
+ std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
243
+ std::unique_ptr<scoped_estream_redirect> redirect_stderr;
244
+
245
+ public:
246
+ explicit OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
247
+ : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
248
+
249
+ void enter() {
250
+ if (do_stdout_) {
251
+ redirect_stdout.reset(new scoped_ostream_redirect());
252
+ }
253
+ if (do_stderr_) {
254
+ redirect_stderr.reset(new scoped_estream_redirect());
255
+ }
256
+ }
257
+
258
+ void exit() {
259
+ redirect_stdout.reset();
260
+ redirect_stderr.reset();
261
+ }
262
+ };
263
+
264
+ PYBIND11_NAMESPACE_END(detail)
265
+
266
+ /** \rst
267
+ This is a helper function to add a C++ redirect context manager to Python
268
+ instead of using a C++ guard. To use it, add the following to your binding code:
269
+
270
+ .. code-block:: cpp
271
+
272
+ #include <pybind11/iostream.h>
273
+
274
+ ...
275
+
276
+ py::add_ostream_redirect(m, "ostream_redirect");
277
+
278
+ You now have a Python context manager that redirects your output:
279
+
280
+ .. code-block:: python
281
+
282
+ with m.ostream_redirect():
283
+ m.print_to_cout_function()
284
+
285
+ This manager can optionally be told which streams to operate on:
286
+
287
+ .. code-block:: python
288
+
289
+ with m.ostream_redirect(stdout=true, stderr=true):
290
+ m.noisy_function_with_error_printing()
291
+
292
+ \endrst */
293
+ inline class_<detail::OstreamRedirect>
294
+ add_ostream_redirect(module_ m, const std::string &name = "ostream_redirect") {
295
+ return class_<detail::OstreamRedirect>(std::move(m), name.c_str(), module_local())
296
+ .def(init<bool, bool>(), arg("stdout") = true, arg("stderr") = true)
297
+ .def("__enter__", &detail::OstreamRedirect::enter)
298
+ .def("__exit__", [](detail::OstreamRedirect &self_, const args &) { self_.exit(); });
299
+ }
300
+
301
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/native_enum.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2022-2025 The pybind Community.
2
+ // All rights reserved. Use of this source code is governed by a
3
+ // BSD-style license that can be found in the LICENSE file.
4
+
5
+ #pragma once
6
+
7
+ #include "detail/common.h"
8
+ #include "detail/native_enum_data.h"
9
+ #include "detail/type_caster_base.h"
10
+ #include "cast.h"
11
+
12
+ #include <cassert>
13
+ #include <limits>
14
+ #include <type_traits>
15
+ #include <typeindex>
16
+
17
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
18
+
19
+ /// Conversions between Python's native (stdlib) enum types and C++ enums.
20
+ template <typename EnumType>
21
+ class native_enum : public detail::native_enum_data {
22
+ public:
23
+ using Underlying = typename std::underlying_type<EnumType>::type;
24
+
25
+ native_enum(handle parent_scope,
26
+ const char *name,
27
+ const char *native_type_name,
28
+ const char *class_doc = "")
29
+ : detail::native_enum_data(
30
+ parent_scope, name, native_type_name, class_doc, make_record()) {
31
+ if (detail::get_local_type_info(typeid(EnumType)) != nullptr
32
+ || detail::get_global_type_info(typeid(EnumType)) != nullptr) {
33
+ pybind11_fail(
34
+ "pybind11::native_enum<...>(\"" + enum_name_encoded
35
+ + "\") is already registered as a `pybind11::enum_` or `pybind11::class_`!");
36
+ }
37
+ if (detail::global_internals_native_enum_type_map_contains(enum_type_index)) {
38
+ pybind11_fail("pybind11::native_enum<...>(\"" + enum_name_encoded
39
+ + "\") is already registered!");
40
+ }
41
+ arm_finalize_check();
42
+ }
43
+
44
+ /// Export enumeration entries into the parent scope
45
+ native_enum &export_values() {
46
+ assert(!export_values_flag); // Catch redundant calls.
47
+ export_values_flag = true;
48
+ return *this;
49
+ }
50
+
51
+ /// Add an enumeration entry
52
+ native_enum &value(char const *name, EnumType value, const char *doc = nullptr) {
53
+ // Disarm for the case that the native_enum_data dtor runs during exception unwinding.
54
+ disarm_finalize_check("value after finalize");
55
+ members.append(make_tuple(name, static_cast<Underlying>(value)));
56
+ if (doc) {
57
+ member_docs.append(make_tuple(name, doc));
58
+ }
59
+ arm_finalize_check(); // There was no exception.
60
+ return *this;
61
+ }
62
+
63
+ native_enum(const native_enum &) = delete;
64
+ native_enum &operator=(const native_enum &) = delete;
65
+
66
+ private:
67
+ static detail::native_enum_record make_record() {
68
+ detail::native_enum_record ret;
69
+ ret.cpptype = &typeid(EnumType);
70
+ ret.size_bytes = sizeof(EnumType);
71
+ ret.is_signed = std::is_signed<Underlying>::value;
72
+ return ret;
73
+ }
74
+ };
75
+
76
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/numpy.h ADDED
@@ -0,0 +1,2412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/numpy.h: Basic NumPy support, vectorize() wrapper
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ #include "detail/common.h"
14
+ #include "complex.h"
15
+ #include "gil_safe_call_once.h"
16
+ #include "pytypes.h"
17
+
18
+ #include <algorithm>
19
+ #include <array>
20
+ #include <cstdint>
21
+ #include <cstdlib>
22
+ #include <cstring>
23
+ #include <functional>
24
+ #include <numeric>
25
+ #include <sstream>
26
+ #include <string>
27
+ #include <type_traits>
28
+ #include <typeindex>
29
+ #include <utility>
30
+ #include <vector>
31
+
32
+ #ifdef PYBIND11_HAS_SPAN
33
+ # include <span>
34
+ #endif
35
+
36
+ #if defined(PYBIND11_NUMPY_1_ONLY)
37
+ # error "PYBIND11_NUMPY_1_ONLY is no longer supported (see PR #5595)."
38
+ #endif
39
+
40
+ /* This will be true on all flat address space platforms and allows us to reduce the
41
+ whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
42
+ and dimension types (e.g. shape, strides, indexing), instead of inflicting this
43
+ upon the library user.
44
+ Note that NumPy 2 now uses ssize_t for `npy_intp` to simplify this. */
45
+ static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
46
+ static_assert(std::is_signed<Py_intptr_t>::value, "Py_intptr_t must be signed");
47
+ // We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares)
48
+
49
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
50
+
51
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
52
+
53
+ class dtype; // Forward declaration
54
+ class array; // Forward declaration
55
+
56
+ template <typename>
57
+ struct numpy_scalar; // Forward declaration
58
+
59
+ PYBIND11_NAMESPACE_BEGIN(detail)
60
+
61
+ template <>
62
+ struct handle_type_name<dtype> {
63
+ static constexpr auto name = const_name("numpy.dtype");
64
+ };
65
+
66
+ template <>
67
+ struct handle_type_name<array> {
68
+ static constexpr auto name = const_name("numpy.ndarray");
69
+ };
70
+
71
+ template <typename type, typename SFINAE = void>
72
+ struct npy_format_descriptor;
73
+
74
+ /* NumPy 1 proxy (always includes legacy fields) */
75
+ struct PyArrayDescr1_Proxy {
76
+ PyObject_HEAD
77
+ PyObject *typeobj;
78
+ char kind;
79
+ char type;
80
+ char byteorder;
81
+ char flags;
82
+ int type_num;
83
+ int elsize;
84
+ int alignment;
85
+ char *subarray;
86
+ PyObject *fields;
87
+ PyObject *names;
88
+ };
89
+
90
+ struct PyArrayDescr_Proxy {
91
+ PyObject_HEAD
92
+ PyObject *typeobj;
93
+ char kind;
94
+ char type;
95
+ char byteorder;
96
+ char _former_flags;
97
+ int type_num;
98
+ /* Additional fields are NumPy version specific. */
99
+ };
100
+
101
+ /* NumPy 2 proxy, including legacy fields */
102
+ struct PyArrayDescr2_Proxy {
103
+ PyObject_HEAD
104
+ PyObject *typeobj;
105
+ char kind;
106
+ char type;
107
+ char byteorder;
108
+ char _former_flags;
109
+ int type_num;
110
+ std::uint64_t flags;
111
+ ssize_t elsize;
112
+ ssize_t alignment;
113
+ PyObject *metadata;
114
+ Py_hash_t hash;
115
+ void *reserved_null[2];
116
+ /* The following fields only exist if 0 <= type_num < 2056 */
117
+ char *subarray;
118
+ PyObject *fields;
119
+ PyObject *names;
120
+ };
121
+
122
+ struct PyArray_Proxy {
123
+ PyObject_HEAD
124
+ char *data;
125
+ int nd;
126
+ ssize_t *dimensions;
127
+ ssize_t *strides;
128
+ PyObject *base;
129
+ PyObject *descr;
130
+ int flags;
131
+ };
132
+
133
+ struct PyVoidScalarObject_Proxy {
134
+ PyObject_VAR_HEAD char *obval;
135
+ PyArrayDescr_Proxy *descr;
136
+ int flags;
137
+ PyObject *base;
138
+ };
139
+
140
+ struct numpy_type_info {
141
+ PyObject *dtype_ptr;
142
+ std::string format_str;
143
+ };
144
+
145
+ struct numpy_internals {
146
+ std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
147
+
148
+ numpy_type_info *get_type_info(const std::type_info &tinfo, bool throw_if_missing = true) {
149
+ auto it = registered_dtypes.find(std::type_index(tinfo));
150
+ if (it != registered_dtypes.end()) {
151
+ return &(it->second);
152
+ }
153
+ if (throw_if_missing) {
154
+ pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
155
+ }
156
+ return nullptr;
157
+ }
158
+
159
+ template <typename T>
160
+ numpy_type_info *get_type_info(bool throw_if_missing = true) {
161
+ return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
162
+ }
163
+ };
164
+
165
+ PYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr) {
166
+ ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
167
+ }
168
+
169
+ inline numpy_internals &get_numpy_internals() {
170
+ static numpy_internals *ptr = nullptr;
171
+ if (!ptr) {
172
+ load_numpy_internals(ptr);
173
+ }
174
+ return *ptr;
175
+ }
176
+
177
+ PYBIND11_NOINLINE module_ import_numpy_core_submodule(const char *submodule_name) {
178
+ module_ numpy = module_::import("numpy");
179
+ str version_string = numpy.attr("__version__");
180
+ module_ numpy_lib = module_::import("numpy.lib");
181
+ object numpy_version = numpy_lib.attr("NumpyVersion")(version_string);
182
+ int major_version = numpy_version.attr("major").cast<int>();
183
+
184
+ /* `numpy.core` was renamed to `numpy._core` in NumPy 2.0 as it officially
185
+ became a private module. */
186
+ std::string numpy_core_path = major_version >= 2 ? "numpy._core" : "numpy.core";
187
+ return module_::import((numpy_core_path + "." + submodule_name).c_str());
188
+ }
189
+
190
+ template <typename T>
191
+ struct same_size {
192
+ template <typename U>
193
+ using as = bool_constant<sizeof(T) == sizeof(U)>;
194
+ };
195
+
196
+ template <typename Concrete>
197
+ constexpr int platform_lookup() {
198
+ return -1;
199
+ }
200
+
201
+ // Lookup a type according to its size, and return a value corresponding to the NumPy typenum.
202
+ template <typename Concrete, typename T, typename... Ts, typename... Ints>
203
+ constexpr int platform_lookup(int I, Ints... Is) {
204
+ return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...);
205
+ }
206
+
207
+ struct npy_api {
208
+ // If you change this code, please review `normalized_dtype_num` below.
209
+ enum constants {
210
+ NPY_ARRAY_C_CONTIGUOUS_ = 0x0001,
211
+ NPY_ARRAY_F_CONTIGUOUS_ = 0x0002,
212
+ NPY_ARRAY_OWNDATA_ = 0x0004,
213
+ NPY_ARRAY_FORCECAST_ = 0x0010,
214
+ NPY_ARRAY_ENSUREARRAY_ = 0x0040,
215
+ NPY_ARRAY_ALIGNED_ = 0x0100,
216
+ NPY_ARRAY_WRITEABLE_ = 0x0400,
217
+ NPY_BOOL_ = 0,
218
+ NPY_BYTE_,
219
+ NPY_UBYTE_,
220
+ NPY_SHORT_,
221
+ NPY_USHORT_,
222
+ NPY_INT_,
223
+ NPY_UINT_,
224
+ NPY_LONG_,
225
+ NPY_ULONG_,
226
+ NPY_LONGLONG_,
227
+ NPY_ULONGLONG_,
228
+ NPY_FLOAT_,
229
+ NPY_DOUBLE_,
230
+ NPY_LONGDOUBLE_,
231
+ NPY_CFLOAT_,
232
+ NPY_CDOUBLE_,
233
+ NPY_CLONGDOUBLE_,
234
+ NPY_OBJECT_ = 17,
235
+ NPY_STRING_,
236
+ NPY_UNICODE_,
237
+ NPY_VOID_,
238
+ // Platform-dependent normalization
239
+ NPY_INT8_ = NPY_BYTE_,
240
+ NPY_UINT8_ = NPY_UBYTE_,
241
+ NPY_INT16_ = NPY_SHORT_,
242
+ NPY_UINT16_ = NPY_USHORT_,
243
+ // `npy_common.h` defines the integer aliases. In order, it checks:
244
+ // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR
245
+ // and assigns the alias to the first matching size, so we should check in this order.
246
+ NPY_INT32_
247
+ = platform_lookup<std::int32_t, long, int, short>(NPY_LONG_, NPY_INT_, NPY_SHORT_),
248
+ NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
249
+ NPY_ULONG_, NPY_UINT_, NPY_USHORT_),
250
+ NPY_INT64_
251
+ = platform_lookup<std::int64_t, long, long long, int>(NPY_LONG_, NPY_LONGLONG_, NPY_INT_),
252
+ NPY_UINT64_
253
+ = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
254
+ NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_),
255
+ NPY_FLOAT32_ = platform_lookup<float, double, float, long double>(
256
+ NPY_DOUBLE_, NPY_FLOAT_, NPY_LONGDOUBLE_),
257
+ NPY_FLOAT64_ = platform_lookup<double, double, float, long double>(
258
+ NPY_DOUBLE_, NPY_FLOAT_, NPY_LONGDOUBLE_),
259
+ NPY_COMPLEX64_
260
+ = platform_lookup<std::complex<float>,
261
+ std::complex<double>,
262
+ std::complex<float>,
263
+ std::complex<long double>>(NPY_DOUBLE_, NPY_FLOAT_, NPY_LONGDOUBLE_),
264
+ NPY_COMPLEX128_
265
+ = platform_lookup<std::complex<double>,
266
+ std::complex<double>,
267
+ std::complex<float>,
268
+ std::complex<long double>>(NPY_DOUBLE_, NPY_FLOAT_, NPY_LONGDOUBLE_),
269
+ NPY_CHAR_ = std::is_signed<char>::value ? NPY_BYTE_ : NPY_UBYTE_,
270
+ };
271
+
272
+ unsigned int PyArray_RUNTIME_VERSION_;
273
+
274
+ struct PyArray_Dims {
275
+ Py_intptr_t *ptr;
276
+ int len;
277
+ };
278
+
279
+ static npy_api &get() {
280
+ PYBIND11_CONSTINIT static gil_safe_call_once_and_store<npy_api> storage;
281
+ return storage.call_once_and_store_result(lookup).get_stored();
282
+ }
283
+
284
+ bool PyArray_Check_(PyObject *obj) const {
285
+ return PyObject_TypeCheck(obj, PyArray_Type_) != 0;
286
+ }
287
+ bool PyArrayDescr_Check_(PyObject *obj) const {
288
+ return PyObject_TypeCheck(obj, PyArrayDescr_Type_) != 0;
289
+ }
290
+
291
+ unsigned int (*PyArray_GetNDArrayCFeatureVersion_)();
292
+ PyObject *(*PyArray_DescrFromType_)(int);
293
+ PyObject *(*PyArray_TypeObjectFromType_)(int);
294
+ PyObject *(*PyArray_NewFromDescr_)(PyTypeObject *,
295
+ PyObject *,
296
+ int,
297
+ Py_intptr_t const *,
298
+ Py_intptr_t const *,
299
+ void *,
300
+ int,
301
+ PyObject *);
302
+ // Unused. Not removed because that affects ABI of the class.
303
+ PyObject *(*PyArray_DescrNewFromType_)(int);
304
+ int (*PyArray_CopyInto_)(PyObject *, PyObject *);
305
+ PyObject *(*PyArray_NewCopy_)(PyObject *, int);
306
+ PyTypeObject *PyArray_Type_;
307
+ PyTypeObject *PyVoidArrType_Type_;
308
+ PyTypeObject *PyArrayDescr_Type_;
309
+ PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
310
+ PyObject *(*PyArray_Scalar_)(void *, PyObject *, PyObject *);
311
+ void (*PyArray_ScalarAsCtype_)(PyObject *, void *);
312
+ PyObject *(*PyArray_FromAny_)(PyObject *, PyObject *, int, int, int, PyObject *);
313
+ int (*PyArray_DescrConverter_)(PyObject *, PyObject **);
314
+ bool (*PyArray_EquivTypes_)(PyObject *, PyObject *);
315
+ PyObject *(*PyArray_Squeeze_)(PyObject *);
316
+ // Unused. Not removed because that affects ABI of the class.
317
+ int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
318
+ PyObject *(*PyArray_Resize_)(PyObject *, PyArray_Dims *, int, int);
319
+ PyObject *(*PyArray_Newshape_)(PyObject *, PyArray_Dims *, int);
320
+ PyObject *(*PyArray_View_)(PyObject *, PyObject *, PyObject *);
321
+
322
+ private:
323
+ enum functions {
324
+ API_PyArray_GetNDArrayCFeatureVersion = 211,
325
+ API_PyArray_Type = 2,
326
+ API_PyArrayDescr_Type = 3,
327
+ API_PyVoidArrType_Type = 39,
328
+ API_PyArray_DescrFromType = 45,
329
+ API_PyArray_TypeObjectFromType = 46,
330
+ API_PyArray_DescrFromScalar = 57,
331
+ API_PyArray_Scalar = 60,
332
+ API_PyArray_ScalarAsCtype = 62,
333
+ API_PyArray_FromAny = 69,
334
+ API_PyArray_Resize = 80,
335
+ // CopyInto was slot 82 and 50 was effectively an alias. NumPy 2 removed 82.
336
+ API_PyArray_CopyInto = 50,
337
+ API_PyArray_NewCopy = 85,
338
+ API_PyArray_NewFromDescr = 94,
339
+ API_PyArray_DescrNewFromType = 96,
340
+ API_PyArray_Newshape = 135,
341
+ API_PyArray_Squeeze = 136,
342
+ API_PyArray_View = 137,
343
+ API_PyArray_DescrConverter = 174,
344
+ API_PyArray_EquivTypes = 182,
345
+ API_PyArray_SetBaseObject = 282
346
+ };
347
+
348
+ static npy_api lookup() {
349
+ module_ m = detail::import_numpy_core_submodule("multiarray");
350
+ auto c = m.attr("_ARRAY_API");
351
+ void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), nullptr);
352
+ if (api_ptr == nullptr) {
353
+ raise_from(PyExc_SystemError, "FAILURE obtaining numpy _ARRAY_API pointer.");
354
+ throw error_already_set();
355
+ }
356
+ npy_api api;
357
+ #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
358
+ DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
359
+ api.PyArray_RUNTIME_VERSION_ = api.PyArray_GetNDArrayCFeatureVersion_();
360
+ if (api.PyArray_RUNTIME_VERSION_ < 0x7) {
361
+ pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
362
+ }
363
+ DECL_NPY_API(PyArray_Type);
364
+ DECL_NPY_API(PyVoidArrType_Type);
365
+ DECL_NPY_API(PyArrayDescr_Type);
366
+ DECL_NPY_API(PyArray_DescrFromType);
367
+ DECL_NPY_API(PyArray_TypeObjectFromType);
368
+ DECL_NPY_API(PyArray_DescrFromScalar);
369
+ DECL_NPY_API(PyArray_Scalar);
370
+ DECL_NPY_API(PyArray_ScalarAsCtype);
371
+ DECL_NPY_API(PyArray_FromAny);
372
+ DECL_NPY_API(PyArray_Resize);
373
+ DECL_NPY_API(PyArray_CopyInto);
374
+ DECL_NPY_API(PyArray_NewCopy);
375
+ DECL_NPY_API(PyArray_NewFromDescr);
376
+ DECL_NPY_API(PyArray_DescrNewFromType);
377
+ DECL_NPY_API(PyArray_Newshape);
378
+ DECL_NPY_API(PyArray_Squeeze);
379
+ DECL_NPY_API(PyArray_View);
380
+ DECL_NPY_API(PyArray_DescrConverter);
381
+ DECL_NPY_API(PyArray_EquivTypes);
382
+ DECL_NPY_API(PyArray_SetBaseObject);
383
+
384
+ #undef DECL_NPY_API
385
+ return api;
386
+ }
387
+ };
388
+
389
+ template <typename T>
390
+ struct is_complex : std::false_type {};
391
+ template <typename T>
392
+ struct is_complex<std::complex<T>> : std::true_type {};
393
+
394
+ template <typename T, typename = void>
395
+ struct npy_format_descriptor_name;
396
+
397
+ template <typename T>
398
+ struct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> {
399
+ static constexpr auto name = const_name<std::is_same<T, bool>::value>(
400
+ const_name("numpy.bool"),
401
+ const_name<std::is_signed<T>::value>("numpy.int", "numpy.uint")
402
+ + const_name<sizeof(T) * 8>());
403
+ };
404
+
405
+ template <typename T>
406
+ struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
407
+ static constexpr auto name = const_name < std::is_same<T, float>::value
408
+ || std::is_same<T, const float>::value
409
+ || std::is_same<T, double>::value
410
+ || std::is_same<T, const double>::value
411
+ > (const_name("numpy.float") + const_name<sizeof(T) * 8>(),
412
+ const_name("numpy.longdouble"));
413
+ };
414
+
415
+ template <typename T>
416
+ struct npy_format_descriptor_name<T, enable_if_t<is_complex<T>::value>> {
417
+ static constexpr auto name = const_name < std::is_same<typename T::value_type, float>::value
418
+ || std::is_same<typename T::value_type, const float>::value
419
+ || std::is_same<typename T::value_type, double>::value
420
+ || std::is_same<typename T::value_type, const double>::value
421
+ > (const_name("numpy.complex")
422
+ + const_name<sizeof(typename T::value_type) * 16>(),
423
+ const_name("numpy.clongdouble"));
424
+ };
425
+
426
+ template <typename T>
427
+ struct numpy_scalar_info {};
428
+
429
+ #define PYBIND11_NUMPY_SCALAR_IMPL(ctype_, typenum_) \
430
+ template <> \
431
+ struct numpy_scalar_info<ctype_> { \
432
+ static constexpr auto name = npy_format_descriptor_name<ctype_>::name; \
433
+ static constexpr int typenum = npy_api::typenum_##_; \
434
+ }
435
+
436
+ // boolean type
437
+ PYBIND11_NUMPY_SCALAR_IMPL(bool, NPY_BOOL);
438
+
439
+ // character types
440
+ PYBIND11_NUMPY_SCALAR_IMPL(char, NPY_CHAR);
441
+ PYBIND11_NUMPY_SCALAR_IMPL(signed char, NPY_BYTE);
442
+ PYBIND11_NUMPY_SCALAR_IMPL(unsigned char, NPY_UBYTE);
443
+
444
+ // signed integer types
445
+ PYBIND11_NUMPY_SCALAR_IMPL(std::int16_t, NPY_INT16);
446
+ PYBIND11_NUMPY_SCALAR_IMPL(std::int32_t, NPY_INT32);
447
+ PYBIND11_NUMPY_SCALAR_IMPL(std::int64_t, NPY_INT64);
448
+
449
+ // unsigned integer types
450
+ PYBIND11_NUMPY_SCALAR_IMPL(std::uint16_t, NPY_UINT16);
451
+ PYBIND11_NUMPY_SCALAR_IMPL(std::uint32_t, NPY_UINT32);
452
+ PYBIND11_NUMPY_SCALAR_IMPL(std::uint64_t, NPY_UINT64);
453
+
454
+ // floating point types
455
+ PYBIND11_NUMPY_SCALAR_IMPL(float, NPY_FLOAT);
456
+ PYBIND11_NUMPY_SCALAR_IMPL(double, NPY_DOUBLE);
457
+ PYBIND11_NUMPY_SCALAR_IMPL(long double, NPY_LONGDOUBLE);
458
+
459
+ // complex types
460
+ PYBIND11_NUMPY_SCALAR_IMPL(std::complex<float>, NPY_CFLOAT);
461
+ PYBIND11_NUMPY_SCALAR_IMPL(std::complex<double>, NPY_CDOUBLE);
462
+ PYBIND11_NUMPY_SCALAR_IMPL(std::complex<long double>, NPY_CLONGDOUBLE);
463
+
464
+ #undef PYBIND11_NUMPY_SCALAR_IMPL
465
+
466
+ // This table normalizes typenums by mapping NPY_INT_, NPY_LONG, ... to NPY_INT32_, NPY_INT64, ...
467
+ // This is needed to correctly handle situations where multiple typenums map to the same type,
468
+ // e.g. NPY_LONG_ may be equivalent to NPY_INT_ or NPY_LONGLONG_ despite having a different
469
+ // typenum. The normalized typenum should always match the values used in npy_format_descriptor.
470
+ // If you change this code, please review `enum constants` above.
471
+ static constexpr int normalized_dtype_num[npy_api::NPY_VOID_ + 1] = {
472
+ // NPY_BOOL_ =>
473
+ npy_api::NPY_BOOL_,
474
+ // NPY_BYTE_ =>
475
+ npy_api::NPY_BYTE_,
476
+ // NPY_UBYTE_ =>
477
+ npy_api::NPY_UBYTE_,
478
+ // NPY_SHORT_ =>
479
+ npy_api::NPY_INT16_,
480
+ // NPY_USHORT_ =>
481
+ npy_api::NPY_UINT16_,
482
+ // NPY_INT_ =>
483
+ sizeof(int) == sizeof(std::int16_t) ? npy_api::NPY_INT16_
484
+ : sizeof(int) == sizeof(std::int32_t) ? npy_api::NPY_INT32_
485
+ : sizeof(int) == sizeof(std::int64_t) ? npy_api::NPY_INT64_
486
+ : npy_api::NPY_INT_,
487
+ // NPY_UINT_ =>
488
+ sizeof(unsigned int) == sizeof(std::uint16_t) ? npy_api::NPY_UINT16_
489
+ : sizeof(unsigned int) == sizeof(std::uint32_t) ? npy_api::NPY_UINT32_
490
+ : sizeof(unsigned int) == sizeof(std::uint64_t) ? npy_api::NPY_UINT64_
491
+ : npy_api::NPY_UINT_,
492
+ // NPY_LONG_ =>
493
+ sizeof(long) == sizeof(std::int16_t) ? npy_api::NPY_INT16_
494
+ : sizeof(long) == sizeof(std::int32_t) ? npy_api::NPY_INT32_
495
+ : sizeof(long) == sizeof(std::int64_t) ? npy_api::NPY_INT64_
496
+ : npy_api::NPY_LONG_,
497
+ // NPY_ULONG_ =>
498
+ sizeof(unsigned long) == sizeof(std::uint16_t) ? npy_api::NPY_UINT16_
499
+ : sizeof(unsigned long) == sizeof(std::uint32_t) ? npy_api::NPY_UINT32_
500
+ : sizeof(unsigned long) == sizeof(std::uint64_t) ? npy_api::NPY_UINT64_
501
+ : npy_api::NPY_ULONG_,
502
+ // NPY_LONGLONG_ =>
503
+ sizeof(long long) == sizeof(std::int16_t) ? npy_api::NPY_INT16_
504
+ : sizeof(long long) == sizeof(std::int32_t) ? npy_api::NPY_INT32_
505
+ : sizeof(long long) == sizeof(std::int64_t) ? npy_api::NPY_INT64_
506
+ : npy_api::NPY_LONGLONG_,
507
+ // NPY_ULONGLONG_ =>
508
+ sizeof(unsigned long long) == sizeof(std::uint16_t) ? npy_api::NPY_UINT16_
509
+ : sizeof(unsigned long long) == sizeof(std::uint32_t) ? npy_api::NPY_UINT32_
510
+ : sizeof(unsigned long long) == sizeof(std::uint64_t) ? npy_api::NPY_UINT64_
511
+ : npy_api::NPY_ULONGLONG_,
512
+ // NPY_FLOAT_ =>
513
+ npy_api::NPY_FLOAT_,
514
+ // NPY_DOUBLE_ =>
515
+ npy_api::NPY_DOUBLE_,
516
+ // NPY_LONGDOUBLE_ =>
517
+ npy_api::NPY_LONGDOUBLE_,
518
+ // NPY_CFLOAT_ =>
519
+ npy_api::NPY_CFLOAT_,
520
+ // NPY_CDOUBLE_ =>
521
+ npy_api::NPY_CDOUBLE_,
522
+ // NPY_CLONGDOUBLE_ =>
523
+ npy_api::NPY_CLONGDOUBLE_,
524
+ // NPY_OBJECT_ =>
525
+ npy_api::NPY_OBJECT_,
526
+ // NPY_STRING_ =>
527
+ npy_api::NPY_STRING_,
528
+ // NPY_UNICODE_ =>
529
+ npy_api::NPY_UNICODE_,
530
+ // NPY_VOID_ =>
531
+ npy_api::NPY_VOID_,
532
+ };
533
+
534
+ inline PyArray_Proxy *array_proxy(void *ptr) { return reinterpret_cast<PyArray_Proxy *>(ptr); }
535
+
536
+ inline const PyArray_Proxy *array_proxy(const void *ptr) {
537
+ return reinterpret_cast<const PyArray_Proxy *>(ptr);
538
+ }
539
+
540
+ inline PyArrayDescr_Proxy *array_descriptor_proxy(PyObject *ptr) {
541
+ return reinterpret_cast<PyArrayDescr_Proxy *>(ptr);
542
+ }
543
+
544
+ inline const PyArrayDescr_Proxy *array_descriptor_proxy(const PyObject *ptr) {
545
+ return reinterpret_cast<const PyArrayDescr_Proxy *>(ptr);
546
+ }
547
+
548
+ inline const PyArrayDescr1_Proxy *array_descriptor1_proxy(const PyObject *ptr) {
549
+ return reinterpret_cast<const PyArrayDescr1_Proxy *>(ptr);
550
+ }
551
+
552
+ inline const PyArrayDescr2_Proxy *array_descriptor2_proxy(const PyObject *ptr) {
553
+ return reinterpret_cast<const PyArrayDescr2_Proxy *>(ptr);
554
+ }
555
+
556
+ inline bool check_flags(const void *ptr, int flag) {
557
+ return (flag == (array_proxy(ptr)->flags & flag));
558
+ }
559
+
560
+ template <typename T>
561
+ struct is_std_array : std::false_type {};
562
+ template <typename T, size_t N>
563
+ struct is_std_array<std::array<T, N>> : std::true_type {};
564
+
565
+ template <typename T>
566
+ struct array_info_scalar {
567
+ using type = T;
568
+ static constexpr bool is_array = false;
569
+ static constexpr bool is_empty = false;
570
+ static constexpr auto extents = const_name("");
571
+ static void append_extents(list & /* shape */) {}
572
+ };
573
+ // Computes underlying type and a comma-separated list of extents for array
574
+ // types (any mix of std::array and built-in arrays). An array of char is
575
+ // treated as scalar because it gets special handling.
576
+ template <typename T>
577
+ struct array_info : array_info_scalar<T> {};
578
+ template <typename T, size_t N>
579
+ struct array_info<std::array<T, N>> {
580
+ using type = typename array_info<T>::type;
581
+ static constexpr bool is_array = true;
582
+ static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
583
+ static constexpr size_t extent = N;
584
+
585
+ // appends the extents to shape
586
+ static void append_extents(list &shape) {
587
+ shape.append(N);
588
+ array_info<T>::append_extents(shape);
589
+ }
590
+
591
+ static constexpr auto extents = const_name<array_info<T>::is_array>(
592
+ ::pybind11::detail::concat(const_name<N>(), array_info<T>::extents), const_name<N>());
593
+ };
594
+ // For numpy we have special handling for arrays of characters, so we don't include
595
+ // the size in the array extents.
596
+ template <size_t N>
597
+ struct array_info<char[N]> : array_info_scalar<char[N]> {};
598
+ template <size_t N>
599
+ struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> {};
600
+ template <typename T, size_t N>
601
+ struct array_info<T[N]> : array_info<std::array<T, N>> {};
602
+ template <typename T>
603
+ using remove_all_extents_t = typename array_info<T>::type;
604
+
605
+ template <typename T>
606
+ using is_pod_struct
607
+ = all_of<std::is_standard_layout<T>, // since we're accessing directly in memory
608
+ // we need a standard layout type
609
+ #if defined(__GLIBCXX__) \
610
+ && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 \
611
+ || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)
612
+ // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after
613
+ // 5) don't implement is_trivially_copyable, so approximate it
614
+ std::is_trivially_destructible<T>,
615
+ satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,
616
+ #else
617
+ std::is_trivially_copyable<T>,
618
+ #endif
619
+ satisfies_none_of<T,
620
+ std::is_reference,
621
+ std::is_array,
622
+ is_std_array,
623
+ std::is_arithmetic,
624
+ is_complex,
625
+ std::is_enum>>;
626
+
627
+ // Replacement for std::is_pod (deprecated in C++20)
628
+ template <typename T>
629
+ using is_pod = all_of<std::is_standard_layout<T>, std::is_trivial<T>>;
630
+
631
+ template <ssize_t Dim = 0, typename Strides>
632
+ ssize_t byte_offset_unsafe(const Strides &) {
633
+ return 0;
634
+ }
635
+ template <ssize_t Dim = 0, typename Strides, typename... Ix>
636
+ ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
637
+ return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
638
+ }
639
+
640
+ /**
641
+ * Proxy class providing unsafe, unchecked const access to array data. This is constructed through
642
+ * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims`
643
+ * will be -1 for dimensions determined at runtime.
644
+ */
645
+ template <typename T, ssize_t Dims>
646
+ class unchecked_reference {
647
+ protected:
648
+ static constexpr bool Dynamic = Dims < 0;
649
+ const unsigned char *data_;
650
+ // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
651
+ // make large performance gains on big, nested loops, but requires compile-time dimensions
652
+ conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>> shape_, strides_;
653
+ const ssize_t dims_;
654
+
655
+ friend class pybind11::array;
656
+ // Constructor for compile-time dimensions:
657
+ template <bool Dyn = Dynamic>
658
+ unchecked_reference(const void *data,
659
+ const ssize_t *shape,
660
+ const ssize_t *strides,
661
+ enable_if_t<!Dyn, ssize_t>)
662
+ : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
663
+ for (size_t i = 0; i < (size_t) dims_; i++) {
664
+ shape_[i] = shape[i];
665
+ strides_[i] = strides[i];
666
+ }
667
+ }
668
+ // Constructor for runtime dimensions:
669
+ template <bool Dyn = Dynamic>
670
+ unchecked_reference(const void *data,
671
+ const ssize_t *shape,
672
+ const ssize_t *strides,
673
+ enable_if_t<Dyn, ssize_t> dims)
674
+ : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides},
675
+ dims_{dims} {}
676
+
677
+ public:
678
+ /**
679
+ * Unchecked const reference access to data at the given indices. For a compile-time known
680
+ * number of dimensions, this requires the correct number of arguments; for run-time
681
+ * dimensionality, this is not checked (and so is up to the caller to use safely).
682
+ */
683
+ template <typename... Ix>
684
+ const T &operator()(Ix... index) const {
685
+ static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
686
+ "Invalid number of indices for unchecked array reference");
687
+ return *reinterpret_cast<const T *>(data_
688
+ + byte_offset_unsafe(strides_, ssize_t(index)...));
689
+ }
690
+ /**
691
+ * Unchecked const reference access to data; this operator only participates if the reference
692
+ * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`.
693
+ */
694
+ template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
695
+ const T &operator[](ssize_t index) const {
696
+ return operator()(index);
697
+ }
698
+
699
+ /// Pointer access to the data at the given indices.
700
+ template <typename... Ix>
701
+ const T *data(Ix... ix) const {
702
+ return &operator()(ssize_t(ix)...);
703
+ }
704
+
705
+ /// Returns the item size, i.e. sizeof(T)
706
+ constexpr static ssize_t itemsize() { return sizeof(T); }
707
+
708
+ /// Returns the shape (i.e. size) of dimension `dim`
709
+ ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }
710
+
711
+ /// Returns the number of dimensions of the array
712
+ ssize_t ndim() const { return dims_; }
713
+
714
+ /// Returns the total number of elements in the referenced array, i.e. the product of the
715
+ /// shapes
716
+ template <bool Dyn = Dynamic>
717
+ enable_if_t<!Dyn, ssize_t> size() const {
718
+ return std::accumulate(
719
+ shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
720
+ }
721
+ template <bool Dyn = Dynamic>
722
+ enable_if_t<Dyn, ssize_t> size() const {
723
+ return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
724
+ }
725
+
726
+ /// Returns the total number of bytes used by the referenced data. Note that the actual span
727
+ /// in memory may be larger if the referenced array has non-contiguous strides (e.g. for a
728
+ /// slice).
729
+ ssize_t nbytes() const { return size() * itemsize(); }
730
+ };
731
+
732
+ template <typename T, ssize_t Dims>
733
+ class unchecked_mutable_reference : public unchecked_reference<T, Dims> {
734
+ friend class pybind11::array;
735
+ using ConstBase = unchecked_reference<T, Dims>;
736
+ using ConstBase::ConstBase;
737
+ using ConstBase::Dynamic;
738
+
739
+ public:
740
+ // Bring in const-qualified versions from base class
741
+ using ConstBase::operator();
742
+ using ConstBase::operator[];
743
+
744
+ /// Mutable, unchecked access to data at the given indices.
745
+ template <typename... Ix>
746
+ T &operator()(Ix... index) {
747
+ static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
748
+ "Invalid number of indices for unchecked array reference");
749
+ return const_cast<T &>(ConstBase::operator()(index...));
750
+ }
751
+ /**
752
+ * Mutable, unchecked access data at the given index; this operator only participates if the
753
+ * reference is to a 1-dimensional array (or has runtime dimensions). When present, this is
754
+ * exactly equivalent to `obj(index)`.
755
+ */
756
+ template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
757
+ T &operator[](ssize_t index) {
758
+ return operator()(index);
759
+ }
760
+
761
+ /// Mutable pointer access to the data at the given indices.
762
+ template <typename... Ix>
763
+ T *mutable_data(Ix... ix) {
764
+ return &operator()(ssize_t(ix)...);
765
+ }
766
+ };
767
+
768
+ template <typename T, ssize_t Dim>
769
+ struct type_caster<unchecked_reference<T, Dim>> {
770
+ static_assert(Dim == 0 && Dim > 0 /* always fail */,
771
+ "unchecked array proxy object is not castable");
772
+ };
773
+ template <typename T, ssize_t Dim>
774
+ struct type_caster<unchecked_mutable_reference<T, Dim>>
775
+ : type_caster<unchecked_reference<T, Dim>> {};
776
+
777
+ template <typename T>
778
+ struct type_caster<numpy_scalar<T>> {
779
+ using value_type = T;
780
+ using type_info = numpy_scalar_info<T>;
781
+
782
+ PYBIND11_TYPE_CASTER(numpy_scalar<T>, type_info::name);
783
+
784
+ static handle &target_type() {
785
+ static handle tp = npy_api::get().PyArray_TypeObjectFromType_(type_info::typenum);
786
+ return tp;
787
+ }
788
+
789
+ static handle &target_dtype() {
790
+ static handle tp = npy_api::get().PyArray_DescrFromType_(type_info::typenum);
791
+ return tp;
792
+ }
793
+
794
+ bool load(handle src, bool) {
795
+ if (isinstance(src, target_type())) {
796
+ npy_api::get().PyArray_ScalarAsCtype_(src.ptr(), &value.value);
797
+ return true;
798
+ }
799
+ return false;
800
+ }
801
+
802
+ static handle cast(numpy_scalar<T> src, return_value_policy, handle) {
803
+ return npy_api::get().PyArray_Scalar_(&src.value, target_dtype().ptr(), nullptr);
804
+ }
805
+ };
806
+
807
+ PYBIND11_NAMESPACE_END(detail)
808
+
809
+ template <typename T>
810
+ struct numpy_scalar {
811
+ using value_type = T;
812
+
813
+ value_type value;
814
+
815
+ numpy_scalar() = default;
816
+ explicit numpy_scalar(value_type value) : value(value) {}
817
+
818
+ explicit operator value_type() const { return value; }
819
+ numpy_scalar &operator=(value_type value) {
820
+ this->value = value;
821
+ return *this;
822
+ }
823
+
824
+ friend bool operator==(const numpy_scalar &a, const numpy_scalar &b) {
825
+ return a.value == b.value;
826
+ }
827
+
828
+ friend bool operator!=(const numpy_scalar &a, const numpy_scalar &b) { return !(a == b); }
829
+ };
830
+
831
+ template <typename T>
832
+ numpy_scalar<T> make_scalar(T value) {
833
+ return numpy_scalar<T>(value);
834
+ }
835
+
836
+ class dtype : public object {
837
+ public:
838
+ PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_)
839
+
840
+ explicit dtype(const buffer_info &info) {
841
+ dtype descr(_dtype_from_pep3118()(pybind11::str(info.format)));
842
+ // If info.itemsize == 0, use the value calculated from the format string
843
+ m_ptr = descr.strip_padding(info.itemsize != 0 ? info.itemsize : descr.itemsize())
844
+ .release()
845
+ .ptr();
846
+ }
847
+
848
+ explicit dtype(const pybind11::str &format) : dtype(from_args(format)) {}
849
+
850
+ explicit dtype(const std::string &format) : dtype(pybind11::str(format)) {}
851
+
852
+ explicit dtype(const char *format) : dtype(pybind11::str(format)) {}
853
+
854
+ dtype(list names, list formats, list offsets, ssize_t itemsize) {
855
+ dict args;
856
+ args["names"] = std::move(names);
857
+ args["formats"] = std::move(formats);
858
+ args["offsets"] = std::move(offsets);
859
+ args["itemsize"] = pybind11::int_(itemsize);
860
+ m_ptr = from_args(args).release().ptr();
861
+ }
862
+
863
+ /// Return dtype for the given typenum (one of the NPY_TYPES).
864
+ /// https://numpy.org/devdocs/reference/c-api/array.html#c.PyArray_DescrFromType
865
+ explicit dtype(int typenum)
866
+ : object(detail::npy_api::get().PyArray_DescrFromType_(typenum), stolen_t{}) {
867
+ if (m_ptr == nullptr) {
868
+ throw error_already_set();
869
+ }
870
+ }
871
+
872
+ /// This is essentially the same as calling numpy.dtype(args) in Python.
873
+ static dtype from_args(const object &args) {
874
+ PyObject *ptr = nullptr;
875
+ if ((detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) == 0) || !ptr) {
876
+ throw error_already_set();
877
+ }
878
+ return reinterpret_steal<dtype>(ptr);
879
+ }
880
+
881
+ /// Return dtype associated with a C++ type.
882
+ template <typename T>
883
+ static dtype of() {
884
+ return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
885
+ }
886
+
887
+ /// Return the type number associated with a C++ type.
888
+ /// This is the constexpr equivalent of `dtype::of<T>().num()`.
889
+ template <typename T>
890
+ static constexpr int num_of() {
891
+ return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::value;
892
+ }
893
+
894
+ /// Size of the data type in bytes.
895
+ ssize_t itemsize() const {
896
+ if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {
897
+ return detail::array_descriptor1_proxy(m_ptr)->elsize;
898
+ }
899
+ return detail::array_descriptor2_proxy(m_ptr)->elsize;
900
+ }
901
+
902
+ /// Returns true for structured data types.
903
+ bool has_fields() const {
904
+ if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {
905
+ return detail::array_descriptor1_proxy(m_ptr)->names != nullptr;
906
+ }
907
+ const auto *proxy = detail::array_descriptor2_proxy(m_ptr);
908
+ if (proxy->type_num < 0 || proxy->type_num >= 2056) {
909
+ return false;
910
+ }
911
+ return proxy->names != nullptr;
912
+ }
913
+
914
+ /// Single-character code for dtype's kind.
915
+ /// For example, floating point types are 'f' and integral types are 'i'.
916
+ char kind() const { return detail::array_descriptor_proxy(m_ptr)->kind; }
917
+
918
+ /// Single-character for dtype's type.
919
+ /// For example, ``float`` is 'f', ``double`` 'd', ``int`` 'i', and ``long`` 'l'.
920
+ char char_() const {
921
+ // Note: The signature, `dtype::char_` follows the naming of NumPy's
922
+ // public Python API (i.e., ``dtype.char``), rather than its internal
923
+ // C API (``PyArray_Descr::type``).
924
+ return detail::array_descriptor_proxy(m_ptr)->type;
925
+ }
926
+
927
+ /// Type number of dtype. Note that different values may be returned for equivalent types,
928
+ /// e.g. even though ``long`` may be equivalent to ``int`` or ``long long``, they still have
929
+ /// different type numbers. Consider using `normalized_num` to avoid this.
930
+ int num() const {
931
+ // Note: The signature, `dtype::num` follows the naming of NumPy's public
932
+ // Python API (i.e., ``dtype.num``), rather than its internal
933
+ // C API (``PyArray_Descr::type_num``).
934
+ return detail::array_descriptor_proxy(m_ptr)->type_num;
935
+ }
936
+
937
+ /// Type number of dtype, normalized to match the return value of `num_of` for equivalent
938
+ /// types. This function can be used to write switch statements that correctly handle
939
+ /// equivalent types with different type numbers.
940
+ int normalized_num() const {
941
+ int value = num();
942
+ if (value >= 0 && value <= detail::npy_api::NPY_VOID_) {
943
+ return detail::normalized_dtype_num[value];
944
+ }
945
+ return value;
946
+ }
947
+
948
+ /// Single character for byteorder
949
+ char byteorder() const { return detail::array_descriptor_proxy(m_ptr)->byteorder; }
950
+
951
+ /// Alignment of the data type
952
+ ssize_t alignment() const {
953
+ if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {
954
+ return detail::array_descriptor1_proxy(m_ptr)->alignment;
955
+ }
956
+ return detail::array_descriptor2_proxy(m_ptr)->alignment;
957
+ }
958
+
959
+ /// Flags for the array descriptor
960
+ std::uint64_t flags() const {
961
+ if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {
962
+ return (unsigned char) detail::array_descriptor1_proxy(m_ptr)->flags;
963
+ }
964
+ return detail::array_descriptor2_proxy(m_ptr)->flags;
965
+ }
966
+
967
+ private:
968
+ static object &_dtype_from_pep3118() {
969
+ PYBIND11_CONSTINIT static gil_safe_call_once_and_store<object> storage;
970
+ return storage
971
+ .call_once_and_store_result([]() {
972
+ return detail::import_numpy_core_submodule("_internal")
973
+ .attr("_dtype_from_pep3118");
974
+ })
975
+ .get_stored();
976
+ }
977
+
978
+ dtype strip_padding(ssize_t itemsize) {
979
+ // Recursively strip all void fields with empty names that are generated for
980
+ // padding fields (as of NumPy v1.11).
981
+ if (!has_fields()) {
982
+ return *this;
983
+ }
984
+
985
+ struct field_descr {
986
+ pybind11::str name;
987
+ object format;
988
+ pybind11::int_ offset;
989
+ field_descr(pybind11::str &&name, object &&format, pybind11::int_ &&offset)
990
+ : name{std::move(name)}, format{std::move(format)}, offset{std::move(offset)} {};
991
+ };
992
+ auto field_dict = attr("fields").cast<dict>();
993
+ std::vector<field_descr> field_descriptors;
994
+ field_descriptors.reserve(field_dict.size());
995
+
996
+ for (auto field : field_dict.attr("items")()) {
997
+ auto spec = field.cast<tuple>();
998
+ auto name = spec[0].cast<pybind11::str>();
999
+ auto spec_fo = spec[1].cast<tuple>();
1000
+ auto format = spec_fo[0].cast<dtype>();
1001
+ auto offset = spec_fo[1].cast<pybind11::int_>();
1002
+ if ((len(name) == 0u) && format.kind() == 'V') {
1003
+ continue;
1004
+ }
1005
+ field_descriptors.emplace_back(
1006
+ std::move(name), format.strip_padding(format.itemsize()), std::move(offset));
1007
+ }
1008
+
1009
+ std::sort(field_descriptors.begin(),
1010
+ field_descriptors.end(),
1011
+ [](const field_descr &a, const field_descr &b) {
1012
+ return a.offset.cast<int>() < b.offset.cast<int>();
1013
+ });
1014
+
1015
+ list names, formats, offsets;
1016
+ for (auto &descr : field_descriptors) {
1017
+ names.append(std::move(descr.name));
1018
+ formats.append(std::move(descr.format));
1019
+ offsets.append(std::move(descr.offset));
1020
+ }
1021
+ return dtype(std::move(names), std::move(formats), std::move(offsets), itemsize);
1022
+ }
1023
+ };
1024
+
1025
+ class array : public buffer {
1026
+ public:
1027
+ PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array)
1028
+
1029
+ enum {
1030
+ c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
1031
+ f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
1032
+ forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
1033
+ };
1034
+
1035
+ array() : array(0, static_cast<const double *>(nullptr)) {}
1036
+
1037
+ using ShapeContainer = detail::any_container<ssize_t>;
1038
+ using StridesContainer = detail::any_container<ssize_t>;
1039
+
1040
+ // Constructs an array taking shape/strides from arbitrary container types
1041
+ array(const pybind11::dtype &dt,
1042
+ ShapeContainer shape,
1043
+ StridesContainer strides,
1044
+ const void *ptr = nullptr,
1045
+ handle base = handle()) {
1046
+
1047
+ if (strides->empty()) {
1048
+ *strides = detail::c_strides(*shape, dt.itemsize());
1049
+ }
1050
+
1051
+ auto ndim = shape->size();
1052
+ if (ndim != strides->size()) {
1053
+ pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
1054
+ }
1055
+ auto descr = dt;
1056
+
1057
+ int flags = 0;
1058
+ if (base && ptr) {
1059
+ if (isinstance<array>(base)) {
1060
+ /* Copy flags from base (except ownership bit) */
1061
+ flags = reinterpret_borrow<array>(base).flags()
1062
+ & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
1063
+ } else {
1064
+ /* Writable by default, easy to downgrade later on if needed */
1065
+ flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
1066
+ }
1067
+ }
1068
+
1069
+ auto &api = detail::npy_api::get();
1070
+ auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
1071
+ api.PyArray_Type_,
1072
+ descr.release().ptr(),
1073
+ (int) ndim,
1074
+ // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
1075
+ reinterpret_cast<Py_intptr_t *>(shape->data()),
1076
+ reinterpret_cast<Py_intptr_t *>(strides->data()),
1077
+ const_cast<void *>(ptr),
1078
+ flags,
1079
+ nullptr));
1080
+ if (!tmp) {
1081
+ throw error_already_set();
1082
+ }
1083
+ if (ptr) {
1084
+ if (base) {
1085
+ api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
1086
+ } else {
1087
+ tmp = reinterpret_steal<object>(
1088
+ api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
1089
+ }
1090
+ }
1091
+ m_ptr = tmp.release().ptr();
1092
+ }
1093
+
1094
+ array(const pybind11::dtype &dt,
1095
+ ShapeContainer shape,
1096
+ const void *ptr = nullptr,
1097
+ handle base = handle())
1098
+ : array(dt, std::move(shape), {}, ptr, base) {}
1099
+
1100
+ template <typename T,
1101
+ typename
1102
+ = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>
1103
+ array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
1104
+ : array(dt, {{count}}, ptr, base) {}
1105
+
1106
+ template <typename T>
1107
+ array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())
1108
+ : array(pybind11::dtype::of<T>(),
1109
+ std::move(shape),
1110
+ std::move(strides),
1111
+ reinterpret_cast<const void *>(ptr),
1112
+ base) {}
1113
+
1114
+ template <typename T>
1115
+ array(ShapeContainer shape, const T *ptr, handle base = handle())
1116
+ : array(std::move(shape), {}, ptr, base) {}
1117
+
1118
+ template <typename T>
1119
+ explicit array(ssize_t count, const T *ptr, handle base = handle())
1120
+ : array({count}, {}, ptr, base) {}
1121
+
1122
+ explicit array(const buffer_info &info, handle base = handle())
1123
+ : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) {}
1124
+
1125
+ /// Array descriptor (dtype)
1126
+ pybind11::dtype dtype() const {
1127
+ return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
1128
+ }
1129
+
1130
+ /// Total number of elements
1131
+ ssize_t size() const {
1132
+ return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
1133
+ }
1134
+
1135
+ /// Byte size of a single element
1136
+ ssize_t itemsize() const { return dtype().itemsize(); }
1137
+
1138
+ /// Total number of bytes
1139
+ ssize_t nbytes() const { return size() * itemsize(); }
1140
+
1141
+ /// Number of dimensions
1142
+ ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; }
1143
+
1144
+ /// Base object
1145
+ object base() const { return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); }
1146
+
1147
+ /// Dimensions of the array
1148
+ const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; }
1149
+
1150
+ #ifdef PYBIND11_HAS_SPAN
1151
+ /// Dimensions of the array as a span
1152
+ std::span<const ssize_t, std::dynamic_extent> shape_span() const {
1153
+ return std::span(shape(), static_cast<std::size_t>(ndim()));
1154
+ }
1155
+ #endif
1156
+
1157
+ /// Dimension along a given axis
1158
+ ssize_t shape(ssize_t dim) const {
1159
+ if (dim >= ndim()) {
1160
+ fail_dim_check(dim, "invalid axis");
1161
+ }
1162
+ return shape()[dim];
1163
+ }
1164
+
1165
+ /// Strides of the array
1166
+ const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; }
1167
+
1168
+ #ifdef PYBIND11_HAS_SPAN
1169
+ /// Strides of the array as a span
1170
+ std::span<const ssize_t, std::dynamic_extent> strides_span() const {
1171
+ return std::span(strides(), static_cast<std::size_t>(ndim()));
1172
+ }
1173
+ #endif
1174
+
1175
+ /// Stride along a given axis
1176
+ ssize_t strides(ssize_t dim) const {
1177
+ if (dim >= ndim()) {
1178
+ fail_dim_check(dim, "invalid axis");
1179
+ }
1180
+ return strides()[dim];
1181
+ }
1182
+
1183
+ /// Return the NumPy array flags
1184
+ int flags() const { return detail::array_proxy(m_ptr)->flags; }
1185
+
1186
+ /// If set, the array is writeable (otherwise the buffer is read-only)
1187
+ bool writeable() const {
1188
+ return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
1189
+ }
1190
+
1191
+ /// If set, the array owns the data (will be freed when the array is deleted)
1192
+ bool owndata() const {
1193
+ return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
1194
+ }
1195
+
1196
+ /// Pointer to the contained data. If index is not provided, points to the
1197
+ /// beginning of the buffer. May throw if the index would lead to out of bounds access.
1198
+ template <typename... Ix>
1199
+ const void *data(Ix... index) const {
1200
+ return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
1201
+ }
1202
+
1203
+ /// Mutable pointer to the contained data. If index is not provided, points to the
1204
+ /// beginning of the buffer. May throw if the index would lead to out of bounds access.
1205
+ /// May throw if the array is not writeable.
1206
+ template <typename... Ix>
1207
+ void *mutable_data(Ix... index) {
1208
+ check_writeable();
1209
+ return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
1210
+ }
1211
+
1212
+ /// Byte offset from beginning of the array to a given index (full or partial).
1213
+ /// May throw if the index would lead to out of bounds access.
1214
+ template <typename... Ix>
1215
+ ssize_t offset_at(Ix... index) const {
1216
+ if ((ssize_t) sizeof...(index) > ndim()) {
1217
+ fail_dim_check(sizeof...(index), "too many indices for an array");
1218
+ }
1219
+ return byte_offset(ssize_t(index)...);
1220
+ }
1221
+
1222
+ ssize_t offset_at() const { return 0; }
1223
+
1224
+ /// Item count from beginning of the array to a given index (full or partial).
1225
+ /// May throw if the index would lead to out of bounds access.
1226
+ template <typename... Ix>
1227
+ ssize_t index_at(Ix... index) const {
1228
+ return offset_at(index...) / itemsize();
1229
+ }
1230
+
1231
+ /**
1232
+ * Returns a proxy object that provides access to the array's data without bounds or
1233
+ * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
1234
+ * care: the array must not be destroyed or reshaped for the duration of the returned object,
1235
+ * and the caller must take care not to access invalid dimensions or dimension indices.
1236
+ */
1237
+ template <typename T, ssize_t Dims = -1>
1238
+ detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
1239
+ if (Dims >= 0 && ndim() != Dims) {
1240
+ throw std::domain_error("array has incorrect number of dimensions: "
1241
+ + std::to_string(ndim()) + "; expected "
1242
+ + std::to_string(Dims));
1243
+ }
1244
+ return detail::unchecked_mutable_reference<T, Dims>(
1245
+ mutable_data(), shape(), strides(), ndim());
1246
+ }
1247
+
1248
+ /**
1249
+ * Returns a proxy object that provides const access to the array's data without bounds or
1250
+ * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the
1251
+ * underlying array have the `writable` flag. Use with care: the array must not be destroyed
1252
+ * or reshaped for the duration of the returned object, and the caller must take care not to
1253
+ * access invalid dimensions or dimension indices.
1254
+ */
1255
+ template <typename T, ssize_t Dims = -1>
1256
+ detail::unchecked_reference<T, Dims> unchecked() const & {
1257
+ if (Dims >= 0 && ndim() != Dims) {
1258
+ throw std::domain_error("array has incorrect number of dimensions: "
1259
+ + std::to_string(ndim()) + "; expected "
1260
+ + std::to_string(Dims));
1261
+ }
1262
+ return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
1263
+ }
1264
+
1265
+ /// Return a new view with all of the dimensions of length 1 removed
1266
+ array squeeze() {
1267
+ auto &api = detail::npy_api::get();
1268
+ return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
1269
+ }
1270
+
1271
+ /// Resize array to given shape
1272
+ /// If refcheck is true and more that one reference exist to this array
1273
+ /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change
1274
+ void resize(ShapeContainer new_shape, bool refcheck = true) {
1275
+ detail::npy_api::PyArray_Dims d
1276
+ = {// Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
1277
+ reinterpret_cast<Py_intptr_t *>(new_shape->data()),
1278
+ int(new_shape->size())};
1279
+ // try to resize, set ordering param to -1 cause it's not used anyway
1280
+ auto new_array = reinterpret_steal<object>(
1281
+ detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1));
1282
+ if (!new_array) {
1283
+ throw error_already_set();
1284
+ }
1285
+ if (isinstance<array>(new_array)) {
1286
+ *this = std::move(new_array);
1287
+ }
1288
+ }
1289
+
1290
+ /// Optional `order` parameter omitted, to be added as needed.
1291
+ array reshape(ShapeContainer new_shape) {
1292
+ detail::npy_api::PyArray_Dims d
1293
+ = {reinterpret_cast<Py_intptr_t *>(new_shape->data()), int(new_shape->size())};
1294
+ auto new_array
1295
+ = reinterpret_steal<array>(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0));
1296
+ if (!new_array) {
1297
+ throw error_already_set();
1298
+ }
1299
+ return new_array;
1300
+ }
1301
+
1302
+ /// Create a view of an array in a different data type.
1303
+ /// This function may fundamentally reinterpret the data in the array.
1304
+ /// It is the responsibility of the caller to ensure that this is safe.
1305
+ /// Only supports the `dtype` argument, the `type` argument is omitted,
1306
+ /// to be added as needed.
1307
+ array view(const std::string &dtype) {
1308
+ auto &api = detail::npy_api::get();
1309
+ auto new_view = reinterpret_steal<array>(api.PyArray_View_(
1310
+ m_ptr, dtype::from_args(pybind11::str(dtype)).release().ptr(), nullptr));
1311
+ if (!new_view) {
1312
+ throw error_already_set();
1313
+ }
1314
+ return new_view;
1315
+ }
1316
+
1317
+ /// Ensure that the argument is a NumPy array
1318
+ /// In case of an error, nullptr is returned and the Python error is cleared.
1319
+ static array ensure(handle h, int ExtraFlags = 0) {
1320
+ auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
1321
+ if (!result) {
1322
+ PyErr_Clear();
1323
+ }
1324
+ return result;
1325
+ }
1326
+
1327
+ protected:
1328
+ template <typename, typename>
1329
+ friend struct detail::npy_format_descriptor;
1330
+
1331
+ void fail_dim_check(ssize_t dim, const std::string &msg) const {
1332
+ throw index_error(msg + ": " + std::to_string(dim) + " (ndim = " + std::to_string(ndim())
1333
+ + ')');
1334
+ }
1335
+
1336
+ template <typename... Ix>
1337
+ ssize_t byte_offset(Ix... index) const {
1338
+ check_dimensions(index...);
1339
+ return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
1340
+ }
1341
+
1342
+ void check_writeable() const {
1343
+ if (!writeable()) {
1344
+ throw std::domain_error("array is not writeable");
1345
+ }
1346
+ }
1347
+
1348
+ template <typename... Ix>
1349
+ void check_dimensions(Ix... index) const {
1350
+ check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
1351
+ }
1352
+
1353
+ void check_dimensions_impl(ssize_t, const ssize_t *) const {}
1354
+
1355
+ template <typename... Ix>
1356
+ void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const {
1357
+ if (i >= *shape) {
1358
+ throw index_error(std::string("index ") + std::to_string(i)
1359
+ + " is out of bounds for axis " + std::to_string(axis)
1360
+ + " with size " + std::to_string(*shape));
1361
+ }
1362
+ check_dimensions_impl(axis + 1, shape + 1, index...);
1363
+ }
1364
+
1365
+ /// Create array from any object -- always returns a new reference
1366
+ static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
1367
+ if (ptr == nullptr) {
1368
+ set_error(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
1369
+ return nullptr;
1370
+ }
1371
+ return detail::npy_api::get().PyArray_FromAny_(
1372
+ ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
1373
+ }
1374
+ };
1375
+
1376
+ template <typename T, int ExtraFlags = array::forcecast>
1377
+ class array_t : public array {
1378
+ private:
1379
+ struct private_ctor {};
1380
+ // Delegating constructor needed when both moving and accessing in the same constructor
1381
+ array_t(private_ctor,
1382
+ ShapeContainer &&shape,
1383
+ StridesContainer &&strides,
1384
+ const T *ptr,
1385
+ handle base)
1386
+ : array(std::move(shape), std::move(strides), ptr, base) {}
1387
+
1388
+ public:
1389
+ static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
1390
+
1391
+ using value_type = T;
1392
+
1393
+ array_t() : array(0, static_cast<const T *>(nullptr)) {}
1394
+ array_t(handle h, borrowed_t) : array(h, borrowed_t{}) {}
1395
+ array_t(handle h, stolen_t) : array(h, stolen_t{}) {}
1396
+
1397
+ PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
1398
+ array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) {
1399
+ if (!m_ptr) {
1400
+ PyErr_Clear();
1401
+ }
1402
+ if (!is_borrowed) {
1403
+ Py_XDECREF(h.ptr());
1404
+ }
1405
+ }
1406
+
1407
+ // NOLINTNEXTLINE(google-explicit-constructor)
1408
+ array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
1409
+ if (!m_ptr) {
1410
+ throw error_already_set();
1411
+ }
1412
+ }
1413
+
1414
+ explicit array_t(const buffer_info &info, handle base = handle()) : array(info, base) {}
1415
+
1416
+ array_t(ShapeContainer shape,
1417
+ StridesContainer strides,
1418
+ const T *ptr = nullptr,
1419
+ handle base = handle())
1420
+ : array(std::move(shape), std::move(strides), ptr, base) {}
1421
+
1422
+ explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
1423
+ : array_t(private_ctor{},
1424
+ std::move(shape),
1425
+ (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize())
1426
+ : detail::c_strides(*shape, itemsize()),
1427
+ ptr,
1428
+ base) {}
1429
+
1430
+ explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())
1431
+ : array({count}, {}, ptr, base) {}
1432
+
1433
+ constexpr ssize_t itemsize() const { return sizeof(T); }
1434
+
1435
+ template <typename... Ix>
1436
+ ssize_t index_at(Ix... index) const {
1437
+ return offset_at(index...) / itemsize();
1438
+ }
1439
+
1440
+ template <typename... Ix>
1441
+ const T *data(Ix... index) const {
1442
+ return static_cast<const T *>(array::data(index...));
1443
+ }
1444
+
1445
+ template <typename... Ix>
1446
+ T *mutable_data(Ix... index) {
1447
+ return static_cast<T *>(array::mutable_data(index...));
1448
+ }
1449
+
1450
+ // Reference to element at a given index
1451
+ template <typename... Ix>
1452
+ const T &at(Ix... index) const {
1453
+ if ((ssize_t) sizeof...(index) != ndim()) {
1454
+ fail_dim_check(sizeof...(index), "index dimension mismatch");
1455
+ }
1456
+ return *(static_cast<const T *>(array::data())
1457
+ + byte_offset(ssize_t(index)...) / itemsize());
1458
+ }
1459
+
1460
+ // Mutable reference to element at a given index
1461
+ template <typename... Ix>
1462
+ T &mutable_at(Ix... index) {
1463
+ if ((ssize_t) sizeof...(index) != ndim()) {
1464
+ fail_dim_check(sizeof...(index), "index dimension mismatch");
1465
+ }
1466
+ return *(static_cast<T *>(array::mutable_data())
1467
+ + byte_offset(ssize_t(index)...) / itemsize());
1468
+ }
1469
+
1470
+ /**
1471
+ * Returns a proxy object that provides access to the array's data without bounds or
1472
+ * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
1473
+ * care: the array must not be destroyed or reshaped for the duration of the returned object,
1474
+ * and the caller must take care not to access invalid dimensions or dimension indices.
1475
+ */
1476
+ template <ssize_t Dims = -1>
1477
+ detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
1478
+ return array::mutable_unchecked<T, Dims>();
1479
+ }
1480
+
1481
+ /**
1482
+ * Returns a proxy object that provides const access to the array's data without bounds or
1483
+ * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the
1484
+ * underlying array have the `writable` flag. Use with care: the array must not be destroyed
1485
+ * or reshaped for the duration of the returned object, and the caller must take care not to
1486
+ * access invalid dimensions or dimension indices.
1487
+ */
1488
+ template <ssize_t Dims = -1>
1489
+ detail::unchecked_reference<T, Dims> unchecked() const & {
1490
+ return array::unchecked<T, Dims>();
1491
+ }
1492
+
1493
+ /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert
1494
+ /// it). In case of an error, nullptr is returned and the Python error is cleared.
1495
+ static array_t ensure(handle h) {
1496
+ auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
1497
+ if (!result) {
1498
+ PyErr_Clear();
1499
+ }
1500
+ return result;
1501
+ }
1502
+
1503
+ static bool check_(handle h) {
1504
+ const auto &api = detail::npy_api::get();
1505
+ return api.PyArray_Check_(h.ptr())
1506
+ && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr,
1507
+ dtype::of<T>().ptr())
1508
+ && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));
1509
+ }
1510
+
1511
+ protected:
1512
+ /// Create array from any object -- always returns a new reference
1513
+ static PyObject *raw_array_t(PyObject *ptr) {
1514
+ if (ptr == nullptr) {
1515
+ set_error(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
1516
+ return nullptr;
1517
+ }
1518
+ return detail::npy_api::get().PyArray_FromAny_(ptr,
1519
+ dtype::of<T>().release().ptr(),
1520
+ 0,
1521
+ 0,
1522
+ detail::npy_api::NPY_ARRAY_ENSUREARRAY_
1523
+ | ExtraFlags,
1524
+ nullptr);
1525
+ }
1526
+ };
1527
+
1528
+ template <typename T>
1529
+ struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1530
+ static std::string format() {
1531
+ return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format();
1532
+ }
1533
+ };
1534
+
1535
+ template <size_t N>
1536
+ struct format_descriptor<char[N]> {
1537
+ static std::string format() { return std::to_string(N) + 's'; }
1538
+ };
1539
+ template <size_t N>
1540
+ struct format_descriptor<std::array<char, N>> {
1541
+ static std::string format() { return std::to_string(N) + 's'; }
1542
+ };
1543
+
1544
+ template <typename T>
1545
+ struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
1546
+ static std::string format() {
1547
+ return format_descriptor<
1548
+ typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format();
1549
+ }
1550
+ };
1551
+
1552
+ template <typename T>
1553
+ struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
1554
+ static std::string format() {
1555
+ using namespace detail;
1556
+ static constexpr auto extents = const_name("(") + array_info<T>::extents + const_name(")");
1557
+ return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
1558
+ }
1559
+ };
1560
+
1561
+ PYBIND11_NAMESPACE_BEGIN(detail)
1562
+ template <typename T, int ExtraFlags>
1563
+ struct pyobject_caster<array_t<T, ExtraFlags>> {
1564
+ using type = array_t<T, ExtraFlags>;
1565
+
1566
+ bool load(handle src, bool convert) {
1567
+ if (!convert && !type::check_(src)) {
1568
+ return false;
1569
+ }
1570
+ value = type::ensure(src);
1571
+ return static_cast<bool>(value);
1572
+ }
1573
+
1574
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1575
+ return src.inc_ref();
1576
+ }
1577
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1578
+ };
1579
+
1580
+ template <typename T>
1581
+ struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1582
+ static bool compare(const buffer_info &b) {
1583
+ return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
1584
+ }
1585
+ };
1586
+
1587
+ template <typename T>
1588
+ struct npy_format_descriptor<
1589
+ T,
1590
+ enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
1591
+ : npy_format_descriptor_name<T> {
1592
+ private:
1593
+ // NB: the order here must match the one in common.h
1594
+ constexpr static const int values[15] = {npy_api::NPY_BOOL_,
1595
+ npy_api::NPY_BYTE_,
1596
+ npy_api::NPY_UBYTE_,
1597
+ npy_api::NPY_INT16_,
1598
+ npy_api::NPY_UINT16_,
1599
+ npy_api::NPY_INT32_,
1600
+ npy_api::NPY_UINT32_,
1601
+ npy_api::NPY_INT64_,
1602
+ npy_api::NPY_UINT64_,
1603
+ npy_api::NPY_FLOAT_,
1604
+ npy_api::NPY_DOUBLE_,
1605
+ npy_api::NPY_LONGDOUBLE_,
1606
+ npy_api::NPY_CFLOAT_,
1607
+ npy_api::NPY_CDOUBLE_,
1608
+ npy_api::NPY_CLONGDOUBLE_};
1609
+
1610
+ public:
1611
+ static constexpr int value = values[detail::is_fmt_numeric<T>::index];
1612
+
1613
+ static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
1614
+ };
1615
+
1616
+ template <typename T>
1617
+ struct npy_format_descriptor<
1618
+ T,
1619
+ enable_if_t<is_same_ignoring_cvref<T, PyObject *>::value
1620
+ || ((std::is_same<T, handle>::value || std::is_same<T, object>::value)
1621
+ && sizeof(T) == sizeof(PyObject *))>> {
1622
+ static constexpr auto name = const_name("numpy.object_");
1623
+
1624
+ static constexpr int value = npy_api::NPY_OBJECT_;
1625
+
1626
+ static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
1627
+ };
1628
+
1629
+ #define PYBIND11_DECL_CHAR_FMT \
1630
+ static constexpr auto name = const_name("S") + const_name<N>(); \
1631
+ static pybind11::dtype dtype() { \
1632
+ return pybind11::dtype(std::string("S") + std::to_string(N)); \
1633
+ }
1634
+ template <size_t N>
1635
+ struct npy_format_descriptor<char[N]> {
1636
+ PYBIND11_DECL_CHAR_FMT
1637
+ };
1638
+ template <size_t N>
1639
+ struct npy_format_descriptor<std::array<char, N>> {
1640
+ PYBIND11_DECL_CHAR_FMT
1641
+ };
1642
+ #undef PYBIND11_DECL_CHAR_FMT
1643
+
1644
+ template <typename T>
1645
+ struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
1646
+ private:
1647
+ using base_descr = npy_format_descriptor<typename array_info<T>::type>;
1648
+
1649
+ public:
1650
+ static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
1651
+
1652
+ static constexpr auto name
1653
+ = const_name("(") + array_info<T>::extents + const_name(")") + base_descr::name;
1654
+ static pybind11::dtype dtype() {
1655
+ list shape;
1656
+ array_info<T>::append_extents(shape);
1657
+ return pybind11::dtype::from_args(
1658
+ pybind11::make_tuple(base_descr::dtype(), std::move(shape)));
1659
+ }
1660
+ };
1661
+
1662
+ template <typename T>
1663
+ struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
1664
+ private:
1665
+ using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>;
1666
+
1667
+ public:
1668
+ static constexpr auto name = base_descr::name;
1669
+ static pybind11::dtype dtype() { return base_descr::dtype(); }
1670
+ };
1671
+
1672
+ struct field_descriptor {
1673
+ const char *name;
1674
+ ssize_t offset;
1675
+ ssize_t size;
1676
+ std::string format;
1677
+ dtype descr;
1678
+ };
1679
+
1680
+ PYBIND11_NOINLINE void register_structured_dtype(any_container<field_descriptor> fields,
1681
+ const std::type_info &tinfo,
1682
+ ssize_t itemsize,
1683
+ bool (*direct_converter)(PyObject *, void *&)) {
1684
+
1685
+ auto &numpy_internals = get_numpy_internals();
1686
+ if (numpy_internals.get_type_info(tinfo, false)) {
1687
+ pybind11_fail("NumPy: dtype is already registered");
1688
+ }
1689
+
1690
+ // Use ordered fields because order matters as of NumPy 1.14:
1691
+ // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
1692
+ std::vector<field_descriptor> ordered_fields(std::move(fields));
1693
+ std::sort(
1694
+ ordered_fields.begin(),
1695
+ ordered_fields.end(),
1696
+ [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
1697
+
1698
+ list names, formats, offsets;
1699
+ for (auto &field : ordered_fields) {
1700
+ if (!field.descr) {
1701
+ pybind11_fail(std::string("NumPy: unsupported field dtype: `") + field.name + "` @ "
1702
+ + tinfo.name());
1703
+ }
1704
+ names.append(pybind11::str(field.name));
1705
+ formats.append(field.descr);
1706
+ offsets.append(pybind11::int_(field.offset));
1707
+ }
1708
+ auto *dtype_ptr
1709
+ = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize)
1710
+ .release()
1711
+ .ptr();
1712
+
1713
+ // There is an existing bug in NumPy (as of v1.11): trailing bytes are
1714
+ // not encoded explicitly into the format string. This will supposedly
1715
+ // get fixed in v1.12; for further details, see these:
1716
+ // - https://github.com/numpy/numpy/issues/7797
1717
+ // - https://github.com/numpy/numpy/pull/7798
1718
+ // Because of this, we won't use numpy's logic to generate buffer format
1719
+ // strings and will just do it ourselves.
1720
+ ssize_t offset = 0;
1721
+ std::ostringstream oss;
1722
+ // mark the structure as unaligned with '^', because numpy and C++ don't
1723
+ // always agree about alignment (particularly for complex), and we're
1724
+ // explicitly listing all our padding. This depends on none of the fields
1725
+ // overriding the endianness. Putting the ^ in front of individual fields
1726
+ // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
1727
+ oss << "^T{";
1728
+ for (auto &field : ordered_fields) {
1729
+ if (field.offset > offset) {
1730
+ oss << (field.offset - offset) << 'x';
1731
+ }
1732
+ oss << field.format << ':' << field.name << ':';
1733
+ offset = field.offset + field.size;
1734
+ }
1735
+ if (itemsize > offset) {
1736
+ oss << (itemsize - offset) << 'x';
1737
+ }
1738
+ oss << '}';
1739
+ auto format_str = oss.str();
1740
+
1741
+ // Smoke test: verify that NumPy properly parses our buffer format string
1742
+ auto &api = npy_api::get();
1743
+ auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
1744
+ if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) {
1745
+ pybind11_fail("NumPy: invalid buffer descriptor!");
1746
+ }
1747
+
1748
+ auto tindex = std::type_index(tinfo);
1749
+ numpy_internals.registered_dtypes[tindex] = {dtype_ptr, std::move(format_str)};
1750
+ with_internals([tindex, &direct_converter](internals &internals) {
1751
+ internals.direct_conversions[tindex].push_back(direct_converter);
1752
+ });
1753
+ }
1754
+
1755
+ template <typename T, typename SFINAE>
1756
+ struct npy_format_descriptor {
1757
+ static_assert(is_pod_struct<T>::value,
1758
+ "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1759
+
1760
+ static constexpr auto name = make_caster<T>::name;
1761
+
1762
+ static pybind11::dtype dtype() { return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); }
1763
+
1764
+ static std::string format() {
1765
+ static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
1766
+ return format_str;
1767
+ }
1768
+
1769
+ static void register_dtype(any_container<field_descriptor> fields) {
1770
+ register_structured_dtype(std::move(fields),
1771
+ typeid(typename std::remove_cv<T>::type),
1772
+ sizeof(T),
1773
+ &direct_converter);
1774
+ }
1775
+
1776
+ private:
1777
+ static PyObject *dtype_ptr() {
1778
+ static PyObject *ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
1779
+ return ptr;
1780
+ }
1781
+
1782
+ static bool direct_converter(PyObject *obj, void *&value) {
1783
+ auto &api = npy_api::get();
1784
+ if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) {
1785
+ return false;
1786
+ }
1787
+ if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
1788
+ if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
1789
+ value = ((PyVoidScalarObject_Proxy *) obj)->obval;
1790
+ return true;
1791
+ }
1792
+ }
1793
+ return false;
1794
+ }
1795
+ };
1796
+
1797
+ #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1798
+ # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
1799
+ # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
1800
+ #else
1801
+
1802
+ # define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
1803
+ ::pybind11::detail::field_descriptor { \
1804
+ Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
1805
+ ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
1806
+ ::pybind11::detail::npy_format_descriptor< \
1807
+ decltype(std::declval<T>().Field)>::dtype() \
1808
+ }
1809
+
1810
+ // Extract name, offset and format descriptor for a struct field
1811
+ # define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1812
+
1813
+ // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
1814
+ // (C) William Swanson, Paul Fultz
1815
+ # define PYBIND11_EVAL0(...) __VA_ARGS__
1816
+ # define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))
1817
+ # define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))
1818
+ # define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))
1819
+ # define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))
1820
+ # define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))
1821
+ # define PYBIND11_MAP_END(...)
1822
+ # define PYBIND11_MAP_OUT
1823
+ # define PYBIND11_MAP_COMMA ,
1824
+ # define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1825
+ # define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1826
+ # define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)
1827
+ # define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)
1828
+ # if defined(_MSC_VER) \
1829
+ && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1830
+ # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1831
+ PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1832
+ # else
1833
+ # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1834
+ PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1835
+ # endif
1836
+ # define PYBIND11_MAP_LIST_NEXT(test, next) \
1837
+ PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1838
+ # define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1839
+ f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)
1840
+ # define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1841
+ f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)
1842
+ // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
1843
+ # define PYBIND11_MAP_LIST(f, t, ...) \
1844
+ PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))
1845
+
1846
+ # define PYBIND11_NUMPY_DTYPE(Type, ...) \
1847
+ ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1848
+ ::std::vector<::pybind11::detail::field_descriptor>{ \
1849
+ PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1850
+
1851
+ # if defined(_MSC_VER) && !defined(__clang__)
1852
+ # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1853
+ PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1854
+ # else
1855
+ # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1856
+ PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1857
+ # endif
1858
+ # define PYBIND11_MAP2_LIST_NEXT(test, next) \
1859
+ PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1860
+ # define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1861
+ f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)
1862
+ # define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1863
+ f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)
1864
+ // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
1865
+ # define PYBIND11_MAP2_LIST(f, t, ...) \
1866
+ PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))
1867
+
1868
+ # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1869
+ ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1870
+ ::std::vector<::pybind11::detail::field_descriptor>{ \
1871
+ PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1872
+
1873
+ #endif // __CLION_IDE__
1874
+
1875
+ class common_iterator {
1876
+ public:
1877
+ using container_type = std::vector<ssize_t>;
1878
+ using value_type = container_type::value_type;
1879
+ using size_type = container_type::size_type;
1880
+
1881
+ common_iterator() = default;
1882
+
1883
+ common_iterator(void *ptr, const container_type &strides, const container_type &shape)
1884
+ : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(strides.size()) {
1885
+ m_strides.back() = static_cast<value_type>(strides.back());
1886
+ for (size_type i = m_strides.size() - 1; i != 0; --i) {
1887
+ size_type j = i - 1;
1888
+ auto s = static_cast<value_type>(shape[i]);
1889
+ m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
1890
+ }
1891
+ }
1892
+
1893
+ void increment(size_type dim) { p_ptr += m_strides[dim]; }
1894
+
1895
+ void *data() const { return p_ptr; }
1896
+
1897
+ private:
1898
+ char *p_ptr{nullptr};
1899
+ container_type m_strides;
1900
+ };
1901
+
1902
+ template <size_t N>
1903
+ class multi_array_iterator {
1904
+ public:
1905
+ using container_type = std::vector<ssize_t>;
1906
+
1907
+ multi_array_iterator(const std::array<buffer_info, N> &buffers, const container_type &shape)
1908
+ : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() {
1909
+
1910
+ // Manual copy to avoid conversion warning if using std::copy
1911
+ for (size_t i = 0; i < shape.size(); ++i) {
1912
+ m_shape[i] = shape[i];
1913
+ }
1914
+
1915
+ container_type strides(shape.size());
1916
+ for (size_t i = 0; i < N; ++i) {
1917
+ init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
1918
+ }
1919
+ }
1920
+
1921
+ multi_array_iterator &operator++() {
1922
+ for (size_t j = m_index.size(); j != 0; --j) {
1923
+ size_t i = j - 1;
1924
+ if (++m_index[i] != m_shape[i]) {
1925
+ increment_common_iterator(i);
1926
+ break;
1927
+ }
1928
+ m_index[i] = 0;
1929
+ }
1930
+ return *this;
1931
+ }
1932
+
1933
+ template <size_t K, class T = void>
1934
+ T *data() const {
1935
+ return reinterpret_cast<T *>(m_common_iterator[K].data());
1936
+ }
1937
+
1938
+ private:
1939
+ using common_iter = common_iterator;
1940
+
1941
+ void init_common_iterator(const buffer_info &buffer,
1942
+ const container_type &shape,
1943
+ common_iter &iterator,
1944
+ container_type &strides) {
1945
+ auto buffer_shape_iter = buffer.shape.rbegin();
1946
+ auto buffer_strides_iter = buffer.strides.rbegin();
1947
+ auto shape_iter = shape.rbegin();
1948
+ auto strides_iter = strides.rbegin();
1949
+
1950
+ while (buffer_shape_iter != buffer.shape.rend()) {
1951
+ if (*shape_iter == *buffer_shape_iter) {
1952
+ *strides_iter = *buffer_strides_iter;
1953
+ } else {
1954
+ *strides_iter = 0;
1955
+ }
1956
+
1957
+ ++buffer_shape_iter;
1958
+ ++buffer_strides_iter;
1959
+ ++shape_iter;
1960
+ ++strides_iter;
1961
+ }
1962
+
1963
+ std::fill(strides_iter, strides.rend(), 0);
1964
+ iterator = common_iter(buffer.ptr, strides, shape);
1965
+ }
1966
+
1967
+ void increment_common_iterator(size_t dim) {
1968
+ for (auto &iter : m_common_iterator) {
1969
+ iter.increment(dim);
1970
+ }
1971
+ }
1972
+
1973
+ container_type m_shape;
1974
+ container_type m_index;
1975
+ std::array<common_iter, N> m_common_iterator;
1976
+ };
1977
+
1978
+ enum class broadcast_trivial { non_trivial, c_trivial, f_trivial };
1979
+
1980
+ // Populates the shape and number of dimensions for the set of buffers. Returns a
1981
+ // broadcast_trivial enum value indicating whether the broadcast is "trivial"--that is, has each
1982
+ // buffer being either a singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous
1983
+ // (`f_trivial`) storage buffer; returns `non_trivial` otherwise.
1984
+ template <size_t N>
1985
+ broadcast_trivial
1986
+ broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
1987
+ ndim = std::accumulate(
1988
+ buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
1989
+ return std::max(res, buf.ndim);
1990
+ });
1991
+
1992
+ shape.clear();
1993
+ shape.resize((size_t) ndim, 1);
1994
+
1995
+ // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1
1996
+ // or the full size).
1997
+ for (size_t i = 0; i < N; ++i) {
1998
+ auto res_iter = shape.rbegin();
1999
+ auto end = buffers[i].shape.rend();
2000
+ for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end;
2001
+ ++shape_iter, ++res_iter) {
2002
+ const auto &dim_size_in = *shape_iter;
2003
+ auto &dim_size_out = *res_iter;
2004
+
2005
+ // Each input dimension can either be 1 or `n`, but `n` values must match across
2006
+ // buffers
2007
+ if (dim_size_out == 1) {
2008
+ dim_size_out = dim_size_in;
2009
+ } else if (dim_size_in != 1 && dim_size_in != dim_size_out) {
2010
+ pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
2011
+ }
2012
+ }
2013
+ }
2014
+
2015
+ bool trivial_broadcast_c = true;
2016
+ bool trivial_broadcast_f = true;
2017
+ for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
2018
+ if (buffers[i].size == 1) {
2019
+ continue;
2020
+ }
2021
+
2022
+ // Require the same number of dimensions:
2023
+ if (buffers[i].ndim != ndim) {
2024
+ return broadcast_trivial::non_trivial;
2025
+ }
2026
+
2027
+ // Require all dimensions be full-size:
2028
+ if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) {
2029
+ return broadcast_trivial::non_trivial;
2030
+ }
2031
+
2032
+ // Check for C contiguity (but only if previous inputs were also C contiguous)
2033
+ if (trivial_broadcast_c) {
2034
+ ssize_t expect_stride = buffers[i].itemsize;
2035
+ auto end = buffers[i].shape.crend();
2036
+ for (auto shape_iter = buffers[i].shape.crbegin(),
2037
+ stride_iter = buffers[i].strides.crbegin();
2038
+ trivial_broadcast_c && shape_iter != end;
2039
+ ++shape_iter, ++stride_iter) {
2040
+ if (expect_stride == *stride_iter) {
2041
+ expect_stride *= *shape_iter;
2042
+ } else {
2043
+ trivial_broadcast_c = false;
2044
+ }
2045
+ }
2046
+ }
2047
+
2048
+ // Check for Fortran contiguity (if previous inputs were also F contiguous)
2049
+ if (trivial_broadcast_f) {
2050
+ ssize_t expect_stride = buffers[i].itemsize;
2051
+ auto end = buffers[i].shape.cend();
2052
+ for (auto shape_iter = buffers[i].shape.cbegin(),
2053
+ stride_iter = buffers[i].strides.cbegin();
2054
+ trivial_broadcast_f && shape_iter != end;
2055
+ ++shape_iter, ++stride_iter) {
2056
+ if (expect_stride == *stride_iter) {
2057
+ expect_stride *= *shape_iter;
2058
+ } else {
2059
+ trivial_broadcast_f = false;
2060
+ }
2061
+ }
2062
+ }
2063
+ }
2064
+
2065
+ return trivial_broadcast_c ? broadcast_trivial::c_trivial
2066
+ : trivial_broadcast_f ? broadcast_trivial::f_trivial
2067
+ : broadcast_trivial::non_trivial;
2068
+ }
2069
+
2070
+ template <typename T>
2071
+ struct vectorize_arg {
2072
+ static_assert(!std::is_rvalue_reference<T>::value,
2073
+ "Functions with rvalue reference arguments cannot be vectorized");
2074
+ // The wrapped function gets called with this type:
2075
+ using call_type = remove_reference_t<T>;
2076
+ // Is this a vectorized argument?
2077
+ static constexpr bool vectorize
2078
+ = satisfies_any_of<call_type, std::is_arithmetic, is_complex, is_pod>::value
2079
+ && satisfies_none_of<call_type,
2080
+ std::is_pointer,
2081
+ std::is_array,
2082
+ is_std_array,
2083
+ std::is_enum>::value
2084
+ && (!std::is_reference<T>::value
2085
+ || (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));
2086
+ // Accept this type: an array for vectorized types, otherwise the type as-is:
2087
+ using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>;
2088
+ };
2089
+
2090
+ // py::vectorize when a return type is present
2091
+ template <typename Func, typename Return, typename... Args>
2092
+ struct vectorize_returned_array {
2093
+ using Type = array_t<Return>;
2094
+
2095
+ static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {
2096
+ if (trivial == broadcast_trivial::f_trivial) {
2097
+ return array_t<Return, array::f_style>(shape);
2098
+ }
2099
+ return array_t<Return>(shape);
2100
+ }
2101
+
2102
+ static Return *mutable_data(Type &array) { return array.mutable_data(); }
2103
+
2104
+ static Return call(Func &f, Args &...args) { return f(args...); }
2105
+
2106
+ static void call(Return *out, size_t i, Func &f, Args &...args) { out[i] = f(args...); }
2107
+ };
2108
+
2109
+ // py::vectorize when a return type is not present
2110
+ template <typename Func, typename... Args>
2111
+ struct vectorize_returned_array<Func, void, Args...> {
2112
+ using Type = none;
2113
+
2114
+ static Type create(broadcast_trivial, const std::vector<ssize_t> &) { return none(); }
2115
+
2116
+ static void *mutable_data(Type &) { return nullptr; }
2117
+
2118
+ static detail::void_type call(Func &f, Args &...args) {
2119
+ f(args...);
2120
+ return {};
2121
+ }
2122
+
2123
+ static void call(void *, size_t, Func &f, Args &...args) { f(args...); }
2124
+ };
2125
+
2126
+ template <typename Func, typename Return, typename... Args>
2127
+ struct vectorize_helper {
2128
+
2129
+ // NVCC for some reason breaks if NVectorized is private
2130
+ #ifdef __CUDACC__
2131
+ public:
2132
+ #else
2133
+ private:
2134
+ #endif
2135
+
2136
+ static constexpr size_t N = sizeof...(Args);
2137
+ static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
2138
+ static_assert(
2139
+ NVectorized >= 1,
2140
+ "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
2141
+
2142
+ public:
2143
+ template <typename T,
2144
+ // SFINAE to prevent shadowing the copy constructor.
2145
+ typename = detail::enable_if_t<
2146
+ !std::is_same<vectorize_helper, typename std::decay<T>::type>::value>>
2147
+ explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) {}
2148
+
2149
+ object operator()(typename vectorize_arg<Args>::type... args) {
2150
+ return run(args...,
2151
+ make_index_sequence<N>(),
2152
+ select_indices<vectorize_arg<Args>::vectorize...>(),
2153
+ make_index_sequence<NVectorized>());
2154
+ }
2155
+
2156
+ private:
2157
+ remove_reference_t<Func> f;
2158
+
2159
+ // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling
2160
+ // with "/permissive-" flag when arg_call_types is manually inlined.
2161
+ using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
2162
+ template <size_t Index>
2163
+ using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;
2164
+
2165
+ using returned_array = vectorize_returned_array<Func, Return, Args...>;
2166
+
2167
+ // Runs a vectorized function given arguments tuple and three index sequences:
2168
+ // - Index is the full set of 0 ... (N-1) argument indices;
2169
+ // - VIndex is the subset of argument indices with vectorized parameters, letting us access
2170
+ // vectorized arguments (anything not in this sequence is passed through)
2171
+ // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
2172
+ // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
2173
+ // index BIndex in the array).
2174
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
2175
+ object run(typename vectorize_arg<Args>::type &...args,
2176
+ index_sequence<Index...> i_seq,
2177
+ index_sequence<VIndex...> vi_seq,
2178
+ index_sequence<BIndex...> bi_seq) {
2179
+
2180
+ // Pointers to values the function was called with; the vectorized ones set here will start
2181
+ // out as array_t<T> pointers, but they will be changed them to T pointers before we make
2182
+ // call the wrapped function. Non-vectorized pointers are left as-is.
2183
+ std::array<void *, N> params{{reinterpret_cast<void *>(&args)...}};
2184
+
2185
+ // The array of `buffer_info`s of vectorized arguments:
2186
+ std::array<buffer_info, NVectorized> buffers{
2187
+ {reinterpret_cast<array *>(params[VIndex])->request()...}};
2188
+
2189
+ /* Determine dimensions parameters of output array */
2190
+ ssize_t nd = 0;
2191
+ std::vector<ssize_t> shape(0);
2192
+ auto trivial = broadcast(buffers, nd, shape);
2193
+ auto ndim = (size_t) nd;
2194
+
2195
+ size_t size
2196
+ = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
2197
+
2198
+ // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
2199
+ // not wrapped in an array).
2200
+ if (size == 1 && ndim == 0) {
2201
+ PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
2202
+ return cast(
2203
+ returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));
2204
+ }
2205
+
2206
+ auto result = returned_array::create(trivial, shape);
2207
+
2208
+ PYBIND11_WARNING_PUSH
2209
+ #ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
2210
+ PYBIND11_WARNING_DISABLE_CLANG("-Wreturn-std-move")
2211
+ #endif
2212
+
2213
+ if (size == 0) {
2214
+ return result;
2215
+ }
2216
+
2217
+ /* Call the function */
2218
+ auto *mutable_data = returned_array::mutable_data(result);
2219
+ if (trivial == broadcast_trivial::non_trivial) {
2220
+ apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);
2221
+ } else {
2222
+ apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);
2223
+ }
2224
+
2225
+ return result;
2226
+ PYBIND11_WARNING_POP
2227
+ }
2228
+
2229
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
2230
+ void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
2231
+ std::array<void *, N> &params,
2232
+ Return *out,
2233
+ size_t size,
2234
+ index_sequence<Index...>,
2235
+ index_sequence<VIndex...>,
2236
+ index_sequence<BIndex...>) {
2237
+
2238
+ // Initialize an array of mutable byte references and sizes with references set to the
2239
+ // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
2240
+ // (except for singletons, which get an increment of 0).
2241
+ std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{
2242
+ {std::pair<unsigned char *&, const size_t>(
2243
+ reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
2244
+ buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>))...}};
2245
+
2246
+ for (size_t i = 0; i < size; ++i) {
2247
+ returned_array::call(
2248
+ out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);
2249
+ for (auto &x : vecparams) {
2250
+ x.first += x.second;
2251
+ }
2252
+ }
2253
+ }
2254
+
2255
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
2256
+ void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
2257
+ std::array<void *, N> &params,
2258
+ Return *out,
2259
+ size_t size,
2260
+ const std::vector<ssize_t> &output_shape,
2261
+ index_sequence<Index...>,
2262
+ index_sequence<VIndex...>,
2263
+ index_sequence<BIndex...>) {
2264
+
2265
+ multi_array_iterator<NVectorized> input_iter(buffers, output_shape);
2266
+
2267
+ for (size_t i = 0; i < size; ++i, ++input_iter) {
2268
+ PYBIND11_EXPAND_SIDE_EFFECTS((params[VIndex] = input_iter.template data<BIndex>()));
2269
+ returned_array::call(
2270
+ out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
2271
+ }
2272
+ }
2273
+ };
2274
+
2275
+ template <typename Func, typename Return, typename... Args>
2276
+ vectorize_helper<Func, Return, Args...> vectorize_extractor(const Func &f, Return (*)(Args...)) {
2277
+ return detail::vectorize_helper<Func, Return, Args...>(f);
2278
+ }
2279
+
2280
+ template <typename T, int Flags>
2281
+ struct handle_type_name<array_t<T, Flags>> {
2282
+ static constexpr auto name
2283
+ = io_name("typing.Annotated[numpy.typing.ArrayLike, ", "numpy.typing.NDArray[")
2284
+ + npy_format_descriptor<T>::name + const_name("]");
2285
+ };
2286
+
2287
+ PYBIND11_NAMESPACE_END(detail)
2288
+
2289
+ // Vanilla pointer vectorizer:
2290
+ template <typename Return, typename... Args>
2291
+ detail::vectorize_helper<Return (*)(Args...), Return, Args...> vectorize(Return (*f)(Args...)) {
2292
+ return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
2293
+ }
2294
+
2295
+ // lambda vectorizer:
2296
+ template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0>
2297
+ auto vectorize(Func &&f)
2298
+ -> decltype(detail::vectorize_extractor(std::forward<Func>(f),
2299
+ (detail::function_signature_t<Func> *) nullptr)) {
2300
+ return detail::vectorize_extractor(std::forward<Func>(f),
2301
+ (detail::function_signature_t<Func> *) nullptr);
2302
+ }
2303
+
2304
+ // Vectorize a class method (non-const):
2305
+ template <typename Return,
2306
+ typename Class,
2307
+ typename... Args,
2308
+ typename Helper = detail::vectorize_helper<
2309
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),
2310
+ Return,
2311
+ Class *,
2312
+ Args...>>
2313
+ Helper vectorize(Return (Class::*f)(Args...)) {
2314
+ return Helper(std::mem_fn(f));
2315
+ }
2316
+
2317
+ // Vectorize a class method (const):
2318
+ template <typename Return,
2319
+ typename Class,
2320
+ typename... Args,
2321
+ typename Helper = detail::vectorize_helper<
2322
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())),
2323
+ Return,
2324
+ const Class *,
2325
+ Args...>>
2326
+ Helper vectorize(Return (Class::*f)(Args...) const) {
2327
+ return Helper(std::mem_fn(f));
2328
+ }
2329
+
2330
+ // Intentionally no &&/const&& overloads: vectorized method calls operate on the bound Python
2331
+ // instance and should not consume/move-from self.
2332
+ // Vectorize a class method (non-const, lvalue ref-qualified):
2333
+ template <typename Return,
2334
+ typename Class,
2335
+ typename... Args,
2336
+ typename Helper = detail::vectorize_helper<
2337
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) &>())),
2338
+ Return,
2339
+ Class *,
2340
+ Args...>>
2341
+ Helper vectorize(Return (Class::*f)(Args...) &) {
2342
+ return Helper(std::mem_fn(f));
2343
+ }
2344
+
2345
+ // Vectorize a class method (const, lvalue ref-qualified):
2346
+ template <typename Return,
2347
+ typename Class,
2348
+ typename... Args,
2349
+ typename Helper = detail::vectorize_helper<
2350
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const &>())),
2351
+ Return,
2352
+ const Class *,
2353
+ Args...>>
2354
+ Helper vectorize(Return (Class::*f)(Args...) const &) {
2355
+ return Helper(std::mem_fn(f));
2356
+ }
2357
+
2358
+ #ifdef __cpp_noexcept_function_type
2359
+ // Vectorize a class method (non-const, noexcept):
2360
+ template <typename Return,
2361
+ typename Class,
2362
+ typename... Args,
2363
+ typename Helper = detail::vectorize_helper<
2364
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) noexcept>())),
2365
+ Return,
2366
+ Class *,
2367
+ Args...>>
2368
+ Helper vectorize(Return (Class::*f)(Args...) noexcept) {
2369
+ return Helper(std::mem_fn(f));
2370
+ }
2371
+
2372
+ // Vectorize a class method (const, noexcept):
2373
+ template <typename Return,
2374
+ typename Class,
2375
+ typename... Args,
2376
+ typename Helper = detail::vectorize_helper<
2377
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const noexcept>())),
2378
+ Return,
2379
+ const Class *,
2380
+ Args...>>
2381
+ Helper vectorize(Return (Class::*f)(Args...) const noexcept) {
2382
+ return Helper(std::mem_fn(f));
2383
+ }
2384
+
2385
+ // Vectorize a class method (non-const, lvalue ref-qualified, noexcept):
2386
+ template <typename Return,
2387
+ typename Class,
2388
+ typename... Args,
2389
+ typename Helper = detail::vectorize_helper<
2390
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) & noexcept>())),
2391
+ Return,
2392
+ Class *,
2393
+ Args...>>
2394
+ Helper vectorize(Return (Class::*f)(Args...) & noexcept) {
2395
+ return Helper(std::mem_fn(f));
2396
+ }
2397
+
2398
+ // Vectorize a class method (const, lvalue ref-qualified, noexcept):
2399
+ template <typename Return,
2400
+ typename Class,
2401
+ typename... Args,
2402
+ typename Helper = detail::vectorize_helper<
2403
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const & noexcept>())),
2404
+ Return,
2405
+ const Class *,
2406
+ Args...>>
2407
+ Helper vectorize(Return (Class::*f)(Args...) const & noexcept) {
2408
+ return Helper(std::mem_fn(f));
2409
+ }
2410
+ #endif
2411
+
2412
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/operators.h ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/operator.h: Metatemplates for operator overloading
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+ PYBIND11_NAMESPACE_BEGIN(detail)
16
+
17
+ /// Enumeration with all supported operator types
18
+ enum op_id : int {
19
+ op_add,
20
+ op_sub,
21
+ op_mul,
22
+ op_div,
23
+ op_mod,
24
+ op_divmod,
25
+ op_pow,
26
+ op_lshift,
27
+ op_rshift,
28
+ op_and,
29
+ op_xor,
30
+ op_or,
31
+ op_neg,
32
+ op_pos,
33
+ op_abs,
34
+ op_invert,
35
+ op_int,
36
+ op_long,
37
+ op_float,
38
+ op_str,
39
+ op_cmp,
40
+ op_gt,
41
+ op_ge,
42
+ op_lt,
43
+ op_le,
44
+ op_eq,
45
+ op_ne,
46
+ op_iadd,
47
+ op_isub,
48
+ op_imul,
49
+ op_idiv,
50
+ op_imod,
51
+ op_ilshift,
52
+ op_irshift,
53
+ op_iand,
54
+ op_ixor,
55
+ op_ior,
56
+ op_complex,
57
+ op_bool,
58
+ op_nonzero,
59
+ op_repr,
60
+ op_truediv,
61
+ op_itruediv,
62
+ op_hash
63
+ };
64
+
65
+ enum op_type : int {
66
+ op_l, /* base type on left */
67
+ op_r, /* base type on right */
68
+ op_u /* unary operator */
69
+ };
70
+
71
+ struct self_t {};
72
+ static const self_t self = self_t();
73
+
74
+ /// Type for an unused type slot
75
+ struct undefined_t {};
76
+
77
+ /// Don't warn about an unused variable
78
+ inline self_t __self() { return self; }
79
+
80
+ /// base template of operator implementations
81
+ template <op_id, op_type, typename B, typename L, typename R>
82
+ struct op_impl {};
83
+
84
+ /// Operator implementation generator
85
+ template <op_id id, op_type ot, typename L, typename R>
86
+ struct op_ {
87
+ static constexpr bool op_enable_if_hook = true;
88
+ template <typename Class, typename... Extra>
89
+ void execute(Class &cl, const Extra &...extra) const {
90
+ using Base = typename Class::type;
91
+ using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
92
+ using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
93
+ using op = op_impl<id, ot, Base, L_type, R_type>;
94
+ cl.def(op::name(), &op::execute, is_operator(), extra...);
95
+ }
96
+ template <typename Class, typename... Extra>
97
+ void execute_cast(Class &cl, const Extra &...extra) const {
98
+ using Base = typename Class::type;
99
+ using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
100
+ using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
101
+ using op = op_impl<id, ot, Base, L_type, R_type>;
102
+ cl.def(op::name(), &op::execute_cast, is_operator(), extra...);
103
+ }
104
+ };
105
+
106
+ #define PYBIND11_BINARY_OPERATOR(id, rid, op, expr) \
107
+ template <typename B, typename L, typename R> \
108
+ struct op_impl<op_##id, op_l, B, L, R> { \
109
+ static char const *name() { return "__" #id "__"; } \
110
+ static auto execute(const L &l, const R &r) -> decltype(expr) { return (expr); } \
111
+ static B execute_cast(const L &l, const R &r) { return B(expr); } \
112
+ }; \
113
+ template <typename B, typename L, typename R> \
114
+ struct op_impl<op_##id, op_r, B, L, R> { \
115
+ static char const *name() { return "__" #rid "__"; } \
116
+ static auto execute(const R &r, const L &l) -> decltype(expr) { return (expr); } \
117
+ static B execute_cast(const R &r, const L &l) { return B(expr); } \
118
+ }; \
119
+ inline op_<op_##id, op_l, self_t, self_t> op(const self_t &, const self_t &) { \
120
+ return op_<op_##id, op_l, self_t, self_t>(); \
121
+ } \
122
+ template <typename T> \
123
+ op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
124
+ return op_<op_##id, op_l, self_t, T>(); \
125
+ } \
126
+ template <typename T> \
127
+ op_<op_##id, op_r, T, self_t> op(const T &, const self_t &) { \
128
+ return op_<op_##id, op_r, T, self_t>(); \
129
+ }
130
+
131
+ #define PYBIND11_INPLACE_OPERATOR(id, op, expr) \
132
+ template <typename B, typename L, typename R> \
133
+ struct op_impl<op_##id, op_l, B, L, R> { \
134
+ static char const *name() { return "__" #id "__"; } \
135
+ static auto execute(L &l, const R &r) -> decltype(expr) { return expr; } \
136
+ static B execute_cast(L &l, const R &r) { return B(expr); } \
137
+ }; \
138
+ template <typename T> \
139
+ op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
140
+ return op_<op_##id, op_l, self_t, T>(); \
141
+ }
142
+
143
+ #define PYBIND11_UNARY_OPERATOR(id, op, expr) \
144
+ template <typename B, typename L> \
145
+ struct op_impl<op_##id, op_u, B, L, undefined_t> { \
146
+ static char const *name() { return "__" #id "__"; } \
147
+ static auto execute(const L &l) -> decltype(expr) { return expr; } \
148
+ static B execute_cast(const L &l) { return B(expr); } \
149
+ }; \
150
+ inline op_<op_##id, op_u, self_t, undefined_t> op(const self_t &) { \
151
+ return op_<op_##id, op_u, self_t, undefined_t>(); \
152
+ }
153
+
154
+ PYBIND11_BINARY_OPERATOR(sub, rsub, operator-, l - r)
155
+ PYBIND11_BINARY_OPERATOR(add, radd, operator+, l + r)
156
+ PYBIND11_BINARY_OPERATOR(mul, rmul, operator*, l *r)
157
+ PYBIND11_BINARY_OPERATOR(truediv, rtruediv, operator/, l / r)
158
+ PYBIND11_BINARY_OPERATOR(mod, rmod, operator%, l % r)
159
+ PYBIND11_BINARY_OPERATOR(lshift, rlshift, operator<<, l << r)
160
+ PYBIND11_BINARY_OPERATOR(rshift, rrshift, operator>>, l >> r)
161
+ PYBIND11_BINARY_OPERATOR(and, rand, operator&, l &r)
162
+ PYBIND11_BINARY_OPERATOR(xor, rxor, operator^, l ^ r)
163
+ PYBIND11_BINARY_OPERATOR(eq, eq, operator==, l == r)
164
+ PYBIND11_BINARY_OPERATOR(ne, ne, operator!=, l != r)
165
+ PYBIND11_BINARY_OPERATOR(or, ror, operator|, l | r)
166
+ PYBIND11_BINARY_OPERATOR(gt, lt, operator>, l > r)
167
+ PYBIND11_BINARY_OPERATOR(ge, le, operator>=, l >= r)
168
+ PYBIND11_BINARY_OPERATOR(lt, gt, operator<, l < r)
169
+ PYBIND11_BINARY_OPERATOR(le, ge, operator<=, l <= r)
170
+ // PYBIND11_BINARY_OPERATOR(pow, rpow, pow, std::pow(l, r))
171
+ PYBIND11_INPLACE_OPERATOR(iadd, operator+=, l += r)
172
+ PYBIND11_INPLACE_OPERATOR(isub, operator-=, l -= r)
173
+ PYBIND11_INPLACE_OPERATOR(imul, operator*=, l *= r)
174
+ PYBIND11_INPLACE_OPERATOR(itruediv, operator/=, l /= r)
175
+ PYBIND11_INPLACE_OPERATOR(imod, operator%=, l %= r)
176
+ PYBIND11_INPLACE_OPERATOR(ilshift, operator<<=, l <<= r)
177
+ PYBIND11_INPLACE_OPERATOR(irshift, operator>>=, l >>= r)
178
+ PYBIND11_INPLACE_OPERATOR(iand, operator&=, l &= r)
179
+ PYBIND11_INPLACE_OPERATOR(ixor, operator^=, l ^= r)
180
+ PYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r)
181
+ PYBIND11_UNARY_OPERATOR(neg, operator-, -l)
182
+ PYBIND11_UNARY_OPERATOR(pos, operator+, +l)
183
+ // WARNING: This usage of `abs` should only be done for existing STL overloads.
184
+ // Adding overloads directly in to the `std::` namespace is advised against:
185
+ // https://en.cppreference.com/w/cpp/language/extending_std
186
+ PYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l))
187
+ PYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l))
188
+ PYBIND11_UNARY_OPERATOR(invert, operator~, (~l))
189
+ PYBIND11_UNARY_OPERATOR(bool, operator!, !!l)
190
+ PYBIND11_UNARY_OPERATOR(int, int_, (int) l)
191
+ PYBIND11_UNARY_OPERATOR(float, float_, (double) l)
192
+
193
+ #undef PYBIND11_BINARY_OPERATOR
194
+ #undef PYBIND11_INPLACE_OPERATOR
195
+ #undef PYBIND11_UNARY_OPERATOR
196
+ PYBIND11_NAMESPACE_END(detail)
197
+
198
+ using detail::self;
199
+ // Add named operators so that they are accessible via `py::`.
200
+ using detail::hash;
201
+
202
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/options.h ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/options.h: global settings that are configurable at runtime.
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ class options {
17
+ public:
18
+ // Default RAII constructor, which leaves settings as they currently are.
19
+ options() : previous_state(global_state()) {}
20
+
21
+ // Class is non-copyable.
22
+ options(const options &) = delete;
23
+ options &operator=(const options &) = delete;
24
+
25
+ // Destructor, which restores settings that were in effect before.
26
+ ~options() { global_state() = previous_state; }
27
+
28
+ // Setter methods (affect the global state):
29
+
30
+ options &disable_user_defined_docstrings() & {
31
+ global_state().show_user_defined_docstrings = false;
32
+ return *this;
33
+ }
34
+
35
+ options &enable_user_defined_docstrings() & {
36
+ global_state().show_user_defined_docstrings = true;
37
+ return *this;
38
+ }
39
+
40
+ options &disable_function_signatures() & {
41
+ global_state().show_function_signatures = false;
42
+ return *this;
43
+ }
44
+
45
+ options &enable_function_signatures() & {
46
+ global_state().show_function_signatures = true;
47
+ return *this;
48
+ }
49
+
50
+ options &disable_enum_members_docstring() & {
51
+ global_state().show_enum_members_docstring = false;
52
+ return *this;
53
+ }
54
+
55
+ options &enable_enum_members_docstring() & {
56
+ global_state().show_enum_members_docstring = true;
57
+ return *this;
58
+ }
59
+
60
+ // Getter methods (return the global state):
61
+
62
+ static bool show_user_defined_docstrings() {
63
+ return global_state().show_user_defined_docstrings;
64
+ }
65
+
66
+ static bool show_function_signatures() { return global_state().show_function_signatures; }
67
+
68
+ static bool show_enum_members_docstring() {
69
+ return global_state().show_enum_members_docstring;
70
+ }
71
+
72
+ // This type is not meant to be allocated on the heap.
73
+ void *operator new(size_t) = delete;
74
+
75
+ private:
76
+ struct state {
77
+ bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings.
78
+ bool show_function_signatures = true; //< Include auto-generated function signatures
79
+ // in docstrings.
80
+ bool show_enum_members_docstring = true; //< Include auto-generated member list in enum
81
+ // docstrings.
82
+ };
83
+
84
+ static state &global_state() {
85
+ static state instance;
86
+ return instance;
87
+ }
88
+
89
+ state previous_state;
90
+ };
91
+
92
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/pybind11.h ADDED
The diff for this file is too large to render. See raw diff
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/pytypes.h ADDED
The diff for this file is too large to render. See raw diff
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/stl.h ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/stl.h: Transparent conversion for STL data types
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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
+ #include "detail/common.h"
14
+ #include "detail/descr.h"
15
+ #include "detail/type_caster_base.h"
16
+
17
+ #include <deque>
18
+ #include <initializer_list>
19
+ #include <list>
20
+ #include <map>
21
+ #include <memory>
22
+ #include <ostream>
23
+ #include <set>
24
+ #include <unordered_map>
25
+ #include <unordered_set>
26
+ #include <valarray>
27
+
28
+ // See `detail/common.h` for implementation of these guards.
29
+ #if defined(PYBIND11_HAS_OPTIONAL)
30
+ # include <optional>
31
+ #elif defined(PYBIND11_HAS_EXP_OPTIONAL)
32
+ # include <experimental/optional>
33
+ #endif
34
+
35
+ #if defined(PYBIND11_HAS_VARIANT)
36
+ # include <variant>
37
+ #endif
38
+
39
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
40
+ PYBIND11_NAMESPACE_BEGIN(detail)
41
+
42
+ //
43
+ // Begin: Equivalent of
44
+ // https://github.com/google/clif/blob/ae4eee1de07cdf115c0c9bf9fec9ff28efce6f6c/clif/python/runtime.cc#L388-L438
45
+ /*
46
+ The three `object_is_convertible_to_*()` functions below are
47
+ the result of converging the behaviors of pybind11 and PyCLIF
48
+ (http://github.com/google/clif).
49
+
50
+ Originally PyCLIF was extremely far on the permissive side of the spectrum,
51
+ while pybind11 was very far on the strict side. Originally PyCLIF accepted any
52
+ Python iterable as input for a C++ `vector`/`set`/`map` argument, as long as
53
+ the elements were convertible. The obvious (in hindsight) problem was that
54
+ any empty Python iterable could be passed to any of these C++ types, e.g. `{}`
55
+ was accepted for C++ `vector`/`set` arguments, or `[]` for C++ `map` arguments.
56
+
57
+ The functions below strike a practical permissive-vs-strict compromise,
58
+ informed by tens of thousands of use cases in the wild. A main objective is
59
+ to prevent accidents and improve readability:
60
+
61
+ - Python literals must match the C++ types.
62
+
63
+ - For C++ `set`: The potentially reducing conversion from a Python sequence
64
+ (e.g. Python `list` or `tuple`) to a C++ `set` must be explicit, by going
65
+ through a Python `set`.
66
+
67
+ - However, a Python `set` can still be passed to a C++ `vector`. The rationale
68
+ is that this conversion is not reducing. Implicit conversions of this kind
69
+ are also fairly commonly used, therefore enforcing explicit conversions
70
+ would have an unfavorable cost : benefit ratio; more sloppily speaking,
71
+ such an enforcement would be more annoying than helpful.
72
+
73
+ Additional checks have been added to allow types derived from `collections.abc.Set` and
74
+ `collections.abc.Mapping` (`collections.abc.Sequence` is already allowed by `PySequence_Check`).
75
+ */
76
+
77
+ inline bool object_is_instance_with_one_of_tp_names(PyObject *obj,
78
+ std::initializer_list<const char *> tp_names) {
79
+ if (PyType_Check(obj)) {
80
+ return false;
81
+ }
82
+ const char *obj_tp_name = Py_TYPE(obj)->tp_name;
83
+ for (const auto *tp_name : tp_names) {
84
+ if (std::strcmp(obj_tp_name, tp_name) == 0) {
85
+ return true;
86
+ }
87
+ }
88
+ return false;
89
+ }
90
+
91
+ inline bool object_is_convertible_to_std_vector(const handle &src) {
92
+ // Allow sequence-like objects, but not (byte-)string-like objects.
93
+ if (PySequence_Check(src.ptr()) != 0) {
94
+ return !PyUnicode_Check(src.ptr()) && !PyBytes_Check(src.ptr());
95
+ }
96
+ // Allow generators, set/frozenset and several common iterable types.
97
+ return (PyGen_Check(src.ptr()) != 0) || (PyAnySet_Check(src.ptr()) != 0)
98
+ || object_is_instance_with_one_of_tp_names(
99
+ src.ptr(), {"dict_keys", "dict_values", "dict_items", "map", "zip"});
100
+ }
101
+
102
+ inline bool object_is_convertible_to_std_set(const handle &src, bool convert) {
103
+ // Allow set/frozenset and dict keys.
104
+ // In convert mode: also allow types derived from collections.abc.Set.
105
+ return ((PyAnySet_Check(src.ptr()) != 0)
106
+ || object_is_instance_with_one_of_tp_names(src.ptr(), {"dict_keys"}))
107
+ || (convert && isinstance(src, module_::import("collections.abc").attr("Set")));
108
+ }
109
+
110
+ inline bool object_is_convertible_to_std_map(const handle &src, bool convert) {
111
+ // Allow dict.
112
+ if (PyDict_Check(src.ptr())) {
113
+ return true;
114
+ }
115
+ // Allow types conforming to Mapping Protocol.
116
+ // According to https://docs.python.org/3/c-api/mapping.html, `PyMappingCheck()` checks for
117
+ // `__getitem__()` without checking the type of keys. In order to restrict the allowed types
118
+ // closer to actual Mapping-like types, we also check for the `items()` method.
119
+ if (PyMapping_Check(src.ptr()) != 0) {
120
+ PyObject *items = PyObject_GetAttrString(src.ptr(), "items");
121
+ if (items != nullptr) {
122
+ bool is_convertible = (PyCallable_Check(items) != 0);
123
+ Py_DECREF(items);
124
+ if (is_convertible) {
125
+ return true;
126
+ }
127
+ } else {
128
+ PyErr_Clear();
129
+ }
130
+ }
131
+ // In convert mode: Allow types derived from collections.abc.Mapping
132
+ return convert && isinstance(src, module_::import("collections.abc").attr("Mapping"));
133
+ }
134
+
135
+ //
136
+ // End: Equivalent of clif/python/runtime.cc
137
+ //
138
+
139
+ /// Extracts an const lvalue reference or rvalue reference for U based on the type of T (e.g. for
140
+ /// forwarding a container element). Typically used indirect via forwarded_type(), below.
141
+ template <typename T, typename U>
142
+ using forwarded_type = conditional_t<std::is_lvalue_reference<T>::value,
143
+ remove_reference_t<U> &,
144
+ remove_reference_t<U> &&>;
145
+
146
+ /// Forwards a value U as rvalue or lvalue according to whether T is rvalue or lvalue; typically
147
+ /// used for forwarding a container's elements.
148
+ template <typename T, typename U>
149
+ constexpr forwarded_type<T, U> forward_like(U &&u) {
150
+ return std::forward<detail::forwarded_type<T, U>>(std::forward<U>(u));
151
+ }
152
+
153
+ // Checks if a container has a STL style reserve method.
154
+ // This will only return true for a `reserve()` with a `void` return.
155
+ template <typename C>
156
+ using has_reserve_method = std::is_same<decltype(std::declval<C>().reserve(0)), void>;
157
+
158
+ template <typename Type, typename Key>
159
+ struct set_caster {
160
+ using type = Type;
161
+ using key_conv = make_caster<Key>;
162
+
163
+ private:
164
+ template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>
165
+ void reserve_maybe(const anyset &s, Type *) {
166
+ value.reserve(s.size());
167
+ }
168
+ void reserve_maybe(const anyset &, void *) {}
169
+
170
+ bool convert_iterable(const iterable &itbl, bool convert) {
171
+ for (const auto &it : itbl) {
172
+ key_conv conv;
173
+ if (!conv.load(it, convert)) {
174
+ return false;
175
+ }
176
+ value.insert(cast_op<Key &&>(std::move(conv)));
177
+ }
178
+ return true;
179
+ }
180
+
181
+ bool convert_anyset(const anyset &s, bool convert) {
182
+ value.clear();
183
+ reserve_maybe(s, &value);
184
+ return convert_iterable(s, convert);
185
+ }
186
+
187
+ public:
188
+ bool load(handle src, bool convert) {
189
+ if (!object_is_convertible_to_std_set(src, convert)) {
190
+ return false;
191
+ }
192
+ if (isinstance<anyset>(src)) {
193
+ value.clear();
194
+ return convert_anyset(reinterpret_borrow<anyset>(src), convert);
195
+ }
196
+ if (!convert) {
197
+ return false;
198
+ }
199
+ assert(isinstance<iterable>(src));
200
+ value.clear();
201
+ return convert_iterable(reinterpret_borrow<iterable>(src), convert);
202
+ }
203
+
204
+ template <typename T>
205
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
206
+ if (!std::is_lvalue_reference<T>::value) {
207
+ policy = return_value_policy_override<Key>::policy(policy);
208
+ }
209
+ pybind11::set s;
210
+ for (auto &&value : src) {
211
+ auto value_ = reinterpret_steal<object>(
212
+ key_conv::cast(detail::forward_like<T>(value), policy, parent));
213
+ if (!value_ || !s.add(std::move(value_))) {
214
+ return handle();
215
+ }
216
+ }
217
+ return s.release();
218
+ }
219
+
220
+ PYBIND11_TYPE_CASTER(type,
221
+ io_name("collections.abc.Set", "set") + const_name("[") + key_conv::name
222
+ + const_name("]"));
223
+ };
224
+
225
+ template <typename Type, typename Key, typename Value>
226
+ struct map_caster {
227
+ using key_conv = make_caster<Key>;
228
+ using value_conv = make_caster<Value>;
229
+
230
+ private:
231
+ template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>
232
+ void reserve_maybe(const dict &d, Type *) {
233
+ value.reserve(d.size());
234
+ }
235
+ void reserve_maybe(const dict &, void *) {}
236
+
237
+ bool convert_elements(const dict &d, bool convert) {
238
+ value.clear();
239
+ reserve_maybe(d, &value);
240
+ for (const auto &it : d) {
241
+ key_conv kconv;
242
+ value_conv vconv;
243
+ if (!kconv.load(it.first.ptr(), convert) || !vconv.load(it.second.ptr(), convert)) {
244
+ return false;
245
+ }
246
+ value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv)));
247
+ }
248
+ return true;
249
+ }
250
+
251
+ public:
252
+ bool load(handle src, bool convert) {
253
+ if (!object_is_convertible_to_std_map(src, convert)) {
254
+ return false;
255
+ }
256
+ if (isinstance<dict>(src)) {
257
+ return convert_elements(reinterpret_borrow<dict>(src), convert);
258
+ }
259
+ if (!convert) {
260
+ return false;
261
+ }
262
+ auto items = reinterpret_steal<object>(PyMapping_Items(src.ptr()));
263
+ if (!items) {
264
+ throw error_already_set();
265
+ }
266
+ assert(isinstance<iterable>(items));
267
+ return convert_elements(dict(reinterpret_borrow<iterable>(items)), convert);
268
+ }
269
+
270
+ template <typename T>
271
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
272
+ dict d;
273
+ return_value_policy policy_key = policy;
274
+ return_value_policy policy_value = policy;
275
+ if (!std::is_lvalue_reference<T>::value) {
276
+ policy_key = return_value_policy_override<Key>::policy(policy_key);
277
+ policy_value = return_value_policy_override<Value>::policy(policy_value);
278
+ }
279
+ for (auto &&kv : src) {
280
+ auto key = reinterpret_steal<object>(
281
+ key_conv::cast(detail::forward_like<T>(kv.first), policy_key, parent));
282
+ auto value = reinterpret_steal<object>(
283
+ value_conv::cast(detail::forward_like<T>(kv.second), policy_value, parent));
284
+ if (!key || !value) {
285
+ return handle();
286
+ }
287
+ d[std::move(key)] = std::move(value);
288
+ }
289
+ return d.release();
290
+ }
291
+
292
+ PYBIND11_TYPE_CASTER(Type,
293
+ io_name("collections.abc.Mapping", "dict") + const_name("[")
294
+ + key_conv::name + const_name(", ") + value_conv::name
295
+ + const_name("]"));
296
+ };
297
+
298
+ template <typename Type, typename Value>
299
+ struct list_caster {
300
+ using value_conv = make_caster<Value>;
301
+
302
+ bool load(handle src, bool convert) {
303
+ if (!object_is_convertible_to_std_vector(src)) {
304
+ return false;
305
+ }
306
+ if (isinstance<sequence>(src)) {
307
+ return convert_elements(src, convert);
308
+ }
309
+ if (!convert) {
310
+ return false;
311
+ }
312
+ // Designed to be behavior-equivalent to passing tuple(src) from Python:
313
+ // The conversion to a tuple will first exhaust the generator object, to ensure that
314
+ // the generator is not left in an unpredictable (to the caller) partially-consumed
315
+ // state.
316
+ assert(isinstance<iterable>(src));
317
+ return convert_elements(tuple(reinterpret_borrow<iterable>(src)), convert);
318
+ }
319
+
320
+ private:
321
+ template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>
322
+ void reserve_maybe(const sequence &s, Type *) {
323
+ value.reserve(s.size());
324
+ }
325
+ void reserve_maybe(const sequence &, void *) {}
326
+
327
+ bool convert_elements(handle seq, bool convert) {
328
+ auto s = reinterpret_borrow<sequence>(seq);
329
+ value.clear();
330
+ reserve_maybe(s, &value);
331
+ for (const auto &it : seq) {
332
+ value_conv conv;
333
+ if (!conv.load(it, convert)) {
334
+ return false;
335
+ }
336
+ value.push_back(cast_op<Value &&>(std::move(conv)));
337
+ }
338
+ return true;
339
+ }
340
+
341
+ public:
342
+ template <typename T>
343
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
344
+ if (!std::is_lvalue_reference<T>::value) {
345
+ policy = return_value_policy_override<Value>::policy(policy);
346
+ }
347
+ list l(src.size());
348
+ ssize_t index = 0;
349
+ for (auto &&value : src) {
350
+ auto value_ = reinterpret_steal<object>(
351
+ value_conv::cast(detail::forward_like<T>(value), policy, parent));
352
+ if (!value_) {
353
+ return handle();
354
+ }
355
+ PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
356
+ }
357
+ return l.release();
358
+ }
359
+
360
+ PYBIND11_TYPE_CASTER(Type,
361
+ io_name("collections.abc.Sequence", "list") + const_name("[")
362
+ + value_conv::name + const_name("]"));
363
+ };
364
+
365
+ template <typename Type, typename Alloc>
366
+ struct type_caster<std::vector<Type, Alloc>> : list_caster<std::vector<Type, Alloc>, Type> {};
367
+
368
+ template <typename Type, typename Alloc>
369
+ struct type_caster<std::deque<Type, Alloc>> : list_caster<std::deque<Type, Alloc>, Type> {};
370
+
371
+ template <typename Type, typename Alloc>
372
+ struct type_caster<std::list<Type, Alloc>> : list_caster<std::list<Type, Alloc>, Type> {};
373
+
374
+ template <typename ArrayType, typename V, size_t... I>
375
+ ArrayType vector_to_array_impl(V &&v, index_sequence<I...>) {
376
+ return {{std::move(v[I])...}};
377
+ }
378
+
379
+ // Based on https://en.cppreference.com/w/cpp/container/array/to_array
380
+ template <typename ArrayType, size_t N, typename V>
381
+ ArrayType vector_to_array(V &&v) {
382
+ return vector_to_array_impl<ArrayType, V>(std::forward<V>(v), make_index_sequence<N>{});
383
+ }
384
+
385
+ template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0>
386
+ struct array_caster {
387
+ using value_conv = make_caster<Value>;
388
+
389
+ private:
390
+ std::unique_ptr<ArrayType> value;
391
+
392
+ template <bool R = Resizable, enable_if_t<R, int> = 0>
393
+ bool convert_elements(handle seq, bool convert) {
394
+ auto l = reinterpret_borrow<sequence>(seq);
395
+ value.reset(new ArrayType{});
396
+ // Using `resize` to preserve the behavior exactly as it was before PR #5305
397
+ // For the `resize` to work, `Value` must be default constructible.
398
+ // For `std::valarray`, this is a requirement:
399
+ // https://en.cppreference.com/w/cpp/named_req/NumericType
400
+ value->resize(l.size());
401
+ size_t ctr = 0;
402
+ for (const auto &it : l) {
403
+ value_conv conv;
404
+ if (!conv.load(it, convert)) {
405
+ return false;
406
+ }
407
+ (*value)[ctr++] = cast_op<Value &&>(std::move(conv));
408
+ }
409
+ return true;
410
+ }
411
+
412
+ template <bool R = Resizable, enable_if_t<!R, int> = 0>
413
+ bool convert_elements(handle seq, bool convert) {
414
+ auto l = reinterpret_borrow<sequence>(seq);
415
+ if (l.size() != Size) {
416
+ return false;
417
+ }
418
+ // The `temp` storage is needed to support `Value` types that are not
419
+ // default-constructible.
420
+ // Deliberate choice: no template specializations, for simplicity, and
421
+ // because the compile time overhead for the specializations is deemed
422
+ // more significant than the runtime overhead for the `temp` storage.
423
+ std::vector<Value> temp;
424
+ temp.reserve(l.size());
425
+ for (auto it : l) {
426
+ value_conv conv;
427
+ if (!conv.load(it, convert)) {
428
+ return false;
429
+ }
430
+ temp.emplace_back(cast_op<Value &&>(std::move(conv)));
431
+ }
432
+ value.reset(new ArrayType(vector_to_array<ArrayType, Size>(std::move(temp))));
433
+ return true;
434
+ }
435
+
436
+ public:
437
+ bool load(handle src, bool convert) {
438
+ if (!object_is_convertible_to_std_vector(src)) {
439
+ return false;
440
+ }
441
+ if (isinstance<sequence>(src)) {
442
+ return convert_elements(src, convert);
443
+ }
444
+ if (!convert) {
445
+ return false;
446
+ }
447
+ // Designed to be behavior-equivalent to passing tuple(src) from Python:
448
+ // The conversion to a tuple will first exhaust the generator object, to ensure that
449
+ // the generator is not left in an unpredictable (to the caller) partially-consumed
450
+ // state.
451
+ assert(isinstance<iterable>(src));
452
+ return convert_elements(tuple(reinterpret_borrow<iterable>(src)), convert);
453
+ }
454
+
455
+ template <typename T>
456
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
457
+ list l(src.size());
458
+ ssize_t index = 0;
459
+ for (auto &&value : src) {
460
+ auto value_ = reinterpret_steal<object>(
461
+ value_conv::cast(detail::forward_like<T>(value), policy, parent));
462
+ if (!value_) {
463
+ return handle();
464
+ }
465
+ PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
466
+ }
467
+ return l.release();
468
+ }
469
+
470
+ // Code copied from PYBIND11_TYPE_CASTER macro.
471
+ // Intentionally preserving the behavior exactly as it was before PR #5305
472
+ template <typename T_, enable_if_t<std::is_same<ArrayType, remove_cv_t<T_>>::value, int> = 0>
473
+ static handle cast(T_ *src, return_value_policy policy, handle parent) {
474
+ if (!src) {
475
+ return none().release();
476
+ }
477
+ if (policy == return_value_policy::take_ownership) {
478
+ auto h = cast(std::move(*src), policy, parent);
479
+ delete src; // WARNING: Assumes `src` was allocated with `new`.
480
+ return h;
481
+ }
482
+ return cast(*src, policy, parent);
483
+ }
484
+
485
+ // NOLINTNEXTLINE(google-explicit-constructor)
486
+ operator ArrayType *() { return &(*value); }
487
+ // NOLINTNEXTLINE(google-explicit-constructor)
488
+ operator ArrayType &() { return *value; }
489
+ // NOLINTNEXTLINE(google-explicit-constructor)
490
+ operator ArrayType &&() && { return std::move(*value); }
491
+
492
+ template <typename T_>
493
+ using cast_op_type = movable_cast_op_type<T_>;
494
+
495
+ static constexpr auto name
496
+ = const_name<Resizable>(const_name(""), const_name("typing.Annotated["))
497
+ + io_name("collections.abc.Sequence", "list") + const_name("[") + value_conv::name
498
+ + const_name("]")
499
+ + const_name<Resizable>(const_name(""),
500
+ const_name(", \"FixedSize(") + const_name<Size>()
501
+ + const_name(")\"]"));
502
+ };
503
+
504
+ template <typename Type, size_t Size>
505
+ struct type_caster<std::array<Type, Size>>
506
+ : array_caster<std::array<Type, Size>, Type, false, Size> {};
507
+
508
+ template <typename Type>
509
+ struct type_caster<std::valarray<Type>> : array_caster<std::valarray<Type>, Type, true> {};
510
+
511
+ template <typename Key, typename Compare, typename Alloc>
512
+ struct type_caster<std::set<Key, Compare, Alloc>>
513
+ : set_caster<std::set<Key, Compare, Alloc>, Key> {};
514
+
515
+ template <typename Key, typename Hash, typename Equal, typename Alloc>
516
+ struct type_caster<std::unordered_set<Key, Hash, Equal, Alloc>>
517
+ : set_caster<std::unordered_set<Key, Hash, Equal, Alloc>, Key> {};
518
+
519
+ template <typename Key, typename Value, typename Compare, typename Alloc>
520
+ struct type_caster<std::map<Key, Value, Compare, Alloc>>
521
+ : map_caster<std::map<Key, Value, Compare, Alloc>, Key, Value> {};
522
+
523
+ template <typename Key, typename Value, typename Hash, typename Equal, typename Alloc>
524
+ struct type_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>>
525
+ : map_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>, Key, Value> {};
526
+
527
+ // This type caster is intended to be used for std::optional and std::experimental::optional
528
+ template <typename Type, typename Value = typename Type::value_type>
529
+ struct optional_caster {
530
+ using value_conv = make_caster<Value>;
531
+
532
+ template <typename T>
533
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
534
+ if (!src) {
535
+ return none().release();
536
+ }
537
+ if (!std::is_lvalue_reference<T>::value) {
538
+ policy = return_value_policy_override<Value>::policy(policy);
539
+ }
540
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
541
+ return value_conv::cast(*std::forward<T>(src), policy, parent);
542
+ }
543
+
544
+ bool load(handle src, bool convert) {
545
+ if (!src) {
546
+ return false;
547
+ }
548
+ if (src.is_none()) {
549
+ return true; // default-constructed value is already empty
550
+ }
551
+ value_conv inner_caster;
552
+ if (!inner_caster.load(src, convert)) {
553
+ return false;
554
+ }
555
+
556
+ value.emplace(cast_op<Value &&>(std::move(inner_caster)));
557
+ return true;
558
+ }
559
+
560
+ PYBIND11_TYPE_CASTER(Type, value_conv::name | make_caster<none>::name);
561
+ };
562
+
563
+ #if defined(PYBIND11_HAS_OPTIONAL)
564
+ template <typename T>
565
+ struct type_caster<std::optional<T>> : public optional_caster<std::optional<T>> {};
566
+
567
+ template <>
568
+ struct type_caster<std::nullopt_t> : public void_caster<std::nullopt_t> {};
569
+ #endif
570
+
571
+ #if defined(PYBIND11_HAS_EXP_OPTIONAL)
572
+ template <typename T>
573
+ struct type_caster<std::experimental::optional<T>>
574
+ : public optional_caster<std::experimental::optional<T>> {};
575
+
576
+ template <>
577
+ struct type_caster<std::experimental::nullopt_t>
578
+ : public void_caster<std::experimental::nullopt_t> {};
579
+ #endif
580
+
581
+ /// Visit a variant and cast any found type to Python
582
+ struct variant_caster_visitor {
583
+ return_value_policy policy;
584
+ handle parent;
585
+
586
+ using result_type = handle; // required by boost::variant in C++11
587
+
588
+ template <typename T>
589
+ result_type operator()(T &&src) const {
590
+ return make_caster<T>::cast(std::forward<T>(src), policy, parent);
591
+ }
592
+ };
593
+
594
+ /// Helper class which abstracts away variant's `visit` function. `std::variant` and similar
595
+ /// `namespace::variant` types which provide a `namespace::visit()` function are handled here
596
+ /// automatically using argument-dependent lookup. Users can provide specializations for other
597
+ /// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`.
598
+ template <template <typename...> class Variant>
599
+ struct visit_helper {
600
+ template <typename... Args>
601
+ static auto call(Args &&...args) -> decltype(visit(std::forward<Args>(args)...)) {
602
+ return visit(std::forward<Args>(args)...);
603
+ }
604
+ };
605
+
606
+ /// Generic variant caster
607
+ template <typename Variant>
608
+ struct variant_caster;
609
+
610
+ template <template <typename...> class V, typename... Ts>
611
+ struct variant_caster<V<Ts...>> {
612
+ static_assert(sizeof...(Ts) > 0, "Variant must consist of at least one alternative.");
613
+
614
+ template <typename U, typename... Us>
615
+ bool load_alternative(handle src, bool convert, type_list<U, Us...>) {
616
+ auto caster = make_caster<U>();
617
+ if (caster.load(src, convert)) {
618
+ value = cast_op<U>(std::move(caster));
619
+ return true;
620
+ }
621
+ return load_alternative(src, convert, type_list<Us...>{});
622
+ }
623
+
624
+ bool load_alternative(handle, bool, type_list<>) { return false; }
625
+
626
+ bool load(handle src, bool convert) {
627
+ // Do a first pass without conversions to improve constructor resolution.
628
+ // E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`
629
+ // slot of the variant. Without two-pass loading `double` would be filled
630
+ // because it appears first and a conversion is possible.
631
+ if (convert && load_alternative(src, false, type_list<Ts...>{})) {
632
+ return true;
633
+ }
634
+ return load_alternative(src, convert, type_list<Ts...>{});
635
+ }
636
+
637
+ template <typename Variant>
638
+ static handle cast(Variant &&src, return_value_policy policy, handle parent) {
639
+ return visit_helper<V>::call(variant_caster_visitor{policy, parent},
640
+ std::forward<Variant>(src));
641
+ }
642
+
643
+ using Type = V<Ts...>;
644
+ PYBIND11_TYPE_CASTER(Type, ::pybind11::detail::union_concat(make_caster<Ts>::name...));
645
+ };
646
+
647
+ #if defined(PYBIND11_HAS_VARIANT)
648
+ template <typename... Ts>
649
+ struct type_caster<std::variant<Ts...>> : variant_caster<std::variant<Ts...>> {};
650
+
651
+ template <>
652
+ struct type_caster<std::monostate> : public void_caster<std::monostate> {};
653
+ #endif
654
+
655
+ PYBIND11_NAMESPACE_END(detail)
656
+
657
+ inline std::ostream &operator<<(std::ostream &os, const handle &obj) {
658
+ #ifdef PYBIND11_HAS_STRING_VIEW
659
+ os << str(obj).cast<std::string_view>();
660
+ #else
661
+ os << (std::string) str(obj);
662
+ #endif
663
+ return os;
664
+ }
665
+
666
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/stl/filesystem.h ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2021 The Pybind Development Team.
2
+ // All rights reserved. Use of this source code is governed by a
3
+ // BSD-style license that can be found in the LICENSE file.
4
+
5
+ #pragma once
6
+
7
+ #include <pybind11/cast.h>
8
+ #include <pybind11/detail/common.h>
9
+ #include <pybind11/detail/descr.h>
10
+ #include <pybind11/pybind11.h>
11
+ #include <pybind11/pytypes.h>
12
+
13
+ #include <string>
14
+
15
+ #if defined(PYBIND11_HAS_FILESYSTEM)
16
+ # include <filesystem>
17
+ #elif defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)
18
+ # include <experimental/filesystem>
19
+ #else
20
+ # error "Neither #include <filesystem> nor #include <experimental/filesystem> is available."
21
+ #endif
22
+
23
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
24
+ PYBIND11_NAMESPACE_BEGIN(detail)
25
+
26
+ #ifdef PYPY_VERSION
27
+ # define PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(...) (__VA_ARGS__)
28
+ #else
29
+ # define PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(...) \
30
+ (reinterpret_cast<void *>(__VA_ARGS__))
31
+ #endif
32
+
33
+ #if defined(PYBIND11_HAS_FILESYSTEM) || defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)
34
+ template <typename T>
35
+ struct path_caster {
36
+
37
+ private:
38
+ static PyObject *unicode_from_fs_native(const std::string &w) {
39
+ # if !defined(PYPY_VERSION)
40
+ return PyUnicode_DecodeFSDefaultAndSize(w.c_str(), ssize_t(w.size()));
41
+ # else
42
+ // PyPy mistakenly declares the first parameter as non-const.
43
+ return PyUnicode_DecodeFSDefaultAndSize(const_cast<char *>(w.c_str()), ssize_t(w.size()));
44
+ # endif
45
+ }
46
+
47
+ static PyObject *unicode_from_fs_native(const std::wstring &w) {
48
+ return PyUnicode_FromWideChar(w.c_str(), ssize_t(w.size()));
49
+ }
50
+
51
+ public:
52
+ static handle cast(const T &path, return_value_policy, handle) {
53
+ if (auto py_str = unicode_from_fs_native(path.native())) {
54
+ return module_::import("pathlib")
55
+ .attr("Path")(reinterpret_steal<object>(py_str))
56
+ .release();
57
+ }
58
+ return nullptr;
59
+ }
60
+
61
+ bool load(handle handle, bool) {
62
+ // PyUnicode_FSConverter and PyUnicode_FSDecoder normally take care of
63
+ // calling PyOS_FSPath themselves, but that's broken on PyPy (PyPy
64
+ // issue #3168) so we do it ourselves instead.
65
+ PyObject *buf = PyOS_FSPath(handle.ptr());
66
+ if (!buf) {
67
+ PyErr_Clear();
68
+ return false;
69
+ }
70
+ PyObject *native = nullptr;
71
+ if constexpr (std::is_same_v<typename T::value_type, char>) {
72
+ if (PyUnicode_FSConverter(buf, PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(&native))
73
+ != 0) {
74
+ if (auto *c_str = PyBytes_AsString(native)) {
75
+ // AsString returns a pointer to the internal buffer, which
76
+ // must not be free'd.
77
+ value = c_str;
78
+ }
79
+ }
80
+ } else if constexpr (std::is_same_v<typename T::value_type, wchar_t>) {
81
+ if (PyUnicode_FSDecoder(buf, PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(&native))
82
+ != 0) {
83
+ if (auto *c_str = PyUnicode_AsWideCharString(native, nullptr)) {
84
+ // AsWideCharString returns a new string that must be free'd.
85
+ value = c_str; // Copies the string.
86
+ PyMem_Free(c_str);
87
+ }
88
+ }
89
+ }
90
+ Py_XDECREF(native);
91
+ Py_DECREF(buf);
92
+ if (PyErr_Occurred()) {
93
+ PyErr_Clear();
94
+ return false;
95
+ }
96
+ return true;
97
+ }
98
+
99
+ PYBIND11_TYPE_CASTER(T, io_name("os.PathLike | str | bytes", "pathlib.Path"));
100
+ };
101
+
102
+ #endif // PYBIND11_HAS_FILESYSTEM || defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)
103
+
104
+ #if defined(PYBIND11_HAS_FILESYSTEM)
105
+ template <>
106
+ struct type_caster<std::filesystem::path> : public path_caster<std::filesystem::path> {};
107
+ #elif defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)
108
+ template <>
109
+ struct type_caster<std::experimental::filesystem::path>
110
+ : public path_caster<std::experimental::filesystem::path> {};
111
+ #endif
112
+
113
+ PYBIND11_NAMESPACE_END(detail)
114
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/stl_bind.h ADDED
@@ -0,0 +1,858 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/std_bind.h: Binding generators for STL data types
3
+
4
+ Copyright (c) 2016 Sergey Lyskov and Wenzel Jakob
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
+ #include "detail/type_caster_base.h"
14
+ #include "cast.h"
15
+ #include "operators.h"
16
+
17
+ #include <algorithm>
18
+ #include <sstream>
19
+ #include <type_traits>
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+ PYBIND11_NAMESPACE_BEGIN(detail)
23
+
24
+ /* SFINAE helper class used by 'is_comparable */
25
+ template <typename T>
26
+ struct container_traits {
27
+ template <typename T2>
28
+ static std::true_type
29
+ test_comparable(decltype(std::declval<const T2 &>() == std::declval<const T2 &>()) *);
30
+ template <typename T2>
31
+ static std::false_type test_comparable(...);
32
+ template <typename T2>
33
+ static std::true_type test_value(typename T2::value_type *);
34
+ template <typename T2>
35
+ static std::false_type test_value(...);
36
+ template <typename T2>
37
+ static std::true_type test_pair(typename T2::first_type *, typename T2::second_type *);
38
+ template <typename T2>
39
+ static std::false_type test_pair(...);
40
+
41
+ static constexpr const bool is_comparable
42
+ = std::is_same<std::true_type, decltype(test_comparable<T>(nullptr))>::value;
43
+ static constexpr const bool is_pair
44
+ = std::is_same<std::true_type, decltype(test_pair<T>(nullptr, nullptr))>::value;
45
+ static constexpr const bool is_vector
46
+ = std::is_same<std::true_type, decltype(test_value<T>(nullptr))>::value;
47
+ static constexpr const bool is_element = !is_pair && !is_vector;
48
+ };
49
+
50
+ /* Default: is_comparable -> std::false_type */
51
+ template <typename T, typename SFINAE = void>
52
+ struct is_comparable : std::false_type {};
53
+
54
+ /* For non-map data structures, check whether operator== can be instantiated */
55
+ template <typename T>
56
+ struct is_comparable<
57
+ T,
58
+ enable_if_t<container_traits<T>::is_element && container_traits<T>::is_comparable>>
59
+ : std::true_type {};
60
+
61
+ /* For a vector/map data structure, recursively check the value type
62
+ (which is std::pair for maps) */
63
+ template <typename T>
64
+ struct is_comparable<T, enable_if_t<container_traits<T>::is_vector>>
65
+ : is_comparable<typename recursive_container_traits<T>::type_to_check_recursively> {};
66
+
67
+ template <>
68
+ struct is_comparable<recursive_bottom> : std::true_type {};
69
+
70
+ /* For pairs, recursively check the two data types */
71
+ template <typename T>
72
+ struct is_comparable<T, enable_if_t<container_traits<T>::is_pair>> {
73
+ static constexpr const bool value = is_comparable<typename T::first_type>::value
74
+ && is_comparable<typename T::second_type>::value;
75
+ };
76
+
77
+ /* Fallback functions */
78
+ template <typename, typename, typename... Args>
79
+ void vector_if_copy_constructible(const Args &...) {}
80
+ template <typename, typename, typename... Args>
81
+ void vector_if_equal_operator(const Args &...) {}
82
+ template <typename, typename, typename... Args>
83
+ void vector_if_insertion_operator(const Args &...) {}
84
+ template <typename, typename, typename... Args>
85
+ void vector_modifiers(const Args &...) {}
86
+
87
+ template <typename Vector, typename Class_>
88
+ void vector_if_copy_constructible(enable_if_t<is_copy_constructible<Vector>::value, Class_> &cl) {
89
+ cl.def(init<const Vector &>(), "Copy constructor");
90
+ }
91
+
92
+ template <typename Vector, typename Class_>
93
+ void vector_if_equal_operator(enable_if_t<is_comparable<Vector>::value, Class_> &cl) {
94
+ using T = typename Vector::value_type;
95
+
96
+ cl.def(self == self);
97
+ cl.def(self != self);
98
+
99
+ cl.def(
100
+ "count",
101
+ [](const Vector &v, const T &x) { return std::count(v.begin(), v.end(), x); },
102
+ arg("x"),
103
+ "Return the number of times ``x`` appears in the list");
104
+
105
+ cl.def(
106
+ "remove",
107
+ [](Vector &v, const T &x) {
108
+ auto p = std::find(v.begin(), v.end(), x);
109
+ if (p != v.end()) {
110
+ v.erase(p);
111
+ } else {
112
+ throw value_error();
113
+ }
114
+ },
115
+ arg("x"),
116
+ "Remove the first item from the list whose value is x. "
117
+ "It is an error if there is no such item.");
118
+
119
+ cl.def(
120
+ "__contains__",
121
+ [](const Vector &v, const T &x) { return std::find(v.begin(), v.end(), x) != v.end(); },
122
+ arg("x"),
123
+ "Return true the container contains ``x``");
124
+ }
125
+
126
+ // Vector modifiers -- requires a copyable vector_type:
127
+ // (Technically, some of these (pop and __delitem__) don't actually require copyability, but it
128
+ // seems silly to allow deletion but not insertion, so include them here too.)
129
+ template <typename Vector, typename Class_>
130
+ void vector_modifiers(
131
+ enable_if_t<is_copy_constructible<typename Vector::value_type>::value, Class_> &cl) {
132
+ using T = typename Vector::value_type;
133
+ using SizeType = typename Vector::size_type;
134
+ using DiffType = typename Vector::difference_type;
135
+
136
+ auto wrap_i = [](DiffType i, SizeType n) {
137
+ if (i < 0) {
138
+ i += n;
139
+ }
140
+ if (i < 0 || (SizeType) i >= n) {
141
+ throw index_error();
142
+ }
143
+ return i;
144
+ };
145
+
146
+ cl.def(
147
+ "append",
148
+ [](Vector &v, const T &value) { v.push_back(value); },
149
+ arg("x"),
150
+ "Add an item to the end of the list");
151
+
152
+ cl.def(init([](const iterable &it) {
153
+ auto v = std::unique_ptr<Vector>(new Vector());
154
+ v->reserve(len_hint(it));
155
+ for (handle h : it) {
156
+ v->push_back(h.cast<T>());
157
+ }
158
+ return v.release();
159
+ }));
160
+
161
+ cl.def("clear", [](Vector &v) { v.clear(); }, "Clear the contents");
162
+
163
+ cl.def(
164
+ "extend",
165
+ [](Vector &v, const Vector &src) { v.insert(v.end(), src.begin(), src.end()); },
166
+ arg("L"),
167
+ "Extend the list by appending all the items in the given list");
168
+
169
+ cl.def(
170
+ "extend",
171
+ [](Vector &v, const iterable &it) {
172
+ const size_t old_size = v.size();
173
+ v.reserve(old_size + len_hint(it));
174
+ try {
175
+ for (handle h : it) {
176
+ v.push_back(h.cast<T>());
177
+ }
178
+ } catch (const cast_error &) {
179
+ v.erase(v.begin() + static_cast<typename Vector::difference_type>(old_size),
180
+ v.end());
181
+ try {
182
+ v.shrink_to_fit();
183
+ } catch (const std::exception &) { // NOLINT(bugprone-empty-catch)
184
+ // Do nothing
185
+ }
186
+ throw;
187
+ }
188
+ },
189
+ arg("L"),
190
+ "Extend the list by appending all the items in the given list");
191
+
192
+ cl.def(
193
+ "insert",
194
+ [](Vector &v, DiffType i, const T &x) {
195
+ // Can't use wrap_i; i == v.size() is OK
196
+ if (i < 0) {
197
+ i += v.size();
198
+ }
199
+ if (i < 0 || (SizeType) i > v.size()) {
200
+ throw index_error();
201
+ }
202
+ v.insert(v.begin() + i, x);
203
+ },
204
+ arg("i"),
205
+ arg("x"),
206
+ "Insert an item at a given position.");
207
+
208
+ cl.def(
209
+ "pop",
210
+ [](Vector &v) {
211
+ if (v.empty()) {
212
+ throw index_error();
213
+ }
214
+ T t = std::move(v.back());
215
+ v.pop_back();
216
+ return t;
217
+ },
218
+ "Remove and return the last item");
219
+
220
+ cl.def(
221
+ "pop",
222
+ [wrap_i](Vector &v, DiffType i) {
223
+ i = wrap_i(i, v.size());
224
+ T t = std::move(v[(SizeType) i]);
225
+ v.erase(std::next(v.begin(), i));
226
+ return t;
227
+ },
228
+ arg("i"),
229
+ "Remove and return the item at index ``i``");
230
+
231
+ cl.def("__setitem__", [wrap_i](Vector &v, DiffType i, const T &t) {
232
+ i = wrap_i(i, v.size());
233
+ v[(SizeType) i] = t;
234
+ });
235
+
236
+ /// Slicing protocol
237
+ cl.def(
238
+ "__getitem__",
239
+ [](const Vector &v, const slice &slice) -> Vector * {
240
+ size_t start = 0, stop = 0, step = 0, slicelength = 0;
241
+
242
+ if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
243
+ throw error_already_set();
244
+ }
245
+
246
+ auto *seq = new Vector();
247
+ seq->reserve(slicelength);
248
+
249
+ for (size_t i = 0; i < slicelength; ++i) {
250
+ seq->push_back(v[start]);
251
+ start += step;
252
+ }
253
+ return seq;
254
+ },
255
+ arg("s"),
256
+ "Retrieve list elements using a slice object");
257
+
258
+ cl.def(
259
+ "__setitem__",
260
+ [](Vector &v, const slice &slice, const Vector &value) {
261
+ size_t start = 0, stop = 0, step = 0, slicelength = 0;
262
+ if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
263
+ throw error_already_set();
264
+ }
265
+
266
+ if (slicelength != value.size()) {
267
+ throw std::runtime_error(
268
+ "Left and right hand size of slice assignment have different sizes!");
269
+ }
270
+
271
+ for (size_t i = 0; i < slicelength; ++i) {
272
+ v[start] = value[i];
273
+ start += step;
274
+ }
275
+ },
276
+ "Assign list elements using a slice object");
277
+
278
+ cl.def(
279
+ "__delitem__",
280
+ [wrap_i](Vector &v, DiffType i) {
281
+ i = wrap_i(i, v.size());
282
+ v.erase(v.begin() + i);
283
+ },
284
+ "Delete the list elements at index ``i``");
285
+
286
+ cl.def(
287
+ "__delitem__",
288
+ [](Vector &v, const slice &slice) {
289
+ size_t start = 0, stop = 0, step = 0, slicelength = 0;
290
+
291
+ if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
292
+ throw error_already_set();
293
+ }
294
+
295
+ if (step == 1 && false) {
296
+ v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength));
297
+ } else {
298
+ for (size_t i = 0; i < slicelength; ++i) {
299
+ v.erase(v.begin() + DiffType(start));
300
+ start += step - 1;
301
+ }
302
+ }
303
+ },
304
+ "Delete list elements using a slice object");
305
+ }
306
+
307
+ // If the type has an operator[] that doesn't return a reference (most notably std::vector<bool>),
308
+ // we have to access by copying; otherwise we return by reference.
309
+ template <typename Vector>
310
+ using vector_needs_copy
311
+ = negation<std::is_same<decltype(std::declval<Vector>()[typename Vector::size_type()]),
312
+ typename Vector::value_type &>>;
313
+
314
+ // The usual case: access and iterate by reference
315
+ template <typename Vector, typename Class_>
316
+ void vector_accessor(enable_if_t<!vector_needs_copy<Vector>::value, Class_> &cl) {
317
+ using T = typename Vector::value_type;
318
+ using SizeType = typename Vector::size_type;
319
+ using DiffType = typename Vector::difference_type;
320
+ using ItType = typename Vector::iterator;
321
+
322
+ auto wrap_i = [](DiffType i, SizeType n) {
323
+ if (i < 0) {
324
+ i += n;
325
+ }
326
+ if (i < 0 || (SizeType) i >= n) {
327
+ throw index_error();
328
+ }
329
+ return i;
330
+ };
331
+
332
+ cl.def(
333
+ "__getitem__",
334
+ [wrap_i](Vector &v, DiffType i) -> T & {
335
+ i = wrap_i(i, v.size());
336
+ return v[(SizeType) i];
337
+ },
338
+ return_value_policy::reference_internal // ref + keepalive
339
+ );
340
+
341
+ cl.def(
342
+ "__iter__",
343
+ [](Vector &v) {
344
+ return make_iterator<return_value_policy::reference_internal, ItType, ItType, T &>(
345
+ v.begin(), v.end());
346
+ },
347
+ keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
348
+ );
349
+ }
350
+
351
+ // The case for special objects, like std::vector<bool>, that have to be returned-by-copy:
352
+ template <typename Vector, typename Class_>
353
+ void vector_accessor(enable_if_t<vector_needs_copy<Vector>::value, Class_> &cl) {
354
+ using T = typename Vector::value_type;
355
+ using SizeType = typename Vector::size_type;
356
+ using DiffType = typename Vector::difference_type;
357
+ using ItType = typename Vector::iterator;
358
+ cl.def("__getitem__", [](const Vector &v, DiffType i) -> T {
359
+ if (i < 0) {
360
+ i += v.size();
361
+ if (i < 0) {
362
+ throw index_error();
363
+ }
364
+ }
365
+ auto i_st = static_cast<SizeType>(i);
366
+ if (i_st >= v.size()) {
367
+ throw index_error();
368
+ }
369
+ return v[i_st];
370
+ });
371
+
372
+ cl.def(
373
+ "__iter__",
374
+ [](Vector &v) {
375
+ return make_iterator<return_value_policy::copy, ItType, ItType, T>(v.begin(), v.end());
376
+ },
377
+ keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
378
+ );
379
+ }
380
+
381
+ template <typename Vector, typename Class_>
382
+ auto vector_if_insertion_operator(Class_ &cl, std::string const &name)
383
+ -> decltype(std::declval<std::ostream &>() << std::declval<typename Vector::value_type>(),
384
+ void()) {
385
+ using size_type = typename Vector::size_type;
386
+
387
+ cl.def(
388
+ "__repr__",
389
+ [name](Vector &v) {
390
+ std::ostringstream s;
391
+ s << name << '[';
392
+ for (size_type i = 0; i < v.size(); ++i) {
393
+ s << v[i];
394
+ if (i != v.size() - 1) {
395
+ s << ", ";
396
+ }
397
+ }
398
+ s << ']';
399
+ return s.str();
400
+ },
401
+ "Return the canonical string representation of this list.");
402
+ }
403
+
404
+ // Provide the buffer interface for vectors if we have data() and we have a format for it
405
+ // GCC seems to have "void std::vector<bool>::data()" - doing SFINAE on the existence of data()
406
+ // is insufficient, we need to check it returns an appropriate pointer
407
+ template <typename Vector, typename = void>
408
+ struct vector_has_data_and_format : std::false_type {};
409
+ template <typename Vector>
410
+ struct vector_has_data_and_format<
411
+ Vector,
412
+ enable_if_t<std::is_same<decltype(format_descriptor<typename Vector::value_type>::format(),
413
+ std::declval<Vector>().data()),
414
+ typename Vector::value_type *>::value>> : std::true_type {};
415
+
416
+ // [workaround(intel)] Separate function required here
417
+ // Workaround as the Intel compiler does not compile the enable_if_t part below
418
+ // (tested with icc (ICC) 2021.1 Beta 20200827)
419
+ template <typename... Args>
420
+ constexpr bool args_any_are_buffer() {
421
+ return detail::any_of<std::is_same<Args, buffer_protocol>...>::value;
422
+ }
423
+
424
+ // [workaround(intel)] Separate function required here
425
+ // [workaround(msvc)] Can't use constexpr bool in return type
426
+
427
+ // Add the buffer interface to a vector
428
+ template <typename Vector, typename Class_, typename... Args>
429
+ void vector_buffer_impl(Class_ &cl, std::true_type) {
430
+ using T = typename Vector::value_type;
431
+
432
+ static_assert(vector_has_data_and_format<Vector>::value,
433
+ "There is not an appropriate format descriptor for this vector");
434
+
435
+ // numpy.h declares this for arbitrary types, but it may raise an exception and crash hard
436
+ // at runtime if PYBIND11_NUMPY_DTYPE hasn't been called, so check here
437
+ format_descriptor<T>::format();
438
+
439
+ cl.def_buffer([](Vector &v) -> buffer_info {
440
+ return buffer_info(v.data(),
441
+ static_cast<ssize_t>(sizeof(T)),
442
+ format_descriptor<T>::format(),
443
+ 1,
444
+ {v.size()},
445
+ {sizeof(T)});
446
+ });
447
+
448
+ cl.def(init([](const buffer &buf) {
449
+ auto info = buf.request();
450
+ if (info.ndim != 1 || info.strides[0] % static_cast<ssize_t>(sizeof(T))) {
451
+ throw type_error("Only valid 1D buffers can be copied to a vector");
452
+ }
453
+ if (!detail::compare_buffer_info<T>::compare(info)
454
+ || (ssize_t) sizeof(T) != info.itemsize) {
455
+ throw type_error("Format mismatch (Python: " + info.format
456
+ + " C++: " + format_descriptor<T>::format() + ")");
457
+ }
458
+
459
+ T *p = static_cast<T *>(info.ptr);
460
+ ssize_t step = info.strides[0] / static_cast<ssize_t>(sizeof(T));
461
+ T *end = p + info.shape[0] * step;
462
+ if (step == 1) {
463
+ return Vector(p, end);
464
+ }
465
+ Vector vec;
466
+ vec.reserve((size_t) info.shape[0]);
467
+ for (; p != end; p += step) {
468
+ vec.push_back(*p);
469
+ }
470
+ return vec;
471
+ }));
472
+
473
+ return;
474
+ }
475
+
476
+ template <typename Vector, typename Class_, typename... Args>
477
+ void vector_buffer_impl(Class_ &, std::false_type) {}
478
+
479
+ template <typename Vector, typename Class_, typename... Args>
480
+ void vector_buffer(Class_ &cl) {
481
+ vector_buffer_impl<Vector, Class_, Args...>(
482
+ cl, detail::any_of<std::is_same<Args, buffer_protocol>...>{});
483
+ }
484
+
485
+ PYBIND11_NAMESPACE_END(detail)
486
+
487
+ //
488
+ // std::vector
489
+ //
490
+ template <typename Vector, typename holder_type = default_holder_type<Vector>, typename... Args>
491
+ class_<Vector, holder_type> bind_vector(handle scope, std::string const &name, Args &&...args) {
492
+ using Class_ = class_<Vector, holder_type>;
493
+
494
+ // If the value_type is unregistered (e.g. a converting type) or is itself registered
495
+ // module-local then make the vector binding module-local as well:
496
+ using vtype = typename Vector::value_type;
497
+ auto *vtype_info = detail::get_type_info(typeid(vtype));
498
+ bool local = !vtype_info || vtype_info->module_local;
499
+
500
+ Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);
501
+
502
+ // Declare the buffer interface if a buffer_protocol() is passed in
503
+ detail::vector_buffer<Vector, Class_, Args...>(cl);
504
+
505
+ cl.def(init<>());
506
+
507
+ // Register copy constructor (if possible)
508
+ detail::vector_if_copy_constructible<Vector, Class_>(cl);
509
+
510
+ // Register comparison-related operators and functions (if possible)
511
+ detail::vector_if_equal_operator<Vector, Class_>(cl);
512
+
513
+ // Register stream insertion operator (if possible)
514
+ detail::vector_if_insertion_operator<Vector, Class_>(cl, name);
515
+
516
+ // Modifiers require copyable vector value type
517
+ detail::vector_modifiers<Vector, Class_>(cl);
518
+
519
+ // Accessor and iterator; return by value if copyable, otherwise we return by ref + keep-alive
520
+ detail::vector_accessor<Vector, Class_>(cl);
521
+
522
+ cl.def(
523
+ "__bool__",
524
+ [](const Vector &v) -> bool { return !v.empty(); },
525
+ "Check whether the list is nonempty");
526
+
527
+ cl.def("__len__", [](const Vector &vec) { return vec.size(); });
528
+
529
+ #if 0
530
+ // C++ style functions deprecated, leaving it here as an example
531
+ cl.def(init<size_type>());
532
+
533
+ cl.def("resize",
534
+ (void (Vector::*) (size_type count)) & Vector::resize,
535
+ "changes the number of elements stored");
536
+
537
+ cl.def("erase",
538
+ [](Vector &v, SizeType i) {
539
+ if (i >= v.size())
540
+ throw index_error();
541
+ v.erase(v.begin() + i);
542
+ }, "erases element at index ``i``");
543
+
544
+ cl.def("empty", &Vector::empty, "checks whether the container is empty");
545
+ cl.def("size", &Vector::size, "returns the number of elements");
546
+ cl.def("push_back", (void (Vector::*)(const T&)) &Vector::push_back, "adds an element to the end");
547
+ cl.def("pop_back", &Vector::pop_back, "removes the last element");
548
+
549
+ cl.def("max_size", &Vector::max_size, "returns the maximum possible number of elements");
550
+ cl.def("reserve", &Vector::reserve, "reserves storage");
551
+ cl.def("capacity", &Vector::capacity, "returns the number of elements that can be held in currently allocated storage");
552
+ cl.def("shrink_to_fit", &Vector::shrink_to_fit, "reduces memory usage by freeing unused memory");
553
+
554
+ cl.def("clear", &Vector::clear, "clears the contents");
555
+ cl.def("swap", &Vector::swap, "swaps the contents");
556
+
557
+ cl.def("front", [](Vector &v) {
558
+ if (v.size()) return v.front();
559
+ else throw index_error();
560
+ }, "access the first element");
561
+
562
+ cl.def("back", [](Vector &v) {
563
+ if (v.size()) return v.back();
564
+ else throw index_error();
565
+ }, "access the last element ");
566
+
567
+ #endif
568
+
569
+ return cl;
570
+ }
571
+
572
+ //
573
+ // std::map, std::unordered_map
574
+ //
575
+
576
+ PYBIND11_NAMESPACE_BEGIN(detail)
577
+
578
+ /* Fallback functions */
579
+ template <typename, typename, typename... Args>
580
+ void map_if_insertion_operator(const Args &...) {}
581
+ template <typename, typename, typename... Args>
582
+ void map_assignment(const Args &...) {}
583
+
584
+ // Map assignment when copy-assignable: just copy the value
585
+ template <typename Map, typename Class_>
586
+ void map_assignment(
587
+ enable_if_t<is_copy_assignable<typename Map::mapped_type>::value, Class_> &cl) {
588
+ using KeyType = typename Map::key_type;
589
+ using MappedType = typename Map::mapped_type;
590
+
591
+ cl.def("__setitem__", [](Map &m, const KeyType &k, const MappedType &v) {
592
+ auto it = m.find(k);
593
+ if (it != m.end()) {
594
+ it->second = v;
595
+ } else {
596
+ m.emplace(k, v);
597
+ }
598
+ });
599
+ }
600
+
601
+ // Not copy-assignable, but still copy-constructible: we can update the value by erasing and
602
+ // reinserting
603
+ template <typename Map, typename Class_>
604
+ void map_assignment(enable_if_t<!is_copy_assignable<typename Map::mapped_type>::value
605
+ && is_copy_constructible<typename Map::mapped_type>::value,
606
+ Class_> &cl) {
607
+ using KeyType = typename Map::key_type;
608
+ using MappedType = typename Map::mapped_type;
609
+
610
+ cl.def("__setitem__", [](Map &m, const KeyType &k, const MappedType &v) {
611
+ // We can't use m[k] = v; because value type might not be default constructable
612
+ auto r = m.emplace(k, v);
613
+ if (!r.second) {
614
+ // value type is not copy assignable so the only way to insert it is to erase it
615
+ // first...
616
+ m.erase(r.first);
617
+ m.emplace(k, v);
618
+ }
619
+ });
620
+ }
621
+
622
+ template <typename Map, typename Class_>
623
+ auto map_if_insertion_operator(Class_ &cl, std::string const &name)
624
+ -> decltype(std::declval<std::ostream &>() << std::declval<typename Map::key_type>()
625
+ << std::declval<typename Map::mapped_type>(),
626
+ void()) {
627
+
628
+ cl.def(
629
+ "__repr__",
630
+ [name](Map &m) {
631
+ std::ostringstream s;
632
+ s << name << '{';
633
+ bool f = false;
634
+ for (auto const &kv : m) {
635
+ if (f) {
636
+ s << ", ";
637
+ }
638
+ s << kv.first << ": " << kv.second;
639
+ f = true;
640
+ }
641
+ s << '}';
642
+ return s.str();
643
+ },
644
+ "Return the canonical string representation of this map.");
645
+ }
646
+
647
+ struct keys_view {
648
+ virtual size_t len() = 0;
649
+ virtual iterator iter() = 0;
650
+ virtual bool contains(const handle &k) = 0;
651
+ virtual ~keys_view() = default;
652
+ };
653
+
654
+ struct values_view {
655
+ virtual size_t len() = 0;
656
+ virtual iterator iter() = 0;
657
+ virtual ~values_view() = default;
658
+ };
659
+
660
+ struct items_view {
661
+ virtual size_t len() = 0;
662
+ virtual iterator iter() = 0;
663
+ virtual ~items_view() = default;
664
+ };
665
+
666
+ template <typename Map>
667
+ struct KeysViewImpl : public detail::keys_view {
668
+ explicit KeysViewImpl(Map &map) : map(map) {}
669
+ size_t len() override { return map.size(); }
670
+ iterator iter() override { return make_key_iterator(map.begin(), map.end()); }
671
+ bool contains(const handle &k) override {
672
+ try {
673
+ return map.find(k.template cast<typename Map::key_type>()) != map.end();
674
+ } catch (const cast_error &) {
675
+ return false;
676
+ }
677
+ }
678
+ Map &map;
679
+ };
680
+
681
+ template <typename Map>
682
+ struct ValuesViewImpl : public detail::values_view {
683
+ explicit ValuesViewImpl(Map &map) : map(map) {}
684
+ size_t len() override { return map.size(); }
685
+ iterator iter() override { return make_value_iterator(map.begin(), map.end()); }
686
+ Map &map;
687
+ };
688
+
689
+ template <typename Map>
690
+ struct ItemsViewImpl : public detail::items_view {
691
+ explicit ItemsViewImpl(Map &map) : map(map) {}
692
+ size_t len() override { return map.size(); }
693
+ iterator iter() override { return make_iterator(map.begin(), map.end()); }
694
+ Map &map;
695
+ };
696
+
697
+ inline str format_message_key_error_key_object(handle py_key) {
698
+ str message = "pybind11::bind_map key";
699
+ if (!py_key) {
700
+ return message;
701
+ }
702
+ try {
703
+ message = str(py_key);
704
+ } catch (const std::exception &) {
705
+ try {
706
+ message = repr(py_key);
707
+ } catch (const std::exception &) {
708
+ return message;
709
+ }
710
+ }
711
+ const ssize_t cut_length = 100;
712
+ if (len(message) > 2 * cut_length + 3) {
713
+ return str(message[slice(0, cut_length, 1)]) + str("✄✄✄")
714
+ + str(message[slice(-cut_length, static_cast<ssize_t>(len(message)), 1)]);
715
+ }
716
+ return message;
717
+ }
718
+
719
+ template <typename KeyType>
720
+ str format_message_key_error(const KeyType &key) {
721
+ object py_key;
722
+ try {
723
+ py_key = cast(key);
724
+ } catch (const std::exception &) {
725
+ do { // Trick to avoid "empty catch" warning/error.
726
+ } while (false);
727
+ }
728
+ return format_message_key_error_key_object(py_key);
729
+ }
730
+
731
+ PYBIND11_NAMESPACE_END(detail)
732
+
733
+ template <typename Map, typename holder_type = default_holder_type<Map>, typename... Args>
734
+ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args &&...args) {
735
+ using KeyType = typename Map::key_type;
736
+ using MappedType = typename Map::mapped_type;
737
+ using KeysView = detail::keys_view;
738
+ using ValuesView = detail::values_view;
739
+ using ItemsView = detail::items_view;
740
+ using Class_ = class_<Map, holder_type>;
741
+
742
+ // If either type is a non-module-local bound type then make the map binding non-local as well;
743
+ // otherwise (e.g. both types are either module-local or converting) the map will be
744
+ // module-local.
745
+ auto *tinfo = detail::get_type_info(typeid(MappedType));
746
+ bool local = !tinfo || tinfo->module_local;
747
+ if (local) {
748
+ tinfo = detail::get_type_info(typeid(KeyType));
749
+ local = !tinfo || tinfo->module_local;
750
+ }
751
+
752
+ Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);
753
+
754
+ // Wrap KeysView if it wasn't already wrapped
755
+ if (!detail::get_type_info(typeid(KeysView))) {
756
+ class_<KeysView> keys_view(scope, "KeysView", pybind11::module_local(local));
757
+ keys_view.def("__len__", &KeysView::len);
758
+ keys_view.def("__iter__",
759
+ &KeysView::iter,
760
+ keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
761
+ );
762
+ keys_view.def("__contains__", &KeysView::contains);
763
+ }
764
+ // Similarly for ValuesView:
765
+ if (!detail::get_type_info(typeid(ValuesView))) {
766
+ class_<ValuesView> values_view(scope, "ValuesView", pybind11::module_local(local));
767
+ values_view.def("__len__", &ValuesView::len);
768
+ values_view.def("__iter__",
769
+ &ValuesView::iter,
770
+ keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
771
+ );
772
+ }
773
+ // Similarly for ItemsView:
774
+ if (!detail::get_type_info(typeid(ItemsView))) {
775
+ class_<ItemsView> items_view(scope, "ItemsView", pybind11::module_local(local));
776
+ items_view.def("__len__", &ItemsView::len);
777
+ items_view.def("__iter__",
778
+ &ItemsView::iter,
779
+ keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
780
+ );
781
+ }
782
+
783
+ cl.def(init<>());
784
+
785
+ // Register stream insertion operator (if possible)
786
+ detail::map_if_insertion_operator<Map, Class_>(cl, name);
787
+
788
+ cl.def(
789
+ "__bool__",
790
+ [](const Map &m) -> bool { return !m.empty(); },
791
+ "Check whether the map is nonempty");
792
+
793
+ cl.def(
794
+ "__iter__",
795
+ [](Map &m) { return make_key_iterator(m.begin(), m.end()); },
796
+ keep_alive<0, 1>() /* Essential: keep map alive while iterator exists */
797
+ );
798
+
799
+ cl.def(
800
+ "keys",
801
+ [](Map &m) { return std::unique_ptr<KeysView>(new detail::KeysViewImpl<Map>(m)); },
802
+ keep_alive<0, 1>() /* Essential: keep map alive while view exists */
803
+ );
804
+
805
+ cl.def(
806
+ "values",
807
+ [](Map &m) { return std::unique_ptr<ValuesView>(new detail::ValuesViewImpl<Map>(m)); },
808
+ keep_alive<0, 1>() /* Essential: keep map alive while view exists */
809
+ );
810
+
811
+ cl.def(
812
+ "items",
813
+ [](Map &m) { return std::unique_ptr<ItemsView>(new detail::ItemsViewImpl<Map>(m)); },
814
+ keep_alive<0, 1>() /* Essential: keep map alive while view exists */
815
+ );
816
+
817
+ cl.def(
818
+ "__getitem__",
819
+ [](Map &m, const KeyType &k) -> MappedType & {
820
+ auto it = m.find(k);
821
+ if (it == m.end()) {
822
+ set_error(PyExc_KeyError, detail::format_message_key_error(k));
823
+ throw error_already_set();
824
+ }
825
+ return it->second;
826
+ },
827
+ return_value_policy::reference_internal // ref + keepalive
828
+ );
829
+
830
+ cl.def("__contains__", [](Map &m, const KeyType &k) -> bool {
831
+ auto it = m.find(k);
832
+ if (it == m.end()) {
833
+ return false;
834
+ }
835
+ return true;
836
+ });
837
+ // Fallback for when the object is not of the key type
838
+ cl.def("__contains__", [](Map &, const object &) -> bool { return false; });
839
+
840
+ // Assignment provided only if the type is copyable
841
+ detail::map_assignment<Map, Class_>(cl);
842
+
843
+ cl.def("__delitem__", [](Map &m, const KeyType &k) {
844
+ auto it = m.find(k);
845
+ if (it == m.end()) {
846
+ set_error(PyExc_KeyError, detail::format_message_key_error(k));
847
+ throw error_already_set();
848
+ }
849
+ m.erase(it);
850
+ });
851
+
852
+ // Always use a lambda in case of `using` declaration
853
+ cl.def("__len__", [](const Map &m) { return m.size(); });
854
+
855
+ return cl;
856
+ }
857
+
858
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/subinterpreter.h ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/subinterpreter.h: Support for creating and using subinterpreters
3
+
4
+ Copyright (c) 2025 The Pybind Development Team.
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
+ #include "detail/internals.h"
14
+ #include "gil.h"
15
+
16
+ #include <stdexcept>
17
+
18
+ #ifndef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
19
+ # error "This platform does not support subinterpreters, do not include this file."
20
+ #endif
21
+
22
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
23
+
24
+ class subinterpreter;
25
+
26
+ /// Activate the subinterpreter and acquire its GIL, while also releasing any GIL and interpreter
27
+ /// currently held. Upon exiting the scope, the previous subinterpreter (if any) and its
28
+ /// associated GIL are restored to their state as they were before the scope was entered.
29
+ class subinterpreter_scoped_activate {
30
+ public:
31
+ explicit subinterpreter_scoped_activate(subinterpreter const &si);
32
+ ~subinterpreter_scoped_activate();
33
+
34
+ subinterpreter_scoped_activate(subinterpreter_scoped_activate &&) = delete;
35
+ subinterpreter_scoped_activate(subinterpreter_scoped_activate const &) = delete;
36
+ subinterpreter_scoped_activate &operator=(subinterpreter_scoped_activate &) = delete;
37
+ subinterpreter_scoped_activate &operator=(subinterpreter_scoped_activate const &) = delete;
38
+
39
+ private:
40
+ PyThreadState *old_tstate_ = nullptr;
41
+ PyThreadState *tstate_ = nullptr;
42
+ PyGILState_STATE gil_state_;
43
+ bool simple_gil_ = false;
44
+ };
45
+
46
+ /// Holds a Python subinterpreter instance
47
+ class subinterpreter {
48
+ public:
49
+ /// empty/unusable, but move-assignable. use create() to create a subinterpreter.
50
+ subinterpreter() = default;
51
+
52
+ subinterpreter(subinterpreter const &copy) = delete;
53
+ subinterpreter &operator=(subinterpreter const &copy) = delete;
54
+
55
+ subinterpreter(subinterpreter &&old) noexcept
56
+ : istate_(old.istate_), creation_tstate_(old.creation_tstate_) {
57
+ old.istate_ = nullptr;
58
+ old.creation_tstate_ = nullptr;
59
+ }
60
+
61
+ subinterpreter &operator=(subinterpreter &&old) noexcept {
62
+ std::swap(old.istate_, istate_);
63
+ std::swap(old.creation_tstate_, creation_tstate_);
64
+ return *this;
65
+ }
66
+
67
+ /// Create a new subinterpreter with the specified configuration
68
+ /// @note This function acquires (and then releases) the main interpreter GIL, but the main
69
+ /// interpreter and its GIL are not required to be held prior to calling this function.
70
+ static subinterpreter create(PyInterpreterConfig const &cfg) {
71
+
72
+ error_scope err_scope;
73
+ subinterpreter result;
74
+ {
75
+ // we must hold the main GIL in order to create a subinterpreter
76
+ subinterpreter_scoped_activate main_guard(main());
77
+
78
+ auto *prev_tstate = PyThreadState_Get();
79
+
80
+ PyStatus status;
81
+
82
+ {
83
+ /*
84
+ Several internal CPython modules are lacking proper subinterpreter support in 3.12
85
+ even though it is "stable" in that version. This most commonly seems to cause
86
+ crashes when two interpreters concurrently initialize, which imports several things
87
+ (like builtins, unicode, codecs).
88
+ */
89
+ #if PY_VERSION_HEX < 0x030D0000 && defined(Py_MOD_PER_INTERPRETER_GIL_SUPPORTED)
90
+ static std::mutex one_at_a_time;
91
+ std::lock_guard<std::mutex> guard(one_at_a_time);
92
+ #endif
93
+ status = Py_NewInterpreterFromConfig(&result.creation_tstate_, &cfg);
94
+ }
95
+
96
+ // this doesn't raise a normal Python exception, it provides an exit() status code.
97
+ if (PyStatus_Exception(status) != 0) {
98
+ pybind11_fail("failed to create new sub-interpreter");
99
+ }
100
+
101
+ // upon success, the new interpreter is activated in this thread
102
+ result.istate_ = result.creation_tstate_->interp;
103
+ detail::has_seen_non_main_interpreter() = true;
104
+ detail::get_internals(); // initialize internals.tstate, amongst other things...
105
+
106
+ // In 3.13+ this state should be deleted right away, and the memory will be reused for
107
+ // the next threadstate on this interpreter. However, on 3.12 we cannot do that, we
108
+ // must keep it around (but not use it) ... see destructor.
109
+ #if PY_VERSION_HEX >= 0x030D0000
110
+ PyThreadState_Clear(result.creation_tstate_);
111
+ PyThreadState_DeleteCurrent();
112
+ #endif
113
+
114
+ // we have to switch back to main, and then the scopes will handle cleanup
115
+ PyThreadState_Swap(prev_tstate);
116
+ }
117
+ return result;
118
+ }
119
+
120
+ /// Calls create() with a default configuration of an isolated interpreter that disallows fork,
121
+ /// exec, and Python threads.
122
+ static subinterpreter create() {
123
+ // same as the default config in the python docs
124
+ PyInterpreterConfig cfg;
125
+ std::memset(&cfg, 0, sizeof(cfg));
126
+ cfg.allow_threads = 1;
127
+ cfg.check_multi_interp_extensions = 1;
128
+ cfg.gil = PyInterpreterConfig_OWN_GIL;
129
+ return create(cfg);
130
+ }
131
+
132
+ ~subinterpreter() {
133
+ if (!creation_tstate_) {
134
+ // non-owning wrapper, do nothing.
135
+ return;
136
+ }
137
+
138
+ PyThreadState *destroy_tstate = nullptr;
139
+ PyThreadState *old_tstate = nullptr;
140
+
141
+ // Python 3.12 requires us to keep the original PyThreadState alive until we are ready to
142
+ // destroy the interpreter. We prefer to use that to destroy the interpreter.
143
+ #if PY_VERSION_HEX < 0x030D0000
144
+ // The tstate passed to Py_EndInterpreter MUST have been created on the current OS thread.
145
+ bool same_thread = false;
146
+ # ifdef PY_HAVE_THREAD_NATIVE_ID
147
+ same_thread = PyThread_get_thread_native_id() == creation_tstate_->native_thread_id;
148
+ # endif
149
+ if (same_thread) {
150
+ // OK it is safe to use the creation state here
151
+ destroy_tstate = creation_tstate_;
152
+ old_tstate = PyThreadState_Swap(destroy_tstate);
153
+ } else {
154
+ // We have to make a new tstate on this thread and use that.
155
+ destroy_tstate = PyThreadState_New(istate_);
156
+ old_tstate = PyThreadState_Swap(destroy_tstate);
157
+
158
+ // We can use the one we just created, so we must delete the creation state.
159
+ PyThreadState_Clear(creation_tstate_);
160
+ PyThreadState_Delete(creation_tstate_);
161
+ }
162
+ #else
163
+ destroy_tstate = PyThreadState_New(istate_);
164
+ old_tstate = PyThreadState_Swap(destroy_tstate);
165
+ #endif
166
+
167
+ bool switch_back = (old_tstate != nullptr) && old_tstate->interp != istate_;
168
+
169
+ // Internals always exists in the subinterpreter, this class enforces it when it creates
170
+ // the subinterpreter. Even if it didn't, this only creates the pointer-to-pointer, not the
171
+ // internals themselves.
172
+ detail::get_internals_pp_manager().get_pp();
173
+ detail::get_local_internals_pp_manager().get_pp();
174
+
175
+ // End it
176
+ Py_EndInterpreter(destroy_tstate);
177
+
178
+ // It's possible for the internals to be created during endinterpreter (e.g. if a
179
+ // py::capsule calls `get_internals()` during destruction), so we destroy afterward.
180
+ detail::get_internals_pp_manager().destroy();
181
+ detail::get_local_internals_pp_manager().destroy();
182
+
183
+ // switch back to the old tstate and old GIL (if there was one)
184
+ if (switch_back) {
185
+ PyThreadState_Swap(old_tstate);
186
+ }
187
+ }
188
+
189
+ /// Get a handle to the main interpreter that can be used with subinterpreter_scoped_activate
190
+ /// Note that destructing the handle is a noop, the main interpreter can only be ended by
191
+ /// py::finalize_interpreter()
192
+ static subinterpreter main() {
193
+ subinterpreter m;
194
+ m.istate_ = PyInterpreterState_Main();
195
+ m.disarm(); // make destruct a noop
196
+ return m;
197
+ }
198
+
199
+ /// Get a non-owning wrapper of the currently active interpreter (if any)
200
+ static subinterpreter current() {
201
+ subinterpreter c;
202
+ c.istate_ = detail::get_interpreter_state_unchecked();
203
+ c.disarm(); // make destruct a noop, we don't own this...
204
+ return c;
205
+ }
206
+
207
+ /// Get the numerical identifier for the sub-interpreter
208
+ int64_t id() const {
209
+ if (istate_ != nullptr) {
210
+ return PyInterpreterState_GetID(istate_);
211
+ }
212
+ return -1; // CPython uses one-up numbers from 0, so negative should be safe to return
213
+ // here.
214
+ }
215
+
216
+ /// Get the interpreter's state dict. This interpreter's GIL must be held before calling!
217
+ dict state_dict() { return reinterpret_borrow<dict>(PyInterpreterState_GetDict(istate_)); }
218
+
219
+ /// abandon cleanup of this subinterpreter (leak it). this might be needed during
220
+ /// finalization...
221
+ void disarm() { creation_tstate_ = nullptr; }
222
+
223
+ /// An empty wrapper cannot be activated
224
+ bool empty() const { return istate_ == nullptr; }
225
+
226
+ /// Is this wrapper non-empty
227
+ explicit operator bool() const { return !empty(); }
228
+
229
+ private:
230
+ friend class subinterpreter_scoped_activate;
231
+ PyInterpreterState *istate_ = nullptr;
232
+ PyThreadState *creation_tstate_ = nullptr;
233
+ };
234
+
235
+ class scoped_subinterpreter {
236
+ public:
237
+ scoped_subinterpreter() : si_(subinterpreter::create()), scope_(si_) {}
238
+
239
+ explicit scoped_subinterpreter(PyInterpreterConfig const &cfg)
240
+ : si_(subinterpreter::create(cfg)), scope_(si_) {}
241
+
242
+ private:
243
+ subinterpreter si_;
244
+ subinterpreter_scoped_activate scope_;
245
+ };
246
+
247
+ inline subinterpreter_scoped_activate::subinterpreter_scoped_activate(subinterpreter const &si) {
248
+ if (!si.istate_) {
249
+ pybind11_fail("null subinterpreter");
250
+ }
251
+
252
+ if (detail::get_interpreter_state_unchecked() == si.istate_) {
253
+ // we are already on this interpreter, make sure we hold the GIL
254
+ simple_gil_ = true;
255
+ gil_state_ = PyGILState_Ensure();
256
+ return;
257
+ }
258
+
259
+ // we can't really interact with the interpreter at all until we switch to it
260
+ // not even to, for example, look in its state dict or touch its internals
261
+ tstate_ = PyThreadState_New(si.istate_);
262
+
263
+ // make the interpreter active and acquire the GIL
264
+ old_tstate_ = PyThreadState_Swap(tstate_);
265
+
266
+ // save this in internals for scoped_gil calls (see also: PR #5870)
267
+ detail::get_internals().tstate = tstate_;
268
+ }
269
+
270
+ inline subinterpreter_scoped_activate::~subinterpreter_scoped_activate() {
271
+ if (simple_gil_) {
272
+ // We were on this interpreter already, so just make sure the GIL goes back as it was
273
+ PyGILState_Release(gil_state_);
274
+ } else {
275
+ if (tstate_) {
276
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
277
+ if (detail::get_thread_state_unchecked() != tstate_) {
278
+ pybind11_fail("~subinterpreter_scoped_activate: thread state must be current!");
279
+ }
280
+ #endif
281
+ detail::get_internals().tstate.reset();
282
+ PyThreadState_Clear(tstate_);
283
+ PyThreadState_DeleteCurrent();
284
+ }
285
+
286
+ // Go back the previous interpreter (if any) and acquire THAT gil
287
+ PyThreadState_Swap(old_tstate_);
288
+ }
289
+ }
290
+
291
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/trampoline_self_life_support.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2021 The Pybind Development Team.
2
+ // All rights reserved. Use of this source code is governed by a
3
+ // BSD-style license that can be found in the LICENSE file.
4
+
5
+ #pragma once
6
+
7
+ #include "detail/common.h"
8
+ #include "detail/using_smart_holder.h"
9
+ #include "detail/value_and_holder.h"
10
+
11
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
12
+
13
+ PYBIND11_NAMESPACE_BEGIN(detail)
14
+ // PYBIND11:REMINDER: Needs refactoring of existing pybind11 code.
15
+ inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo);
16
+ PYBIND11_NAMESPACE_END(detail)
17
+
18
+ // The original core idea for this struct goes back to PyCLIF:
19
+ // https://github.com/google/clif/blob/07f95d7e69dca2fcf7022978a55ef3acff506c19/clif/python/runtime.cc#L37
20
+ // URL provided here mainly to give proper credit.
21
+ struct trampoline_self_life_support {
22
+ // NOTE: PYBIND11_INTERNALS_VERSION needs to be bumped if changes are made to this struct.
23
+ detail::value_and_holder v_h;
24
+
25
+ trampoline_self_life_support() = default;
26
+
27
+ void activate_life_support(const detail::value_and_holder &v_h_) {
28
+ Py_INCREF((PyObject *) v_h_.inst);
29
+ v_h = v_h_;
30
+ }
31
+
32
+ void deactivate_life_support() {
33
+ Py_DECREF((PyObject *) v_h.inst);
34
+ v_h = detail::value_and_holder();
35
+ }
36
+
37
+ ~trampoline_self_life_support() {
38
+ if (v_h.inst != nullptr && v_h.vh != nullptr) {
39
+ void *value_void_ptr = v_h.value_ptr();
40
+ if (value_void_ptr != nullptr) {
41
+ PyGILState_STATE threadstate = PyGILState_Ensure();
42
+ v_h.value_ptr() = nullptr;
43
+ v_h.holder<smart_holder>().release_disowned();
44
+ detail::deregister_instance(v_h.inst, value_void_ptr, v_h.type);
45
+ Py_DECREF((PyObject *) v_h.inst); // Must be after deregister.
46
+ PyGILState_Release(threadstate);
47
+ }
48
+ }
49
+ }
50
+
51
+ // For the next two, the default implementations generate undefined behavior (ASAN failures
52
+ // manually verified). The reason is that v_h needs to be kept default-initialized.
53
+ trampoline_self_life_support(const trampoline_self_life_support &) {}
54
+ trampoline_self_life_support(trampoline_self_life_support &&) noexcept {}
55
+
56
+ // These should never be needed (please provide test cases if you think they are).
57
+ trampoline_self_life_support &operator=(const trampoline_self_life_support &) = delete;
58
+ trampoline_self_life_support &operator=(trampoline_self_life_support &&) = delete;
59
+ };
60
+
61
+ PYBIND11_NAMESPACE_BEGIN(detail)
62
+ using get_trampoline_self_life_support_fn = trampoline_self_life_support *(*) (void *);
63
+ PYBIND11_NAMESPACE_END(detail)
64
+
65
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/type_caster_pyobject_ptr.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2023 The pybind Community.
2
+
3
+ #pragma once
4
+
5
+ #include "detail/common.h"
6
+ #include "detail/descr.h"
7
+ #include "cast.h"
8
+ #include "pytypes.h"
9
+
10
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
11
+ PYBIND11_NAMESPACE_BEGIN(detail)
12
+
13
+ template <>
14
+ class type_caster<PyObject> {
15
+ public:
16
+ static constexpr auto name = const_name("object"); // See discussion under PR #4601.
17
+
18
+ // This overload is purely to guard against accidents.
19
+ template <typename T,
20
+ detail::enable_if_t<!is_same_ignoring_cvref<T, PyObject *>::value, int> = 0>
21
+ static handle cast(T &&, return_value_policy, handle /*parent*/) {
22
+ static_assert(is_same_ignoring_cvref<T, PyObject *>::value,
23
+ "Invalid C++ type T for to-Python conversion (type_caster<PyObject>).");
24
+ return nullptr; // Unreachable.
25
+ }
26
+
27
+ static handle cast(PyObject *src, return_value_policy policy, handle /*parent*/) {
28
+ if (src == nullptr) {
29
+ throw error_already_set();
30
+ }
31
+ if (PyErr_Occurred()) {
32
+ raise_from(PyExc_SystemError, "src != nullptr but PyErr_Occurred()");
33
+ throw error_already_set();
34
+ }
35
+ if (policy == return_value_policy::take_ownership) {
36
+ return src;
37
+ }
38
+ if (policy == return_value_policy::reference
39
+ || policy == return_value_policy::automatic_reference) {
40
+ return handle(src).inc_ref();
41
+ }
42
+ pybind11_fail("type_caster<PyObject>::cast(): unsupported return_value_policy: "
43
+ + std::to_string(static_cast<int>(policy)));
44
+ }
45
+
46
+ bool load(handle src, bool) {
47
+ value = reinterpret_borrow<object>(src);
48
+ return true;
49
+ }
50
+
51
+ template <typename T>
52
+ using cast_op_type = PyObject *;
53
+
54
+ explicit operator PyObject *() { return value.ptr(); }
55
+
56
+ private:
57
+ object value;
58
+ };
59
+
60
+ PYBIND11_NAMESPACE_END(detail)
61
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/typing.h ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/typing.h: Convenience wrapper classes for basic Python types
3
+ with more explicit annotations.
4
+
5
+ Copyright (c) 2023 Dustin Spicuzza <dustin@virtualroadside.com>
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
+ #include "pytypes.h"
16
+
17
+ #include <algorithm>
18
+
19
+ #if defined(__cpp_nontype_template_args) && __cpp_nontype_template_args >= 201911L
20
+ # define PYBIND11_TYPING_H_HAS_STRING_LITERAL
21
+ # include <numeric>
22
+ # include <ranges>
23
+ # include <string_view>
24
+ #endif
25
+
26
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
27
+ PYBIND11_NAMESPACE_BEGIN(typing)
28
+
29
+ /*
30
+ The following types can be used to direct pybind11-generated docstrings
31
+ to have have more explicit types (e.g., `list[str]` instead of `list`).
32
+ Just use these in place of existing types.
33
+
34
+ There is no additional enforcement of types at runtime.
35
+ */
36
+
37
+ // Tuple type hint defined in cast.h for use in py::make_tuple to avoid circular includes
38
+
39
+ template <typename K, typename V>
40
+ class Dict : public dict {
41
+ using dict::dict;
42
+ };
43
+
44
+ template <typename T>
45
+ class List : public list {
46
+ using list::list;
47
+ };
48
+
49
+ template <typename T>
50
+ class Set : public set {
51
+ using set::set;
52
+ };
53
+
54
+ template <typename T>
55
+ class Iterable : public iterable {
56
+ using iterable::iterable;
57
+ };
58
+
59
+ template <typename T>
60
+ class Iterator : public iterator {
61
+ using iterator::iterator;
62
+ };
63
+
64
+ template <typename Signature>
65
+ class Callable;
66
+
67
+ template <typename Return, typename... Args>
68
+ class Callable<Return(Args...)> : public function {
69
+ using function::function;
70
+ };
71
+
72
+ template <typename T>
73
+ class Type : public type {
74
+ using type::type;
75
+ };
76
+
77
+ template <typename... Types>
78
+ class Union : public object {
79
+ PYBIND11_OBJECT_DEFAULT(Union, object, PyObject_Type)
80
+ using object::object;
81
+ };
82
+
83
+ template <typename T>
84
+ class Optional : public object {
85
+ PYBIND11_OBJECT_DEFAULT(Optional, object, PyObject_Type)
86
+ using object::object;
87
+ };
88
+
89
+ template <typename T>
90
+ class Final : public object {
91
+ PYBIND11_OBJECT_DEFAULT(Final, object, PyObject_Type)
92
+ using object::object;
93
+ };
94
+
95
+ template <typename T>
96
+ class ClassVar : public object {
97
+ PYBIND11_OBJECT_DEFAULT(ClassVar, object, PyObject_Type)
98
+ using object::object;
99
+ };
100
+
101
+ template <typename T>
102
+ class TypeGuard : public bool_ {
103
+ using bool_::bool_;
104
+ };
105
+
106
+ template <typename T>
107
+ class TypeIs : public bool_ {
108
+ using bool_::bool_;
109
+ };
110
+
111
+ class NoReturn : public none {
112
+ using none::none;
113
+ };
114
+
115
+ class Never : public none {
116
+ using none::none;
117
+ };
118
+
119
+ #if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL)
120
+ template <size_t N>
121
+ struct StringLiteral {
122
+ constexpr StringLiteral(const char (&str)[N]) { std::copy_n(str, N, name); }
123
+ char name[N];
124
+ };
125
+
126
+ template <StringLiteral... StrLits>
127
+ class Literal : public object {
128
+ PYBIND11_OBJECT_DEFAULT(Literal, object, PyObject_Type)
129
+ };
130
+
131
+ // Example syntax for creating a TypeVar.
132
+ // typedef typing::TypeVar<"T"> TypeVarT;
133
+ template <StringLiteral>
134
+ class TypeVar : public object {
135
+ PYBIND11_OBJECT_DEFAULT(TypeVar, object, PyObject_Type)
136
+ using object::object;
137
+ };
138
+ #endif
139
+
140
+ PYBIND11_NAMESPACE_END(typing)
141
+
142
+ PYBIND11_NAMESPACE_BEGIN(detail)
143
+
144
+ template <typename... Types>
145
+ struct handle_type_name<typing::Tuple<Types...>> {
146
+ static constexpr auto name = const_name("tuple[")
147
+ + ::pybind11::detail::concat(make_caster<Types>::name...)
148
+ + const_name("]");
149
+ };
150
+
151
+ template <>
152
+ struct handle_type_name<typing::Tuple<>> {
153
+ // PEP 484 specifies this syntax for an empty tuple
154
+ static constexpr auto name = const_name("tuple[()]");
155
+ };
156
+
157
+ template <typename T>
158
+ struct handle_type_name<typing::Tuple<T, ellipsis>> {
159
+ // PEP 484 specifies this syntax for a variable-length tuple
160
+ static constexpr auto name
161
+ = const_name("tuple[") + make_caster<T>::name + const_name(", ...]");
162
+ };
163
+
164
+ template <typename K, typename V>
165
+ struct handle_type_name<typing::Dict<K, V>> {
166
+ static constexpr auto name = const_name("dict[") + make_caster<K>::name + const_name(", ")
167
+ + make_caster<V>::name + const_name("]");
168
+ };
169
+
170
+ template <typename T>
171
+ struct handle_type_name<typing::List<T>> {
172
+ static constexpr auto name = const_name("list[") + make_caster<T>::name + const_name("]");
173
+ };
174
+
175
+ template <typename T>
176
+ struct handle_type_name<typing::Set<T>> {
177
+ static constexpr auto name = const_name("set[") + make_caster<T>::name + const_name("]");
178
+ };
179
+
180
+ template <typename T>
181
+ struct handle_type_name<typing::Iterable<T>> {
182
+ static constexpr auto name
183
+ = const_name("collections.abc.Iterable[") + make_caster<T>::name + const_name("]");
184
+ };
185
+
186
+ template <typename T>
187
+ struct handle_type_name<typing::Iterator<T>> {
188
+ static constexpr auto name
189
+ = const_name("collections.abc.Iterator[") + make_caster<T>::name + const_name("]");
190
+ };
191
+
192
+ template <typename Return, typename... Args>
193
+ struct handle_type_name<typing::Callable<Return(Args...)>> {
194
+ using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
195
+ static constexpr auto name
196
+ = const_name("collections.abc.Callable[[")
197
+ + ::pybind11::detail::concat(::pybind11::detail::arg_descr(make_caster<Args>::name)...)
198
+ + const_name("], ") + ::pybind11::detail::return_descr(make_caster<retval_type>::name)
199
+ + const_name("]");
200
+ };
201
+
202
+ template <typename Return>
203
+ struct handle_type_name<typing::Callable<Return(ellipsis)>> {
204
+ // PEP 484 specifies this syntax for defining only return types of callables
205
+ using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
206
+ static constexpr auto name = const_name("collections.abc.Callable[..., ")
207
+ + ::pybind11::detail::return_descr(make_caster<retval_type>::name)
208
+ + const_name("]");
209
+ };
210
+
211
+ template <typename T>
212
+ struct handle_type_name<typing::Type<T>> {
213
+ static constexpr auto name = const_name("type[") + make_caster<T>::name + const_name("]");
214
+ };
215
+
216
+ template <typename... Types>
217
+ struct handle_type_name<typing::Union<Types...>> {
218
+ static constexpr auto name = ::pybind11::detail::union_concat(make_caster<Types>::name...);
219
+ };
220
+
221
+ template <typename T>
222
+ struct handle_type_name<typing::Optional<T>> {
223
+ static constexpr auto name = make_caster<T>::name | make_caster<none>::name;
224
+ };
225
+
226
+ template <typename T>
227
+ struct handle_type_name<typing::Final<T>> {
228
+ static constexpr auto name = const_name("typing.Final[")
229
+ + ::pybind11::detail::return_descr(make_caster<T>::name)
230
+ + const_name("]");
231
+ };
232
+
233
+ template <typename T>
234
+ struct handle_type_name<typing::ClassVar<T>> {
235
+ static constexpr auto name
236
+ = const_name("typing.ClassVar[") + make_caster<T>::name + const_name("]");
237
+ };
238
+
239
+ template <typename T>
240
+ struct handle_type_name<typing::TypeGuard<T>> {
241
+ static constexpr auto name = const_name(PYBIND11_TYPE_GUARD_TYPE_HINT) + const_name("[")
242
+ + make_caster<T>::name + const_name("]");
243
+ };
244
+
245
+ template <typename T>
246
+ struct handle_type_name<typing::TypeIs<T>> {
247
+ static constexpr auto name = const_name(PYBIND11_TYPE_IS_TYPE_HINT) + const_name("[")
248
+ + make_caster<T>::name + const_name("]");
249
+ };
250
+
251
+ template <>
252
+ struct handle_type_name<typing::NoReturn> {
253
+ static constexpr auto name = const_name("typing.NoReturn");
254
+ };
255
+
256
+ template <>
257
+ struct handle_type_name<typing::Never> {
258
+ static constexpr auto name = const_name(PYBIND11_NEVER_TYPE_HINT);
259
+ };
260
+
261
+ #if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL)
262
+ template <typing::StringLiteral StrLit>
263
+ consteval auto sanitize_string_literal() {
264
+ constexpr std::string_view v(StrLit.name);
265
+ constexpr std::string_view special_chars("!@%{}-");
266
+ constexpr auto num_special_chars = std::accumulate(
267
+ special_chars.begin(), special_chars.end(), (size_t) 0, [&v](auto acc, const char &c) {
268
+ return std::move(acc) + std::ranges::count(v, c);
269
+ });
270
+ char result[v.size() + num_special_chars + 1];
271
+ size_t i = 0;
272
+ for (auto c : StrLit.name) {
273
+ if (special_chars.find(c) != std::string_view::npos) {
274
+ result[i++] = '!';
275
+ }
276
+ result[i++] = c;
277
+ }
278
+ return typing::StringLiteral(result);
279
+ }
280
+
281
+ template <typing::StringLiteral... Literals>
282
+ struct handle_type_name<typing::Literal<Literals...>> {
283
+ static constexpr auto name
284
+ = const_name("typing.Literal[")
285
+ + pybind11::detail::concat(const_name(sanitize_string_literal<Literals>().name)...)
286
+ + const_name("]");
287
+ };
288
+ template <typing::StringLiteral StrLit>
289
+ struct handle_type_name<typing::TypeVar<StrLit>> {
290
+ static constexpr auto name = const_name(sanitize_string_literal<StrLit>().name);
291
+ };
292
+ #endif
293
+
294
+ PYBIND11_NAMESPACE_END(detail)
295
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/include/pybind11/warnings.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/warnings.h: Python warnings wrappers.
3
+
4
+ Copyright (c) 2024 Jan Iwaszkiewicz <jiwaszkiewicz6@gmail.com>
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
+ #include "detail/common.h"
14
+
15
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16
+
17
+ PYBIND11_NAMESPACE_BEGIN(detail)
18
+
19
+ inline bool PyWarning_Check(PyObject *obj) {
20
+ int result = PyObject_IsSubclass(obj, PyExc_Warning);
21
+ if (result == 1) {
22
+ return true;
23
+ }
24
+ if (result == -1) {
25
+ raise_from(PyExc_SystemError,
26
+ "pybind11::detail::PyWarning_Check(): PyObject_IsSubclass() call failed.");
27
+ throw error_already_set();
28
+ }
29
+ return false;
30
+ }
31
+
32
+ PYBIND11_NAMESPACE_END(detail)
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(warnings)
35
+
36
+ inline object
37
+ new_warning_type(handle scope, const char *name, handle base = PyExc_RuntimeWarning) {
38
+ if (!detail::PyWarning_Check(base.ptr())) {
39
+ pybind11_fail("pybind11::warnings::new_warning_type(): cannot create custom warning, base "
40
+ "must be a subclass of "
41
+ "PyExc_Warning!");
42
+ }
43
+ if (hasattr(scope, name)) {
44
+ pybind11_fail("pybind11::warnings::new_warning_type(): an attribute with name \""
45
+ + std::string(name) + "\" exists already.");
46
+ }
47
+ std::string full_name = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
48
+ handle h(PyErr_NewException(full_name.c_str(), base.ptr(), nullptr));
49
+ if (!h) {
50
+ raise_from(PyExc_SystemError,
51
+ "pybind11::warnings::new_warning_type(): PyErr_NewException() call failed.");
52
+ throw error_already_set();
53
+ }
54
+ auto obj = reinterpret_steal<object>(h);
55
+ scope.attr(name) = obj;
56
+ return obj;
57
+ }
58
+
59
+ // Similar to Python `warnings.warn()`
60
+ inline void
61
+ warn(const char *message, handle category = PyExc_RuntimeWarning, int stack_level = 2) {
62
+ if (!detail::PyWarning_Check(category.ptr())) {
63
+ pybind11_fail(
64
+ "pybind11::warnings::warn(): cannot raise warning, category must be a subclass of "
65
+ "PyExc_Warning!");
66
+ }
67
+
68
+ if (PyErr_WarnEx(category.ptr(), message, stack_level) == -1) {
69
+ throw error_already_set();
70
+ }
71
+ }
72
+
73
+ PYBIND11_NAMESPACE_END(warnings)
74
+
75
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/pybind11/share/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (54.9 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_gpu_trace.cpython-310.pyc ADDED
Binary file (2.75 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_memory_viz.cpython-310.pyc ADDED
Binary file (21 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_pin_memory_utils.cpython-310.pyc ADDED
Binary file (967 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_sanitizer.cpython-310.pyc ADDED
Binary file (22.8 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (9.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/comm.cpython-310.pyc ADDED
Binary file (404 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/error.cpython-310.pyc ADDED
Binary file (181 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/cuda/__pycache__/gds.cpython-310.pyc ADDED
Binary file (5.94 kB). View file