1 /*
2     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
3 
4     All rights reserved. Use of this source code is governed by a
5     BSD-style license that can be found in the LICENSE file.
6 */
7 
8 
9 
10 
11 #pragma once
12 
13 #include "pytypes.h"
14 #include "detail/typeid.h"
15 #include "detail/descr.h"
16 #include "detail/internals.h"
17 #include <array>
18 #include <limits>
19 #include <tuple>
20 #include <type_traits>
21 
22 #if defined(PYBIND11_CPP17)
23 #  if defined(__has_include)
24 #    if __has_include(<string_view>)
25 #      define PYBIND11_HAS_STRING_VIEW
26 #    endif
27 #  elif defined(_MSC_VER)
28 #    define PYBIND11_HAS_STRING_VIEW
29 #  endif
30 #endif
31 #ifdef PYBIND11_HAS_STRING_VIEW
32 #include <string_view>
33 #endif
34 
35 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
NAMESPACE_BEGIN(detail)36 NAMESPACE_BEGIN(detail)
37 
38 
39 
40 class loader_life_support {
41 public:
42 
43     loader_life_support() {
44         get_internals().loader_patient_stack.push_back(nullptr);
45     }
46 
47 
48     ~loader_life_support() {
49         auto &stack = get_internals().loader_patient_stack;
50         if (stack.empty())
51             pybind11_fail("loader_life_support: internal error");
52 
53         auto ptr = stack.back();
54         stack.pop_back();
55         Py_CLEAR(ptr);
56 
57 
58         if (stack.capacity() > 16 && stack.size() != 0 && stack.capacity() / stack.size() > 2)
59             stack.shrink_to_fit();
60     }
61 
62 
63 
64     PYBIND11_NOINLINE static void add_patient(handle h) {
65         auto &stack = get_internals().loader_patient_stack;
66         if (stack.empty())
67             throw cast_error("When called outside a bound function, py::cast() cannot "
68                              "do Python -> C++ conversions which require the creation "
69                              "of temporary values");
70 
71         auto &list_ptr = stack.back();
72         if (list_ptr == nullptr) {
73             list_ptr = PyList_New(1);
74             if (!list_ptr)
75                 pybind11_fail("loader_life_support: error allocating list");
76             PyList_SET_ITEM(list_ptr, 0, h.inc_ref().ptr());
77         } else {
78             auto result = PyList_Append(list_ptr, h.ptr());
79             if (result == -1)
80                 pybind11_fail("loader_life_support: error adding patient");
81         }
82     }
83 };
84 
85 
86 
87 
88 inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type);
89 
90 
all_type_info_populate(PyTypeObject * t,std::vector<type_info * > & bases)91 PYBIND11_NOINLINE inline void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
92     std::vector<PyTypeObject *> check;
93     for (handle parent : reinterpret_borrow<tuple>(t->tp_bases))
94         check.push_back((PyTypeObject *) parent.ptr());
95 
96     auto const &type_dict = get_internals().registered_types_py;
97     for (size_t i = 0; i < check.size(); i++) {
98         auto type = check[i];
99 
100         if (!PyType_Check((PyObject *) type)) continue;
101 
102 
103         auto it = type_dict.find(type);
104         if (it != type_dict.end()) {
105 
106 
107 
108 
109             for (auto *tinfo : it->second) {
110 
111 
112 
113                 bool found = false;
114                 for (auto *known : bases) {
115                     if (known == tinfo) { found = true; break; }
116                 }
117                 if (!found) bases.push_back(tinfo);
118             }
119         }
120         else if (type->tp_bases) {
121 
122 
123             if (i + 1 == check.size()) {
124 
125 
126 
127                 check.pop_back();
128                 i--;
129             }
130             for (handle parent : reinterpret_borrow<tuple>(type->tp_bases))
131                 check.push_back((PyTypeObject *) parent.ptr());
132         }
133     }
134 }
135 
136 
all_type_info(PyTypeObject * type)137 inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
138     auto ins = all_type_info_get_cache(type);
139     if (ins.second)
140 
141         all_type_info_populate(type, ins.first->second);
142 
143     return ins.first->second;
144 }
145 
146 
get_type_info(PyTypeObject * type)147 PYBIND11_NOINLINE inline detail::type_info* get_type_info(PyTypeObject *type) {
148     auto &bases = all_type_info(type);
149     if (bases.size() == 0)
150         return nullptr;
151     if (bases.size() > 1)
152         pybind11_fail("pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
153     return bases.front();
154 }
155 
get_local_type_info(const std::type_index & tp)156 inline detail::type_info *get_local_type_info(const std::type_index &tp) {
157     auto &locals = registered_local_types_cpp();
158     auto it = locals.find(tp);
159     if (it != locals.end())
160         return it->second;
161     return nullptr;
162 }
163 
get_global_type_info(const std::type_index & tp)164 inline detail::type_info *get_global_type_info(const std::type_index &tp) {
165     auto &types = get_internals().registered_types_cpp;
166     auto it = types.find(tp);
167     if (it != types.end())
168         return it->second;
169     return nullptr;
170 }
171 
172 
173 PYBIND11_NOINLINE inline detail::type_info *get_type_info(const std::type_index &tp,
174                                                           bool throw_if_missing = false) {
175     if (auto ltype = get_local_type_info(tp))
176         return ltype;
177     if (auto gtype = get_global_type_info(tp))
178         return gtype;
179 
180     if (throw_if_missing) {
181         std::string tname = tp.name();
182         detail::clean_type_id(tname);
183         pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \"" + tname + "\"");
184     }
185     return nullptr;
186 }
187 
get_type_handle(const std::type_info & tp,bool throw_if_missing)188 PYBIND11_NOINLINE inline handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
189     detail::type_info *type_info = get_type_info(tp, throw_if_missing);
190     return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
191 }
192 
193 struct value_and_holder {
194     instance *inst;
195     size_t index;
196     const detail::type_info *type;
197     void **vh;
198 
199 
value_and_holdervalue_and_holder200     value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index) :
201         inst{i}, index{index}, type{type},
202         vh{inst->simple_layout ? inst->simple_value_holder : &inst->nonsimple.values_and_holders[vpos]}
203     {}
204 
205 
value_and_holdervalue_and_holder206     value_and_holder() : inst{nullptr} {}
207 
208 
value_and_holdervalue_and_holder209     value_and_holder(size_t index) : index{index} {}
210 
value_ptrvalue_and_holder211     template <typename V = void> V *&value_ptr() const {
212         return reinterpret_cast<V *&>(vh[0]);
213     }
214 
215     explicit operator bool() const { return value_ptr(); }
216 
holdervalue_and_holder217     template <typename H> H &holder() const {
218         return reinterpret_cast<H &>(vh[1]);
219     }
holder_constructedvalue_and_holder220     bool holder_constructed() const {
221         return inst->simple_layout
222             ? inst->simple_holder_constructed
223             : inst->nonsimple.status[index] & instance::status_holder_constructed;
224     }
225     void set_holder_constructed(bool v = true) {
226         if (inst->simple_layout)
227             inst->simple_holder_constructed = v;
228         else if (v)
229             inst->nonsimple.status[index] |= instance::status_holder_constructed;
230         else
231             inst->nonsimple.status[index] &= (uint8_t) ~instance::status_holder_constructed;
232     }
instance_registeredvalue_and_holder233     bool instance_registered() const {
234         return inst->simple_layout
235             ? inst->simple_instance_registered
236             : inst->nonsimple.status[index] & instance::status_instance_registered;
237     }
238     void set_instance_registered(bool v = true) {
239         if (inst->simple_layout)
240             inst->simple_instance_registered = v;
241         else if (v)
242             inst->nonsimple.status[index] |= instance::status_instance_registered;
243         else
244             inst->nonsimple.status[index] &= (uint8_t) ~instance::status_instance_registered;
245     }
246 };
247 
248 
249 struct values_and_holders {
250 private:
251     instance *inst;
252     using type_vec = std::vector<detail::type_info *>;
253     const type_vec &tinfo;
254 
255 public:
values_and_holdersvalues_and_holders256     values_and_holders(instance *inst) : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
257 
258     struct iterator {
259     private:
260         instance *inst;
261         const type_vec *types;
262         value_and_holder curr;
263         friend struct values_and_holders;
iteratorvalues_and_holders::iterator264         iterator(instance *inst, const type_vec *tinfo)
265             : inst{inst}, types{tinfo},
266             curr(inst  ,
267                  types->empty() ? nullptr : (*types)[0]  ,
268                  0,
269                  0  )
270         {}
271 
iteratorvalues_and_holders::iterator272         iterator(size_t end) : curr(end) {}
273     public:
274         bool operator==(const iterator &other) { return curr.index == other.curr.index; }
275         bool operator!=(const iterator &other) { return curr.index != other.curr.index; }
276         iterator &operator++() {
277             if (!inst->simple_layout)
278                 curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
279             ++curr.index;
280             curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
281             return *this;
282         }
283         value_and_holder &operator*() { return curr; }
284         value_and_holder *operator->() { return &curr; }
285     };
286 
beginvalues_and_holders287     iterator begin() { return iterator(inst, &tinfo); }
endvalues_and_holders288     iterator end() { return iterator(tinfo.size()); }
289 
findvalues_and_holders290     iterator find(const type_info *find_type) {
291         auto it = begin(), endit = end();
292         while (it != endit && it->type != find_type) ++it;
293         return it;
294     }
295 
sizevalues_and_holders296     size_t size() { return tinfo.size(); }
297 };
298 
299 
get_value_and_holder(const type_info * find_type,bool throw_if_missing)300 PYBIND11_NOINLINE inline value_and_holder instance::get_value_and_holder(const type_info *find_type  , bool throw_if_missing  ) {
301 
302     if (!find_type || Py_TYPE(this) == find_type->type)
303         return value_and_holder(this, find_type, 0, 0);
304 
305     detail::values_and_holders vhs(this);
306     auto it = vhs.find(find_type);
307     if (it != vhs.end())
308         return *it;
309 
310     if (!throw_if_missing)
311         return value_and_holder();
312 
313 #if defined(NDEBUG)
314     pybind11_fail("pybind11::detail::instance::get_value_and_holder: "
315             "type is not a pybind11 base of the given instance "
316             "(compile in debug mode for type details)");
317 #else
318     pybind11_fail("pybind11::detail::instance::get_value_and_holder: `" +
319             std::string(find_type->type->tp_name) + "' is not a pybind11 base of the given `" +
320             std::string(Py_TYPE(this)->tp_name) + "' instance");
321 #endif
322 }
323 
allocate_layout()324 PYBIND11_NOINLINE inline void instance::allocate_layout() {
325     auto &tinfo = all_type_info(Py_TYPE(this));
326 
327     const size_t n_types = tinfo.size();
328 
329     if (n_types == 0)
330         pybind11_fail("instance allocation failed: new instance has no pybind11-registered base types");
331 
332     simple_layout =
333         n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
334 
335 
336     if (simple_layout) {
337         simple_value_holder[0] = nullptr;
338         simple_holder_constructed = false;
339         simple_instance_registered = false;
340     }
341     else {
342 
343 
344 
345 
346         size_t space = 0;
347         for (auto t : tinfo) {
348             space += 1;
349             space += t->holder_size_in_ptrs;
350         }
351         size_t flags_at = space;
352         space += size_in_ptrs(n_types);
353 
354 
355 
356 
357 
358 
359 #if PY_VERSION_HEX >= 0x03050000
360         nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
361         if (!nonsimple.values_and_holders) throw std::bad_alloc();
362 #else
363         nonsimple.values_and_holders = (void **) PyMem_New(void *, space);
364         if (!nonsimple.values_and_holders) throw std::bad_alloc();
365         std::memset(nonsimple.values_and_holders, 0, space * sizeof(void *));
366 #endif
367         nonsimple.status = reinterpret_cast<uint8_t *>(&nonsimple.values_and_holders[flags_at]);
368     }
369     owned = true;
370 }
371 
deallocate_layout()372 PYBIND11_NOINLINE inline void instance::deallocate_layout() {
373     if (!simple_layout)
374         PyMem_Free(nonsimple.values_and_holders);
375 }
376 
isinstance_generic(handle obj,const std::type_info & tp)377 PYBIND11_NOINLINE inline bool isinstance_generic(handle obj, const std::type_info &tp) {
378     handle type = detail::get_type_handle(tp, false);
379     if (!type)
380         return false;
381     return isinstance(obj, type);
382 }
383 
error_string()384 PYBIND11_NOINLINE inline std::string error_string() {
385     if (!PyErr_Occurred()) {
386         PyErr_SetString(PyExc_RuntimeError, "Unknown internal error occurred");
387         return "Unknown internal error occurred";
388     }
389 
390     error_scope scope;
391 
392     std::string errorString;
393     if (scope.type) {
394         errorString += handle(scope.type).attr("__name__").cast<std::string>();
395         errorString += ": ";
396     }
397     if (scope.value)
398         errorString += (std::string) str(scope.value);
399 
400     PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
401 
402 #if PY_MAJOR_VERSION >= 3
403     if (scope.trace != nullptr)
404         PyException_SetTraceback(scope.value, scope.trace);
405 #endif
406 
407 #if !defined(PYPY_VERSION)
408     if (scope.trace) {
409         PyTracebackObject *trace = (PyTracebackObject *) scope.trace;
410 
411 
412         while (trace->tb_next)
413             trace = trace->tb_next;
414 
415         PyFrameObject *frame = trace->tb_frame;
416         errorString += "\n\nAt:\n";
417         while (frame) {
418             int lineno = PyFrame_GetLineNumber(frame);
419             errorString +=
420                 "  " + handle(frame->f_code->co_filename).cast<std::string>() +
421                 "(" + std::to_string(lineno) + "): " +
422                 handle(frame->f_code->co_name).cast<std::string>() + "\n";
423             frame = frame->f_back;
424         }
425     }
426 #endif
427 
428     return errorString;
429 }
430 
get_object_handle(const void * ptr,const detail::type_info * type)431 PYBIND11_NOINLINE inline handle get_object_handle(const void *ptr, const detail::type_info *type ) {
432     auto &instances = get_internals().registered_instances;
433     auto range = instances.equal_range(ptr);
434     for (auto it = range.first; it != range.second; ++it) {
435         for (auto vh : values_and_holders(it->second)) {
436             if (vh.type == type)
437                 return handle((PyObject *) it->second);
438         }
439     }
440     return handle();
441 }
442 
get_thread_state_unchecked()443 inline PyThreadState *get_thread_state_unchecked() {
444 #if defined(PYPY_VERSION)
445     return PyThreadState_GET();
446 #elif PY_VERSION_HEX < 0x03000000
447     return _PyThreadState_Current;
448 #elif PY_VERSION_HEX < 0x03050000
449     return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
450 #elif PY_VERSION_HEX < 0x03050200
451     return (PyThreadState*) _PyThreadState_Current.value;
452 #else
453     return _PyThreadState_UncheckedGet();
454 #endif
455 }
456 
457 
458 inline void keep_alive_impl(handle nurse, handle patient);
459 inline PyObject *make_new_instance(PyTypeObject *type);
460 
461 class type_caster_generic {
462 public:
type_caster_generic(const std::type_info & type_info)463     PYBIND11_NOINLINE type_caster_generic(const std::type_info &type_info)
464         : typeinfo(get_type_info(type_info)), cpptype(&type_info) { }
465 
type_caster_generic(const type_info * typeinfo)466     type_caster_generic(const type_info *typeinfo)
467         : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) { }
468 
load(handle src,bool convert)469     bool load(handle src, bool convert) {
470         return load_impl<type_caster_generic>(src, convert);
471     }
472 
473     PYBIND11_NOINLINE static handle cast(const void *_src, return_value_policy policy, handle parent,
474                                          const detail::type_info *tinfo,
475                                          void *(*copy_constructor)(const void *),
476                                          void *(*move_constructor)(const void *),
477                                          const void *existing_holder = nullptr) {
478         if (!tinfo)
479             return handle();
480 
481         void *src = const_cast<void *>(_src);
482         if (src == nullptr)
483             return none().release();
484 
485         auto it_instances = get_internals().registered_instances.equal_range(src);
486         for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
487             for (auto instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
488                 if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype))
489                     return handle((PyObject *) it_i->second).inc_ref();
490             }
491         }
492 
493         auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
494         auto wrapper = reinterpret_cast<instance *>(inst.ptr());
495         wrapper->owned = false;
496         void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
497 
498         switch (policy) {
499             case return_value_policy::automatic:
500             case return_value_policy::take_ownership:
501                 valueptr = src;
502                 wrapper->owned = true;
503                 break;
504 
505             case return_value_policy::automatic_reference:
506             case return_value_policy::reference:
507                 valueptr = src;
508                 wrapper->owned = false;
509                 break;
510 
511             case return_value_policy::copy:
512                 if (copy_constructor)
513                     valueptr = copy_constructor(src);
514                 else
515                     throw cast_error("return_value_policy = copy, but the "
516                                      "object is non-copyable!");
517                 wrapper->owned = true;
518                 break;
519 
520             case return_value_policy::move:
521                 if (move_constructor)
522                     valueptr = move_constructor(src);
523                 else if (copy_constructor)
524                     valueptr = copy_constructor(src);
525                 else
526                     throw cast_error("return_value_policy = move, but the "
527                                      "object is neither movable nor copyable!");
528                 wrapper->owned = true;
529                 break;
530 
531             case return_value_policy::reference_internal:
532                 valueptr = src;
533                 wrapper->owned = false;
534                 keep_alive_impl(inst, parent);
535                 break;
536 
537             default:
538                 throw cast_error("unhandled return_value_policy: should not happen!");
539         }
540 
541         tinfo->init_instance(wrapper, existing_holder);
542 
543         return inst.release();
544     }
545 
546 
load_value(value_and_holder && v_h)547     void load_value(value_and_holder &&v_h) {
548         auto *&vptr = v_h.value_ptr();
549 
550         if (vptr == nullptr) {
551             auto *type = v_h.type ? v_h.type : typeinfo;
552             if (type->operator_new) {
553                 vptr = type->operator_new(type->type_size);
554             } else {
555                 #if defined(PYBIND11_CPP17)
556                     if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
557                         vptr = ::operator new(type->type_size,
558                                               (std::align_val_t) type->type_align);
559                     else
560                 #endif
561                 vptr = ::operator new(type->type_size);
562             }
563         }
564         value = vptr;
565     }
try_implicit_casts(handle src,bool convert)566     bool try_implicit_casts(handle src, bool convert) {
567         for (auto &cast : typeinfo->implicit_casts) {
568             type_caster_generic sub_caster(*cast.first);
569             if (sub_caster.load(src, convert)) {
570                 value = cast.second(sub_caster.value);
571                 return true;
572             }
573         }
574         return false;
575     }
try_direct_conversions(handle src)576     bool try_direct_conversions(handle src) {
577         for (auto &converter : *typeinfo->direct_conversions) {
578             if (converter(src.ptr(), value))
579                 return true;
580         }
581         return false;
582     }
check_holder_compat()583     void check_holder_compat() {}
584 
local_load(PyObject * src,const type_info * ti)585     PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
586         auto caster = type_caster_generic(ti);
587         if (caster.load(src, false))
588             return caster.value;
589         return nullptr;
590     }
591 
592 
593 
try_load_foreign_module_local(handle src)594     PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
595         constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
596         const auto pytype = src.get_type();
597         if (!hasattr(pytype, local_key))
598             return false;
599 
600         type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
601 
602         if (foreign_typeinfo->module_local_load == &local_load
603             || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype)))
604             return false;
605 
606         if (auto result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
607             value = result;
608             return true;
609         }
610         return false;
611     }
612 
613 
614 
615 
616     template <typename ThisT>
load_impl(handle src,bool convert)617     PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
618         if (!src) return false;
619         if (!typeinfo) return try_load_foreign_module_local(src);
620         if (src.is_none()) {
621 
622             if (!convert) return false;
623             value = nullptr;
624             return true;
625         }
626 
627         auto &this_ = static_cast<ThisT &>(*this);
628         this_.check_holder_compat();
629 
630         PyTypeObject *srctype = Py_TYPE(src.ptr());
631 
632 
633 
634         if (srctype == typeinfo->type) {
635             this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
636             return true;
637         }
638 
639         else if (PyType_IsSubtype(srctype, typeinfo->type)) {
640             auto &bases = all_type_info(srctype);
641             bool no_cpp_mi = typeinfo->simple_type;
642 
643 
644 
645 
646 
647 
648 
649             if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
650                 this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
651                 return true;
652             }
653 
654 
655 
656             else if (bases.size() > 1) {
657                 for (auto base : bases) {
658                     if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type) : base->type == typeinfo->type) {
659                         this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
660                         return true;
661                     }
662                 }
663             }
664 
665 
666 
667 
668             if (this_.try_implicit_casts(src, convert))
669                 return true;
670         }
671 
672 
673         if (convert) {
674             for (auto &converter : typeinfo->implicit_conversions) {
675                 auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
676                 if (load_impl<ThisT>(temp, false)) {
677                     loader_life_support::add_patient(temp);
678                     return true;
679                 }
680             }
681             if (this_.try_direct_conversions(src))
682                 return true;
683         }
684 
685 
686         if (typeinfo->module_local) {
687             if (auto gtype = get_global_type_info(*typeinfo->cpptype)) {
688                 typeinfo = gtype;
689                 return load(src, false);
690             }
691         }
692 
693 
694         return try_load_foreign_module_local(src);
695     }
696 
697 
698 
699 
700 
701     PYBIND11_NOINLINE static std::pair<const void *, const type_info *> src_and_type(
702             const void *src, const std::type_info &cast_type, const std::type_info *rtti_type = nullptr) {
703         if (auto *tpi = get_type_info(cast_type))
704             return {src, const_cast<const type_info *>(tpi)};
705 
706 
707         std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
708         detail::clean_type_id(tname);
709         std::string msg = "Unregistered type : " + tname;
710         PyErr_SetString(PyExc_TypeError, msg.c_str());
711         return {nullptr, nullptr};
712     }
713 
714     const type_info *typeinfo = nullptr;
715     const std::type_info *cpptype = nullptr;
716     void *value = nullptr;
717 };
718 
719 
720 template <typename T>
721 using cast_op_type =
722     conditional_t<std::is_pointer<remove_reference_t<T>>::value,
723         typename std::add_pointer<intrinsic_t<T>>::type,
724         typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
725 
726 
727 template <typename T>
728 using movable_cast_op_type =
729     conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
730         typename std::add_pointer<intrinsic_t<T>>::type,
731     conditional_t<std::is_rvalue_reference<T>::value,
732         typename std::add_rvalue_reference<intrinsic_t<T>>::type,
733         typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
734 
735 
736 
737 template <typename T, typename SFINAE = void> struct is_copy_constructible : std::is_copy_constructible<T> {};
738 
739 
740 
741 
742 template <typename Container> struct is_copy_constructible<Container, enable_if_t<all_of<
743         std::is_copy_constructible<Container>,
744         std::is_same<typename Container::value_type &, typename Container::reference>
745     >::value>> : is_copy_constructible<typename Container::value_type> {};
746 
747 #if !defined(PYBIND11_CPP17)
748 
749 
750 template <typename T1, typename T2> struct is_copy_constructible<std::pair<T1, T2>>
751     : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
752 #endif
753 
754 NAMESPACE_END(detail)
755 
756 
757 
758 
759 
760 
761 
762 
763 
764 
765 
766 
767 
768 
769 
770 
771 
772 
773 template <typename itype, typename SFINAE = void>
774 struct polymorphic_type_hook
775 {
776     static const void *get(const itype *src, const std::type_info*&) { return src; }
777 };
778 template <typename itype>
779 struct polymorphic_type_hook<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>>
780 {
781     static const void *get(const itype *src, const std::type_info*& type) {
782         type = src ? &typeid(*src) : nullptr;
783         return dynamic_cast<const void*>(src);
784     }
785 };
786 
787 NAMESPACE_BEGIN(detail)
788 
789 
790 template <typename type> class type_caster_base : public type_caster_generic {
791     using itype = intrinsic_t<type>;
792 
793 public:
794     static constexpr auto name = _<type>();
795 
796     type_caster_base() : type_caster_base(typeid(type)) { }
797     explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) { }
798 
799     static handle cast(const itype &src, return_value_policy policy, handle parent) {
800         if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
801             policy = return_value_policy::copy;
802         return cast(&src, policy, parent);
803     }
804 
805     static handle cast(itype &&src, return_value_policy, handle parent) {
806         return cast(&src, return_value_policy::move, parent);
807     }
808 
809 
810 
811 
812     static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
813         auto &cast_type = typeid(itype);
814         const std::type_info *instance_type = nullptr;
815         const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
816         if (instance_type && !same_type(cast_type, *instance_type)) {
817 
818 
819 
820 
821 
822 
823 
824 
825             if (const auto *tpi = get_type_info(*instance_type))
826                 return {vsrc, tpi};
827         }
828 
829 
830         return type_caster_generic::src_and_type(src, cast_type, instance_type);
831     }
832 
833     static handle cast(const itype *src, return_value_policy policy, handle parent) {
834         auto st = src_and_type(src);
835         return type_caster_generic::cast(
836             st.first, policy, parent, st.second,
837             make_copy_constructor(src), make_move_constructor(src));
838     }
839 
840     static handle cast_holder(const itype *src, const void *holder) {
841         auto st = src_and_type(src);
842         return type_caster_generic::cast(
843             st.first, return_value_policy::take_ownership, {}, st.second,
844             nullptr, nullptr, holder);
845     }
846 
847     template <typename T> using cast_op_type = detail::cast_op_type<T>;
848 
849     operator itype*() { return (type *) value; }
850     operator itype&() { if (!value) throw reference_cast_error(); return *((itype *) value); }
851 
852 protected:
853     using Constructor = void *(*)(const void *);
854 
855 
856     template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
857     static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor{}) {
858         return [](const void *arg) -> void * {
859             return new T(*reinterpret_cast<const T *>(arg));
860         };
861     }
862 
863     template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
864     static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast<T *>(x))), Constructor{}) {
865         return [](const void *arg) -> void * {
866             return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
867         };
868     }
869 
870     static Constructor make_copy_constructor(...) { return nullptr; }
871     static Constructor make_move_constructor(...) { return nullptr; }
872 };
873 
874 template <typename type, typename SFINAE = void> class type_caster : public type_caster_base<type> { };
875 template <typename type> using make_caster = type_caster<intrinsic_t<type>>;
876 
877 
878 template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
879     return caster.operator typename make_caster<T>::template cast_op_type<T>();
880 }
881 template <typename T> typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
882 cast_op(make_caster<T> &&caster) {
883     return std::move(caster).operator
884         typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>();
885 }
886 
887 template <typename type> class type_caster<std::reference_wrapper<type>> {
888 private:
889     using caster_t = make_caster<type>;
890     caster_t subcaster;
891     using subcaster_cast_op_type = typename caster_t::template cast_op_type<type>;
892     static_assert(std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value,
893             "std::reference_wrapper<T> caster requires T to have a caster with an `T &` operator");
894 public:
895     bool load(handle src, bool convert) { return subcaster.load(src, convert); }
896     static constexpr auto name = caster_t::name;
897     static handle cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
898 
899         if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic)
900             policy = return_value_policy::automatic_reference;
901         return caster_t::cast(&src.get(), policy, parent);
902     }
903     template <typename T> using cast_op_type = std::reference_wrapper<type>;
904     operator std::reference_wrapper<type>() { return subcaster.operator subcaster_cast_op_type&(); }
905 };
906 
907 #define PYBIND11_TYPE_CASTER(type, py_name) \
908     protected: \
909         type value; \
910     public: \
911         static constexpr auto name = py_name; \
912         template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \
913         static handle cast(T_ *src, return_value_policy policy, handle parent) { \
914             if (!src) return none().release(); \
915             if (policy == return_value_policy::take_ownership) { \
916                 auto h = cast(std::move(*src), policy, parent); delete src; return h; \
917             } else { \
918                 return cast(*src, policy, parent); \
919             } \
920         } \
921         operator type*() { return &value; } \
922         operator type&() { return value; } \
923         operator type&&() && { return std::move(value); } \
924         template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_>
925 
926 
927 template <typename CharT> using is_std_char_type = any_of<
928     std::is_same<CharT, char>,
929     std::is_same<CharT, char16_t>,
930     std::is_same<CharT, char32_t>,
931     std::is_same<CharT, wchar_t>
932 >;
933 
934 template <typename T>
935 struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
936     using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
937     using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0, typename std::make_unsigned<_py_type_0>::type>;
938     using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
939 public:
940 
941     bool load(handle src, bool convert) {
942         py_type py_value;
943 
944         if (!src)
945             return false;
946 
947         if (std::is_floating_point<T>::value) {
948             if (convert || PyFloat_Check(src.ptr()))
949                 py_value = (py_type) PyFloat_AsDouble(src.ptr());
950             else
951                 return false;
952         } else if (PyFloat_Check(src.ptr())) {
953             return false;
954         } else if (std::is_unsigned<py_type>::value) {
955             py_value = as_unsigned<py_type>(src.ptr());
956         } else {
957             py_value = sizeof(T) <= sizeof(long)
958                 ? (py_type) PyLong_AsLong(src.ptr())
959                 : (py_type) PYBIND11_LONG_AS_LONGLONG(src.ptr());
960         }
961 
962         bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
963         if (py_err || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T) &&
964                        (py_value < (py_type) std::numeric_limits<T>::min() ||
965                         py_value > (py_type) std::numeric_limits<T>::max()))) {
966             bool type_error = py_err && PyErr_ExceptionMatches(
967 #if PY_VERSION_HEX < 0x03000000 && !defined(PYPY_VERSION)
968                 PyExc_SystemError
969 #else
970                 PyExc_TypeError
971 #endif
972             );
973             PyErr_Clear();
974             if (type_error && convert && PyNumber_Check(src.ptr())) {
975                 auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
976                                                      ? PyNumber_Float(src.ptr())
977                                                      : PyNumber_Long(src.ptr()));
978                 PyErr_Clear();
979                 return load(tmp, false);
980             }
981             return false;
982         }
983 
984         value = (T) py_value;
985         return true;
986     }
987 
988     template<typename U = T>
989     static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
990     cast(U src, return_value_policy  , handle  ) {
991         return PyFloat_FromDouble((double) src);
992     }
993 
994     template<typename U = T>
995     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) <= sizeof(long)), handle>::type
996     cast(U src, return_value_policy  , handle  ) {
997         return PYBIND11_LONG_FROM_SIGNED((long) src);
998     }
999 
1000     template<typename U = T>
1001     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) <= sizeof(unsigned long)), handle>::type
1002     cast(U src, return_value_policy  , handle  ) {
1003         return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
1004     }
1005 
1006     template<typename U = T>
1007     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) > sizeof(long)), handle>::type
1008     cast(U src, return_value_policy  , handle  ) {
1009         return PyLong_FromLongLong((long long) src);
1010     }
1011 
1012     template<typename U = T>
1013     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) > sizeof(unsigned long)), handle>::type
1014     cast(U src, return_value_policy  , handle  ) {
1015         return PyLong_FromUnsignedLongLong((unsigned long long) src);
1016     }
1017 
1018     PYBIND11_TYPE_CASTER(T, _<std::is_integral<T>::value>("int", "float"));
1019 };
1020 
1021 template<typename T> struct void_caster {
1022 public:
1023     bool load(handle src, bool) {
1024         if (src && src.is_none())
1025             return true;
1026         return false;
1027     }
1028     static handle cast(T, return_value_policy  , handle  ) {
1029         return none().inc_ref();
1030     }
1031     PYBIND11_TYPE_CASTER(T, _("None"));
1032 };
1033 
1034 template <> class type_caster<void_type> : public void_caster<void_type> {};
1035 
1036 template <> class type_caster<void> : public type_caster<void_type> {
1037 public:
1038     using type_caster<void_type>::cast;
1039 
1040     bool load(handle h, bool) {
1041         if (!h) {
1042             return false;
1043         } else if (h.is_none()) {
1044             value = nullptr;
1045             return true;
1046         }
1047 
1048 
1049         if (isinstance<capsule>(h)) {
1050             value = reinterpret_borrow<capsule>(h);
1051             return true;
1052         }
1053 
1054 
1055         auto &bases = all_type_info((PyTypeObject *) h.get_type().ptr());
1056         if (bases.size() == 1) {
1057             value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
1058             return true;
1059         }
1060 
1061 
1062         return false;
1063     }
1064 
1065     static handle cast(const void *ptr, return_value_policy  , handle  ) {
1066         if (ptr)
1067             return capsule(ptr).release();
1068         else
1069             return none().inc_ref();
1070     }
1071 
1072     template <typename T> using cast_op_type = void*&;
1073     operator void *&() { return value; }
1074     static constexpr auto name = _("capsule");
1075 private:
1076     void *value = nullptr;
1077 };
1078 
1079 template <> class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> { };
1080 
1081 template <> class type_caster<bool> {
1082 public:
1083     bool load(handle src, bool convert) {
1084         if (!src) return false;
1085         else if (src.ptr() == Py_True) { value = true; return true; }
1086         else if (src.ptr() == Py_False) { value = false; return true; }
1087         else if (convert || !strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name)) {
1088 
1089 
1090             Py_ssize_t res = -1;
1091             if (src.is_none()) {
1092                 res = 0;
1093             }
1094             #if defined(PYPY_VERSION)
1095 
1096             else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
1097                 res = PyObject_IsTrue(src.ptr());
1098             }
1099             #else
1100 
1101 
1102             else if (auto tp_as_number = src.ptr()->ob_type->tp_as_number) {
1103                 if (PYBIND11_NB_BOOL(tp_as_number)) {
1104                     res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
1105                 }
1106             }
1107             #endif
1108             if (res == 0 || res == 1) {
1109                 value = (bool) res;
1110                 return true;
1111             }
1112         }
1113         return false;
1114     }
1115     static handle cast(bool src, return_value_policy  , handle  ) {
1116         return handle(src ? Py_True : Py_False).inc_ref();
1117     }
1118     PYBIND11_TYPE_CASTER(bool, _("bool"));
1119 };
1120 
1121 
1122 template <typename StringType, bool IsView = false> struct string_caster {
1123     using CharT = typename StringType::value_type;
1124 
1125 
1126 
1127     static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1, "Unsupported char size != 1");
1128     static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2, "Unsupported char16_t size != 2");
1129     static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4, "Unsupported char32_t size != 4");
1130 
1131     static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
1132             "Unsupported wchar_t size != 2/4");
1133     static constexpr size_t UTF_N = 8 * sizeof(CharT);
1134 
1135     bool load(handle src, bool) {
1136 #if PY_MAJOR_VERSION < 3
1137         object temp;
1138 #endif
1139         handle load_src = src;
1140         if (!src) {
1141             return false;
1142         } else if (!PyUnicode_Check(load_src.ptr())) {
1143 #if PY_MAJOR_VERSION >= 3
1144             return load_bytes(load_src);
1145 #else
1146             if (sizeof(CharT) == 1) {
1147                 return load_bytes(load_src);
1148             }
1149 
1150 
1151             if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
1152                 return false;
1153 
1154             temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
1155             if (!temp) { PyErr_Clear(); return false; }
1156             load_src = temp;
1157 #endif
1158         }
1159 
1160         object utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
1161             load_src.ptr(), UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr));
1162         if (!utfNbytes) { PyErr_Clear(); return false; }
1163 
1164         const CharT *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
1165         size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
1166         if (UTF_N > 8) { buffer++; length--; }
1167         value = StringType(buffer, length);
1168 
1169 
1170         if (IsView)
1171             loader_life_support::add_patient(utfNbytes);
1172 
1173         return true;
1174     }
1175 
1176     static handle cast(const StringType &src, return_value_policy  , handle  ) {
1177         const char *buffer = reinterpret_cast<const char *>(src.data());
1178         ssize_t nbytes = ssize_t(src.size() * sizeof(CharT));
1179         handle s = decode_utfN(buffer, nbytes);
1180         if (!s) throw error_already_set();
1181         return s;
1182     }
1183 
1184     PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME));
1185 
1186 private:
1187     static handle decode_utfN(const char *buffer, ssize_t nbytes) {
1188 #if !defined(PYPY_VERSION)
1189         return
1190             UTF_N == 8  ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) :
1191             UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) :
1192                           PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
1193 #else
1194 
1195 
1196 
1197 
1198         return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr);
1199 #endif
1200     }
1201 
1202 
1203 
1204 
1205     template <typename C = CharT>
1206     bool load_bytes(enable_if_t<sizeof(C) == 1, handle> src) {
1207         if (PYBIND11_BYTES_CHECK(src.ptr())) {
1208 
1209 
1210             const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
1211             if (bytes) {
1212                 value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
1213                 return true;
1214             }
1215         }
1216 
1217         return false;
1218     }
1219 
1220     template <typename C = CharT>
1221     bool load_bytes(enable_if_t<sizeof(C) != 1, handle>) { return false; }
1222 };
1223 
1224 template <typename CharT, class Traits, class Allocator>
1225 struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>>
1226     : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
1227 
1228 #ifdef PYBIND11_HAS_STRING_VIEW
1229 template <typename CharT, class Traits>
1230 struct type_caster<std::basic_string_view<CharT, Traits>, enable_if_t<is_std_char_type<CharT>::value>>
1231     : string_caster<std::basic_string_view<CharT, Traits>, true> {};
1232 #endif
1233 
1234 
1235 
1236 template <typename CharT> struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
1237     using StringType = std::basic_string<CharT>;
1238     using StringCaster = type_caster<StringType>;
1239     StringCaster str_caster;
1240     bool none = false;
1241     CharT one_char = 0;
1242 public:
1243     bool load(handle src, bool convert) {
1244         if (!src) return false;
1245         if (src.is_none()) {
1246 
1247             if (!convert) return false;
1248             none = true;
1249             return true;
1250         }
1251         return str_caster.load(src, convert);
1252     }
1253 
1254     static handle cast(const CharT *src, return_value_policy policy, handle parent) {
1255         if (src == nullptr) return pybind11::none().inc_ref();
1256         return StringCaster::cast(StringType(src), policy, parent);
1257     }
1258 
1259     static handle cast(CharT src, return_value_policy policy, handle parent) {
1260         if (std::is_same<char, CharT>::value) {
1261             handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
1262             if (!s) throw error_already_set();
1263             return s;
1264         }
1265         return StringCaster::cast(StringType(1, src), policy, parent);
1266     }
1267 
1268     operator CharT*() { return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str()); }
1269     operator CharT&() {
1270         if (none)
1271             throw value_error("Cannot convert None to a character");
1272 
1273         auto &value = static_cast<StringType &>(str_caster);
1274         size_t str_len = value.size();
1275         if (str_len == 0)
1276             throw value_error("Cannot convert empty string to a character");
1277 
1278 
1279 
1280 
1281 
1282 
1283         if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
1284             unsigned char v0 = static_cast<unsigned char>(value[0]);
1285             size_t char0_bytes = !(v0 & 0x80) ? 1 :
1286                 (v0 & 0xE0) == 0xC0 ? 2 :
1287                 (v0 & 0xF0) == 0xE0 ? 3 :
1288                 4;
1289 
1290             if (char0_bytes == str_len) {
1291 
1292                 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) {
1293                     one_char = static_cast<CharT>(((v0 & 3) << 6) + (static_cast<unsigned char>(value[1]) & 0x3F));
1294                     return one_char;
1295                 }
1296 
1297                 throw value_error("Character code point not in range(0x100)");
1298             }
1299         }
1300 
1301 
1302 
1303 
1304         else if (StringCaster::UTF_N == 16 && str_len == 2) {
1305             one_char = static_cast<CharT>(value[0]);
1306             if (one_char >= 0xD800 && one_char < 0xE000)
1307                 throw value_error("Character code point not in range(0x10000)");
1308         }
1309 
1310         if (str_len != 1)
1311             throw value_error("Expected a character, but multi-character string found");
1312 
1313         one_char = value[0];
1314         return one_char;
1315     }
1316 
1317     static constexpr auto name = _(PYBIND11_STRING_NAME);
1318     template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>;
1319 };
1320 
1321 
1322 template <template<typename...> class Tuple, typename... Ts> class tuple_caster {
1323     using type = Tuple<Ts...>;
1324     static constexpr auto size = sizeof...(Ts);
1325     using indices = make_index_sequence<size>;
1326 public:
1327 
1328     bool load(handle src, bool convert) {
1329         if (!isinstance<sequence>(src))
1330             return false;
1331         const auto seq = reinterpret_borrow<sequence>(src);
1332         if (seq.size() != size)
1333             return false;
1334         return load_impl(seq, convert, indices{});
1335     }
1336 
1337     template <typename T>
1338     static handle cast(T &&src, return_value_policy policy, handle parent) {
1339         return cast_impl(std::forward<T>(src), policy, parent, indices{});
1340     }
1341 
1342     static constexpr auto name = _("Tuple[") + concat(make_caster<Ts>::name...) + _("]");
1343 
1344     template <typename T> using cast_op_type = type;
1345 
1346     operator type() & { return implicit_cast(indices{}); }
1347     operator type() && { return std::move(*this).implicit_cast(indices{}); }
1348 
1349 protected:
1350     template <size_t... Is>
1351     type implicit_cast(index_sequence<Is...>) & { return type(cast_op<Ts>(std::get<Is>(subcasters))...); }
1352     template <size_t... Is>
1353     type implicit_cast(index_sequence<Is...>) && { return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...); }
1354 
1355     static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
1356 
1357     template <size_t... Is>
1358     bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
1359         for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
1360             if (!r)
1361                 return false;
1362         return true;
1363     }
1364 
1365 
1366     template <typename T, size_t... Is>
1367     static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
1368         std::array<object, size> entries{{
1369             reinterpret_steal<object>(make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...
1370         }};
1371         for (const auto &entry: entries)
1372             if (!entry)
1373                 return handle();
1374         tuple result(size);
1375         int counter = 0;
1376         for (auto & entry: entries)
1377             PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
1378         return result.release();
1379     }
1380 
1381     Tuple<make_caster<Ts>...> subcasters;
1382 };
1383 
1384 template <typename T1, typename T2> class type_caster<std::pair<T1, T2>>
1385     : public tuple_caster<std::pair, T1, T2> {};
1386 
1387 template <typename... Ts> class type_caster<std::tuple<Ts...>>
1388     : public tuple_caster<std::tuple, Ts...> {};
1389 
1390 
1391 
1392 template <typename T>
1393 struct holder_helper {
1394     static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
1395 };
1396 
1397 
1398 template <typename type, typename holder_type>
1399 struct copyable_holder_caster : public type_caster_base<type> {
1400 public:
1401     using base = type_caster_base<type>;
1402     static_assert(std::is_base_of<base, type_caster<type>>::value,
1403             "Holder classes are only supported for custom types");
1404     using base::base;
1405     using base::cast;
1406     using base::typeinfo;
1407     using base::value;
1408 
1409     bool load(handle src, bool convert) {
1410         return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
1411     }
1412 
1413     explicit operator type*() { return this->value; }
1414     explicit operator type&() { return *(this->value); }
1415     explicit operator holder_type*() { return std::addressof(holder); }
1416 
1417 
1418 
1419     #if defined(__ICC) || defined(__INTEL_COMPILER)
1420     operator holder_type&() { return holder; }
1421     #else
1422     explicit operator holder_type&() { return holder; }
1423     #endif
1424 
1425     static handle cast(const holder_type &src, return_value_policy, handle) {
1426         const auto *ptr = holder_helper<holder_type>::get(src);
1427         return type_caster_base<type>::cast_holder(ptr, &src);
1428     }
1429 
1430 protected:
1431     friend class type_caster_generic;
1432     void check_holder_compat() {
1433         if (typeinfo->default_holder)
1434             throw cast_error("Unable to load a custom holder type from a default-holder instance");
1435     }
1436 
1437     bool load_value(value_and_holder &&v_h) {
1438         if (v_h.holder_constructed()) {
1439             value = v_h.value_ptr();
1440             holder = v_h.template holder<holder_type>();
1441             return true;
1442         } else {
1443             throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
1444 #if defined(NDEBUG)
1445                              "(compile in debug mode for type information)");
1446 #else
1447                              "of type '" + type_id<holder_type>() + "''");
1448 #endif
1449         }
1450     }
1451 
1452     template <typename T = holder_type, detail::enable_if_t<!std::is_constructible<T, const T &, type*>::value, int> = 0>
1453     bool try_implicit_casts(handle, bool) { return false; }
1454 
1455     template <typename T = holder_type, detail::enable_if_t<std::is_constructible<T, const T &, type*>::value, int> = 0>
1456     bool try_implicit_casts(handle src, bool convert) {
1457         for (auto &cast : typeinfo->implicit_casts) {
1458             copyable_holder_caster sub_caster(*cast.first);
1459             if (sub_caster.load(src, convert)) {
1460                 value = cast.second(sub_caster.value);
1461                 holder = holder_type(sub_caster.holder, (type *) value);
1462                 return true;
1463             }
1464         }
1465         return false;
1466     }
1467 
1468     static bool try_direct_conversions(handle) { return false; }
1469 
1470 
1471     holder_type holder;
1472 };
1473 
1474 
1475 template <typename T>
1476 class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> { };
1477 
1478 template <typename type, typename holder_type>
1479 struct move_only_holder_caster {
1480     static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
1481             "Holder classes are only supported for custom types");
1482 
1483     static handle cast(holder_type &&src, return_value_policy, handle) {
1484         auto *ptr = holder_helper<holder_type>::get(src);
1485         return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
1486     }
1487     static constexpr auto name = type_caster_base<type>::name;
1488 };
1489 
1490 template <typename type, typename deleter>
1491 class type_caster<std::unique_ptr<type, deleter>>
1492     : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> { };
1493 
1494 template <typename type, typename holder_type>
1495 using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
1496                                          copyable_holder_caster<type, holder_type>,
1497                                          move_only_holder_caster<type, holder_type>>;
1498 
1499 template <typename T, bool Value = false> struct always_construct_holder { static constexpr bool value = Value; };
1500 
1501 
1502 #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
1503     namespace pybind11 { namespace detail { \
1504     template <typename type> \
1505     struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__>  { }; \
1506     template <typename type> \
1507     class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
1508         : public type_caster_holder<type, holder_type> { }; \
1509     }}
1510 
1511 
1512 template <typename base, typename holder> struct is_holder_type :
1513     std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
1514 
1515 template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> :
1516     std::true_type {};
1517 
1518 template <typename T> struct handle_type_name { static constexpr auto name = _<T>(); };
1519 template <> struct handle_type_name<bytes> { static constexpr auto name = _(PYBIND11_BYTES_NAME); };
1520 template <> struct handle_type_name<args> { static constexpr auto name = _("*args"); };
1521 template <> struct handle_type_name<kwargs> { static constexpr auto name = _("**kwargs"); };
1522 
1523 template <typename type>
1524 struct pyobject_caster {
1525     template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1526     bool load(handle src, bool  ) { value = src; return static_cast<bool>(value); }
1527 
1528     template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1529     bool load(handle src, bool  ) {
1530         if (!isinstance<type>(src))
1531             return false;
1532         value = reinterpret_borrow<type>(src);
1533         return true;
1534     }
1535 
1536     static handle cast(const handle &src, return_value_policy  , handle  ) {
1537         return src.inc_ref();
1538     }
1539     PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1540 };
1541 
1542 template <typename T>
1543 class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> { };
1544 
1545 
1546 
1547 
1548 
1549 
1550 
1551 
1552 
1553 
1554 template <typename T> using move_is_plain_type = satisfies_none_of<T,
1555     std::is_void, std::is_pointer, std::is_reference, std::is_const
1556 >;
1557 template <typename T, typename SFINAE = void> struct move_always : std::false_type {};
1558 template <typename T> struct move_always<T, enable_if_t<all_of<
1559     move_is_plain_type<T>,
1560     negation<is_copy_constructible<T>>,
1561     std::is_move_constructible<T>,
1562     std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1563 >::value>> : std::true_type {};
1564 template <typename T, typename SFINAE = void> struct move_if_unreferenced : std::false_type {};
1565 template <typename T> struct move_if_unreferenced<T, enable_if_t<all_of<
1566     move_is_plain_type<T>,
1567     negation<move_always<T>>,
1568     std::is_move_constructible<T>,
1569     std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1570 >::value>> : std::true_type {};
1571 template <typename T> using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
1572 
1573 
1574 
1575 
1576 
1577 template <typename type> using cast_is_temporary_value_reference = bool_constant<
1578     (std::is_reference<type>::value || std::is_pointer<type>::value) &&
1579     !std::is_base_of<type_caster_generic, make_caster<type>>::value &&
1580     !std::is_same<intrinsic_t<type>, void>::value
1581 >;
1582 
1583 
1584 
1585 
1586 template <typename Return, typename SFINAE = void> struct return_value_policy_override {
1587     static return_value_policy policy(return_value_policy p) { return p; }
1588 };
1589 
1590 template <typename Return> struct return_value_policy_override<Return,
1591         detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1592     static return_value_policy policy(return_value_policy p) {
1593         return !std::is_lvalue_reference<Return>::value &&
1594                !std::is_pointer<Return>::value
1595                    ? return_value_policy::move : p;
1596     }
1597 };
1598 
1599 
1600 template <typename T, typename SFINAE> type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1601     if (!conv.load(handle, true)) {
1602 #if defined(NDEBUG)
1603         throw cast_error("Unable to cast Python instance to C++ type (compile in debug mode for details)");
1604 #else
1605         throw cast_error("Unable to cast Python instance of type " +
1606             (std::string) str(handle.get_type()) + " to C++ type '" + type_id<T>() + "'");
1607 #endif
1608     }
1609     return conv;
1610 }
1611 
1612 template <typename T> make_caster<T> load_type(const handle &handle) {
1613     make_caster<T> conv;
1614     load_type(conv, handle);
1615     return conv;
1616 }
1617 
1618 NAMESPACE_END(detail)
1619 
1620 
1621 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1622 T cast(const handle &handle) {
1623     using namespace detail;
1624     static_assert(!cast_is_temporary_value_reference<T>::value,
1625             "Unable to cast type to reference: value is local to type caster");
1626     return cast_op<T>(load_type<T>(handle));
1627 }
1628 
1629 
1630 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1631 T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); }
1632 
1633 
1634 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1635 object cast(const T &value, return_value_policy policy = return_value_policy::automatic_reference,
1636             handle parent = handle()) {
1637     if (policy == return_value_policy::automatic)
1638         policy = std::is_pointer<T>::value ? return_value_policy::take_ownership : return_value_policy::copy;
1639     else if (policy == return_value_policy::automatic_reference)
1640         policy = std::is_pointer<T>::value ? return_value_policy::reference : return_value_policy::copy;
1641     return reinterpret_steal<object>(detail::make_caster<T>::cast(value, policy, parent));
1642 }
1643 
1644 template <typename T> T handle::cast() const { return pybind11::cast<T>(*this); }
1645 template <> inline void handle::cast() const { return; }
1646 
1647 template <typename T>
1648 detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1649     if (obj.ref_count() > 1)
1650 #if defined(NDEBUG)
1651         throw cast_error("Unable to cast Python instance to C++ rvalue: instance has multiple references"
1652             " (compile in debug mode for details)");
1653 #else
1654         throw cast_error("Unable to move from Python " + (std::string) str(obj.get_type()) +
1655                 " instance to C++ " + type_id<T>() + " instance: instance has multiple references");
1656 #endif
1657 
1658 
1659     T ret = std::move(detail::load_type<T>(obj).operator T&());
1660     return ret;
1661 }
1662 
1663 
1664 
1665 
1666 
1667 
1668 template <typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
1669     return move<T>(std::move(object));
1670 }
1671 template <typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
1672     if (object.ref_count() > 1)
1673         return cast<T>(object);
1674     else
1675         return move<T>(std::move(object));
1676 }
1677 template <typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
1678     return cast<T>(object);
1679 }
1680 
1681 template <typename T> T object::cast() const & { return pybind11::cast<T>(*this); }
1682 template <typename T> T object::cast() && { return pybind11::cast<T>(std::move(*this)); }
1683 template <> inline void object::cast() const & { return; }
1684 template <> inline void object::cast() && { return; }
1685 
1686 NAMESPACE_BEGIN(detail)
1687 
1688 
1689 template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1690 object object_or_cast(T &&o) { return pybind11::cast(std::forward<T>(o)); }
1691 
1692 struct overload_unused {};
1693 template <typename ret_type> using overload_caster_t = conditional_t<
1694     cast_is_temporary_value_reference<ret_type>::value, make_caster<ret_type>, overload_unused>;
1695 
1696 
1697 
1698 template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o, make_caster<T> &caster) {
1699     return cast_op<T>(load_type(caster, o));
1700 }
1701 template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&, overload_unused &) {
1702     pybind11_fail("Internal error: cast_ref fallback invoked"); }
1703 
1704 
1705 
1706 
1707 template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) {
1708     return pybind11::cast<T>(std::move(o)); }
1709 template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
1710     pybind11_fail("Internal error: cast_safe fallback invoked"); }
1711 template <> inline void cast_safe<void>(object &&) {}
1712 
1713 NAMESPACE_END(detail)
1714 
1715 template <return_value_policy policy = return_value_policy::automatic_reference>
1716 tuple make_tuple() { return tuple(0); }
1717 
1718 template <return_value_policy policy = return_value_policy::automatic_reference,
1719           typename... Args> tuple make_tuple(Args&&... args_) {
1720     constexpr size_t size = sizeof...(Args);
1721     std::array<object, size> args {
1722         { reinterpret_steal<object>(detail::make_caster<Args>::cast(
1723             std::forward<Args>(args_), policy, nullptr))... }
1724     };
1725     for (size_t i = 0; i < args.size(); i++) {
1726         if (!args[i]) {
1727 #if defined(NDEBUG)
1728             throw cast_error("make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
1729 #else
1730             std::array<std::string, size> argtypes { {type_id<Args>()...} };
1731             throw cast_error("make_tuple(): unable to convert argument of type '" +
1732                 argtypes[i] + "' to Python object");
1733 #endif
1734         }
1735     }
1736     tuple result(size);
1737     int counter = 0;
1738     for (auto &arg_value : args)
1739         PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1740     return result;
1741 }
1742 
1743 
1744 
1745 struct arg {
1746 
1747     constexpr explicit arg(const char *name = nullptr) : name(name), flag_noconvert(false), flag_none(true) { }
1748 
1749     template <typename T> arg_v operator=(T &&value) const;
1750 
1751     arg &noconvert(bool flag = true) { flag_noconvert = flag; return *this; }
1752 
1753     arg &none(bool flag = true) { flag_none = flag; return *this; }
1754 
1755     const char *name;
1756     bool flag_noconvert : 1;
1757     bool flag_none : 1;
1758 };
1759 
1760 
1761 
1762 struct arg_v : arg {
1763 private:
1764     template <typename T>
1765     arg_v(arg &&base, T &&x, const char *descr = nullptr)
1766         : arg(base),
1767           value(reinterpret_steal<object>(
1768               detail::make_caster<T>::cast(x, return_value_policy::automatic, {})
1769           )),
1770           descr(descr)
1771 #if !defined(NDEBUG)
1772         , type(type_id<T>())
1773 #endif
1774     { }
1775 
1776 public:
1777 
1778     template <typename T>
1779     arg_v(const char *name, T &&x, const char *descr = nullptr)
1780         : arg_v(arg(name), std::forward<T>(x), descr) { }
1781 
1782 
1783     template <typename T>
1784     arg_v(const arg &base, T &&x, const char *descr = nullptr)
1785         : arg_v(arg(base), std::forward<T>(x), descr) { }
1786 
1787 
1788     arg_v &noconvert(bool flag = true) { arg::noconvert(flag); return *this; }
1789 
1790 
1791     arg_v &none(bool flag = true) { arg::none(flag); return *this; }
1792 
1793 
1794     object value;
1795 
1796     const char *descr;
1797 #if !defined(NDEBUG)
1798 
1799     std::string type;
1800 #endif
1801 };
1802 
1803 template <typename T>
1804 arg_v arg::operator=(T &&value) const { return {std::move(*this), std::forward<T>(value)}; }
1805 
1806 
1807 template <typename  > using arg_t = arg_v;
1808 
1809 inline namespace literals {
1810 
1811 constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
1812 }
1813 
1814 NAMESPACE_BEGIN(detail)
1815 
1816 
1817 struct function_record;
1818 
1819 
1820 struct function_call {
1821     function_call(const function_record &f, handle p);
1822 
1823 
1824     const function_record &func;
1825 
1826 
1827     std::vector<handle> args;
1828 
1829 
1830     std::vector<bool> args_convert;
1831 
1832 
1833 
1834     object args_ref, kwargs_ref;
1835 
1836 
1837     handle parent;
1838 
1839 
1840     handle init_self;
1841 };
1842 
1843 
1844 
1845 template <typename... Args>
1846 class argument_loader {
1847     using indices = make_index_sequence<sizeof...(Args)>;
1848 
1849     template <typename Arg> using argument_is_args   = std::is_same<intrinsic_t<Arg>, args>;
1850     template <typename Arg> using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
1851 
1852     static constexpr auto args_pos = constexpr_first<argument_is_args, Args...>() - (int) sizeof...(Args),
1853                         kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int) sizeof...(Args);
1854 
1855     static constexpr bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
1856 
1857     static_assert(args_kwargs_are_last, "py::args/py::kwargs are only permitted as the last argument(s) of a function");
1858 
1859 public:
1860     static constexpr bool has_kwargs = kwargs_pos < 0;
1861     static constexpr bool has_args = args_pos < 0;
1862 
1863     static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...);
1864 
1865     bool load_args(function_call &call) {
1866         return load_impl_sequence(call, indices{});
1867     }
1868 
1869     template <typename Return, typename Guard, typename Func>
1870     enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
1871         return std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
1872     }
1873 
1874     template <typename Return, typename Guard, typename Func>
1875     enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
1876         std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
1877         return void_type();
1878     }
1879 
1880 private:
1881 
1882     static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
1883 
1884     template <size_t... Is>
1885     bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
1886         for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...})
1887             if (!r)
1888                 return false;
1889         return true;
1890     }
1891 
1892     template <typename Return, typename Func, size_t... Is, typename Guard>
1893     Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) {
1894         return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
1895     }
1896 
1897     std::tuple<make_caster<Args>...> argcasters;
1898 };
1899 
1900 
1901 
1902 template <return_value_policy policy>
1903 class simple_collector {
1904 public:
1905     template <typename... Ts>
1906     explicit simple_collector(Ts &&...values)
1907         : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { }
1908 
1909     const tuple &args() const & { return m_args; }
1910     dict kwargs() const { return {}; }
1911 
1912     tuple args() && { return std::move(m_args); }
1913 
1914 
1915     object call(PyObject *ptr) const {
1916         PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1917         if (!result)
1918             throw error_already_set();
1919         return reinterpret_steal<object>(result);
1920     }
1921 
1922 private:
1923     tuple m_args;
1924 };
1925 
1926 
1927 template <return_value_policy policy>
1928 class unpacking_collector {
1929 public:
1930     template <typename... Ts>
1931     explicit unpacking_collector(Ts &&...values) {
1932 
1933 
1934         auto args_list = list();
1935         int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
1936         ignore_unused(_);
1937 
1938         m_args = std::move(args_list);
1939     }
1940 
1941     const tuple &args() const & { return m_args; }
1942     const dict &kwargs() const & { return m_kwargs; }
1943 
1944     tuple args() && { return std::move(m_args); }
1945     dict kwargs() && { return std::move(m_kwargs); }
1946 
1947 
1948     object call(PyObject *ptr) const {
1949         PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1950         if (!result)
1951             throw error_already_set();
1952         return reinterpret_steal<object>(result);
1953     }
1954 
1955 private:
1956     template <typename T>
1957     void process(list &args_list, T &&x) {
1958         auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
1959         if (!o) {
1960 #if defined(NDEBUG)
1961             argument_cast_error();
1962 #else
1963             argument_cast_error(std::to_string(args_list.size()), type_id<T>());
1964 #endif
1965         }
1966         args_list.append(o);
1967     }
1968 
1969     void process(list &args_list, detail::args_proxy ap) {
1970         for (const auto &a : ap)
1971             args_list.append(a);
1972     }
1973 
1974     void process(list & , arg_v a) {
1975         if (!a.name)
1976 #if defined(NDEBUG)
1977             nameless_argument_error();
1978 #else
1979             nameless_argument_error(a.type);
1980 #endif
1981 
1982         if (m_kwargs.contains(a.name)) {
1983 #if defined(NDEBUG)
1984             multiple_values_error();
1985 #else
1986             multiple_values_error(a.name);
1987 #endif
1988         }
1989         if (!a.value) {
1990 #if defined(NDEBUG)
1991             argument_cast_error();
1992 #else
1993             argument_cast_error(a.name, a.type);
1994 #endif
1995         }
1996         m_kwargs[a.name] = a.value;
1997     }
1998 
1999     void process(list & , detail::kwargs_proxy kp) {
2000         if (!kp)
2001             return;
2002         for (const auto &k : reinterpret_borrow<dict>(kp)) {
2003             if (m_kwargs.contains(k.first)) {
2004 #if defined(NDEBUG)
2005                 multiple_values_error();
2006 #else
2007                 multiple_values_error(str(k.first));
2008 #endif
2009             }
2010             m_kwargs[k.first] = k.second;
2011         }
2012     }
2013 
2014     [[noreturn]] static void nameless_argument_error() {
2015         throw type_error("Got kwargs without a name; only named arguments "
2016                          "may be passed via py::arg() to a python function call. "
2017                          "(compile in debug mode for details)");
2018     }
2019     [[noreturn]] static void nameless_argument_error(std::string type) {
2020         throw type_error("Got kwargs without a name of type '" + type + "'; only named "
2021                          "arguments may be passed via py::arg() to a python function call. ");
2022     }
2023     [[noreturn]] static void multiple_values_error() {
2024         throw type_error("Got multiple values for keyword argument "
2025                          "(compile in debug mode for details)");
2026     }
2027 
2028     [[noreturn]] static void multiple_values_error(std::string name) {
2029         throw type_error("Got multiple values for keyword argument '" + name + "'");
2030     }
2031 
2032     [[noreturn]] static void argument_cast_error() {
2033         throw cast_error("Unable to convert call argument to Python object "
2034                          "(compile in debug mode for details)");
2035     }
2036 
2037     [[noreturn]] static void argument_cast_error(std::string name, std::string type) {
2038         throw cast_error("Unable to convert call argument '" + name
2039                          + "' of type '" + type + "' to Python object");
2040     }
2041 
2042 private:
2043     tuple m_args;
2044     dict m_kwargs;
2045 };
2046 
2047 
2048 template <return_value_policy policy, typename... Args,
2049           typename = enable_if_t<all_of<is_positional<Args>...>::value>>
2050 simple_collector<policy> collect_arguments(Args &&...args) {
2051     return simple_collector<policy>(std::forward<Args>(args)...);
2052 }
2053 
2054 
2055 template <return_value_policy policy, typename... Args,
2056           typename = enable_if_t<!all_of<is_positional<Args>...>::value>>
2057 unpacking_collector<policy> collect_arguments(Args &&...args) {
2058 
2059     static_assert(
2060         constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
2061         && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
2062         "Invalid function call: positional args must precede keywords and ** unpacking; "
2063         "* unpacking must precede ** unpacking"
2064     );
2065     return unpacking_collector<policy>(std::forward<Args>(args)...);
2066 }
2067 
2068 template <typename Derived>
2069 template <return_value_policy policy, typename... Args>
2070 object object_api<Derived>::operator()(Args &&...args) const {
2071     return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
2072 }
2073 
2074 template <typename Derived>
2075 template <return_value_policy policy, typename... Args>
2076 object object_api<Derived>::call(Args &&...args) const {
2077     return operator()<policy>(std::forward<Args>(args)...);
2078 }
2079 
2080 NAMESPACE_END(detail)
2081 
2082 #define PYBIND11_MAKE_OPAQUE(...) \
2083     namespace pybind11 { namespace detail { \
2084         template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \
2085     }}
2086 
2087 
2088 
2089 #define PYBIND11_TYPE(...) __VA_ARGS__
2090 
2091 NAMESPACE_END(PYBIND11_NAMESPACE)
2092