]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - tidl/tidl-api.git/blob - tidl_api/pybind11/include/pybind11/detail/internals.h
Adding pybind11 v2.2.4 to repo
[tidl/tidl-api.git] / tidl_api / pybind11 / include / pybind11 / detail / internals.h
1 /*
2     pybind11/detail/internals.h: Internal data structure and related functions
4     Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
6     All rights reserved. Use of this source code is governed by a
7     BSD-style license that can be found in the LICENSE file.
8 */
10 #pragma once
12 #include "../pytypes.h"
14 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15 NAMESPACE_BEGIN(detail)
16 // Forward declarations
17 inline PyTypeObject *make_static_property_type();
18 inline PyTypeObject *make_default_metaclass();
19 inline PyObject *make_object_base_type(PyTypeObject *metaclass);
21 // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
22 // Thread Specific Storage (TSS) API.
23 #if PY_VERSION_HEX >= 0x03070000
24 #    define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr
25 #    define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
26 #    define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (tstate))
27 #    define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
28 #else
29     // Usually an int but a long on Cygwin64 with Python 3.x
30 #    define PYBIND11_TLS_KEY_INIT(var) decltype(PyThread_create_key()) var = 0
31 #    define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
32 #    if PY_MAJOR_VERSION < 3
33 #        define PYBIND11_TLS_DELETE_VALUE(key)                               \
34              PyThread_delete_key_value(key)
35 #        define PYBIND11_TLS_REPLACE_VALUE(key, value)                       \
36              do {                                                            \
37                  PyThread_delete_key_value((key));                           \
38                  PyThread_set_key_value((key), (value));                     \
39              } while (false)
40 #    else
41 #        define PYBIND11_TLS_DELETE_VALUE(key)                               \
42              PyThread_set_key_value((key), nullptr)
43 #        define PYBIND11_TLS_REPLACE_VALUE(key, value)                       \
44              PyThread_set_key_value((key), (value))
45 #    endif
46 #endif
48 // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
49 // other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
50 // even when `A` is the same, non-hidden-visibility type (e.g. from a common include).  Under
51 // libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
52 // which works.  If not under a known-good stl, provide our own name-based hash and equality
53 // functions that use the type name.
54 #if defined(__GLIBCXX__)
55 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
56 using type_hash = std::hash<std::type_index>;
57 using type_equal_to = std::equal_to<std::type_index>;
58 #else
59 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
60     return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
61 }
63 struct type_hash {
64     size_t operator()(const std::type_index &t) const {
65         size_t hash = 5381;
66         const char *ptr = t.name();
67         while (auto c = static_cast<unsigned char>(*ptr++))
68             hash = (hash * 33) ^ c;
69         return hash;
70     }
71 };
73 struct type_equal_to {
74     bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
75         return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
76     }
77 };
78 #endif
80 template <typename value_type>
81 using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
83 struct overload_hash {
84     inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
85         size_t value = std::hash<const void *>()(v.first);
86         value ^= std::hash<const void *>()(v.second)  + 0x9e3779b9 + (value<<6) + (value>>2);
87         return value;
88     }
89 };
91 /// Internal data structure used to track registered instances and types.
92 /// Whenever binary incompatible changes are made to this structure,
93 /// `PYBIND11_INTERNALS_VERSION` must be incremented.
94 struct internals {
95     type_map<type_info *> registered_types_cpp; // std::type_index -> pybind11's type information
96     std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py; // PyTypeObject* -> base type_info(s)
97     std::unordered_multimap<const void *, instance*> registered_instances; // void * -> instance*
98     std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
99     type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
100     std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
101     std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
102     std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
103     std::vector<PyObject *> loader_patient_stack; // Used by `loader_life_support`
104     std::forward_list<std::string> static_strings; // Stores the std::strings backing detail::c_str()
105     PyTypeObject *static_property_type;
106     PyTypeObject *default_metaclass;
107     PyObject *instance_base;
108 #if defined(WITH_THREAD)
109     PYBIND11_TLS_KEY_INIT(tstate);
110     PyInterpreterState *istate = nullptr;
111 #endif
112 };
114 /// Additional type information which does not fit into the PyTypeObject.
115 /// Changes to this struct also require bumping `PYBIND11_INTERNALS_VERSION`.
116 struct type_info {
117     PyTypeObject *type;
118     const std::type_info *cpptype;
119     size_t type_size, holder_size_in_ptrs;
120     void *(*operator_new)(size_t);
121     void (*init_instance)(instance *, const void *);
122     void (*dealloc)(value_and_holder &v_h);
123     std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions;
124     std::vector<std::pair<const std::type_info *, void *(*)(void *)>> implicit_casts;
125     std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
126     buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
127     void *get_buffer_data = nullptr;
128     void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
129     /* A simple type never occurs as a (direct or indirect) parent
130      * of a class that makes use of multiple inheritance */
131     bool simple_type : 1;
132     /* True if there is no multiple inheritance in this type's inheritance tree */
133     bool simple_ancestors : 1;
134     /* for base vs derived holder_type checks */
135     bool default_holder : 1;
136     /* true if this is a type registered with py::module_local */
137     bool module_local : 1;
138 };
140 /// Tracks the `internals` and `type_info` ABI version independent of the main library version
141 #define PYBIND11_INTERNALS_VERSION 2
143 #if defined(WITH_THREAD)
144 #  define PYBIND11_INTERNALS_KIND ""
145 #else
146 #  define PYBIND11_INTERNALS_KIND "_without_thread"
147 #endif
149 #define PYBIND11_INTERNALS_ID "__pybind11_internals_v" \
150     PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND "__"
152 #define PYBIND11_MODULE_LOCAL_ID "__pybind11_module_local_v" \
153     PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND "__"
155 /// Each module locally stores a pointer to the `internals` data. The data
156 /// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.
157 inline internals **&get_internals_pp() {
158     static internals **internals_pp = nullptr;
159     return internals_pp;
162 /// Return a reference to the current `internals` data
163 PYBIND11_NOINLINE inline internals &get_internals() {
164     auto **&internals_pp = get_internals_pp();
165     if (internals_pp && *internals_pp)
166         return **internals_pp;
168     constexpr auto *id = PYBIND11_INTERNALS_ID;
169     auto builtins = handle(PyEval_GetBuiltins());
170     if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
171         internals_pp = static_cast<internals **>(capsule(builtins[id]));
173         // We loaded builtins through python's builtins, which means that our `error_already_set`
174         // and `builtin_exception` may be different local classes than the ones set up in the
175         // initial exception translator, below, so add another for our local exception classes.
176         //
177         // libstdc++ doesn't require this (types there are identified only by name)
178 #if !defined(__GLIBCXX__)
179         (*internals_pp)->registered_exception_translators.push_front(
180             [](std::exception_ptr p) -> void {
181                 try {
182                     if (p) std::rethrow_exception(p);
183                 } catch (error_already_set &e)       { e.restore();   return;
184                 } catch (const builtin_exception &e) { e.set_error(); return;
185                 }
186             }
187         );
188 #endif
189     } else {
190         if (!internals_pp) internals_pp = new internals*();
191         auto *&internals_ptr = *internals_pp;
192         internals_ptr = new internals();
193 #if defined(WITH_THREAD)
194         PyEval_InitThreads();
195         PyThreadState *tstate = PyThreadState_Get();
196         #if PY_VERSION_HEX >= 0x03070000
197             internals_ptr->tstate = PyThread_tss_alloc();
198             if (!internals_ptr->tstate || PyThread_tss_create(internals_ptr->tstate))
199                 pybind11_fail("get_internals: could not successfully initialize the TSS key!");
200             PyThread_tss_set(internals_ptr->tstate, tstate);
201         #else
202             internals_ptr->tstate = PyThread_create_key();
203             if (internals_ptr->tstate == -1)
204                 pybind11_fail("get_internals: could not successfully initialize the TLS key!");
205             PyThread_set_key_value(internals_ptr->tstate, tstate);
206         #endif
207         internals_ptr->istate = tstate->interp;
208 #endif
209         builtins[id] = capsule(internals_pp);
210         internals_ptr->registered_exception_translators.push_front(
211             [](std::exception_ptr p) -> void {
212                 try {
213                     if (p) std::rethrow_exception(p);
214                 } catch (error_already_set &e)           { e.restore();                                    return;
215                 } catch (const builtin_exception &e)     { e.set_error();                                  return;
216                 } catch (const std::bad_alloc &e)        { PyErr_SetString(PyExc_MemoryError,   e.what()); return;
217                 } catch (const std::domain_error &e)     { PyErr_SetString(PyExc_ValueError,    e.what()); return;
218                 } catch (const std::invalid_argument &e) { PyErr_SetString(PyExc_ValueError,    e.what()); return;
219                 } catch (const std::length_error &e)     { PyErr_SetString(PyExc_ValueError,    e.what()); return;
220                 } catch (const std::out_of_range &e)     { PyErr_SetString(PyExc_IndexError,    e.what()); return;
221                 } catch (const std::range_error &e)      { PyErr_SetString(PyExc_ValueError,    e.what()); return;
222                 } catch (const std::exception &e)        { PyErr_SetString(PyExc_RuntimeError,  e.what()); return;
223                 } catch (...) {
224                     PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
225                     return;
226                 }
227             }
228         );
229         internals_ptr->static_property_type = make_static_property_type();
230         internals_ptr->default_metaclass = make_default_metaclass();
231         internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
232     }
233     return **internals_pp;
236 /// Works like `internals.registered_types_cpp`, but for module-local registered types:
237 inline type_map<type_info *> &registered_local_types_cpp() {
238     static type_map<type_info *> locals{};
239     return locals;
242 /// Constructs a std::string with the given arguments, stores it in `internals`, and returns its
243 /// `c_str()`.  Such strings objects have a long storage duration -- the internal strings are only
244 /// cleared when the program exits or after interpreter shutdown (when embedding), and so are
245 /// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name).
246 template <typename... Args>
247 const char *c_str(Args &&...args) {
248     auto &strings = get_internals().static_strings;
249     strings.emplace_front(std::forward<Args>(args)...);
250     return strings.front().c_str();
253 NAMESPACE_END(detail)
255 /// Returns a named pointer that is shared among all extension modules (using the same
256 /// pybind11 version) running in the current interpreter. Names starting with underscores
257 /// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
258 inline PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
259     auto &internals = detail::get_internals();
260     auto it = internals.shared_data.find(name);
261     return it != internals.shared_data.end() ? it->second : nullptr;
264 /// Set the shared data that can be later recovered by `get_shared_data()`.
265 inline PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
266     detail::get_internals().shared_data[name] = data;
267     return data;
270 /// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
271 /// such entry exists. Otherwise, a new object of default-constructible type `T` is
272 /// added to the shared data under the given name and a reference to it is returned.
273 template<typename T>
274 T &get_or_create_shared_data(const std::string &name) {
275     auto &internals = detail::get_internals();
276     auto it = internals.shared_data.find(name);
277     T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
278     if (!ptr) {
279         ptr = new T();
280         internals.shared_data[name] = ptr;
281     }
282     return *ptr;
285 NAMESPACE_END(PYBIND11_NAMESPACE)