/* pybind11/stl.h: Transparent conversion for STL data types Copyright (c) 2016 Wenzel Jakob All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pybind11.h" #include "detail/common.h" #include "detail/descr.h" #include "detail/type_caster_base.h" #include #include #include #include #include #include #include #include #include #include // See `detail/common.h` for implementation of these guards. #if defined(PYBIND11_HAS_OPTIONAL) # include #elif defined(PYBIND11_HAS_EXP_OPTIONAL) # include #endif #if defined(PYBIND11_HAS_VARIANT) # include #endif PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) // // Begin: Equivalent of // https://github.com/google/clif/blob/ae4eee1de07cdf115c0c9bf9fec9ff28efce6f6c/clif/python/runtime.cc#L388-L438 /* The three `object_is_convertible_to_*()` functions below are the result of converging the behaviors of pybind11 and PyCLIF (http://github.com/google/clif). Originally PyCLIF was extremely far on the permissive side of the spectrum, while pybind11 was very far on the strict side. Originally PyCLIF accepted any Python iterable as input for a C++ `vector`/`set`/`map` argument, as long as the elements were convertible. The obvious (in hindsight) problem was that any empty Python iterable could be passed to any of these C++ types, e.g. `{}` was accepted for C++ `vector`/`set` arguments, or `[]` for C++ `map` arguments. The functions below strike a practical permissive-vs-strict compromise, informed by tens of thousands of use cases in the wild. A main objective is to prevent accidents and improve readability: - Python literals must match the C++ types. - For C++ `set`: The potentially reducing conversion from a Python sequence (e.g. Python `list` or `tuple`) to a C++ `set` must be explicit, by going through a Python `set`. - However, a Python `set` can still be passed to a C++ `vector`. The rationale is that this conversion is not reducing. Implicit conversions of this kind are also fairly commonly used, therefore enforcing explicit conversions would have an unfavorable cost : benefit ratio; more sloppily speaking, such an enforcement would be more annoying than helpful. Additional checks have been added to allow types derived from `collections.abc.Set` and `collections.abc.Mapping` (`collections.abc.Sequence` is already allowed by `PySequence_Check`). */ inline bool object_is_instance_with_one_of_tp_names(PyObject *obj, std::initializer_list tp_names) { if (PyType_Check(obj)) { return false; } const char *obj_tp_name = Py_TYPE(obj)->tp_name; for (const auto *tp_name : tp_names) { if (std::strcmp(obj_tp_name, tp_name) == 0) { return true; } } return false; } inline bool object_is_convertible_to_std_vector(const handle &src) { // Allow sequence-like objects, but not (byte-)string-like objects. if (PySequence_Check(src.ptr()) != 0) { return !PyUnicode_Check(src.ptr()) && !PyBytes_Check(src.ptr()); } // Allow generators, set/frozenset and several common iterable types. return (PyGen_Check(src.ptr()) != 0) || (PyAnySet_Check(src.ptr()) != 0) || object_is_instance_with_one_of_tp_names( src.ptr(), {"dict_keys", "dict_values", "dict_items", "map", "zip"}); } inline bool object_is_convertible_to_std_set(const handle &src, bool convert) { // Allow set/frozenset and dict keys. // In convert mode: also allow types derived from collections.abc.Set. return ((PyAnySet_Check(src.ptr()) != 0) || object_is_instance_with_one_of_tp_names(src.ptr(), {"dict_keys"})) || (convert && isinstance(src, module_::import("collections.abc").attr("Set"))); } inline bool object_is_convertible_to_std_map(const handle &src, bool convert) { // Allow dict. if (PyDict_Check(src.ptr())) { return true; } // Allow types conforming to Mapping Protocol. // According to https://docs.python.org/3/c-api/mapping.html, `PyMappingCheck()` checks for // `__getitem__()` without checking the type of keys. In order to restrict the allowed types // closer to actual Mapping-like types, we also check for the `items()` method. if (PyMapping_Check(src.ptr()) != 0) { PyObject *items = PyObject_GetAttrString(src.ptr(), "items"); if (items != nullptr) { bool is_convertible = (PyCallable_Check(items) != 0); Py_DECREF(items); if (is_convertible) { return true; } } else { PyErr_Clear(); } } // In convert mode: Allow types derived from collections.abc.Mapping return convert && isinstance(src, module_::import("collections.abc").attr("Mapping")); } // // End: Equivalent of clif/python/runtime.cc // /// Extracts an const lvalue reference or rvalue reference for U based on the type of T (e.g. for /// forwarding a container element). Typically used indirect via forwarded_type(), below. template using forwarded_type = conditional_t::value, remove_reference_t &, remove_reference_t &&>; /// Forwards a value U as rvalue or lvalue according to whether T is rvalue or lvalue; typically /// used for forwarding a container's elements. template constexpr forwarded_type forward_like(U &&u) { return std::forward>(std::forward(u)); } // Checks if a container has a STL style reserve method. // This will only return true for a `reserve()` with a `void` return. template using has_reserve_method = std::is_same().reserve(0)), void>; template struct set_caster { using type = Type; using key_conv = make_caster; private: template ::value, int> = 0> void reserve_maybe(const anyset &s, Type *) { value.reserve(s.size()); } void reserve_maybe(const anyset &, void *) {} bool convert_iterable(const iterable &itbl, bool convert) { for (const auto &it : itbl) { key_conv conv; if (!conv.load(it, convert)) { return false; } value.insert(cast_op(std::move(conv))); } return true; } bool convert_anyset(const anyset &s, bool convert) { value.clear(); reserve_maybe(s, &value); return convert_iterable(s, convert); } public: bool load(handle src, bool convert) { if (!object_is_convertible_to_std_set(src, convert)) { return false; } if (isinstance(src)) { value.clear(); return convert_anyset(reinterpret_borrow(src), convert); } if (!convert) { return false; } assert(isinstance(src)); value.clear(); return convert_iterable(reinterpret_borrow(src), convert); } template static handle cast(T &&src, return_value_policy policy, handle parent) { if (!std::is_lvalue_reference::value) { policy = return_value_policy_override::policy(policy); } pybind11::set s; for (auto &&value : src) { auto value_ = reinterpret_steal( key_conv::cast(detail::forward_like(value), policy, parent)); if (!value_ || !s.add(std::move(value_))) { return handle(); } } return s.release(); } PYBIND11_TYPE_CASTER(type, io_name("collections.abc.Set", "set") + const_name("[") + key_conv::name + const_name("]")); }; template struct map_caster { using key_conv = make_caster; using value_conv = make_caster; private: template ::value, int> = 0> void reserve_maybe(const dict &d, Type *) { value.reserve(d.size()); } void reserve_maybe(const dict &, void *) {} bool convert_elements(const dict &d, bool convert) { value.clear(); reserve_maybe(d, &value); for (const auto &it : d) { key_conv kconv; value_conv vconv; if (!kconv.load(it.first.ptr(), convert) || !vconv.load(it.second.ptr(), convert)) { return false; } value.emplace(cast_op(std::move(kconv)), cast_op(std::move(vconv))); } return true; } public: bool load(handle src, bool convert) { if (!object_is_convertible_to_std_map(src, convert)) { return false; } if (isinstance(src)) { return convert_elements(reinterpret_borrow(src), convert); } if (!convert) { return false; } auto items = reinterpret_steal(PyMapping_Items(src.ptr())); if (!items) { throw error_already_set(); } assert(isinstance(items)); return convert_elements(dict(reinterpret_borrow(items)), convert); } template static handle cast(T &&src, return_value_policy policy, handle parent) { dict d; return_value_policy policy_key = policy; return_value_policy policy_value = policy; if (!std::is_lvalue_reference::value) { policy_key = return_value_policy_override::policy(policy_key); policy_value = return_value_policy_override::policy(policy_value); } for (auto &&kv : src) { auto key = reinterpret_steal( key_conv::cast(detail::forward_like(kv.first), policy_key, parent)); auto value = reinterpret_steal( value_conv::cast(detail::forward_like(kv.second), policy_value, parent)); if (!key || !value) { return handle(); } d[std::move(key)] = std::move(value); } return d.release(); } PYBIND11_TYPE_CASTER(Type, io_name("collections.abc.Mapping", "dict") + const_name("[") + key_conv::name + const_name(", ") + value_conv::name + const_name("]")); }; template struct list_caster { using value_conv = make_caster; bool load(handle src, bool convert) { if (!object_is_convertible_to_std_vector(src)) { return false; } if (isinstance(src)) { return convert_elements(src, convert); } if (!convert) { return false; } // Designed to be behavior-equivalent to passing tuple(src) from Python: // The conversion to a tuple will first exhaust the generator object, to ensure that // the generator is not left in an unpredictable (to the caller) partially-consumed // state. assert(isinstance(src)); return convert_elements(tuple(reinterpret_borrow(src)), convert); } private: template ::value, int> = 0> void reserve_maybe(const sequence &s, Type *) { value.reserve(s.size()); } void reserve_maybe(const sequence &, void *) {} bool convert_elements(handle seq, bool convert) { auto s = reinterpret_borrow(seq); value.clear(); reserve_maybe(s, &value); for (const auto &it : seq) { value_conv conv; if (!conv.load(it, convert)) { return false; } value.push_back(cast_op(std::move(conv))); } return true; } public: template static handle cast(T &&src, return_value_policy policy, handle parent) { if (!std::is_lvalue_reference::value) { policy = return_value_policy_override::policy(policy); } list l(src.size()); ssize_t index = 0; for (auto &&value : src) { auto value_ = reinterpret_steal( value_conv::cast(detail::forward_like(value), policy, parent)); if (!value_) { return handle(); } PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference } return l.release(); } PYBIND11_TYPE_CASTER(Type, io_name("collections.abc.Sequence", "list") + const_name("[") + value_conv::name + const_name("]")); }; template struct type_caster> : list_caster, Type> {}; template struct type_caster> : list_caster, Type> {}; template struct type_caster> : list_caster, Type> {}; template ArrayType vector_to_array_impl(V &&v, index_sequence) { return {{std::move(v[I])...}}; } // Based on https://en.cppreference.com/w/cpp/container/array/to_array template ArrayType vector_to_array(V &&v) { return vector_to_array_impl(std::forward(v), make_index_sequence{}); } template struct array_caster { using value_conv = make_caster; private: std::unique_ptr value; template = 0> bool convert_elements(handle seq, bool convert) { auto l = reinterpret_borrow(seq); value.reset(new ArrayType{}); // Using `resize` to preserve the behavior exactly as it was before PR #5305 // For the `resize` to work, `Value` must be default constructible. // For `std::valarray`, this is a requirement: // https://en.cppreference.com/w/cpp/named_req/NumericType value->resize(l.size()); size_t ctr = 0; for (const auto &it : l) { value_conv conv; if (!conv.load(it, convert)) { return false; } (*value)[ctr++] = cast_op(std::move(conv)); } return true; } template = 0> bool convert_elements(handle seq, bool convert) { auto l = reinterpret_borrow(seq); if (l.size() != Size) { return false; } // The `temp` storage is needed to support `Value` types that are not // default-constructible. // Deliberate choice: no template specializations, for simplicity, and // because the compile time overhead for the specializations is deemed // more significant than the runtime overhead for the `temp` storage. std::vector temp; temp.reserve(l.size()); for (auto it : l) { value_conv conv; if (!conv.load(it, convert)) { return false; } temp.emplace_back(cast_op(std::move(conv))); } value.reset(new ArrayType(vector_to_array(std::move(temp)))); return true; } public: bool load(handle src, bool convert) { if (!object_is_convertible_to_std_vector(src)) { return false; } if (isinstance(src)) { return convert_elements(src, convert); } if (!convert) { return false; } // Designed to be behavior-equivalent to passing tuple(src) from Python: // The conversion to a tuple will first exhaust the generator object, to ensure that // the generator is not left in an unpredictable (to the caller) partially-consumed // state. assert(isinstance(src)); return convert_elements(tuple(reinterpret_borrow(src)), convert); } template static handle cast(T &&src, return_value_policy policy, handle parent) { list l(src.size()); ssize_t index = 0; for (auto &&value : src) { auto value_ = reinterpret_steal( value_conv::cast(detail::forward_like(value), policy, parent)); if (!value_) { return handle(); } PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference } return l.release(); } // Code copied from PYBIND11_TYPE_CASTER macro. // Intentionally preserving the behavior exactly as it was before PR #5305 template >::value, int> = 0> static handle cast(T_ *src, return_value_policy policy, handle parent) { if (!src) { return none().release(); } if (policy == return_value_policy::take_ownership) { auto h = cast(std::move(*src), policy, parent); delete src; // WARNING: Assumes `src` was allocated with `new`. return h; } return cast(*src, policy, parent); } // NOLINTNEXTLINE(google-explicit-constructor) operator ArrayType *() { return &(*value); } // NOLINTNEXTLINE(google-explicit-constructor) operator ArrayType &() { return *value; } // NOLINTNEXTLINE(google-explicit-constructor) operator ArrayType &&() && { return std::move(*value); } template using cast_op_type = movable_cast_op_type; static constexpr auto name = const_name(const_name(""), const_name("typing.Annotated[")) + io_name("collections.abc.Sequence", "list") + const_name("[") + value_conv::name + const_name("]") + const_name(const_name(""), const_name(", \"FixedSize(") + const_name() + const_name(")\"]")); }; template struct type_caster> : array_caster, Type, false, Size> {}; template struct type_caster> : array_caster, Type, true> {}; template struct type_caster> : set_caster, Key> {}; template struct type_caster> : set_caster, Key> {}; template struct type_caster> : map_caster, Key, Value> {}; template struct type_caster> : map_caster, Key, Value> {}; // This type caster is intended to be used for std::optional and std::experimental::optional template struct optional_caster { using value_conv = make_caster; template static handle cast(T &&src, return_value_policy policy, handle parent) { if (!src) { return none().release(); } if (!std::is_lvalue_reference::value) { policy = return_value_policy_override::policy(policy); } // NOLINTNEXTLINE(bugprone-unchecked-optional-access) return value_conv::cast(*std::forward(src), policy, parent); } bool load(handle src, bool convert) { if (!src) { return false; } if (src.is_none()) { return true; // default-constructed value is already empty } value_conv inner_caster; if (!inner_caster.load(src, convert)) { return false; } value.emplace(cast_op(std::move(inner_caster))); return true; } PYBIND11_TYPE_CASTER(Type, value_conv::name | make_caster::name); }; #if defined(PYBIND11_HAS_OPTIONAL) template struct type_caster> : public optional_caster> {}; template <> struct type_caster : public void_caster {}; #endif #if defined(PYBIND11_HAS_EXP_OPTIONAL) template struct type_caster> : public optional_caster> {}; template <> struct type_caster : public void_caster {}; #endif /// Visit a variant and cast any found type to Python struct variant_caster_visitor { return_value_policy policy; handle parent; using result_type = handle; // required by boost::variant in C++11 template result_type operator()(T &&src) const { return make_caster::cast(std::forward(src), policy, parent); } }; /// Helper class which abstracts away variant's `visit` function. `std::variant` and similar /// `namespace::variant` types which provide a `namespace::visit()` function are handled here /// automatically using argument-dependent lookup. Users can provide specializations for other /// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`. template