netgen-mesher 6.2.2506.post35.dev0__cp314-cp314-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. netgen/NgOCC.py +7 -0
  2. netgen/__init__.py +114 -0
  3. netgen/__init__.pyi +22 -0
  4. netgen/__main__.py +53 -0
  5. netgen/cmake/NetgenConfig.cmake +79 -0
  6. netgen/cmake/netgen-targets-release.cmake +69 -0
  7. netgen/cmake/netgen-targets.cmake +146 -0
  8. netgen/config/__init__.py +1 -0
  9. netgen/config/__init__.pyi +52 -0
  10. netgen/config/__main__.py +4 -0
  11. netgen/config/config.py +68 -0
  12. netgen/config/config.pyi +54 -0
  13. netgen/csg.py +25 -0
  14. netgen/geom2d.py +178 -0
  15. netgen/gui.py +82 -0
  16. netgen/include/core/archive.hpp +1256 -0
  17. netgen/include/core/array.hpp +1760 -0
  18. netgen/include/core/autodiff.hpp +1131 -0
  19. netgen/include/core/autodiffdiff.hpp +733 -0
  20. netgen/include/core/bitarray.hpp +240 -0
  21. netgen/include/core/concurrentqueue.h +3619 -0
  22. netgen/include/core/exception.hpp +145 -0
  23. netgen/include/core/flags.hpp +199 -0
  24. netgen/include/core/hashtable.hpp +1281 -0
  25. netgen/include/core/localheap.hpp +318 -0
  26. netgen/include/core/logging.hpp +117 -0
  27. netgen/include/core/memtracer.hpp +221 -0
  28. netgen/include/core/mpi4py_pycapi.h +245 -0
  29. netgen/include/core/mpi_wrapper.hpp +643 -0
  30. netgen/include/core/ng_mpi.hpp +94 -0
  31. netgen/include/core/ng_mpi_generated_declarations.hpp +155 -0
  32. netgen/include/core/ng_mpi_native.hpp +25 -0
  33. netgen/include/core/ngcore.hpp +32 -0
  34. netgen/include/core/ngcore_api.hpp +152 -0
  35. netgen/include/core/ngstream.hpp +115 -0
  36. netgen/include/core/paje_trace.hpp +279 -0
  37. netgen/include/core/profiler.hpp +382 -0
  38. netgen/include/core/python_ngcore.hpp +457 -0
  39. netgen/include/core/ranges.hpp +109 -0
  40. netgen/include/core/register_archive.hpp +100 -0
  41. netgen/include/core/signal.hpp +82 -0
  42. netgen/include/core/simd.hpp +160 -0
  43. netgen/include/core/simd_arm64.hpp +407 -0
  44. netgen/include/core/simd_avx.hpp +394 -0
  45. netgen/include/core/simd_avx512.hpp +285 -0
  46. netgen/include/core/simd_generic.hpp +1053 -0
  47. netgen/include/core/simd_math.hpp +178 -0
  48. netgen/include/core/simd_sse.hpp +289 -0
  49. netgen/include/core/statushandler.hpp +37 -0
  50. netgen/include/core/symboltable.hpp +153 -0
  51. netgen/include/core/table.hpp +810 -0
  52. netgen/include/core/taskmanager.hpp +1161 -0
  53. netgen/include/core/type_traits.hpp +65 -0
  54. netgen/include/core/utils.hpp +385 -0
  55. netgen/include/core/version.hpp +102 -0
  56. netgen/include/core/xbool.hpp +47 -0
  57. netgen/include/csg/algprim.hpp +563 -0
  58. netgen/include/csg/brick.hpp +150 -0
  59. netgen/include/csg/csg.hpp +43 -0
  60. netgen/include/csg/csgeom.hpp +389 -0
  61. netgen/include/csg/csgparser.hpp +101 -0
  62. netgen/include/csg/curve2d.hpp +67 -0
  63. netgen/include/csg/edgeflw.hpp +112 -0
  64. netgen/include/csg/explicitcurve2d.hpp +113 -0
  65. netgen/include/csg/extrusion.hpp +185 -0
  66. netgen/include/csg/gencyl.hpp +70 -0
  67. netgen/include/csg/geoml.hpp +16 -0
  68. netgen/include/csg/identify.hpp +213 -0
  69. netgen/include/csg/manifold.hpp +29 -0
  70. netgen/include/csg/meshsurf.hpp +46 -0
  71. netgen/include/csg/polyhedra.hpp +121 -0
  72. netgen/include/csg/revolution.hpp +180 -0
  73. netgen/include/csg/singularref.hpp +84 -0
  74. netgen/include/csg/solid.hpp +295 -0
  75. netgen/include/csg/specpoin.hpp +194 -0
  76. netgen/include/csg/spline3d.hpp +99 -0
  77. netgen/include/csg/splinesurface.hpp +85 -0
  78. netgen/include/csg/surface.hpp +394 -0
  79. netgen/include/csg/triapprox.hpp +63 -0
  80. netgen/include/csg/vscsg.hpp +34 -0
  81. netgen/include/general/autodiff.hpp +356 -0
  82. netgen/include/general/autoptr.hpp +39 -0
  83. netgen/include/general/gzstream.h +121 -0
  84. netgen/include/general/hashtabl.hpp +1692 -0
  85. netgen/include/general/myadt.hpp +48 -0
  86. netgen/include/general/mystring.hpp +226 -0
  87. netgen/include/general/netgenout.hpp +205 -0
  88. netgen/include/general/ngarray.hpp +797 -0
  89. netgen/include/general/ngbitarray.hpp +149 -0
  90. netgen/include/general/ngpython.hpp +74 -0
  91. netgen/include/general/optmem.hpp +44 -0
  92. netgen/include/general/parthreads.hpp +138 -0
  93. netgen/include/general/seti.hpp +50 -0
  94. netgen/include/general/sort.hpp +47 -0
  95. netgen/include/general/spbita2d.hpp +59 -0
  96. netgen/include/general/stack.hpp +114 -0
  97. netgen/include/general/table.hpp +280 -0
  98. netgen/include/general/template.hpp +509 -0
  99. netgen/include/geom2d/csg2d.hpp +750 -0
  100. netgen/include/geom2d/geometry2d.hpp +280 -0
  101. netgen/include/geom2d/spline2d.hpp +234 -0
  102. netgen/include/geom2d/vsgeom2d.hpp +28 -0
  103. netgen/include/gprim/adtree.hpp +1392 -0
  104. netgen/include/gprim/geom2d.hpp +858 -0
  105. netgen/include/gprim/geom3d.hpp +749 -0
  106. netgen/include/gprim/geomfuncs.hpp +212 -0
  107. netgen/include/gprim/geomobjects.hpp +544 -0
  108. netgen/include/gprim/geomops.hpp +404 -0
  109. netgen/include/gprim/geomtest3d.hpp +101 -0
  110. netgen/include/gprim/gprim.hpp +33 -0
  111. netgen/include/gprim/spline.hpp +778 -0
  112. netgen/include/gprim/splinegeometry.hpp +73 -0
  113. netgen/include/gprim/transform3d.hpp +216 -0
  114. netgen/include/include/acisgeom.hpp +3 -0
  115. netgen/include/include/csg.hpp +1 -0
  116. netgen/include/include/geometry2d.hpp +1 -0
  117. netgen/include/include/gprim.hpp +1 -0
  118. netgen/include/include/incopengl.hpp +62 -0
  119. netgen/include/include/inctcl.hpp +13 -0
  120. netgen/include/include/incvis.hpp +6 -0
  121. netgen/include/include/linalg.hpp +1 -0
  122. netgen/include/include/meshing.hpp +1 -0
  123. netgen/include/include/myadt.hpp +1 -0
  124. netgen/include/include/mydefs.hpp +70 -0
  125. netgen/include/include/mystdlib.h +59 -0
  126. netgen/include/include/netgen_config.hpp +27 -0
  127. netgen/include/include/netgen_version.hpp +9 -0
  128. netgen/include/include/nginterface_v2_impl.hpp +395 -0
  129. netgen/include/include/ngsimd.hpp +1 -0
  130. netgen/include/include/occgeom.hpp +1 -0
  131. netgen/include/include/opti.hpp +1 -0
  132. netgen/include/include/parallel.hpp +1 -0
  133. netgen/include/include/stlgeom.hpp +1 -0
  134. netgen/include/include/visual.hpp +1 -0
  135. netgen/include/interface/rw_medit.hpp +11 -0
  136. netgen/include/interface/writeuser.hpp +80 -0
  137. netgen/include/linalg/densemat.hpp +414 -0
  138. netgen/include/linalg/linalg.hpp +29 -0
  139. netgen/include/linalg/opti.hpp +142 -0
  140. netgen/include/linalg/polynomial.hpp +47 -0
  141. netgen/include/linalg/vector.hpp +217 -0
  142. netgen/include/meshing/adfront2.hpp +274 -0
  143. netgen/include/meshing/adfront3.hpp +332 -0
  144. netgen/include/meshing/basegeom.hpp +370 -0
  145. netgen/include/meshing/bcfunctions.hpp +53 -0
  146. netgen/include/meshing/bisect.hpp +72 -0
  147. netgen/include/meshing/boundarylayer.hpp +113 -0
  148. netgen/include/meshing/classifyhpel.hpp +1984 -0
  149. netgen/include/meshing/clusters.hpp +46 -0
  150. netgen/include/meshing/curvedelems.hpp +274 -0
  151. netgen/include/meshing/delaunay2d.hpp +73 -0
  152. netgen/include/meshing/fieldlines.hpp +103 -0
  153. netgen/include/meshing/findip.hpp +198 -0
  154. netgen/include/meshing/findip2.hpp +103 -0
  155. netgen/include/meshing/geomsearch.hpp +69 -0
  156. netgen/include/meshing/global.hpp +54 -0
  157. netgen/include/meshing/hpref_hex.hpp +330 -0
  158. netgen/include/meshing/hpref_prism.hpp +3405 -0
  159. netgen/include/meshing/hpref_pyramid.hpp +154 -0
  160. netgen/include/meshing/hpref_quad.hpp +2082 -0
  161. netgen/include/meshing/hpref_segm.hpp +122 -0
  162. netgen/include/meshing/hpref_tet.hpp +4230 -0
  163. netgen/include/meshing/hpref_trig.hpp +848 -0
  164. netgen/include/meshing/hprefinement.hpp +366 -0
  165. netgen/include/meshing/improve2.hpp +178 -0
  166. netgen/include/meshing/improve3.hpp +151 -0
  167. netgen/include/meshing/localh.hpp +223 -0
  168. netgen/include/meshing/meshclass.hpp +1076 -0
  169. netgen/include/meshing/meshfunc.hpp +47 -0
  170. netgen/include/meshing/meshing.hpp +63 -0
  171. netgen/include/meshing/meshing2.hpp +163 -0
  172. netgen/include/meshing/meshing3.hpp +123 -0
  173. netgen/include/meshing/meshtool.hpp +90 -0
  174. netgen/include/meshing/meshtype.hpp +1930 -0
  175. netgen/include/meshing/msghandler.hpp +62 -0
  176. netgen/include/meshing/paralleltop.hpp +172 -0
  177. netgen/include/meshing/python_mesh.hpp +206 -0
  178. netgen/include/meshing/ruler2.hpp +172 -0
  179. netgen/include/meshing/ruler3.hpp +211 -0
  180. netgen/include/meshing/soldata.hpp +141 -0
  181. netgen/include/meshing/specials.hpp +17 -0
  182. netgen/include/meshing/surfacegeom.hpp +73 -0
  183. netgen/include/meshing/topology.hpp +1003 -0
  184. netgen/include/meshing/validate.hpp +21 -0
  185. netgen/include/meshing/visual_interface.hpp +71 -0
  186. netgen/include/mydefs.hpp +70 -0
  187. netgen/include/nginterface.h +474 -0
  188. netgen/include/nginterface_v2.hpp +406 -0
  189. netgen/include/nglib.h +697 -0
  190. netgen/include/nglib_occ.h +50 -0
  191. netgen/include/occ/occ_edge.hpp +47 -0
  192. netgen/include/occ/occ_face.hpp +52 -0
  193. netgen/include/occ/occ_solid.hpp +23 -0
  194. netgen/include/occ/occ_utils.hpp +376 -0
  195. netgen/include/occ/occ_vertex.hpp +30 -0
  196. netgen/include/occ/occgeom.hpp +659 -0
  197. netgen/include/occ/occmeshsurf.hpp +168 -0
  198. netgen/include/occ/vsocc.hpp +33 -0
  199. netgen/include/pybind11/LICENSE +29 -0
  200. netgen/include/pybind11/attr.h +722 -0
  201. netgen/include/pybind11/buffer_info.h +208 -0
  202. netgen/include/pybind11/cast.h +2361 -0
  203. netgen/include/pybind11/chrono.h +228 -0
  204. netgen/include/pybind11/common.h +2 -0
  205. netgen/include/pybind11/complex.h +74 -0
  206. netgen/include/pybind11/conduit/README.txt +15 -0
  207. netgen/include/pybind11/conduit/pybind11_conduit_v1.h +116 -0
  208. netgen/include/pybind11/conduit/pybind11_platform_abi_id.h +87 -0
  209. netgen/include/pybind11/conduit/wrap_include_python_h.h +72 -0
  210. netgen/include/pybind11/critical_section.h +56 -0
  211. netgen/include/pybind11/detail/class.h +823 -0
  212. netgen/include/pybind11/detail/common.h +1348 -0
  213. netgen/include/pybind11/detail/cpp_conduit.h +75 -0
  214. netgen/include/pybind11/detail/descr.h +226 -0
  215. netgen/include/pybind11/detail/dynamic_raw_ptr_cast_if_possible.h +39 -0
  216. netgen/include/pybind11/detail/exception_translation.h +71 -0
  217. netgen/include/pybind11/detail/function_record_pyobject.h +191 -0
  218. netgen/include/pybind11/detail/init.h +538 -0
  219. netgen/include/pybind11/detail/internals.h +799 -0
  220. netgen/include/pybind11/detail/native_enum_data.h +209 -0
  221. netgen/include/pybind11/detail/pybind11_namespace_macros.h +82 -0
  222. netgen/include/pybind11/detail/struct_smart_holder.h +378 -0
  223. netgen/include/pybind11/detail/type_caster_base.h +1591 -0
  224. netgen/include/pybind11/detail/typeid.h +65 -0
  225. netgen/include/pybind11/detail/using_smart_holder.h +22 -0
  226. netgen/include/pybind11/detail/value_and_holder.h +90 -0
  227. netgen/include/pybind11/eigen/common.h +9 -0
  228. netgen/include/pybind11/eigen/matrix.h +723 -0
  229. netgen/include/pybind11/eigen/tensor.h +521 -0
  230. netgen/include/pybind11/eigen.h +12 -0
  231. netgen/include/pybind11/embed.h +320 -0
  232. netgen/include/pybind11/eval.h +161 -0
  233. netgen/include/pybind11/functional.h +147 -0
  234. netgen/include/pybind11/gil.h +199 -0
  235. netgen/include/pybind11/gil_safe_call_once.h +102 -0
  236. netgen/include/pybind11/gil_simple.h +37 -0
  237. netgen/include/pybind11/iostream.h +265 -0
  238. netgen/include/pybind11/native_enum.h +67 -0
  239. netgen/include/pybind11/numpy.h +2312 -0
  240. netgen/include/pybind11/operators.h +202 -0
  241. netgen/include/pybind11/options.h +92 -0
  242. netgen/include/pybind11/pybind11.h +3645 -0
  243. netgen/include/pybind11/pytypes.h +2680 -0
  244. netgen/include/pybind11/stl/filesystem.h +114 -0
  245. netgen/include/pybind11/stl.h +666 -0
  246. netgen/include/pybind11/stl_bind.h +858 -0
  247. netgen/include/pybind11/subinterpreter.h +299 -0
  248. netgen/include/pybind11/trampoline_self_life_support.h +65 -0
  249. netgen/include/pybind11/type_caster_pyobject_ptr.h +61 -0
  250. netgen/include/pybind11/typing.h +298 -0
  251. netgen/include/pybind11/warnings.h +75 -0
  252. netgen/include/stlgeom/meshstlsurface.hpp +67 -0
  253. netgen/include/stlgeom/stlgeom.hpp +491 -0
  254. netgen/include/stlgeom/stlline.hpp +193 -0
  255. netgen/include/stlgeom/stltool.hpp +331 -0
  256. netgen/include/stlgeom/stltopology.hpp +419 -0
  257. netgen/include/stlgeom/vsstl.hpp +58 -0
  258. netgen/include/visualization/meshdoc.hpp +42 -0
  259. netgen/include/visualization/mvdraw.hpp +325 -0
  260. netgen/include/visualization/vispar.hpp +128 -0
  261. netgen/include/visualization/visual.hpp +28 -0
  262. netgen/include/visualization/visual_api.hpp +10 -0
  263. netgen/include/visualization/vssolution.hpp +399 -0
  264. netgen/lib/libnggui.lib +0 -0
  265. netgen/lib/ngcore.lib +0 -0
  266. netgen/lib/nglib.lib +0 -0
  267. netgen/lib/togl.lib +0 -0
  268. netgen/libnggui.dll +0 -0
  269. netgen/libngguipy.lib +0 -0
  270. netgen/libngguipy.pyd +0 -0
  271. netgen/libngpy/_NgOCC.pyi +1545 -0
  272. netgen/libngpy/__init__.pyi +7 -0
  273. netgen/libngpy/_csg.pyi +259 -0
  274. netgen/libngpy/_geom2d.pyi +323 -0
  275. netgen/libngpy/_meshing.pyi +1111 -0
  276. netgen/libngpy/_stl.pyi +131 -0
  277. netgen/libngpy.lib +0 -0
  278. netgen/libngpy.pyd +0 -0
  279. netgen/meshing.py +65 -0
  280. netgen/ngcore.dll +0 -0
  281. netgen/nglib.dll +0 -0
  282. netgen/occ.py +52 -0
  283. netgen/read_gmsh.py +259 -0
  284. netgen/read_meshio.py +22 -0
  285. netgen/stl.py +2 -0
  286. netgen/togl.dll +0 -0
  287. netgen/version.py +2 -0
  288. netgen/webgui.py +529 -0
  289. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/boundarycondition.geo +16 -0
  290. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/boxcyl.geo +32 -0
  291. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/circle_on_cube.geo +27 -0
  292. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cone.geo +13 -0
  293. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cube.geo +16 -0
  294. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cubeandring.geo +55 -0
  295. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cubeandspheres.geo +21 -0
  296. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cubemcyl.geo +18 -0
  297. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cubemsphere.geo +19 -0
  298. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cylinder.geo +12 -0
  299. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/cylsphere.geo +12 -0
  300. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/doc/ng4.pdf +0 -0
  301. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/ellipsoid.geo +8 -0
  302. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/ellipticcyl.geo +10 -0
  303. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/extrusion.geo +99 -0
  304. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/fichera.geo +24 -0
  305. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/frame.step +11683 -0
  306. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/hinge.stl +8486 -0
  307. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/lshape3d.geo +26 -0
  308. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/manyholes.geo +26 -0
  309. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/manyholes2.geo +26 -0
  310. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/matrix.geo +27 -0
  311. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/ortho.geo +11 -0
  312. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/part1.stl +2662 -0
  313. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/period.geo +33 -0
  314. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/py_tutorials/exportNeutral.py +26 -0
  315. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/py_tutorials/mesh.py +19 -0
  316. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/py_tutorials/shaft.geo +65 -0
  317. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/revolution.geo +18 -0
  318. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/screw.step +1694 -0
  319. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/sculpture.geo +13 -0
  320. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/shaft.geo +65 -0
  321. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/shell.geo +10 -0
  322. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/sphere.geo +8 -0
  323. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/sphereincube.geo +17 -0
  324. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/square.in2d +35 -0
  325. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/squarecircle.in2d +48 -0
  326. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/squarehole.in2d +47 -0
  327. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/torus.geo +8 -0
  328. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/trafo.geo +57 -0
  329. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/twobricks.geo +15 -0
  330. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/twocubes.geo +18 -0
  331. netgen_mesher-6.2.2506.post35.dev0.data/data/share/netgen/twocyl.geo +16 -0
  332. netgen_mesher-6.2.2506.post35.dev0.dist-info/METADATA +15 -0
  333. netgen_mesher-6.2.2506.post35.dev0.dist-info/RECORD +340 -0
  334. netgen_mesher-6.2.2506.post35.dev0.dist-info/WHEEL +5 -0
  335. netgen_mesher-6.2.2506.post35.dev0.dist-info/entry_points.txt +2 -0
  336. netgen_mesher-6.2.2506.post35.dev0.dist-info/licenses/AUTHORS +1 -0
  337. netgen_mesher-6.2.2506.post35.dev0.dist-info/licenses/LICENSE +504 -0
  338. netgen_mesher-6.2.2506.post35.dev0.dist-info/top_level.txt +2 -0
  339. pyngcore/__init__.py +1 -0
  340. pyngcore/pyngcore.cp314-win_amd64.pyd +0 -0
@@ -0,0 +1,2361 @@
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/common.h"
14
+ #include "detail/descr.h"
15
+ #include "detail/native_enum_data.h"
16
+ #include "detail/type_caster_base.h"
17
+ #include "detail/typeid.h"
18
+ #include "pytypes.h"
19
+
20
+ #include <array>
21
+ #include <cstring>
22
+ #include <functional>
23
+ #include <iosfwd>
24
+ #include <iterator>
25
+ #include <memory>
26
+ #include <string>
27
+ #include <tuple>
28
+ #include <type_traits>
29
+ #include <utility>
30
+ #include <vector>
31
+
32
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
33
+
34
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
35
+
36
+ PYBIND11_NAMESPACE_BEGIN(detail)
37
+
38
+ template <typename type, typename SFINAE = void>
39
+ class type_caster : public type_caster_base<type> {};
40
+ template <typename type>
41
+ using make_caster = type_caster<intrinsic_t<type>>;
42
+
43
+ // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
44
+ template <typename T>
45
+ typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
46
+ using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893
47
+ return caster.operator result_t();
48
+ }
49
+ template <typename T>
50
+ typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
51
+ cast_op(make_caster<T> &&caster) {
52
+ using result_t = typename make_caster<T>::template cast_op_type<
53
+ typename std::add_rvalue_reference<T>::type>; // See PR #4893
54
+ return std::move(caster).operator result_t();
55
+ }
56
+
57
+ template <typename EnumType>
58
+ class type_caster_enum_type {
59
+ private:
60
+ using Underlying = typename std::underlying_type<EnumType>::type;
61
+
62
+ public:
63
+ static constexpr auto name = const_name<EnumType>();
64
+
65
+ template <typename SrcType>
66
+ static handle cast(SrcType &&src, return_value_policy, handle parent) {
67
+ handle native_enum
68
+ = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));
69
+ if (native_enum) {
70
+ return native_enum(static_cast<Underlying>(src)).release();
71
+ }
72
+ return type_caster_base<EnumType>::cast(
73
+ std::forward<SrcType>(src),
74
+ // Fixes https://github.com/pybind/pybind11/pull/3643#issuecomment-1022987818:
75
+ return_value_policy::copy,
76
+ parent);
77
+ }
78
+
79
+ template <typename SrcType>
80
+ static handle cast(SrcType *src, return_value_policy policy, handle parent) {
81
+ return cast(*src, policy, parent);
82
+ }
83
+
84
+ bool load(handle src, bool convert) {
85
+ handle native_enum
86
+ = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));
87
+ if (native_enum) {
88
+ if (!isinstance(src, native_enum)) {
89
+ return false;
90
+ }
91
+ type_caster<Underlying> underlying_caster;
92
+ if (!underlying_caster.load(src.attr("value"), convert)) {
93
+ pybind11_fail("native_enum internal consistency failure.");
94
+ }
95
+ value = static_cast<EnumType>(static_cast<Underlying>(underlying_caster));
96
+ return true;
97
+ }
98
+ if (!pybind11_enum_) {
99
+ pybind11_enum_.reset(new type_caster_base<EnumType>());
100
+ }
101
+ return pybind11_enum_->load(src, convert);
102
+ }
103
+
104
+ template <typename T>
105
+ using cast_op_type = detail::cast_op_type<T>;
106
+
107
+ // NOLINTNEXTLINE(google-explicit-constructor)
108
+ operator EnumType *() {
109
+ if (!pybind11_enum_) {
110
+ return &value;
111
+ }
112
+ return pybind11_enum_->operator EnumType *();
113
+ }
114
+
115
+ // NOLINTNEXTLINE(google-explicit-constructor)
116
+ operator EnumType &() {
117
+ if (!pybind11_enum_) {
118
+ return value;
119
+ }
120
+ return pybind11_enum_->operator EnumType &();
121
+ }
122
+
123
+ private:
124
+ std::unique_ptr<type_caster_base<EnumType>> pybind11_enum_;
125
+ EnumType value;
126
+ };
127
+
128
+ template <typename EnumType, typename SFINAE = void>
129
+ struct type_caster_enum_type_enabled : std::true_type {};
130
+
131
+ template <typename T>
132
+ struct type_uses_type_caster_enum_type {
133
+ static constexpr bool value
134
+ = std::is_enum<T>::value && type_caster_enum_type_enabled<T>::value;
135
+ };
136
+
137
+ template <typename EnumType>
138
+ class type_caster<EnumType, detail::enable_if_t<type_uses_type_caster_enum_type<EnumType>::value>>
139
+ : public type_caster_enum_type<EnumType> {};
140
+
141
+ template <typename T, detail::enable_if_t<std::is_enum<T>::value, int> = 0>
142
+ bool isinstance_native_enum_impl(handle obj, const std::type_info &tp) {
143
+ handle native_enum = global_internals_native_enum_type_map_get_item(tp);
144
+ if (!native_enum) {
145
+ return false;
146
+ }
147
+ return isinstance(obj, native_enum);
148
+ }
149
+
150
+ template <typename T, detail::enable_if_t<!std::is_enum<T>::value, int> = 0>
151
+ bool isinstance_native_enum_impl(handle, const std::type_info &) {
152
+ return false;
153
+ }
154
+
155
+ template <typename T>
156
+ bool isinstance_native_enum(handle obj, const std::type_info &tp) {
157
+ return isinstance_native_enum_impl<intrinsic_t<T>>(obj, tp);
158
+ }
159
+
160
+ template <typename type>
161
+ class type_caster<std::reference_wrapper<type>> {
162
+ private:
163
+ using caster_t = make_caster<type>;
164
+ caster_t subcaster;
165
+ using reference_t = type &;
166
+ using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
167
+
168
+ static_assert(
169
+ std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
170
+ || std::is_same<reference_t, subcaster_cast_op_type>::value,
171
+ "std::reference_wrapper<T> caster requires T to have a caster with an "
172
+ "`operator T &()` or `operator const T &()`");
173
+
174
+ public:
175
+ bool load(handle src, bool convert) { return subcaster.load(src, convert); }
176
+ static constexpr auto name = caster_t::name;
177
+ static handle
178
+ cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
179
+ // It is definitely wrong to take ownership of this pointer, so mask that rvp
180
+ if (policy == return_value_policy::take_ownership
181
+ || policy == return_value_policy::automatic) {
182
+ policy = return_value_policy::automatic_reference;
183
+ }
184
+ return caster_t::cast(&src.get(), policy, parent);
185
+ }
186
+ template <typename T>
187
+ using cast_op_type = std::reference_wrapper<type>;
188
+ explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
189
+ };
190
+
191
+ #define PYBIND11_TYPE_CASTER(type, py_name) \
192
+ protected: \
193
+ type value; \
194
+ \
195
+ public: \
196
+ static constexpr auto name = py_name; \
197
+ template <typename T_, \
198
+ ::pybind11::detail::enable_if_t< \
199
+ std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
200
+ int> \
201
+ = 0> \
202
+ static ::pybind11::handle cast( \
203
+ T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
204
+ if (!src) \
205
+ return ::pybind11::none().release(); \
206
+ if (policy == ::pybind11::return_value_policy::take_ownership) { \
207
+ auto h = cast(std::move(*src), policy, parent); \
208
+ delete src; \
209
+ return h; \
210
+ } \
211
+ return cast(*src, policy, parent); \
212
+ } \
213
+ operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
214
+ operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
215
+ operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
216
+ template <typename T_> \
217
+ using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
218
+
219
+ template <typename CharT>
220
+ using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
221
+ #if defined(PYBIND11_HAS_U8STRING)
222
+ std::is_same<CharT, char8_t>, /* std::u8string */
223
+ #endif
224
+ std::is_same<CharT, char16_t>, /* std::u16string */
225
+ std::is_same<CharT, char32_t>, /* std::u32string */
226
+ std::is_same<CharT, wchar_t> /* std::wstring */
227
+ >;
228
+
229
+ template <typename T>
230
+ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
231
+ using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
232
+ using _py_type_1 = conditional_t<std::is_signed<T>::value,
233
+ _py_type_0,
234
+ typename std::make_unsigned<_py_type_0>::type>;
235
+ using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
236
+
237
+ public:
238
+ bool load(handle src, bool convert) {
239
+ py_type py_value;
240
+
241
+ if (!src) {
242
+ return false;
243
+ }
244
+
245
+ #if !defined(PYPY_VERSION)
246
+ auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
247
+ #else
248
+ // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
249
+ // while CPython only considers the existence of `nb_index`/`__index__`.
250
+ auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
251
+ #endif
252
+
253
+ if (std::is_floating_point<T>::value) {
254
+ if (convert || PyFloat_Check(src.ptr())) {
255
+ py_value = (py_type) PyFloat_AsDouble(src.ptr());
256
+ } else {
257
+ return false;
258
+ }
259
+ } else if (PyFloat_Check(src.ptr())
260
+ || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
261
+ return false;
262
+ } else {
263
+ handle src_or_index = src;
264
+ // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
265
+ #if defined(PYPY_VERSION)
266
+ object index;
267
+ if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
268
+ index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
269
+ if (!index) {
270
+ PyErr_Clear();
271
+ if (!convert)
272
+ return false;
273
+ } else {
274
+ src_or_index = index;
275
+ }
276
+ }
277
+ #endif
278
+ if (std::is_unsigned<py_type>::value) {
279
+ py_value = as_unsigned<py_type>(src_or_index.ptr());
280
+ } else { // signed integer:
281
+ py_value = sizeof(T) <= sizeof(long)
282
+ ? (py_type) PyLong_AsLong(src_or_index.ptr())
283
+ : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
284
+ }
285
+ }
286
+
287
+ // Python API reported an error
288
+ bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
289
+
290
+ // Check to see if the conversion is valid (integers should match exactly)
291
+ // Signed/unsigned checks happen elsewhere
292
+ if (py_err
293
+ || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
294
+ && py_value != (py_type) (T) py_value)) {
295
+ PyErr_Clear();
296
+ if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
297
+ auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
298
+ ? PyNumber_Float(src.ptr())
299
+ : PyNumber_Long(src.ptr()));
300
+ PyErr_Clear();
301
+ return load(tmp, false);
302
+ }
303
+ return false;
304
+ }
305
+
306
+ value = (T) py_value;
307
+ return true;
308
+ }
309
+
310
+ template <typename U = T>
311
+ static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
312
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
313
+ return PyFloat_FromDouble((double) src);
314
+ }
315
+
316
+ template <typename U = T>
317
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
318
+ && (sizeof(U) <= sizeof(long)),
319
+ handle>::type
320
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
321
+ return PYBIND11_LONG_FROM_SIGNED((long) src);
322
+ }
323
+
324
+ template <typename U = T>
325
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
326
+ && (sizeof(U) <= sizeof(unsigned long)),
327
+ handle>::type
328
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
329
+ return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
330
+ }
331
+
332
+ template <typename U = T>
333
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
334
+ && (sizeof(U) > sizeof(long)),
335
+ handle>::type
336
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
337
+ return PyLong_FromLongLong((long long) src);
338
+ }
339
+
340
+ template <typename U = T>
341
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
342
+ && (sizeof(U) > sizeof(unsigned long)),
343
+ handle>::type
344
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
345
+ return PyLong_FromUnsignedLongLong((unsigned long long) src);
346
+ }
347
+
348
+ PYBIND11_TYPE_CASTER(T,
349
+ io_name<std::is_integral<T>::value>(
350
+ "typing.SupportsInt", "int", "typing.SupportsFloat", "float"));
351
+ };
352
+
353
+ template <typename T>
354
+ struct void_caster {
355
+ public:
356
+ bool load(handle src, bool) {
357
+ if (src && src.is_none()) {
358
+ return true;
359
+ }
360
+ return false;
361
+ }
362
+ static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
363
+ return none().release();
364
+ }
365
+ PYBIND11_TYPE_CASTER(T, const_name("None"));
366
+ };
367
+
368
+ template <>
369
+ class type_caster<void_type> : public void_caster<void_type> {};
370
+
371
+ template <>
372
+ class type_caster<void> : public type_caster<void_type> {
373
+ public:
374
+ using type_caster<void_type>::cast;
375
+
376
+ bool load(handle h, bool) {
377
+ if (!h) {
378
+ return false;
379
+ }
380
+ if (h.is_none()) {
381
+ value = nullptr;
382
+ return true;
383
+ }
384
+
385
+ /* Check if this is a capsule */
386
+ if (isinstance<capsule>(h)) {
387
+ value = reinterpret_borrow<capsule>(h);
388
+ return true;
389
+ }
390
+
391
+ /* Check if this is a C++ type */
392
+ const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
393
+ if (bases.size() == 1) { // Only allowing loading from a single-value type
394
+ value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
395
+ return true;
396
+ }
397
+
398
+ /* Fail */
399
+ return false;
400
+ }
401
+
402
+ static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
403
+ if (ptr) {
404
+ return capsule(ptr).release();
405
+ }
406
+ return none().release();
407
+ }
408
+
409
+ template <typename T>
410
+ using cast_op_type = void *&;
411
+ explicit operator void *&() { return value; }
412
+ static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);
413
+
414
+ private:
415
+ void *value = nullptr;
416
+ };
417
+
418
+ template <>
419
+ class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
420
+
421
+ template <>
422
+ class type_caster<bool> {
423
+ public:
424
+ bool load(handle src, bool convert) {
425
+ if (!src) {
426
+ return false;
427
+ }
428
+ if (src.ptr() == Py_True) {
429
+ value = true;
430
+ return true;
431
+ }
432
+ if (src.ptr() == Py_False) {
433
+ value = false;
434
+ return true;
435
+ }
436
+ if (convert || is_numpy_bool(src)) {
437
+ // (allow non-implicit conversion for numpy booleans), use strncmp
438
+ // since NumPy 1.x had an additional trailing underscore.
439
+
440
+ Py_ssize_t res = -1;
441
+ if (src.is_none()) {
442
+ res = 0; // None is implicitly converted to False
443
+ }
444
+ #if defined(PYPY_VERSION)
445
+ // On PyPy, check that "__bool__" attr exists
446
+ else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
447
+ res = PyObject_IsTrue(src.ptr());
448
+ }
449
+ #else
450
+ // Alternate approach for CPython: this does the same as the above, but optimized
451
+ // using the CPython API so as to avoid an unneeded attribute lookup.
452
+ else if (auto *tp_as_number = Py_TYPE(src.ptr())->tp_as_number) {
453
+ if (PYBIND11_NB_BOOL(tp_as_number)) {
454
+ res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
455
+ }
456
+ }
457
+ #endif
458
+ if (res == 0 || res == 1) {
459
+ value = (res != 0);
460
+ return true;
461
+ }
462
+ PyErr_Clear();
463
+ }
464
+ return false;
465
+ }
466
+ static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
467
+ return handle(src ? Py_True : Py_False).inc_ref();
468
+ }
469
+ PYBIND11_TYPE_CASTER(bool, const_name("bool"));
470
+
471
+ private:
472
+ // Test if an object is a NumPy boolean (without fetching the type).
473
+ static inline bool is_numpy_bool(handle object) {
474
+ const char *type_name = Py_TYPE(object.ptr())->tp_name;
475
+ // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support
476
+ return std::strcmp("numpy.bool", type_name) == 0
477
+ || std::strcmp("numpy.bool_", type_name) == 0;
478
+ }
479
+ };
480
+
481
+ // Helper class for UTF-{8,16,32} C++ stl strings:
482
+ template <typename StringType, bool IsView = false>
483
+ struct string_caster {
484
+ using CharT = typename StringType::value_type;
485
+
486
+ // Simplify life by being able to assume standard char sizes (the standard only guarantees
487
+ // minimums, but Python requires exact sizes)
488
+ static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
489
+ "Unsupported char size != 1");
490
+ #if defined(PYBIND11_HAS_U8STRING)
491
+ static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
492
+ "Unsupported char8_t size != 1");
493
+ #endif
494
+ static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
495
+ "Unsupported char16_t size != 2");
496
+ static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
497
+ "Unsupported char32_t size != 4");
498
+ // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
499
+ static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
500
+ "Unsupported wchar_t size != 2/4");
501
+ static constexpr size_t UTF_N = 8 * sizeof(CharT);
502
+
503
+ bool load(handle src, bool) {
504
+ handle load_src = src;
505
+ if (!src) {
506
+ return false;
507
+ }
508
+ if (!PyUnicode_Check(load_src.ptr())) {
509
+ return load_raw(load_src);
510
+ }
511
+
512
+ // For UTF-8 we avoid the need for a temporary `bytes` object by using
513
+ // `PyUnicode_AsUTF8AndSize`.
514
+ if (UTF_N == 8) {
515
+ Py_ssize_t size = -1;
516
+ const auto *buffer
517
+ = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
518
+ if (!buffer) {
519
+ PyErr_Clear();
520
+ return false;
521
+ }
522
+ value = StringType(buffer, static_cast<size_t>(size));
523
+ return true;
524
+ }
525
+
526
+ auto utfNbytes
527
+ = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
528
+ UTF_N == 8 ? "utf-8"
529
+ : UTF_N == 16 ? "utf-16"
530
+ : "utf-32",
531
+ nullptr));
532
+ if (!utfNbytes) {
533
+ PyErr_Clear();
534
+ return false;
535
+ }
536
+
537
+ const auto *buffer
538
+ = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
539
+ size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
540
+ // Skip BOM for UTF-16/32
541
+ if (UTF_N > 8) {
542
+ buffer++;
543
+ length--;
544
+ }
545
+ value = StringType(buffer, length);
546
+
547
+ // If we're loading a string_view we need to keep the encoded Python object alive:
548
+ if (IsView) {
549
+ loader_life_support::add_patient(utfNbytes);
550
+ }
551
+
552
+ return true;
553
+ }
554
+
555
+ static handle
556
+ cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
557
+ const char *buffer = reinterpret_cast<const char *>(src.data());
558
+ auto nbytes = ssize_t(src.size() * sizeof(CharT));
559
+ handle s = decode_utfN(buffer, nbytes);
560
+ if (!s) {
561
+ throw error_already_set();
562
+ }
563
+ return s;
564
+ }
565
+
566
+ PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
567
+
568
+ private:
569
+ static handle decode_utfN(const char *buffer, ssize_t nbytes) {
570
+ #if !defined(PYPY_VERSION)
571
+ return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
572
+ : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
573
+ : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
574
+ #else
575
+ // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
576
+ // well), so bypass the whole thing by just passing the encoding as a string value, which
577
+ // works properly:
578
+ return PyUnicode_Decode(buffer,
579
+ nbytes,
580
+ UTF_N == 8 ? "utf-8"
581
+ : UTF_N == 16 ? "utf-16"
582
+ : "utf-32",
583
+ nullptr);
584
+ #endif
585
+ }
586
+
587
+ // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
588
+ // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
589
+ // which supports loading a unicode from a str, doesn't take this path.
590
+ template <typename C = CharT>
591
+ bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
592
+ if (PYBIND11_BYTES_CHECK(src.ptr())) {
593
+ // We were passed raw bytes; accept it into a std::string or char*
594
+ // without any encoding attempt.
595
+ const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
596
+ if (!bytes) {
597
+ pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
598
+ }
599
+ value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
600
+ return true;
601
+ }
602
+ if (PyByteArray_Check(src.ptr())) {
603
+ // We were passed a bytearray; accept it into a std::string or char*
604
+ // without any encoding attempt.
605
+ const char *bytearray = PyByteArray_AsString(src.ptr());
606
+ if (!bytearray) {
607
+ pybind11_fail("Unexpected PyByteArray_AsString() failure.");
608
+ }
609
+ value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
610
+ return true;
611
+ }
612
+
613
+ return false;
614
+ }
615
+
616
+ template <typename C = CharT>
617
+ bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
618
+ return false;
619
+ }
620
+ };
621
+
622
+ template <typename CharT, class Traits, class Allocator>
623
+ struct type_caster<std::basic_string<CharT, Traits, Allocator>,
624
+ enable_if_t<is_std_char_type<CharT>::value>>
625
+ : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
626
+
627
+ #ifdef PYBIND11_HAS_STRING_VIEW
628
+ template <typename CharT, class Traits>
629
+ struct type_caster<std::basic_string_view<CharT, Traits>,
630
+ enable_if_t<is_std_char_type<CharT>::value>>
631
+ : string_caster<std::basic_string_view<CharT, Traits>, true> {};
632
+ #endif
633
+
634
+ // Type caster for C-style strings. We basically use a std::string type caster, but also add the
635
+ // ability to use None as a nullptr char* (which the string caster doesn't allow).
636
+ template <typename CharT>
637
+ struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
638
+ using StringType = std::basic_string<CharT>;
639
+ using StringCaster = make_caster<StringType>;
640
+ StringCaster str_caster;
641
+ bool none = false;
642
+ CharT one_char = 0;
643
+
644
+ public:
645
+ bool load(handle src, bool convert) {
646
+ if (!src) {
647
+ return false;
648
+ }
649
+ if (src.is_none()) {
650
+ // Defer accepting None to other overloads (if we aren't in convert mode):
651
+ if (!convert) {
652
+ return false;
653
+ }
654
+ none = true;
655
+ return true;
656
+ }
657
+ return str_caster.load(src, convert);
658
+ }
659
+
660
+ static handle cast(const CharT *src, return_value_policy policy, handle parent) {
661
+ if (src == nullptr) {
662
+ return pybind11::none().release();
663
+ }
664
+ return StringCaster::cast(StringType(src), policy, parent);
665
+ }
666
+
667
+ static handle cast(CharT src, return_value_policy policy, handle parent) {
668
+ if (std::is_same<char, CharT>::value) {
669
+ handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
670
+ if (!s) {
671
+ throw error_already_set();
672
+ }
673
+ return s;
674
+ }
675
+ return StringCaster::cast(StringType(1, src), policy, parent);
676
+ }
677
+
678
+ explicit operator CharT *() {
679
+ return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
680
+ }
681
+ explicit operator CharT &() {
682
+ if (none) {
683
+ throw value_error("Cannot convert None to a character");
684
+ }
685
+
686
+ auto &value = static_cast<StringType &>(str_caster);
687
+ size_t str_len = value.size();
688
+ if (str_len == 0) {
689
+ throw value_error("Cannot convert empty string to a character");
690
+ }
691
+
692
+ // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
693
+ // is too high, and one for multiple unicode characters (caught later), so we need to
694
+ // figure out how long the first encoded character is in bytes to distinguish between these
695
+ // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
696
+ // those can fit into a single char value.
697
+ if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
698
+ auto v0 = static_cast<unsigned char>(value[0]);
699
+ // low bits only: 0-127
700
+ // 0b110xxxxx - start of 2-byte sequence
701
+ // 0b1110xxxx - start of 3-byte sequence
702
+ // 0b11110xxx - start of 4-byte sequence
703
+ size_t char0_bytes = (v0 & 0x80) == 0 ? 1
704
+ : (v0 & 0xE0) == 0xC0 ? 2
705
+ : (v0 & 0xF0) == 0xE0 ? 3
706
+ : 4;
707
+
708
+ if (char0_bytes == str_len) {
709
+ // If we have a 128-255 value, we can decode it into a single char:
710
+ if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
711
+ one_char = static_cast<CharT>(((v0 & 3) << 6)
712
+ + (static_cast<unsigned char>(value[1]) & 0x3F));
713
+ return one_char;
714
+ }
715
+ // Otherwise we have a single character, but it's > U+00FF
716
+ throw value_error("Character code point not in range(0x100)");
717
+ }
718
+ }
719
+
720
+ // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
721
+ // surrogate pair with total length 2 instantly indicates a range error (but not a "your
722
+ // string was too long" error).
723
+ else if (StringCaster::UTF_N == 16 && str_len == 2) {
724
+ one_char = static_cast<CharT>(value[0]);
725
+ if (one_char >= 0xD800 && one_char < 0xE000) {
726
+ throw value_error("Character code point not in range(0x10000)");
727
+ }
728
+ }
729
+
730
+ if (str_len != 1) {
731
+ throw value_error("Expected a character, but multi-character string found");
732
+ }
733
+
734
+ one_char = value[0];
735
+ return one_char;
736
+ }
737
+
738
+ static constexpr auto name = const_name(PYBIND11_STRING_NAME);
739
+ template <typename _T>
740
+ using cast_op_type = pybind11::detail::cast_op_type<_T>;
741
+ };
742
+
743
+ // Base implementation for std::tuple and std::pair
744
+ template <template <typename...> class Tuple, typename... Ts>
745
+ class tuple_caster {
746
+ using type = Tuple<Ts...>;
747
+ static constexpr auto size = sizeof...(Ts);
748
+ using indices = make_index_sequence<size>;
749
+
750
+ public:
751
+ bool load(handle src, bool convert) {
752
+ if (!isinstance<sequence>(src)) {
753
+ return false;
754
+ }
755
+ const auto seq = reinterpret_borrow<sequence>(src);
756
+ if (seq.size() != size) {
757
+ return false;
758
+ }
759
+ return load_impl(seq, convert, indices{});
760
+ }
761
+
762
+ template <typename T>
763
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
764
+ return cast_impl(std::forward<T>(src), policy, parent, indices{});
765
+ }
766
+
767
+ // copied from the PYBIND11_TYPE_CASTER macro
768
+ template <typename T>
769
+ static handle cast(T *src, return_value_policy policy, handle parent) {
770
+ if (!src) {
771
+ return none().release();
772
+ }
773
+ if (policy == return_value_policy::take_ownership) {
774
+ auto h = cast(std::move(*src), policy, parent);
775
+ delete src;
776
+ return h;
777
+ }
778
+ return cast(*src, policy, parent);
779
+ }
780
+
781
+ static constexpr auto name = const_name("tuple[")
782
+ + ::pybind11::detail::concat(make_caster<Ts>::name...)
783
+ + const_name("]");
784
+
785
+ template <typename T>
786
+ using cast_op_type = type;
787
+
788
+ explicit operator type() & { return implicit_cast(indices{}); }
789
+ explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
790
+
791
+ protected:
792
+ template <size_t... Is>
793
+ type implicit_cast(index_sequence<Is...>) & {
794
+ return type(cast_op<Ts>(std::get<Is>(subcasters))...);
795
+ }
796
+ template <size_t... Is>
797
+ type implicit_cast(index_sequence<Is...>) && {
798
+ return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
799
+ }
800
+
801
+ static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
802
+
803
+ template <size_t... Is>
804
+ bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
805
+ #ifdef __cpp_fold_expressions
806
+ if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
807
+ return false;
808
+ }
809
+ #else
810
+ for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
811
+ if (!r) {
812
+ return false;
813
+ }
814
+ }
815
+ #endif
816
+ return true;
817
+ }
818
+
819
+ /* Implementation: Convert a C++ tuple into a Python tuple */
820
+ template <typename T, size_t... Is>
821
+ static handle
822
+ cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
823
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
824
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
825
+
826
+ std::array<object, size> entries{{reinterpret_steal<object>(
827
+ // NOLINTNEXTLINE(bugprone-use-after-move)
828
+ make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
829
+ for (const auto &entry : entries) {
830
+ if (!entry) {
831
+ return handle();
832
+ }
833
+ }
834
+ tuple result(size);
835
+ int counter = 0;
836
+ for (auto &entry : entries) {
837
+ PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
838
+ }
839
+ return result.release();
840
+ }
841
+
842
+ Tuple<make_caster<Ts>...> subcasters;
843
+ };
844
+
845
+ template <typename T1, typename T2>
846
+ class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
847
+
848
+ template <typename... Ts>
849
+ class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
850
+
851
+ template <>
852
+ class type_caster<std::tuple<>> : public tuple_caster<std::tuple> {
853
+ public:
854
+ // PEP 484 specifies this syntax for an empty tuple
855
+ static constexpr auto name = const_name("tuple[()]");
856
+ };
857
+
858
+ /// Helper class which abstracts away certain actions. Users can provide specializations for
859
+ /// custom holders, but it's only necessary if the type has a non-standard interface.
860
+ template <typename T>
861
+ struct holder_helper {
862
+ static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
863
+ };
864
+
865
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to shared_ptr specialization.
866
+ /// Type caster for holder types like std::shared_ptr, etc.
867
+ /// The SFINAE hook is provided to help work around the current lack of support
868
+ /// for smart-pointer interoperability. Please consider it an implementation
869
+ /// detail that may change in the future, as formal support for smart-pointer
870
+ /// interoperability is added into pybind11.
871
+ template <typename type, typename holder_type, typename SFINAE = void>
872
+ struct copyable_holder_caster : public type_caster_base<type> {
873
+ public:
874
+ using base = type_caster_base<type>;
875
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
876
+ "Holder classes are only supported for custom types");
877
+ using base::base;
878
+ using base::cast;
879
+ using base::typeinfo;
880
+ using base::value;
881
+
882
+ bool load(handle src, bool convert) {
883
+ return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
884
+ }
885
+
886
+ explicit operator type *() { return this->value; }
887
+ // static_cast works around compiler error with MSVC 17 and CUDA 10.2
888
+ // see issue #2180
889
+ explicit operator type &() { return *(static_cast<type *>(this->value)); }
890
+ explicit operator holder_type *() { return std::addressof(holder); }
891
+ explicit operator holder_type &() { return holder; }
892
+
893
+ static handle cast(const holder_type &src, return_value_policy, handle) {
894
+ const auto *ptr = holder_helper<holder_type>::get(src);
895
+ return type_caster_base<type>::cast_holder(ptr, &src);
896
+ }
897
+
898
+ protected:
899
+ friend class type_caster_generic;
900
+ void check_holder_compat() {
901
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
902
+ bool inst_has_unique_ptr_holder
903
+ = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);
904
+ if (inst_has_unique_ptr_holder) {
905
+ throw cast_error("Unable to load a custom holder type from a default-holder instance");
906
+ }
907
+ }
908
+
909
+ void load_value(value_and_holder &&v_h) {
910
+ if (v_h.holder_constructed()) {
911
+ value = v_h.value_ptr();
912
+ holder = v_h.template holder<holder_type>();
913
+ return;
914
+ }
915
+ throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
916
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
917
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
918
+ "type information)");
919
+ #else
920
+ "of type '"
921
+ + type_id<holder_type>() + "''");
922
+ #endif
923
+ }
924
+
925
+ template <typename T = holder_type,
926
+ detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
927
+ bool try_implicit_casts(handle, bool) {
928
+ return false;
929
+ }
930
+
931
+ template <typename T = holder_type,
932
+ detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
933
+ bool try_implicit_casts(handle src, bool convert) {
934
+ for (auto &cast : typeinfo->implicit_casts) {
935
+ copyable_holder_caster sub_caster(*cast.first);
936
+ if (sub_caster.load(src, convert)) {
937
+ value = cast.second(sub_caster.value);
938
+ holder = holder_type(sub_caster.holder, (type *) value);
939
+ return true;
940
+ }
941
+ }
942
+ return false;
943
+ }
944
+
945
+ static bool try_direct_conversions(handle) { return false; }
946
+
947
+ holder_type holder;
948
+ };
949
+
950
+ template <typename, typename SFINAE = void>
951
+ struct copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled : std::true_type {};
952
+
953
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor copyable_holder_caster to reduce code duplication.
954
+ template <typename type>
955
+ struct copyable_holder_caster<
956
+ type,
957
+ std::shared_ptr<type>,
958
+ enable_if_t<copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled<type>::value>>
959
+ : public type_caster_base<type> {
960
+ public:
961
+ using base = type_caster_base<type>;
962
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
963
+ "Holder classes are only supported for custom types");
964
+ using base::base;
965
+ using base::cast;
966
+ using base::typeinfo;
967
+ using base::value;
968
+
969
+ bool load(handle src, bool convert) {
970
+ if (base::template load_impl<copyable_holder_caster<type, std::shared_ptr<type>>>(
971
+ src, convert)) {
972
+ sh_load_helper.maybe_set_python_instance_is_alias(src);
973
+ return true;
974
+ }
975
+ return false;
976
+ }
977
+
978
+ explicit operator std::shared_ptr<type> *() {
979
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
980
+ pybind11_fail("Passing `std::shared_ptr<T> *` from Python to C++ is not supported "
981
+ "(inherently unsafe).");
982
+ }
983
+ return std::addressof(shared_ptr_storage);
984
+ }
985
+
986
+ explicit operator std::shared_ptr<type> &() {
987
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
988
+ shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);
989
+ }
990
+ return shared_ptr_storage;
991
+ }
992
+
993
+ std::weak_ptr<type> potentially_slicing_weak_ptr() {
994
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
995
+ // Reusing shared_ptr code to minimize code complexity.
996
+ shared_ptr_storage
997
+ = sh_load_helper.load_as_shared_ptr(typeinfo,
998
+ value,
999
+ /*responsible_parent=*/nullptr,
1000
+ /*force_potentially_slicing_shared_ptr=*/true);
1001
+ }
1002
+ return shared_ptr_storage;
1003
+ }
1004
+
1005
+ static handle
1006
+ cast(const std::shared_ptr<type> &src, return_value_policy policy, handle parent) {
1007
+ const auto *ptr = src.get();
1008
+ auto st = type_caster_base<type>::src_and_type(ptr);
1009
+ if (st.second == nullptr) {
1010
+ return handle(); // no type info: error will be set already
1011
+ }
1012
+ if (st.second->holder_enum_v == detail::holder_enum_t::smart_holder) {
1013
+ return smart_holder_type_caster_support::smart_holder_from_shared_ptr(
1014
+ src, policy, parent, st);
1015
+ }
1016
+ return type_caster_base<type>::cast_holder(ptr, &src);
1017
+ }
1018
+
1019
+ // This function will succeed even if the `responsible_parent` does not own the
1020
+ // wrapped C++ object directly.
1021
+ // It is the responsibility of the caller to ensure that the `responsible_parent`
1022
+ // has a `keep_alive` relationship with the owner of the wrapped C++ object, or
1023
+ // that the wrapped C++ object lives for the duration of the process.
1024
+ static std::shared_ptr<type> shared_ptr_with_responsible_parent(handle responsible_parent) {
1025
+ copyable_holder_caster loader;
1026
+ loader.load(responsible_parent, /*convert=*/false);
1027
+ assert(loader.typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder);
1028
+ return loader.sh_load_helper.load_as_shared_ptr(
1029
+ loader.typeinfo, loader.value, responsible_parent);
1030
+ }
1031
+
1032
+ protected:
1033
+ friend class type_caster_generic;
1034
+ void check_holder_compat() {
1035
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
1036
+ bool inst_has_unique_ptr_holder
1037
+ = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);
1038
+ if (inst_has_unique_ptr_holder) {
1039
+ throw cast_error("Unable to load a custom holder type from a default-holder instance");
1040
+ }
1041
+ }
1042
+
1043
+ void load_value(value_and_holder &&v_h) {
1044
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1045
+ sh_load_helper.loaded_v_h = v_h;
1046
+ sh_load_helper.was_populated = true;
1047
+ value = sh_load_helper.get_void_ptr_or_nullptr();
1048
+ return;
1049
+ }
1050
+ if (v_h.holder_constructed()) {
1051
+ value = v_h.value_ptr();
1052
+ shared_ptr_storage = v_h.template holder<std::shared_ptr<type>>();
1053
+ return;
1054
+ }
1055
+ throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
1056
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1057
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
1058
+ "type information)");
1059
+ #else
1060
+ "of type '"
1061
+ + type_id<std::shared_ptr<type>>() + "''");
1062
+ #endif
1063
+ }
1064
+
1065
+ template <typename T = std::shared_ptr<type>,
1066
+ detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
1067
+ bool try_implicit_casts(handle, bool) {
1068
+ return false;
1069
+ }
1070
+
1071
+ template <typename T = std::shared_ptr<type>,
1072
+ detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
1073
+ bool try_implicit_casts(handle src, bool convert) {
1074
+ for (auto &cast : typeinfo->implicit_casts) {
1075
+ copyable_holder_caster sub_caster(*cast.first);
1076
+ if (sub_caster.load(src, convert)) {
1077
+ value = cast.second(sub_caster.value);
1078
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1079
+ sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;
1080
+ } else {
1081
+ shared_ptr_storage
1082
+ = std::shared_ptr<type>(sub_caster.shared_ptr_storage, (type *) value);
1083
+ }
1084
+ return true;
1085
+ }
1086
+ }
1087
+ return false;
1088
+ }
1089
+
1090
+ static bool try_direct_conversions(handle) { return false; }
1091
+
1092
+ smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl
1093
+ std::shared_ptr<type> shared_ptr_storage;
1094
+ };
1095
+
1096
+ /// Specialize for the common std::shared_ptr, so users don't need to
1097
+ template <typename T>
1098
+ class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
1099
+
1100
+ PYBIND11_NAMESPACE_END(detail)
1101
+
1102
+ /// Return a std::shared_ptr with the SAME CONTROL BLOCK as the std::shared_ptr owned by the
1103
+ /// class_ holder. For class_-wrapped types with trampolines, the returned std::shared_ptr
1104
+ /// does NOT keep any derived Python objects alive (see issue #1333).
1105
+ ///
1106
+ /// For class_-wrapped types using std::shared_ptr as the holder, the following expressions
1107
+ /// produce equivalent results (see tests/test_potentially_slicing_weak_ptr.cpp,py):
1108
+ ///
1109
+ /// - obj.cast<std::shared_ptr<T>>()
1110
+ /// - py::potentially_slicing_weak_ptr<T>(obj).lock()
1111
+ ///
1112
+ /// For class_-wrapped types with trampolines and using py::smart_holder, obj.cast<>()
1113
+ /// produces a std::shared_ptr that keeps any derived Python objects alive for its own lifetime,
1114
+ /// but this is achieved by introducing a std::shared_ptr control block that is independent of
1115
+ /// the one owned by the py::smart_holder. This can lead to surprising std::weak_ptr behavior
1116
+ /// (see issue #5623). An easy solution is to use py::potentially_slicing_weak_ptr<>(obj),
1117
+ /// as exercised in tests/test_potentially_slicing_weak_ptr.cpp,py (look for
1118
+ /// "set_wp_potentially_slicing"). Note, however, that this reintroduces the inheritance
1119
+ /// slicing issue (see issue #1333). The ideal — but usually more involved — solution is to use
1120
+ /// a Python weakref to the derived Python object, instead of a C++ base-class std::weak_ptr.
1121
+ ///
1122
+ /// It is not possible (at least no known approach exists at the time of this writing) to
1123
+ /// simultaneously achieve both desirable properties:
1124
+ ///
1125
+ /// - the same std::shared_ptr control block as the class_ holder
1126
+ /// - automatic lifetime extension of any derived Python objects
1127
+ ///
1128
+ /// The reason is that this would introduce a reference cycle that cannot be garbage collected:
1129
+ ///
1130
+ /// - the derived Python object owns the class_ holder
1131
+ /// - the class_ holder owns the std::shared_ptr
1132
+ /// - the std::shared_ptr would own a reference to the derived Python object,
1133
+ /// completing the cycle
1134
+ template <typename T>
1135
+ std::weak_ptr<T> potentially_slicing_weak_ptr(handle obj) {
1136
+ detail::make_caster<std::shared_ptr<T>> caster;
1137
+ if (caster.load(obj, /*convert=*/true)) {
1138
+ return caster.potentially_slicing_weak_ptr();
1139
+ }
1140
+ const char *obj_type_name = detail::obj_class_name(obj.ptr());
1141
+ throw type_error("\"" + std::string(obj_type_name)
1142
+ + "\" object is not convertible to std::weak_ptr<T> (with T = " + type_id<T>()
1143
+ + ")");
1144
+ }
1145
+
1146
+ PYBIND11_NAMESPACE_BEGIN(detail)
1147
+
1148
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to unique_ptr specialization.
1149
+ /// Type caster for holder types like std::unique_ptr.
1150
+ /// Please consider the SFINAE hook an implementation detail, as explained
1151
+ /// in the comment for the copyable_holder_caster.
1152
+ template <typename type, typename holder_type, typename SFINAE = void>
1153
+ struct move_only_holder_caster {
1154
+ static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
1155
+ "Holder classes are only supported for custom types");
1156
+
1157
+ static handle cast(holder_type &&src, return_value_policy, handle) {
1158
+ auto *ptr = holder_helper<holder_type>::get(src);
1159
+ return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
1160
+ }
1161
+ static constexpr auto name = type_caster_base<type>::name;
1162
+ };
1163
+
1164
+ template <typename, typename SFINAE = void>
1165
+ struct move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled : std::true_type {};
1166
+
1167
+ // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor move_only_holder_caster to reduce code duplication.
1168
+ template <typename type, typename deleter>
1169
+ struct move_only_holder_caster<
1170
+ type,
1171
+ std::unique_ptr<type, deleter>,
1172
+ enable_if_t<move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled<type>::value>>
1173
+ : public type_caster_base<type> {
1174
+ public:
1175
+ using base = type_caster_base<type>;
1176
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
1177
+ "Holder classes are only supported for custom types");
1178
+ using base::base;
1179
+ using base::cast;
1180
+ using base::typeinfo;
1181
+ using base::value;
1182
+
1183
+ static handle
1184
+ cast(std::unique_ptr<type, deleter> &&src, return_value_policy policy, handle parent) {
1185
+ auto *ptr = src.get();
1186
+ auto st = type_caster_base<type>::src_and_type(ptr);
1187
+ if (st.second == nullptr) {
1188
+ return handle(); // no type info: error will be set already
1189
+ }
1190
+ if (st.second->holder_enum_v == detail::holder_enum_t::smart_holder) {
1191
+ return smart_holder_type_caster_support::smart_holder_from_unique_ptr(
1192
+ std::move(src), policy, parent, st);
1193
+ }
1194
+ return type_caster_generic::cast(st.first,
1195
+ return_value_policy::take_ownership,
1196
+ {},
1197
+ st.second,
1198
+ nullptr,
1199
+ nullptr,
1200
+ std::addressof(src));
1201
+ }
1202
+
1203
+ static handle
1204
+ cast(const std::unique_ptr<type, deleter> &src, return_value_policy policy, handle parent) {
1205
+ if (!src) {
1206
+ return none().release();
1207
+ }
1208
+ if (policy == return_value_policy::automatic) {
1209
+ policy = return_value_policy::reference_internal;
1210
+ }
1211
+ if (policy != return_value_policy::reference_internal) {
1212
+ throw cast_error("Invalid return_value_policy for const unique_ptr&");
1213
+ }
1214
+ return type_caster_base<type>::cast(src.get(), policy, parent);
1215
+ }
1216
+
1217
+ bool load(handle src, bool convert) {
1218
+ if (base::template load_impl<
1219
+ move_only_holder_caster<type, std::unique_ptr<type, deleter>>>(src, convert)) {
1220
+ sh_load_helper.maybe_set_python_instance_is_alias(src);
1221
+ return true;
1222
+ }
1223
+ return false;
1224
+ }
1225
+
1226
+ void load_value(value_and_holder &&v_h) {
1227
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1228
+ sh_load_helper.loaded_v_h = v_h;
1229
+ sh_load_helper.loaded_v_h.type = typeinfo;
1230
+ sh_load_helper.was_populated = true;
1231
+ value = sh_load_helper.get_void_ptr_or_nullptr();
1232
+ return;
1233
+ }
1234
+ pybind11_fail("Passing `std::unique_ptr<T>` from Python to C++ requires `py::class_<T, "
1235
+ "py::smart_holder>` (with T = "
1236
+ + clean_type_id(typeinfo->cpptype->name()) + ")");
1237
+ }
1238
+
1239
+ template <typename T_>
1240
+ using cast_op_type
1241
+ = conditional_t<std::is_same<typename std::remove_volatile<T_>::type,
1242
+ const std::unique_ptr<type, deleter> &>::value
1243
+ || std::is_same<typename std::remove_volatile<T_>::type,
1244
+ const std::unique_ptr<const type, deleter> &>::value,
1245
+ const std::unique_ptr<type, deleter> &,
1246
+ std::unique_ptr<type, deleter>>;
1247
+
1248
+ explicit operator std::unique_ptr<type, deleter>() {
1249
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1250
+ return sh_load_helper.template load_as_unique_ptr<deleter>(typeinfo, value);
1251
+ }
1252
+ pybind11_fail("Expected to be UNREACHABLE: " __FILE__ ":" PYBIND11_TOSTRING(__LINE__));
1253
+ }
1254
+
1255
+ explicit operator const std::unique_ptr<type, deleter> &() {
1256
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1257
+ // Get shared_ptr to ensure that the Python object is not disowned elsewhere.
1258
+ shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);
1259
+ // Build a temporary unique_ptr that is meant to never expire.
1260
+ unique_ptr_storage = std::shared_ptr<std::unique_ptr<type, deleter>>(
1261
+ new std::unique_ptr<type, deleter>{
1262
+ sh_load_helper.template load_as_const_unique_ptr<deleter>(
1263
+ typeinfo, shared_ptr_storage.get())},
1264
+ [](std::unique_ptr<type, deleter> *ptr) {
1265
+ if (!ptr) {
1266
+ pybind11_fail("FATAL: `const std::unique_ptr<T, D> &` was disowned "
1267
+ "(EXPECT UNDEFINED BEHAVIOR).");
1268
+ }
1269
+ (void) ptr->release();
1270
+ delete ptr;
1271
+ });
1272
+ return *unique_ptr_storage;
1273
+ }
1274
+ pybind11_fail("Expected to be UNREACHABLE: " __FILE__ ":" PYBIND11_TOSTRING(__LINE__));
1275
+ }
1276
+
1277
+ bool try_implicit_casts(handle src, bool convert) {
1278
+ for (auto &cast : typeinfo->implicit_casts) {
1279
+ move_only_holder_caster sub_caster(*cast.first);
1280
+ if (sub_caster.load(src, convert)) {
1281
+ value = cast.second(sub_caster.value);
1282
+ if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1283
+ sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;
1284
+ } else {
1285
+ pybind11_fail("Expected to be UNREACHABLE: " __FILE__
1286
+ ":" PYBIND11_TOSTRING(__LINE__));
1287
+ }
1288
+ return true;
1289
+ }
1290
+ }
1291
+ return false;
1292
+ }
1293
+
1294
+ static bool try_direct_conversions(handle) { return false; }
1295
+
1296
+ smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl
1297
+ std::shared_ptr<type> shared_ptr_storage; // Serves as a pseudo lock.
1298
+ std::shared_ptr<std::unique_ptr<type, deleter>> unique_ptr_storage;
1299
+ };
1300
+
1301
+ template <typename type, typename deleter>
1302
+ class type_caster<std::unique_ptr<type, deleter>>
1303
+ : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
1304
+
1305
+ template <typename type, typename holder_type>
1306
+ using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
1307
+ copyable_holder_caster<type, holder_type>,
1308
+ move_only_holder_caster<type, holder_type>>;
1309
+
1310
+ template <bool Value = false>
1311
+ struct always_construct_holder_value {
1312
+ static constexpr bool value = Value;
1313
+ };
1314
+
1315
+ template <typename T, bool Value = false>
1316
+ struct always_construct_holder : always_construct_holder_value<Value> {};
1317
+
1318
+ /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
1319
+ #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
1320
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
1321
+ namespace detail { \
1322
+ template <typename type> \
1323
+ struct always_construct_holder<holder_type> : always_construct_holder_value<__VA_ARGS__> {}; \
1324
+ template <typename type> \
1325
+ class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
1326
+ : public type_caster_holder<type, holder_type> {}; \
1327
+ } \
1328
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1329
+
1330
+ // PYBIND11_DECLARE_HOLDER_TYPE holder types:
1331
+ template <typename base, typename holder>
1332
+ struct is_holder_type
1333
+ : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
1334
+
1335
+ // Specializations for always-supported holders:
1336
+ template <typename base, typename deleter>
1337
+ struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
1338
+
1339
+ template <typename base>
1340
+ struct is_holder_type<base, smart_holder> : std::true_type {};
1341
+
1342
+ #ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
1343
+
1344
+ // This leads to compilation errors if a specialization is missing.
1345
+ template <typename T>
1346
+ struct handle_type_name;
1347
+
1348
+ #else
1349
+
1350
+ template <typename T>
1351
+ struct handle_type_name {
1352
+ static constexpr auto name = const_name<T>();
1353
+ };
1354
+
1355
+ #endif
1356
+
1357
+ template <>
1358
+ struct handle_type_name<object> {
1359
+ static constexpr auto name = const_name("object");
1360
+ };
1361
+ template <>
1362
+ struct handle_type_name<list> {
1363
+ static constexpr auto name = const_name("list");
1364
+ };
1365
+ template <>
1366
+ struct handle_type_name<dict> {
1367
+ static constexpr auto name = const_name("dict");
1368
+ };
1369
+ template <>
1370
+ struct handle_type_name<anyset> {
1371
+ static constexpr auto name = const_name("set | frozenset");
1372
+ };
1373
+ template <>
1374
+ struct handle_type_name<set> {
1375
+ static constexpr auto name = const_name("set");
1376
+ };
1377
+ template <>
1378
+ struct handle_type_name<frozenset> {
1379
+ static constexpr auto name = const_name("frozenset");
1380
+ };
1381
+ template <>
1382
+ struct handle_type_name<str> {
1383
+ static constexpr auto name = const_name("str");
1384
+ };
1385
+ template <>
1386
+ struct handle_type_name<tuple> {
1387
+ static constexpr auto name = const_name("tuple");
1388
+ };
1389
+ template <>
1390
+ struct handle_type_name<bool_> {
1391
+ static constexpr auto name = const_name("bool");
1392
+ };
1393
+ template <>
1394
+ struct handle_type_name<bytes> {
1395
+ static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
1396
+ };
1397
+ template <>
1398
+ struct handle_type_name<buffer> {
1399
+ static constexpr auto name = const_name(PYBIND11_BUFFER_TYPE_HINT);
1400
+ };
1401
+ template <>
1402
+ struct handle_type_name<int_> {
1403
+ static constexpr auto name = io_name("typing.SupportsInt", "int");
1404
+ };
1405
+ template <>
1406
+ struct handle_type_name<iterable> {
1407
+ static constexpr auto name = const_name("collections.abc.Iterable");
1408
+ };
1409
+ template <>
1410
+ struct handle_type_name<iterator> {
1411
+ static constexpr auto name = const_name("collections.abc.Iterator");
1412
+ };
1413
+ template <>
1414
+ struct handle_type_name<float_> {
1415
+ static constexpr auto name = io_name("typing.SupportsFloat", "float");
1416
+ };
1417
+ template <>
1418
+ struct handle_type_name<function> {
1419
+ static constexpr auto name = const_name("collections.abc.Callable");
1420
+ };
1421
+ template <>
1422
+ struct handle_type_name<handle> {
1423
+ static constexpr auto name = handle_type_name<object>::name;
1424
+ };
1425
+ template <>
1426
+ struct handle_type_name<none> {
1427
+ static constexpr auto name = const_name("None");
1428
+ };
1429
+ template <>
1430
+ struct handle_type_name<sequence> {
1431
+ static constexpr auto name = const_name("collections.abc.Sequence");
1432
+ };
1433
+ template <>
1434
+ struct handle_type_name<bytearray> {
1435
+ static constexpr auto name = const_name("bytearray");
1436
+ };
1437
+ template <>
1438
+ struct handle_type_name<memoryview> {
1439
+ static constexpr auto name = const_name("memoryview");
1440
+ };
1441
+ template <>
1442
+ struct handle_type_name<slice> {
1443
+ static constexpr auto name = const_name("slice");
1444
+ };
1445
+ template <>
1446
+ struct handle_type_name<type> {
1447
+ static constexpr auto name = const_name("type");
1448
+ };
1449
+ template <>
1450
+ struct handle_type_name<capsule> {
1451
+ static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);
1452
+ };
1453
+ template <>
1454
+ struct handle_type_name<ellipsis> {
1455
+ static constexpr auto name = const_name("ellipsis");
1456
+ };
1457
+ template <>
1458
+ struct handle_type_name<weakref> {
1459
+ static constexpr auto name = const_name("weakref.ReferenceType");
1460
+ };
1461
+ template <>
1462
+ struct handle_type_name<args> {
1463
+ static constexpr auto name = const_name("*args");
1464
+ };
1465
+ template <typename T>
1466
+ struct handle_type_name<Args<T>> {
1467
+ static constexpr auto name = const_name("*args: ") + make_caster<T>::name;
1468
+ };
1469
+ template <>
1470
+ struct handle_type_name<kwargs> {
1471
+ static constexpr auto name = const_name("**kwargs");
1472
+ };
1473
+ template <typename T>
1474
+ struct handle_type_name<KWArgs<T>> {
1475
+ static constexpr auto name = const_name("**kwargs: ") + make_caster<T>::name;
1476
+ };
1477
+ template <>
1478
+ struct handle_type_name<obj_attr_accessor> {
1479
+ static constexpr auto name = const_name<obj_attr_accessor>();
1480
+ };
1481
+ template <>
1482
+ struct handle_type_name<str_attr_accessor> {
1483
+ static constexpr auto name = const_name<str_attr_accessor>();
1484
+ };
1485
+ template <>
1486
+ struct handle_type_name<item_accessor> {
1487
+ static constexpr auto name = const_name<item_accessor>();
1488
+ };
1489
+ template <>
1490
+ struct handle_type_name<sequence_accessor> {
1491
+ static constexpr auto name = const_name<sequence_accessor>();
1492
+ };
1493
+ template <>
1494
+ struct handle_type_name<list_accessor> {
1495
+ static constexpr auto name = const_name<list_accessor>();
1496
+ };
1497
+ template <>
1498
+ struct handle_type_name<tuple_accessor> {
1499
+ static constexpr auto name = const_name<tuple_accessor>();
1500
+ };
1501
+
1502
+ template <typename type>
1503
+ struct pyobject_caster {
1504
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1505
+ pyobject_caster() : value() {}
1506
+
1507
+ // `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
1508
+ // to a nil handle is safe since it will only be accessed if `load` succeeds.
1509
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1510
+ pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
1511
+
1512
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1513
+ bool load(handle src, bool /* convert */) {
1514
+ value = src;
1515
+ return static_cast<bool>(value);
1516
+ }
1517
+
1518
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1519
+ bool load(handle src, bool /* convert */) {
1520
+ if (!isinstance<type>(src)) {
1521
+ return false;
1522
+ }
1523
+ value = reinterpret_borrow<type>(src);
1524
+ return true;
1525
+ }
1526
+
1527
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1528
+ return src.inc_ref();
1529
+ }
1530
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1531
+ };
1532
+
1533
+ template <typename T>
1534
+ class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
1535
+
1536
+ // Our conditions for enabling moving are quite restrictive:
1537
+ // At compile time:
1538
+ // - T needs to be a non-const, non-pointer, non-reference type
1539
+ // - type_caster<T>::operator T&() must exist
1540
+ // - the type must be move constructible (obviously)
1541
+ // At run-time:
1542
+ // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
1543
+ // must have ref_count() == 1)h
1544
+ // If any of the above are not satisfied, we fall back to copying.
1545
+ template <typename T>
1546
+ using move_is_plain_type
1547
+ = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
1548
+ template <typename T, typename SFINAE = void>
1549
+ struct move_always : std::false_type {};
1550
+ template <typename T>
1551
+ struct move_always<
1552
+ T,
1553
+ enable_if_t<
1554
+ all_of<move_is_plain_type<T>,
1555
+ negation<is_copy_constructible<T>>,
1556
+ is_move_constructible<T>,
1557
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1558
+ : std::true_type {};
1559
+ template <typename T, typename SFINAE = void>
1560
+ struct move_if_unreferenced : std::false_type {};
1561
+ template <typename T>
1562
+ struct move_if_unreferenced<
1563
+ T,
1564
+ enable_if_t<
1565
+ all_of<move_is_plain_type<T>,
1566
+ negation<move_always<T>>,
1567
+ is_move_constructible<T>,
1568
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1569
+ : std::true_type {};
1570
+ template <typename T>
1571
+ using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
1572
+
1573
+ // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
1574
+ // reference or pointer to a local variable of the type_caster. Basically, only
1575
+ // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
1576
+ // everything else returns a reference/pointer to a local variable.
1577
+ template <typename type>
1578
+ using cast_is_temporary_value_reference
1579
+ = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
1580
+ && !std::is_base_of<type_caster_generic, make_caster<type>>::value
1581
+ && !std::is_same<intrinsic_t<type>, void>::value>;
1582
+
1583
+ // When a value returned from a C++ function is being cast back to Python, we almost always want to
1584
+ // force `policy = move`, regardless of the return value policy the function/method was declared
1585
+ // with.
1586
+ template <typename Return, typename SFINAE = void>
1587
+ struct return_value_policy_override {
1588
+ static return_value_policy policy(return_value_policy p) { return p; }
1589
+ };
1590
+
1591
+ template <typename Return>
1592
+ struct return_value_policy_override<
1593
+ Return,
1594
+ detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1595
+ static return_value_policy policy(return_value_policy p) {
1596
+ return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1597
+ ? return_value_policy::move
1598
+ : p;
1599
+ }
1600
+ };
1601
+
1602
+ // Basic python -> C++ casting; throws if casting fails
1603
+ template <typename T, typename SFINAE>
1604
+ type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1605
+ static_assert(!detail::is_pyobject<T>::value,
1606
+ "Internal error: type_caster should only be used for C++ types");
1607
+ if (!conv.load(handle, true)) {
1608
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1609
+ throw cast_error(
1610
+ "Unable to cast Python instance of type "
1611
+ + str(type::handle_of(handle)).cast<std::string>()
1612
+ + " to C++ type '?' (#define "
1613
+ "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1614
+ #else
1615
+ throw cast_error("Unable to cast Python instance of type "
1616
+ + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
1617
+ + type_id<T>() + "'");
1618
+ #endif
1619
+ }
1620
+ return conv;
1621
+ }
1622
+ // Wrapper around the above that also constructs and returns a type_caster
1623
+ template <typename T>
1624
+ make_caster<T> load_type(const handle &handle) {
1625
+ make_caster<T> conv;
1626
+ load_type(conv, handle);
1627
+ return conv;
1628
+ }
1629
+
1630
+ PYBIND11_NAMESPACE_END(detail)
1631
+
1632
+ // pytype -> C++ type
1633
+ template <typename T,
1634
+ detail::enable_if_t<!detail::is_pyobject<T>::value
1635
+ && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1636
+ int>
1637
+ = 0>
1638
+ T cast(const handle &handle) {
1639
+ using namespace detail;
1640
+ constexpr bool is_enum_cast = type_uses_type_caster_enum_type<intrinsic_t<T>>::value;
1641
+ static_assert(!cast_is_temporary_value_reference<T>::value || is_enum_cast,
1642
+ "Unable to cast type to reference: value is local to type caster");
1643
+ #ifndef NDEBUG
1644
+ if (is_enum_cast && cast_is_temporary_value_reference<T>::value) {
1645
+ if (detail::global_internals_native_enum_type_map_contains(
1646
+ std::type_index(typeid(intrinsic_t<T>)))) {
1647
+ pybind11_fail("Unable to cast native enum type to reference");
1648
+ }
1649
+ }
1650
+ #endif
1651
+ return cast_op<T>(load_type<T>(handle));
1652
+ }
1653
+
1654
+ // pytype -> pytype (calls converting constructor)
1655
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1656
+ T cast(const handle &handle) {
1657
+ return T(reinterpret_borrow<object>(handle));
1658
+ }
1659
+
1660
+ // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
1661
+ // This is necessary for the case that `obj` is a temporary, and could
1662
+ // not possibly be different, given
1663
+ // 1. the established convention that the passed `handle` is borrowed, and
1664
+ // 2. we don't want to force all generic code using `cast<T>()` to special-case
1665
+ // handling of `T` = `PyObject *` (to increment the reference count there).
1666
+ // It is the responsibility of the caller to ensure that the reference count
1667
+ // is decremented.
1668
+ template <typename T,
1669
+ typename Handle,
1670
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1671
+ && detail::is_same_ignoring_cvref<Handle, handle>::value,
1672
+ int>
1673
+ = 0>
1674
+ T cast(Handle &&handle) {
1675
+ return handle.inc_ref().ptr();
1676
+ }
1677
+ // To optimize way an inc_ref/dec_ref cycle:
1678
+ template <typename T,
1679
+ typename Object,
1680
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1681
+ && detail::is_same_ignoring_cvref<Object, object>::value,
1682
+ int>
1683
+ = 0>
1684
+ T cast(Object &&obj) {
1685
+ return obj.release().ptr();
1686
+ }
1687
+
1688
+ // C++ type -> py::object
1689
+ template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1690
+ object cast(T &&value,
1691
+ return_value_policy policy = return_value_policy::automatic_reference,
1692
+ handle parent = handle()) {
1693
+ using no_ref_T = typename std::remove_reference<T>::type;
1694
+ if (policy == return_value_policy::automatic) {
1695
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
1696
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1697
+ : return_value_policy::move;
1698
+ } else if (policy == return_value_policy::automatic_reference) {
1699
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
1700
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1701
+ : return_value_policy::move;
1702
+ }
1703
+ return reinterpret_steal<object>(
1704
+ detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1705
+ }
1706
+
1707
+ template <typename T>
1708
+ T handle::cast() const {
1709
+ return pybind11::cast<T>(*this);
1710
+ }
1711
+ template <>
1712
+ inline void handle::cast() const {
1713
+ return;
1714
+ }
1715
+
1716
+ template <typename T>
1717
+ detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1718
+ if (obj.ref_count() > 1) {
1719
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1720
+ throw cast_error(
1721
+ "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
1722
+ + " instance to C++ rvalue: instance has multiple references"
1723
+ " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1724
+ #else
1725
+ throw cast_error("Unable to move from Python "
1726
+ + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
1727
+ + type_id<T>() + " instance: instance has multiple references");
1728
+ #endif
1729
+ }
1730
+
1731
+ // Move into a temporary and return that, because the reference may be a local value of `conv`
1732
+ T ret = std::move(detail::load_type<T>(obj).operator T &());
1733
+ return ret;
1734
+ }
1735
+
1736
+ // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1737
+ // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
1738
+ // object has multiple references, but trying to copy will fail to compile.
1739
+ // - If both movable and copyable, check ref count: if 1, move; otherwise copy
1740
+ // - Otherwise (not movable), copy.
1741
+ template <typename T>
1742
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
1743
+ cast(object &&object) {
1744
+ return move<T>(std::move(object));
1745
+ }
1746
+ template <typename T>
1747
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
1748
+ cast(object &&object) {
1749
+ if (object.ref_count() > 1) {
1750
+ return cast<T>(object);
1751
+ }
1752
+ return move<T>(std::move(object));
1753
+ }
1754
+ template <typename T>
1755
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
1756
+ cast(object &&object) {
1757
+ return cast<T>(object);
1758
+ }
1759
+
1760
+ // pytype rvalue -> pytype (calls converting constructor)
1761
+ template <typename T>
1762
+ detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
1763
+ return T(std::move(object));
1764
+ }
1765
+
1766
+ template <typename T>
1767
+ T object::cast() const & {
1768
+ return pybind11::cast<T>(*this);
1769
+ }
1770
+ template <typename T>
1771
+ T object::cast() && {
1772
+ return pybind11::cast<T>(std::move(*this));
1773
+ }
1774
+ template <>
1775
+ inline void object::cast() const & {
1776
+ return;
1777
+ }
1778
+ template <>
1779
+ inline void object::cast() && {
1780
+ return;
1781
+ }
1782
+
1783
+ PYBIND11_NAMESPACE_BEGIN(detail)
1784
+
1785
+ // forward declaration (definition in pybind11.h)
1786
+ template <typename T>
1787
+ std::string generate_type_signature();
1788
+
1789
+ // Declared in pytypes.h:
1790
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1791
+ object object_or_cast(T &&o) {
1792
+ return pybind11::cast(std::forward<T>(o));
1793
+ }
1794
+
1795
+ // Declared in pytypes.h:
1796
+ // Implemented here so that make_caster<T> can be used.
1797
+ template <typename D>
1798
+ template <typename T>
1799
+ str_attr_accessor object_api<D>::attr_with_type_hint(const char *key) const {
1800
+ #if !defined(__cpp_inline_variables)
1801
+ static_assert(always_false<T>::value,
1802
+ "C++17 feature __cpp_inline_variables not available: "
1803
+ "https://en.cppreference.com/w/cpp/language/static#Static_data_members");
1804
+ #endif
1805
+ object ann = annotations();
1806
+ if (ann.contains(key)) {
1807
+ throw std::runtime_error("__annotations__[\"" + std::string(key) + "\"] was set already.");
1808
+ }
1809
+
1810
+ ann[key] = generate_type_signature<T>();
1811
+ return {derived(), key};
1812
+ }
1813
+
1814
+ template <typename D>
1815
+ template <typename T>
1816
+ obj_attr_accessor object_api<D>::attr_with_type_hint(handle key) const {
1817
+ (void) attr_with_type_hint<T>(key.cast<std::string>().c_str());
1818
+ return {derived(), reinterpret_borrow<object>(key)};
1819
+ }
1820
+
1821
+ // Placeholder type for the unneeded (and dead code) static variable in the
1822
+ // PYBIND11_OVERRIDE_OVERRIDE macro
1823
+ struct override_unused {};
1824
+ template <typename ret_type>
1825
+ using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
1826
+ make_caster<ret_type>,
1827
+ override_unused>;
1828
+
1829
+ // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1830
+ // store the result in the given variable. For other types, this is a no-op.
1831
+ template <typename T>
1832
+ enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
1833
+ make_caster<T> &caster) {
1834
+ return cast_op<T>(load_type(caster, o));
1835
+ }
1836
+ template <typename T>
1837
+ enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
1838
+ override_unused &) {
1839
+ pybind11_fail("Internal error: cast_ref fallback invoked");
1840
+ }
1841
+
1842
+ // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
1843
+ // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
1844
+ // that only does anything in cases where pybind11::cast is valid.
1845
+ template <typename T>
1846
+ enable_if_t<cast_is_temporary_value_reference<T>::value
1847
+ && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1848
+ T>
1849
+ cast_safe(object &&) {
1850
+ pybind11_fail("Internal error: cast_safe fallback invoked");
1851
+ }
1852
+ template <typename T>
1853
+ enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
1854
+ template <typename T>
1855
+ enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>
1856
+ cast_safe(object &&o) {
1857
+ return o.release().ptr();
1858
+ }
1859
+ template <typename T>
1860
+ enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
1861
+ detail::is_same_ignoring_cvref<T, PyObject *>,
1862
+ std::is_void<T>>::value,
1863
+ T>
1864
+ cast_safe(object &&o) {
1865
+ return pybind11::cast<T>(std::move(o));
1866
+ }
1867
+
1868
+ PYBIND11_NAMESPACE_END(detail)
1869
+
1870
+ // The overloads could coexist, i.e. the #if is not strictly speaking needed,
1871
+ // but it is an easy minor optimization.
1872
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1873
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
1874
+ return cast_error("Unable to convert call argument '" + name
1875
+ + "' to Python object (#define "
1876
+ "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1877
+ }
1878
+ #else
1879
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1880
+ const std::string &type) {
1881
+ return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1882
+ + "' to Python object");
1883
+ }
1884
+ #endif
1885
+
1886
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1887
+ tuple make_tuple() {
1888
+ return tuple(0);
1889
+ }
1890
+
1891
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1892
+ tuple make_tuple(Args &&...args_) {
1893
+ constexpr size_t size = sizeof...(Args);
1894
+ std::array<object, size> args{{reinterpret_steal<object>(
1895
+ detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1896
+ for (size_t i = 0; i < args.size(); i++) {
1897
+ if (!args[i]) {
1898
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1899
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i));
1900
+ #else
1901
+ std::array<std::string, size> argtypes{{type_id<Args>()...}};
1902
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1903
+ #endif
1904
+ }
1905
+ }
1906
+ tuple result(size);
1907
+ int counter = 0;
1908
+ for (auto &arg_value : args) {
1909
+ PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1910
+ }
1911
+ return result;
1912
+ }
1913
+
1914
+ /// \ingroup annotations
1915
+ /// Annotation for arguments
1916
+ struct arg {
1917
+ /// Constructs an argument with the name of the argument; if null or omitted, this is a
1918
+ /// positional argument.
1919
+ constexpr explicit arg(const char *name = nullptr)
1920
+ : name(name), flag_noconvert(false), flag_none(true) {}
1921
+ /// Assign a value to this argument
1922
+ template <typename T>
1923
+ arg_v operator=(T &&value) const;
1924
+ /// Indicate that the type should not be converted in the type caster
1925
+ arg &noconvert(bool flag = true) {
1926
+ flag_noconvert = flag;
1927
+ return *this;
1928
+ }
1929
+ /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1930
+ arg &none(bool flag = true) {
1931
+ flag_none = flag;
1932
+ return *this;
1933
+ }
1934
+
1935
+ const char *name; ///< If non-null, this is a named kwargs argument
1936
+ bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
1937
+ ///< caster!)
1938
+ bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
1939
+ };
1940
+
1941
+ /// \ingroup annotations
1942
+ /// Annotation for arguments with values
1943
+ struct arg_v : arg {
1944
+ private:
1945
+ template <typename T>
1946
+ arg_v(arg &&base, T &&x, const char *descr = nullptr)
1947
+ : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
1948
+ std::forward<T>(x), return_value_policy::automatic, {}))),
1949
+ descr(descr)
1950
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1951
+ ,
1952
+ type(type_id<T>())
1953
+ #endif
1954
+ {
1955
+ // Workaround! See:
1956
+ // https://github.com/pybind/pybind11/issues/2336
1957
+ // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1958
+ if (PyErr_Occurred()) {
1959
+ PyErr_Clear();
1960
+ }
1961
+ }
1962
+
1963
+ public:
1964
+ /// Direct construction with name, default, and description
1965
+ template <typename T>
1966
+ arg_v(const char *name, T &&x, const char *descr = nullptr)
1967
+ : arg_v(arg(name), std::forward<T>(x), descr) {}
1968
+
1969
+ /// Called internally when invoking `py::arg("a") = value`
1970
+ template <typename T>
1971
+ arg_v(const arg &base, T &&x, const char *descr = nullptr)
1972
+ : arg_v(arg(base), std::forward<T>(x), descr) {}
1973
+
1974
+ /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
1975
+ arg_v &noconvert(bool flag = true) {
1976
+ arg::noconvert(flag);
1977
+ return *this;
1978
+ }
1979
+
1980
+ /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
1981
+ arg_v &none(bool flag = true) {
1982
+ arg::none(flag);
1983
+ return *this;
1984
+ }
1985
+
1986
+ /// The default value
1987
+ object value;
1988
+ /// The (optional) description of the default value
1989
+ const char *descr;
1990
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1991
+ /// The C++ type name of the default value (only available when compiled in debug mode)
1992
+ std::string type;
1993
+ #endif
1994
+ };
1995
+
1996
+ /// \ingroup annotations
1997
+ /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
1998
+ /// an unnamed '*' argument
1999
+ struct kw_only {};
2000
+
2001
+ /// \ingroup annotations
2002
+ /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
2003
+ /// an unnamed '/' argument
2004
+ struct pos_only {};
2005
+
2006
+ template <typename T>
2007
+ arg_v arg::operator=(T &&value) const {
2008
+ return {*this, std::forward<T>(value)};
2009
+ }
2010
+
2011
+ /// Alias for backward compatibility -- to be removed in version 2.0
2012
+ template <typename /*unused*/>
2013
+ using arg_t = arg_v;
2014
+
2015
+ inline namespace literals {
2016
+ /** \rst
2017
+ String literal version of `arg`
2018
+ \endrst */
2019
+ constexpr arg
2020
+ #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
2021
+ operator"" _a // gcc 4.8.5 insists on having a space (hard error).
2022
+ #else
2023
+ operator""_a // clang 17 generates a deprecation warning if there is a space.
2024
+ #endif
2025
+ (const char *name, size_t) {
2026
+ return arg(name);
2027
+ }
2028
+ } // namespace literals
2029
+
2030
+ PYBIND11_NAMESPACE_BEGIN(detail)
2031
+
2032
+ template <typename T>
2033
+ using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
2034
+ template <typename T>
2035
+ using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
2036
+
2037
+ // forward declaration (definition in attr.h)
2038
+ struct function_record;
2039
+
2040
+ /// Internal data associated with a single function call
2041
+ struct function_call {
2042
+ function_call(const function_record &f, handle p); // Implementation in attr.h
2043
+
2044
+ /// The function data:
2045
+ const function_record &func;
2046
+
2047
+ /// Arguments passed to the function:
2048
+ std::vector<handle> args;
2049
+
2050
+ /// The `convert` value the arguments should be loaded with
2051
+ std::vector<bool> args_convert;
2052
+
2053
+ /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
2054
+ /// present, are also in `args` but without a reference).
2055
+ object args_ref, kwargs_ref;
2056
+
2057
+ /// The parent, if any
2058
+ handle parent;
2059
+
2060
+ /// If this is a call to an initializer, this argument contains `self`
2061
+ handle init_self;
2062
+ };
2063
+
2064
+ // See PR #5396 for the discussion that led to this
2065
+ template <typename Base, typename Derived, typename = void>
2066
+ struct is_same_or_base_of : std::is_same<Base, Derived> {};
2067
+
2068
+ // Only evaluate is_base_of if Derived is complete.
2069
+ // is_base_of raises a compiler error if Derived is incomplete.
2070
+ template <typename Base, typename Derived>
2071
+ struct is_same_or_base_of<Base, Derived, decltype(void(sizeof(Derived)))>
2072
+ : any_of<std::is_same<Base, Derived>, std::is_base_of<Base, Derived>> {};
2073
+
2074
+ /// Helper class which loads arguments for C++ functions called from Python
2075
+ template <typename... Args>
2076
+ class argument_loader {
2077
+ using indices = make_index_sequence<sizeof...(Args)>;
2078
+ template <typename Arg>
2079
+ using argument_is_args = is_same_or_base_of<args, intrinsic_t<Arg>>;
2080
+ template <typename Arg>
2081
+ using argument_is_kwargs = is_same_or_base_of<kwargs, intrinsic_t<Arg>>;
2082
+ // Get kwargs argument position, or -1 if not present:
2083
+ static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
2084
+
2085
+ static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
2086
+ "py::kwargs is only permitted as the last argument of a function");
2087
+
2088
+ public:
2089
+ static constexpr bool has_kwargs = kwargs_pos != -1;
2090
+
2091
+ // py::args argument position; -1 if not present.
2092
+ static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
2093
+
2094
+ static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
2095
+ "py::args cannot be specified more than once");
2096
+
2097
+ static constexpr auto arg_names
2098
+ = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
2099
+
2100
+ bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
2101
+
2102
+ template <typename Return, typename Guard, typename Func>
2103
+ // NOLINTNEXTLINE(readability-const-return-type)
2104
+ enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
2105
+ return std::move(*this).template call_impl<remove_cv_t<Return>>(
2106
+ std::forward<Func>(f), indices{}, Guard{});
2107
+ }
2108
+
2109
+ template <typename Return, typename Guard, typename Func>
2110
+ enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
2111
+ std::move(*this).template call_impl<remove_cv_t<Return>>(
2112
+ std::forward<Func>(f), indices{}, Guard{});
2113
+ return void_type();
2114
+ }
2115
+
2116
+ private:
2117
+ static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
2118
+
2119
+ template <size_t... Is>
2120
+ bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
2121
+ #ifdef __cpp_fold_expressions
2122
+ if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
2123
+ return false;
2124
+ }
2125
+ #else
2126
+ for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
2127
+ if (!r) {
2128
+ return false;
2129
+ }
2130
+ }
2131
+ #endif
2132
+ return true;
2133
+ }
2134
+
2135
+ template <typename Return, typename Func, size_t... Is, typename Guard>
2136
+ Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
2137
+ return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
2138
+ }
2139
+
2140
+ std::tuple<make_caster<Args>...> argcasters;
2141
+ };
2142
+
2143
+ /// Helper class which collects only positional arguments for a Python function call.
2144
+ /// A fancier version below can collect any argument, but this one is optimal for simple calls.
2145
+ template <return_value_policy policy>
2146
+ class simple_collector {
2147
+ public:
2148
+ template <typename... Ts>
2149
+ explicit simple_collector(Ts &&...values)
2150
+ : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
2151
+
2152
+ const tuple &args() const & { return m_args; }
2153
+ dict kwargs() const { return {}; }
2154
+
2155
+ tuple args() && { return std::move(m_args); }
2156
+
2157
+ /// Call a Python function and pass the collected arguments
2158
+ object call(PyObject *ptr) const {
2159
+ PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
2160
+ if (!result) {
2161
+ throw error_already_set();
2162
+ }
2163
+ return reinterpret_steal<object>(result);
2164
+ }
2165
+
2166
+ private:
2167
+ tuple m_args;
2168
+ };
2169
+
2170
+ /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
2171
+ template <return_value_policy policy>
2172
+ class unpacking_collector {
2173
+ public:
2174
+ template <typename... Ts>
2175
+ explicit unpacking_collector(Ts &&...values) {
2176
+ // Tuples aren't (easily) resizable so a list is needed for collection,
2177
+ // but the actual function call strictly requires a tuple.
2178
+ auto args_list = list();
2179
+ using expander = int[];
2180
+ (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
2181
+
2182
+ m_args = std::move(args_list);
2183
+ }
2184
+
2185
+ const tuple &args() const & { return m_args; }
2186
+ const dict &kwargs() const & { return m_kwargs; }
2187
+
2188
+ tuple args() && { return std::move(m_args); }
2189
+ dict kwargs() && { return std::move(m_kwargs); }
2190
+
2191
+ /// Call a Python function and pass the collected arguments
2192
+ object call(PyObject *ptr) const {
2193
+ PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
2194
+ if (!result) {
2195
+ throw error_already_set();
2196
+ }
2197
+ return reinterpret_steal<object>(result);
2198
+ }
2199
+
2200
+ private:
2201
+ template <typename T>
2202
+ void process(list &args_list, T &&x) {
2203
+ auto o = reinterpret_steal<object>(
2204
+ detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
2205
+ if (!o) {
2206
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2207
+ throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()));
2208
+ #else
2209
+ throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
2210
+ type_id<T>());
2211
+ #endif
2212
+ }
2213
+ args_list.append(std::move(o));
2214
+ }
2215
+
2216
+ void process(list &args_list, detail::args_proxy ap) {
2217
+ for (auto a : ap) {
2218
+ args_list.append(a);
2219
+ }
2220
+ }
2221
+
2222
+ void process(list & /*args_list*/, arg_v a) {
2223
+ if (!a.name) {
2224
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2225
+ nameless_argument_error();
2226
+ #else
2227
+ nameless_argument_error(a.type);
2228
+ #endif
2229
+ }
2230
+ if (m_kwargs.contains(a.name)) {
2231
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2232
+ multiple_values_error();
2233
+ #else
2234
+ multiple_values_error(a.name);
2235
+ #endif
2236
+ }
2237
+ if (!a.value) {
2238
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2239
+ throw cast_error_unable_to_convert_call_arg(a.name);
2240
+ #else
2241
+ throw cast_error_unable_to_convert_call_arg(a.name, a.type);
2242
+ #endif
2243
+ }
2244
+ m_kwargs[a.name] = std::move(a.value);
2245
+ }
2246
+
2247
+ void process(list & /*args_list*/, detail::kwargs_proxy kp) {
2248
+ if (!kp) {
2249
+ return;
2250
+ }
2251
+ for (auto k : reinterpret_borrow<dict>(kp)) {
2252
+ if (m_kwargs.contains(k.first)) {
2253
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2254
+ multiple_values_error();
2255
+ #else
2256
+ multiple_values_error(str(k.first));
2257
+ #endif
2258
+ }
2259
+ m_kwargs[k.first] = k.second;
2260
+ }
2261
+ }
2262
+
2263
+ [[noreturn]] static void nameless_argument_error() {
2264
+ throw type_error(
2265
+ "Got kwargs without a name; only named arguments "
2266
+ "may be passed via py::arg() to a python function call. "
2267
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
2268
+ }
2269
+ [[noreturn]] static void nameless_argument_error(const std::string &type) {
2270
+ throw type_error("Got kwargs without a name of type '" + type
2271
+ + "'; only named "
2272
+ "arguments may be passed via py::arg() to a python function call. ");
2273
+ }
2274
+ [[noreturn]] static void multiple_values_error() {
2275
+ throw type_error(
2276
+ "Got multiple values for keyword argument "
2277
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
2278
+ }
2279
+
2280
+ [[noreturn]] static void multiple_values_error(const std::string &name) {
2281
+ throw type_error("Got multiple values for keyword argument '" + name + "'");
2282
+ }
2283
+
2284
+ private:
2285
+ tuple m_args;
2286
+ dict m_kwargs;
2287
+ };
2288
+
2289
+ // [workaround(intel)] Separate function required here
2290
+ // We need to put this into a separate function because the Intel compiler
2291
+ // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
2292
+ // (tested with ICC 2021.1 Beta 20200827).
2293
+ template <typename... Args>
2294
+ constexpr bool args_are_all_positional() {
2295
+ return all_of<is_positional<Args>...>::value;
2296
+ }
2297
+
2298
+ /// Collect only positional arguments for a Python function call
2299
+ template <return_value_policy policy,
2300
+ typename... Args,
2301
+ typename = enable_if_t<args_are_all_positional<Args...>()>>
2302
+ simple_collector<policy> collect_arguments(Args &&...args) {
2303
+ return simple_collector<policy>(std::forward<Args>(args)...);
2304
+ }
2305
+
2306
+ /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
2307
+ template <return_value_policy policy,
2308
+ typename... Args,
2309
+ typename = enable_if_t<!args_are_all_positional<Args...>()>>
2310
+ unpacking_collector<policy> collect_arguments(Args &&...args) {
2311
+ // Following argument order rules for generalized unpacking according to PEP 448
2312
+ static_assert(constexpr_last<is_positional, Args...>()
2313
+ < constexpr_first<is_keyword_or_ds, Args...>()
2314
+ && constexpr_last<is_s_unpacking, Args...>()
2315
+ < constexpr_first<is_ds_unpacking, Args...>(),
2316
+ "Invalid function call: positional args must precede keywords and ** unpacking; "
2317
+ "* unpacking must precede ** unpacking");
2318
+ return unpacking_collector<policy>(std::forward<Args>(args)...);
2319
+ }
2320
+
2321
+ template <typename Derived>
2322
+ template <return_value_policy policy, typename... Args>
2323
+ object object_api<Derived>::operator()(Args &&...args) const {
2324
+ #ifndef NDEBUG
2325
+ if (!PyGILState_Check()) {
2326
+ pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
2327
+ }
2328
+ #endif
2329
+ return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
2330
+ }
2331
+
2332
+ template <typename Derived>
2333
+ template <return_value_policy policy, typename... Args>
2334
+ object object_api<Derived>::call(Args &&...args) const {
2335
+ return operator()<policy>(std::forward<Args>(args)...);
2336
+ }
2337
+
2338
+ PYBIND11_NAMESPACE_END(detail)
2339
+
2340
+ template <typename T>
2341
+ handle type::handle_of() {
2342
+ static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
2343
+ "py::type::of<T> only supports the case where T is a registered C++ types.");
2344
+
2345
+ return detail::get_type_handle(typeid(T), true);
2346
+ }
2347
+
2348
+ #define PYBIND11_MAKE_OPAQUE(...) \
2349
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
2350
+ namespace detail { \
2351
+ template <> \
2352
+ class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
2353
+ } \
2354
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
2355
+
2356
+ /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
2357
+ /// typedef, e.g.:
2358
+ /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
2359
+ #define PYBIND11_TYPE(...) __VA_ARGS__
2360
+
2361
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)